angular.js 1.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821
  1. /**
  2. * @license AngularJS v1.5.9-build.5020+sha.0784977
  3. * (c) 2010-2016 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window) {'use strict';
  7. /**
  8. * @description
  9. *
  10. * This object provides a utility for producing rich Error messages within
  11. * Angular. It can be called as follows:
  12. *
  13. * var exampleMinErr = minErr('example');
  14. * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
  15. *
  16. * The above creates an instance of minErr in the example namespace. The
  17. * resulting error will have a namespaced error code of example.one. The
  18. * resulting error will replace {0} with the value of foo, and {1} with the
  19. * value of bar. The object is not restricted in the number of arguments it can
  20. * take.
  21. *
  22. * If fewer arguments are specified than necessary for interpolation, the extra
  23. * interpolation markers will be preserved in the final string.
  24. *
  25. * Since data will be parsed statically during a build step, some restrictions
  26. * are applied with respect to how minErr instances are created and called.
  27. * Instances should have names of the form namespaceMinErr for a minErr created
  28. * using minErr('namespace') . Error codes, namespaces and template strings
  29. * should all be static strings, not variables or general expressions.
  30. *
  31. * @param {string} module The namespace to use for the new minErr instance.
  32. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
  33. * error from returned function, for cases when a particular type of error is useful.
  34. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
  35. */
  36. function minErr(module, ErrorConstructor) {
  37. ErrorConstructor = ErrorConstructor || Error;
  38. return function() {
  39. var SKIP_INDEXES = 2;
  40. var templateArgs = arguments,
  41. code = templateArgs[0],
  42. message = '[' + (module ? module + ':' : '') + code + '] ',
  43. template = templateArgs[1],
  44. paramPrefix, i;
  45. message += template.replace(/\{\d+\}/g, function(match) {
  46. var index = +match.slice(1, -1),
  47. shiftedIndex = index + SKIP_INDEXES;
  48. if (shiftedIndex < templateArgs.length) {
  49. return toDebugString(templateArgs[shiftedIndex]);
  50. }
  51. return match;
  52. });
  53. message += '\nhttp://errors.angularjs.org/1.5.9-build.5020+sha.0784977/' +
  54. (module ? module + '/' : '') + code;
  55. for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
  56. message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
  57. encodeURIComponent(toDebugString(templateArgs[i]));
  58. }
  59. return new ErrorConstructor(message);
  60. };
  61. }
  62. /* We need to tell ESLint what variables are being exported */
  63. /* exported
  64. angular,
  65. msie,
  66. jqLite,
  67. jQuery,
  68. slice,
  69. splice,
  70. push,
  71. toString,
  72. ngMinErr,
  73. angularModule,
  74. uid,
  75. REGEX_STRING_REGEXP,
  76. VALIDITY_STATE_PROPERTY,
  77. lowercase,
  78. uppercase,
  79. manualLowercase,
  80. manualUppercase,
  81. nodeName_,
  82. isArrayLike,
  83. forEach,
  84. forEachSorted,
  85. reverseParams,
  86. nextUid,
  87. setHashKey,
  88. extend,
  89. toInt,
  90. inherit,
  91. merge,
  92. noop,
  93. identity,
  94. valueFn,
  95. isUndefined,
  96. isDefined,
  97. isObject,
  98. isBlankObject,
  99. isString,
  100. isNumber,
  101. isNumberNaN,
  102. isDate,
  103. isArray,
  104. isFunction,
  105. isRegExp,
  106. isWindow,
  107. isScope,
  108. isFile,
  109. isFormData,
  110. isBlob,
  111. isBoolean,
  112. isPromiseLike,
  113. trim,
  114. escapeForRegexp,
  115. isElement,
  116. makeMap,
  117. includes,
  118. arrayRemove,
  119. copy,
  120. equals,
  121. csp,
  122. jq,
  123. concat,
  124. sliceArgs,
  125. bind,
  126. toJsonReplacer,
  127. toJson,
  128. fromJson,
  129. convertTimezoneToLocal,
  130. timezoneToOffset,
  131. startingTag,
  132. tryDecodeURIComponent,
  133. parseKeyValue,
  134. toKeyValue,
  135. encodeUriSegment,
  136. encodeUriQuery,
  137. angularInit,
  138. bootstrap,
  139. getTestability,
  140. snake_case,
  141. bindJQuery,
  142. assertArg,
  143. assertArgFn,
  144. assertNotHasOwnProperty,
  145. getter,
  146. getBlockNodes,
  147. hasOwnProperty,
  148. createMap,
  149. stringify,
  150. NODE_TYPE_ELEMENT,
  151. NODE_TYPE_ATTRIBUTE,
  152. NODE_TYPE_TEXT,
  153. NODE_TYPE_COMMENT,
  154. NODE_TYPE_DOCUMENT,
  155. NODE_TYPE_DOCUMENT_FRAGMENT
  156. */
  157. ////////////////////////////////////
  158. /**
  159. * @ngdoc module
  160. * @name ng
  161. * @module ng
  162. * @installation
  163. * @description
  164. *
  165. * # ng (core module)
  166. * The ng module is loaded by default when an AngularJS application is started. The module itself
  167. * contains the essential components for an AngularJS application to function. The table below
  168. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  169. * components available within this core module.
  170. *
  171. * <div doc-module-components="ng"></div>
  172. */
  173. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  174. // The name of a form control's ValidityState property.
  175. // This is used so that it's possible for internal tests to create mock ValidityStates.
  176. var VALIDITY_STATE_PROPERTY = 'validity';
  177. var hasOwnProperty = Object.prototype.hasOwnProperty;
  178. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  179. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  180. var manualLowercase = function(s) {
  181. /* eslint-disable no-bitwise */
  182. return isString(s)
  183. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  184. : s;
  185. /* eslint-enable */
  186. };
  187. var manualUppercase = function(s) {
  188. /* eslint-disable no-bitwise */
  189. return isString(s)
  190. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  191. : s;
  192. /* eslint-enable */
  193. };
  194. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  195. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  196. // with correct but slower alternatives. See https://github.com/angular/angular.js/issues/11387
  197. if ('i' !== 'I'.toLowerCase()) {
  198. lowercase = manualLowercase;
  199. uppercase = manualUppercase;
  200. }
  201. var
  202. msie, // holds major version number for IE, or NaN if UA is not IE.
  203. jqLite, // delay binding since jQuery could be loaded after us.
  204. jQuery, // delay binding
  205. slice = [].slice,
  206. splice = [].splice,
  207. push = [].push,
  208. toString = Object.prototype.toString,
  209. getPrototypeOf = Object.getPrototypeOf,
  210. ngMinErr = minErr('ng'),
  211. /** @name angular */
  212. angular = window.angular || (window.angular = {}),
  213. angularModule,
  214. uid = 0;
  215. /**
  216. * documentMode is an IE-only property
  217. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  218. */
  219. msie = window.document.documentMode;
  220. /**
  221. * @private
  222. * @param {*} obj
  223. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  224. * String ...)
  225. */
  226. function isArrayLike(obj) {
  227. // `null`, `undefined` and `window` are not array-like
  228. if (obj == null || isWindow(obj)) return false;
  229. // arrays, strings and jQuery/jqLite objects are array like
  230. // * jqLite is either the jQuery or jqLite constructor function
  231. // * we have to check the existence of jqLite first as this method is called
  232. // via the forEach method when constructing the jqLite object in the first place
  233. if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
  234. // Support: iOS 8.2 (not reproducible in simulator)
  235. // "length" in obj used to prevent JIT error (gh-11508)
  236. var length = 'length' in Object(obj) && obj.length;
  237. // NodeList objects (with `item` method) and
  238. // other objects with suitable length characteristics are array-like
  239. return isNumber(length) &&
  240. (length >= 0 && ((length - 1) in obj || obj instanceof Array) || typeof obj.item === 'function');
  241. }
  242. /**
  243. * @ngdoc function
  244. * @name angular.forEach
  245. * @module ng
  246. * @kind function
  247. *
  248. * @description
  249. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  250. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  251. * is the value of an object property or an array element, `key` is the object property key or
  252. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  253. *
  254. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  255. * using the `hasOwnProperty` method.
  256. *
  257. * Unlike ES262's
  258. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  259. * providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  260. * return the value provided.
  261. *
  262. ```js
  263. var values = {name: 'misko', gender: 'male'};
  264. var log = [];
  265. angular.forEach(values, function(value, key) {
  266. this.push(key + ': ' + value);
  267. }, log);
  268. expect(log).toEqual(['name: misko', 'gender: male']);
  269. ```
  270. *
  271. * @param {Object|Array} obj Object to iterate over.
  272. * @param {Function} iterator Iterator function.
  273. * @param {Object=} context Object to become context (`this`) for the iterator function.
  274. * @returns {Object|Array} Reference to `obj`.
  275. */
  276. function forEach(obj, iterator, context) {
  277. var key, length;
  278. if (obj) {
  279. if (isFunction(obj)) {
  280. for (key in obj) {
  281. if (key !== 'prototype' && key !== 'length' && key !== 'name' && obj.hasOwnProperty(key)) {
  282. iterator.call(context, obj[key], key, obj);
  283. }
  284. }
  285. } else if (isArray(obj) || isArrayLike(obj)) {
  286. var isPrimitive = typeof obj !== 'object';
  287. for (key = 0, length = obj.length; key < length; key++) {
  288. if (isPrimitive || key in obj) {
  289. iterator.call(context, obj[key], key, obj);
  290. }
  291. }
  292. } else if (obj.forEach && obj.forEach !== forEach) {
  293. obj.forEach(iterator, context, obj);
  294. } else if (isBlankObject(obj)) {
  295. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  296. for (key in obj) {
  297. iterator.call(context, obj[key], key, obj);
  298. }
  299. } else if (typeof obj.hasOwnProperty === 'function') {
  300. // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
  301. for (key in obj) {
  302. if (obj.hasOwnProperty(key)) {
  303. iterator.call(context, obj[key], key, obj);
  304. }
  305. }
  306. } else {
  307. // Slow path for objects which do not have a method `hasOwnProperty`
  308. for (key in obj) {
  309. if (hasOwnProperty.call(obj, key)) {
  310. iterator.call(context, obj[key], key, obj);
  311. }
  312. }
  313. }
  314. }
  315. return obj;
  316. }
  317. function forEachSorted(obj, iterator, context) {
  318. var keys = Object.keys(obj).sort();
  319. for (var i = 0; i < keys.length; i++) {
  320. iterator.call(context, obj[keys[i]], keys[i]);
  321. }
  322. return keys;
  323. }
  324. /**
  325. * when using forEach the params are value, key, but it is often useful to have key, value.
  326. * @param {function(string, *)} iteratorFn
  327. * @returns {function(*, string)}
  328. */
  329. function reverseParams(iteratorFn) {
  330. return function(value, key) {iteratorFn(key, value);};
  331. }
  332. /**
  333. * A consistent way of creating unique IDs in angular.
  334. *
  335. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  336. * we hit number precision issues in JavaScript.
  337. *
  338. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  339. *
  340. * @returns {number} an unique alpha-numeric string
  341. */
  342. function nextUid() {
  343. return ++uid;
  344. }
  345. /**
  346. * Set or clear the hashkey for an object.
  347. * @param obj object
  348. * @param h the hashkey (!truthy to delete the hashkey)
  349. */
  350. function setHashKey(obj, h) {
  351. if (h) {
  352. obj.$$hashKey = h;
  353. } else {
  354. delete obj.$$hashKey;
  355. }
  356. }
  357. function baseExtend(dst, objs, deep) {
  358. var h = dst.$$hashKey;
  359. for (var i = 0, ii = objs.length; i < ii; ++i) {
  360. var obj = objs[i];
  361. if (!isObject(obj) && !isFunction(obj)) continue;
  362. var keys = Object.keys(obj);
  363. for (var j = 0, jj = keys.length; j < jj; j++) {
  364. var key = keys[j];
  365. var src = obj[key];
  366. if (deep && isObject(src)) {
  367. if (isDate(src)) {
  368. dst[key] = new Date(src.valueOf());
  369. } else if (isRegExp(src)) {
  370. dst[key] = new RegExp(src);
  371. } else if (src.nodeName) {
  372. dst[key] = src.cloneNode(true);
  373. } else if (isElement(src)) {
  374. dst[key] = src.clone();
  375. } else {
  376. if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
  377. baseExtend(dst[key], [src], true);
  378. }
  379. } else {
  380. dst[key] = src;
  381. }
  382. }
  383. }
  384. setHashKey(dst, h);
  385. return dst;
  386. }
  387. /**
  388. * @ngdoc function
  389. * @name angular.extend
  390. * @module ng
  391. * @kind function
  392. *
  393. * @description
  394. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  395. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  396. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  397. *
  398. * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
  399. * {@link angular.merge} for this.
  400. *
  401. * @param {Object} dst Destination object.
  402. * @param {...Object} src Source object(s).
  403. * @returns {Object} Reference to `dst`.
  404. */
  405. function extend(dst) {
  406. return baseExtend(dst, slice.call(arguments, 1), false);
  407. }
  408. /**
  409. * @ngdoc function
  410. * @name angular.merge
  411. * @module ng
  412. * @kind function
  413. *
  414. * @description
  415. * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  416. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  417. * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
  418. *
  419. * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
  420. * objects, performing a deep copy.
  421. *
  422. * @param {Object} dst Destination object.
  423. * @param {...Object} src Source object(s).
  424. * @returns {Object} Reference to `dst`.
  425. */
  426. function merge(dst) {
  427. return baseExtend(dst, slice.call(arguments, 1), true);
  428. }
  429. function toInt(str) {
  430. return parseInt(str, 10);
  431. }
  432. var isNumberNaN = Number.isNaN || function isNumberNaN(num) {
  433. // eslint-disable-next-line no-self-compare
  434. return num !== num;
  435. };
  436. function inherit(parent, extra) {
  437. return extend(Object.create(parent), extra);
  438. }
  439. /**
  440. * @ngdoc function
  441. * @name angular.noop
  442. * @module ng
  443. * @kind function
  444. *
  445. * @description
  446. * A function that performs no operations. This function can be useful when writing code in the
  447. * functional style.
  448. ```js
  449. function foo(callback) {
  450. var result = calculateResult();
  451. (callback || angular.noop)(result);
  452. }
  453. ```
  454. */
  455. function noop() {}
  456. noop.$inject = [];
  457. /**
  458. * @ngdoc function
  459. * @name angular.identity
  460. * @module ng
  461. * @kind function
  462. *
  463. * @description
  464. * A function that returns its first argument. This function is useful when writing code in the
  465. * functional style.
  466. *
  467. ```js
  468. function transformer(transformationFn, value) {
  469. return (transformationFn || angular.identity)(value);
  470. };
  471. // E.g.
  472. function getResult(fn, input) {
  473. return (fn || angular.identity)(input);
  474. };
  475. getResult(function(n) { return n * 2; }, 21); // returns 42
  476. getResult(null, 21); // returns 21
  477. getResult(undefined, 21); // returns 21
  478. ```
  479. *
  480. * @param {*} value to be returned.
  481. * @returns {*} the value passed in.
  482. */
  483. function identity($) {return $;}
  484. identity.$inject = [];
  485. function valueFn(value) {return function valueRef() {return value;};}
  486. function hasCustomToString(obj) {
  487. return isFunction(obj.toString) && obj.toString !== toString;
  488. }
  489. /**
  490. * @ngdoc function
  491. * @name angular.isUndefined
  492. * @module ng
  493. * @kind function
  494. *
  495. * @description
  496. * Determines if a reference is undefined.
  497. *
  498. * @param {*} value Reference to check.
  499. * @returns {boolean} True if `value` is undefined.
  500. */
  501. function isUndefined(value) {return typeof value === 'undefined';}
  502. /**
  503. * @ngdoc function
  504. * @name angular.isDefined
  505. * @module ng
  506. * @kind function
  507. *
  508. * @description
  509. * Determines if a reference is defined.
  510. *
  511. * @param {*} value Reference to check.
  512. * @returns {boolean} True if `value` is defined.
  513. */
  514. function isDefined(value) {return typeof value !== 'undefined';}
  515. /**
  516. * @ngdoc function
  517. * @name angular.isObject
  518. * @module ng
  519. * @kind function
  520. *
  521. * @description
  522. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  523. * considered to be objects. Note that JavaScript arrays are objects.
  524. *
  525. * @param {*} value Reference to check.
  526. * @returns {boolean} True if `value` is an `Object` but not `null`.
  527. */
  528. function isObject(value) {
  529. // http://jsperf.com/isobject4
  530. return value !== null && typeof value === 'object';
  531. }
  532. /**
  533. * Determine if a value is an object with a null prototype
  534. *
  535. * @returns {boolean} True if `value` is an `Object` with a null prototype
  536. */
  537. function isBlankObject(value) {
  538. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  539. }
  540. /**
  541. * @ngdoc function
  542. * @name angular.isString
  543. * @module ng
  544. * @kind function
  545. *
  546. * @description
  547. * Determines if a reference is a `String`.
  548. *
  549. * @param {*} value Reference to check.
  550. * @returns {boolean} True if `value` is a `String`.
  551. */
  552. function isString(value) {return typeof value === 'string';}
  553. /**
  554. * @ngdoc function
  555. * @name angular.isNumber
  556. * @module ng
  557. * @kind function
  558. *
  559. * @description
  560. * Determines if a reference is a `Number`.
  561. *
  562. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  563. *
  564. * If you wish to exclude these then you can use the native
  565. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  566. * method.
  567. *
  568. * @param {*} value Reference to check.
  569. * @returns {boolean} True if `value` is a `Number`.
  570. */
  571. function isNumber(value) {return typeof value === 'number';}
  572. /**
  573. * @ngdoc function
  574. * @name angular.isDate
  575. * @module ng
  576. * @kind function
  577. *
  578. * @description
  579. * Determines if a value is a date.
  580. *
  581. * @param {*} value Reference to check.
  582. * @returns {boolean} True if `value` is a `Date`.
  583. */
  584. function isDate(value) {
  585. return toString.call(value) === '[object Date]';
  586. }
  587. /**
  588. * @ngdoc function
  589. * @name angular.isArray
  590. * @module ng
  591. * @kind function
  592. *
  593. * @description
  594. * Determines if a reference is an `Array`.
  595. *
  596. * @param {*} value Reference to check.
  597. * @returns {boolean} True if `value` is an `Array`.
  598. */
  599. var isArray = Array.isArray;
  600. /**
  601. * @ngdoc function
  602. * @name angular.isFunction
  603. * @module ng
  604. * @kind function
  605. *
  606. * @description
  607. * Determines if a reference is a `Function`.
  608. *
  609. * @param {*} value Reference to check.
  610. * @returns {boolean} True if `value` is a `Function`.
  611. */
  612. function isFunction(value) {return typeof value === 'function';}
  613. /**
  614. * Determines if a value is a regular expression object.
  615. *
  616. * @private
  617. * @param {*} value Reference to check.
  618. * @returns {boolean} True if `value` is a `RegExp`.
  619. */
  620. function isRegExp(value) {
  621. return toString.call(value) === '[object RegExp]';
  622. }
  623. /**
  624. * Checks if `obj` is a window object.
  625. *
  626. * @private
  627. * @param {*} obj Object to check
  628. * @returns {boolean} True if `obj` is a window obj.
  629. */
  630. function isWindow(obj) {
  631. return obj && obj.window === obj;
  632. }
  633. function isScope(obj) {
  634. return obj && obj.$evalAsync && obj.$watch;
  635. }
  636. function isFile(obj) {
  637. return toString.call(obj) === '[object File]';
  638. }
  639. function isFormData(obj) {
  640. return toString.call(obj) === '[object FormData]';
  641. }
  642. function isBlob(obj) {
  643. return toString.call(obj) === '[object Blob]';
  644. }
  645. function isBoolean(value) {
  646. return typeof value === 'boolean';
  647. }
  648. function isPromiseLike(obj) {
  649. return obj && isFunction(obj.then);
  650. }
  651. var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array\]$/;
  652. function isTypedArray(value) {
  653. return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
  654. }
  655. function isArrayBuffer(obj) {
  656. return toString.call(obj) === '[object ArrayBuffer]';
  657. }
  658. var trim = function(value) {
  659. return isString(value) ? value.trim() : value;
  660. };
  661. // Copied from:
  662. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  663. // Prereq: s is a string.
  664. var escapeForRegexp = function(s) {
  665. return s
  666. .replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1')
  667. // eslint-disable-next-line no-control-regex
  668. .replace(/\x08/g, '\\x08');
  669. };
  670. /**
  671. * @ngdoc function
  672. * @name angular.isElement
  673. * @module ng
  674. * @kind function
  675. *
  676. * @description
  677. * Determines if a reference is a DOM element (or wrapped jQuery element).
  678. *
  679. * @param {*} value Reference to check.
  680. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  681. */
  682. function isElement(node) {
  683. return !!(node &&
  684. (node.nodeName // We are a direct element.
  685. || (node.prop && node.attr && node.find))); // We have an on and find method part of jQuery API.
  686. }
  687. /**
  688. * @param str 'key1,key2,...'
  689. * @returns {object} in the form of {key1:true, key2:true, ...}
  690. */
  691. function makeMap(str) {
  692. var obj = {}, items = str.split(','), i;
  693. for (i = 0; i < items.length; i++) {
  694. obj[items[i]] = true;
  695. }
  696. return obj;
  697. }
  698. function nodeName_(element) {
  699. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  700. }
  701. function includes(array, obj) {
  702. return Array.prototype.indexOf.call(array, obj) !== -1;
  703. }
  704. function arrayRemove(array, value) {
  705. var index = array.indexOf(value);
  706. if (index >= 0) {
  707. array.splice(index, 1);
  708. }
  709. return index;
  710. }
  711. /**
  712. * @ngdoc function
  713. * @name angular.copy
  714. * @module ng
  715. * @kind function
  716. *
  717. * @description
  718. * Creates a deep copy of `source`, which should be an object or an array.
  719. *
  720. * * If no destination is supplied, a copy of the object or array is created.
  721. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  722. * are deleted and then all elements/properties from the source are copied to it.
  723. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  724. * * If `source` is identical to `destination` an exception will be thrown.
  725. *
  726. * <br />
  727. * <div class="alert alert-warning">
  728. * Only enumerable properties are taken into account. Non-enumerable properties (both on `source`
  729. * and on `destination`) will be ignored.
  730. * </div>
  731. *
  732. * @param {*} source The source that will be used to make a copy.
  733. * Can be any type, including primitives, `null`, and `undefined`.
  734. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  735. * provided, must be of the same type as `source`.
  736. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  737. *
  738. * @example
  739. <example module="copyExample" name="angular-copy">
  740. <file name="index.html">
  741. <div ng-controller="ExampleController">
  742. <form novalidate class="simple-form">
  743. <label>Name: <input type="text" ng-model="user.name" /></label><br />
  744. <label>Age: <input type="number" ng-model="user.age" /></label><br />
  745. Gender: <label><input type="radio" ng-model="user.gender" value="male" />male</label>
  746. <label><input type="radio" ng-model="user.gender" value="female" />female</label><br />
  747. <button ng-click="reset()">RESET</button>
  748. <button ng-click="update(user)">SAVE</button>
  749. </form>
  750. <pre>form = {{user | json}}</pre>
  751. <pre>master = {{master | json}}</pre>
  752. </div>
  753. </file>
  754. <file name="script.js">
  755. // Module: copyExample
  756. angular.
  757. module('copyExample', []).
  758. controller('ExampleController', ['$scope', function($scope) {
  759. $scope.master = {};
  760. $scope.reset = function() {
  761. // Example with 1 argument
  762. $scope.user = angular.copy($scope.master);
  763. };
  764. $scope.update = function(user) {
  765. // Example with 2 arguments
  766. angular.copy(user, $scope.master);
  767. };
  768. $scope.reset();
  769. }]);
  770. </file>
  771. </example>
  772. */
  773. function copy(source, destination) {
  774. var stackSource = [];
  775. var stackDest = [];
  776. if (destination) {
  777. if (isTypedArray(destination) || isArrayBuffer(destination)) {
  778. throw ngMinErr('cpta', 'Can\'t copy! TypedArray destination cannot be mutated.');
  779. }
  780. if (source === destination) {
  781. throw ngMinErr('cpi', 'Can\'t copy! Source and destination are identical.');
  782. }
  783. // Empty the destination object
  784. if (isArray(destination)) {
  785. destination.length = 0;
  786. } else {
  787. forEach(destination, function(value, key) {
  788. if (key !== '$$hashKey') {
  789. delete destination[key];
  790. }
  791. });
  792. }
  793. stackSource.push(source);
  794. stackDest.push(destination);
  795. return copyRecurse(source, destination);
  796. }
  797. return copyElement(source);
  798. function copyRecurse(source, destination) {
  799. var h = destination.$$hashKey;
  800. var key;
  801. if (isArray(source)) {
  802. for (var i = 0, ii = source.length; i < ii; i++) {
  803. destination.push(copyElement(source[i]));
  804. }
  805. } else if (isBlankObject(source)) {
  806. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  807. for (key in source) {
  808. destination[key] = copyElement(source[key]);
  809. }
  810. } else if (source && typeof source.hasOwnProperty === 'function') {
  811. // Slow path, which must rely on hasOwnProperty
  812. for (key in source) {
  813. if (source.hasOwnProperty(key)) {
  814. destination[key] = copyElement(source[key]);
  815. }
  816. }
  817. } else {
  818. // Slowest path --- hasOwnProperty can't be called as a method
  819. for (key in source) {
  820. if (hasOwnProperty.call(source, key)) {
  821. destination[key] = copyElement(source[key]);
  822. }
  823. }
  824. }
  825. setHashKey(destination, h);
  826. return destination;
  827. }
  828. function copyElement(source) {
  829. // Simple values
  830. if (!isObject(source)) {
  831. return source;
  832. }
  833. // Already copied values
  834. var index = stackSource.indexOf(source);
  835. if (index !== -1) {
  836. return stackDest[index];
  837. }
  838. if (isWindow(source) || isScope(source)) {
  839. throw ngMinErr('cpws',
  840. 'Can\'t copy! Making copies of Window or Scope instances is not supported.');
  841. }
  842. var needsRecurse = false;
  843. var destination = copyType(source);
  844. if (destination === undefined) {
  845. destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
  846. needsRecurse = true;
  847. }
  848. stackSource.push(source);
  849. stackDest.push(destination);
  850. return needsRecurse
  851. ? copyRecurse(source, destination)
  852. : destination;
  853. }
  854. function copyType(source) {
  855. switch (toString.call(source)) {
  856. case '[object Int8Array]':
  857. case '[object Int16Array]':
  858. case '[object Int32Array]':
  859. case '[object Float32Array]':
  860. case '[object Float64Array]':
  861. case '[object Uint8Array]':
  862. case '[object Uint8ClampedArray]':
  863. case '[object Uint16Array]':
  864. case '[object Uint32Array]':
  865. return new source.constructor(copyElement(source.buffer), source.byteOffset, source.length);
  866. case '[object ArrayBuffer]':
  867. // Support: IE10
  868. if (!source.slice) {
  869. // If we're in this case we know the environment supports ArrayBuffer
  870. /* eslint-disable no-undef */
  871. var copied = new ArrayBuffer(source.byteLength);
  872. new Uint8Array(copied).set(new Uint8Array(source));
  873. /* eslint-enable */
  874. return copied;
  875. }
  876. return source.slice(0);
  877. case '[object Boolean]':
  878. case '[object Number]':
  879. case '[object String]':
  880. case '[object Date]':
  881. return new source.constructor(source.valueOf());
  882. case '[object RegExp]':
  883. var re = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  884. re.lastIndex = source.lastIndex;
  885. return re;
  886. case '[object Blob]':
  887. return new source.constructor([source], {type: source.type});
  888. }
  889. if (isFunction(source.cloneNode)) {
  890. return source.cloneNode(true);
  891. }
  892. }
  893. }
  894. /**
  895. * @ngdoc function
  896. * @name angular.equals
  897. * @module ng
  898. * @kind function
  899. *
  900. * @description
  901. * Determines if two objects or two values are equivalent. Supports value types, regular
  902. * expressions, arrays and objects.
  903. *
  904. * Two objects or values are considered equivalent if at least one of the following is true:
  905. *
  906. * * Both objects or values pass `===` comparison.
  907. * * Both objects or values are of the same type and all of their properties are equal by
  908. * comparing them with `angular.equals`.
  909. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  910. * * Both values represent the same regular expression (In JavaScript,
  911. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  912. * representation matches).
  913. *
  914. * During a property comparison, properties of `function` type and properties with names
  915. * that begin with `$` are ignored.
  916. *
  917. * Scope and DOMWindow objects are being compared only by identify (`===`).
  918. *
  919. * @param {*} o1 Object or value to compare.
  920. * @param {*} o2 Object or value to compare.
  921. * @returns {boolean} True if arguments are equal.
  922. *
  923. * @example
  924. <example module="equalsExample" name="equalsExample">
  925. <file name="index.html">
  926. <div ng-controller="ExampleController">
  927. <form novalidate>
  928. <h3>User 1</h3>
  929. Name: <input type="text" ng-model="user1.name">
  930. Age: <input type="number" ng-model="user1.age">
  931. <h3>User 2</h3>
  932. Name: <input type="text" ng-model="user2.name">
  933. Age: <input type="number" ng-model="user2.age">
  934. <div>
  935. <br/>
  936. <input type="button" value="Compare" ng-click="compare()">
  937. </div>
  938. User 1: <pre>{{user1 | json}}</pre>
  939. User 2: <pre>{{user2 | json}}</pre>
  940. Equal: <pre>{{result}}</pre>
  941. </form>
  942. </div>
  943. </file>
  944. <file name="script.js">
  945. angular.module('equalsExample', []).controller('ExampleController', ['$scope', function($scope) {
  946. $scope.user1 = {};
  947. $scope.user2 = {};
  948. $scope.compare = function() {
  949. $scope.result = angular.equals($scope.user1, $scope.user2);
  950. };
  951. }]);
  952. </file>
  953. </example>
  954. */
  955. function equals(o1, o2) {
  956. if (o1 === o2) return true;
  957. if (o1 === null || o2 === null) return false;
  958. // eslint-disable-next-line no-self-compare
  959. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  960. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  961. if (t1 === t2 && t1 === 'object') {
  962. if (isArray(o1)) {
  963. if (!isArray(o2)) return false;
  964. if ((length = o1.length) === o2.length) {
  965. for (key = 0; key < length; key++) {
  966. if (!equals(o1[key], o2[key])) return false;
  967. }
  968. return true;
  969. }
  970. } else if (isDate(o1)) {
  971. if (!isDate(o2)) return false;
  972. return equals(o1.getTime(), o2.getTime());
  973. } else if (isRegExp(o1)) {
  974. if (!isRegExp(o2)) return false;
  975. return o1.toString() === o2.toString();
  976. } else {
  977. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  978. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  979. keySet = createMap();
  980. for (key in o1) {
  981. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  982. if (!equals(o1[key], o2[key])) return false;
  983. keySet[key] = true;
  984. }
  985. for (key in o2) {
  986. if (!(key in keySet) &&
  987. key.charAt(0) !== '$' &&
  988. isDefined(o2[key]) &&
  989. !isFunction(o2[key])) return false;
  990. }
  991. return true;
  992. }
  993. }
  994. return false;
  995. }
  996. var csp = function() {
  997. if (!isDefined(csp.rules)) {
  998. var ngCspElement = (window.document.querySelector('[ng-csp]') ||
  999. window.document.querySelector('[data-ng-csp]'));
  1000. if (ngCspElement) {
  1001. var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
  1002. ngCspElement.getAttribute('data-ng-csp');
  1003. csp.rules = {
  1004. noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
  1005. noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
  1006. };
  1007. } else {
  1008. csp.rules = {
  1009. noUnsafeEval: noUnsafeEval(),
  1010. noInlineStyle: false
  1011. };
  1012. }
  1013. }
  1014. return csp.rules;
  1015. function noUnsafeEval() {
  1016. try {
  1017. // eslint-disable-next-line no-new, no-new-func
  1018. new Function('');
  1019. return false;
  1020. } catch (e) {
  1021. return true;
  1022. }
  1023. }
  1024. };
  1025. /**
  1026. * @ngdoc directive
  1027. * @module ng
  1028. * @name ngJq
  1029. *
  1030. * @element ANY
  1031. * @param {string=} ngJq the name of the library available under `window`
  1032. * to be used for angular.element
  1033. * @description
  1034. * Use this directive to force the angular.element library. This should be
  1035. * used to force either jqLite by leaving ng-jq blank or setting the name of
  1036. * the jquery variable under window (eg. jQuery).
  1037. *
  1038. * Since angular looks for this directive when it is loaded (doesn't wait for the
  1039. * DOMContentLoaded event), it must be placed on an element that comes before the script
  1040. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  1041. * others ignored.
  1042. *
  1043. * @example
  1044. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  1045. ```html
  1046. <!doctype html>
  1047. <html ng-app ng-jq>
  1048. ...
  1049. ...
  1050. </html>
  1051. ```
  1052. * @example
  1053. * This example shows how to use a jQuery based library of a different name.
  1054. * The library name must be available at the top most 'window'.
  1055. ```html
  1056. <!doctype html>
  1057. <html ng-app ng-jq="jQueryLib">
  1058. ...
  1059. ...
  1060. </html>
  1061. ```
  1062. */
  1063. var jq = function() {
  1064. if (isDefined(jq.name_)) return jq.name_;
  1065. var el;
  1066. var i, ii = ngAttrPrefixes.length, prefix, name;
  1067. for (i = 0; i < ii; ++i) {
  1068. prefix = ngAttrPrefixes[i];
  1069. el = window.document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]');
  1070. if (el) {
  1071. name = el.getAttribute(prefix + 'jq');
  1072. break;
  1073. }
  1074. }
  1075. return (jq.name_ = name);
  1076. };
  1077. function concat(array1, array2, index) {
  1078. return array1.concat(slice.call(array2, index));
  1079. }
  1080. function sliceArgs(args, startIndex) {
  1081. return slice.call(args, startIndex || 0);
  1082. }
  1083. /**
  1084. * @ngdoc function
  1085. * @name angular.bind
  1086. * @module ng
  1087. * @kind function
  1088. *
  1089. * @description
  1090. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  1091. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  1092. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  1093. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  1094. *
  1095. * @param {Object} self Context which `fn` should be evaluated in.
  1096. * @param {function()} fn Function to be bound.
  1097. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  1098. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  1099. */
  1100. function bind(self, fn) {
  1101. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  1102. if (isFunction(fn) && !(fn instanceof RegExp)) {
  1103. return curryArgs.length
  1104. ? function() {
  1105. return arguments.length
  1106. ? fn.apply(self, concat(curryArgs, arguments, 0))
  1107. : fn.apply(self, curryArgs);
  1108. }
  1109. : function() {
  1110. return arguments.length
  1111. ? fn.apply(self, arguments)
  1112. : fn.call(self);
  1113. };
  1114. } else {
  1115. // In IE, native methods are not functions so they cannot be bound (note: they don't need to be).
  1116. return fn;
  1117. }
  1118. }
  1119. function toJsonReplacer(key, value) {
  1120. var val = value;
  1121. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  1122. val = undefined;
  1123. } else if (isWindow(value)) {
  1124. val = '$WINDOW';
  1125. } else if (value && window.document === value) {
  1126. val = '$DOCUMENT';
  1127. } else if (isScope(value)) {
  1128. val = '$SCOPE';
  1129. }
  1130. return val;
  1131. }
  1132. /**
  1133. * @ngdoc function
  1134. * @name angular.toJson
  1135. * @module ng
  1136. * @kind function
  1137. *
  1138. * @description
  1139. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  1140. * stripped since angular uses this notation internally.
  1141. *
  1142. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  1143. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  1144. * If set to an integer, the JSON output will contain that many spaces per indentation.
  1145. * @returns {string|undefined} JSON-ified string representing `obj`.
  1146. * @knownIssue
  1147. *
  1148. * The Safari browser throws a `RangeError` instead of returning `null` when it tries to stringify a `Date`
  1149. * object with an invalid date value. The only reliable way to prevent this is to monkeypatch the
  1150. * `Date.prototype.toJSON` method as follows:
  1151. *
  1152. * ```
  1153. * var _DatetoJSON = Date.prototype.toJSON;
  1154. * Date.prototype.toJSON = function() {
  1155. * try {
  1156. * return _DatetoJSON.call(this);
  1157. * } catch(e) {
  1158. * if (e instanceof RangeError) {
  1159. * return null;
  1160. * }
  1161. * throw e;
  1162. * }
  1163. * };
  1164. * ```
  1165. *
  1166. * See https://github.com/angular/angular.js/pull/14221 for more information.
  1167. */
  1168. function toJson(obj, pretty) {
  1169. if (isUndefined(obj)) return undefined;
  1170. if (!isNumber(pretty)) {
  1171. pretty = pretty ? 2 : null;
  1172. }
  1173. return JSON.stringify(obj, toJsonReplacer, pretty);
  1174. }
  1175. /**
  1176. * @ngdoc function
  1177. * @name angular.fromJson
  1178. * @module ng
  1179. * @kind function
  1180. *
  1181. * @description
  1182. * Deserializes a JSON string.
  1183. *
  1184. * @param {string} json JSON string to deserialize.
  1185. * @returns {Object|Array|string|number} Deserialized JSON string.
  1186. */
  1187. function fromJson(json) {
  1188. return isString(json)
  1189. ? JSON.parse(json)
  1190. : json;
  1191. }
  1192. var ALL_COLONS = /:/g;
  1193. function timezoneToOffset(timezone, fallback) {
  1194. // IE/Edge do not "understand" colon (`:`) in timezone
  1195. timezone = timezone.replace(ALL_COLONS, '');
  1196. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  1197. return isNumberNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  1198. }
  1199. function addDateMinutes(date, minutes) {
  1200. date = new Date(date.getTime());
  1201. date.setMinutes(date.getMinutes() + minutes);
  1202. return date;
  1203. }
  1204. function convertTimezoneToLocal(date, timezone, reverse) {
  1205. reverse = reverse ? -1 : 1;
  1206. var dateTimezoneOffset = date.getTimezoneOffset();
  1207. var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  1208. return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));
  1209. }
  1210. /**
  1211. * @returns {string} Returns the string representation of the element.
  1212. */
  1213. function startingTag(element) {
  1214. element = jqLite(element).clone();
  1215. try {
  1216. // turns out IE does not let you set .html() on elements which
  1217. // are not allowed to have children. So we just ignore it.
  1218. element.empty();
  1219. } catch (e) { /* empty */ }
  1220. var elemHtml = jqLite('<div>').append(element).html();
  1221. try {
  1222. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  1223. elemHtml.
  1224. match(/^(<[^>]+>)/)[1].
  1225. replace(/^<([\w\-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
  1226. } catch (e) {
  1227. return lowercase(elemHtml);
  1228. }
  1229. }
  1230. /////////////////////////////////////////////////
  1231. /**
  1232. * Tries to decode the URI component without throwing an exception.
  1233. *
  1234. * @private
  1235. * @param str value potential URI component to check.
  1236. * @returns {boolean} True if `value` can be decoded
  1237. * with the decodeURIComponent function.
  1238. */
  1239. function tryDecodeURIComponent(value) {
  1240. try {
  1241. return decodeURIComponent(value);
  1242. } catch (e) {
  1243. // Ignore any invalid uri component.
  1244. }
  1245. }
  1246. /**
  1247. * Parses an escaped url query string into key-value pairs.
  1248. * @returns {Object.<string,boolean|Array>}
  1249. */
  1250. function parseKeyValue(/**string*/keyValue) {
  1251. var obj = {};
  1252. forEach((keyValue || '').split('&'), function(keyValue) {
  1253. var splitPoint, key, val;
  1254. if (keyValue) {
  1255. key = keyValue = keyValue.replace(/\+/g,'%20');
  1256. splitPoint = keyValue.indexOf('=');
  1257. if (splitPoint !== -1) {
  1258. key = keyValue.substring(0, splitPoint);
  1259. val = keyValue.substring(splitPoint + 1);
  1260. }
  1261. key = tryDecodeURIComponent(key);
  1262. if (isDefined(key)) {
  1263. val = isDefined(val) ? tryDecodeURIComponent(val) : true;
  1264. if (!hasOwnProperty.call(obj, key)) {
  1265. obj[key] = val;
  1266. } else if (isArray(obj[key])) {
  1267. obj[key].push(val);
  1268. } else {
  1269. obj[key] = [obj[key],val];
  1270. }
  1271. }
  1272. }
  1273. });
  1274. return obj;
  1275. }
  1276. function toKeyValue(obj) {
  1277. var parts = [];
  1278. forEach(obj, function(value, key) {
  1279. if (isArray(value)) {
  1280. forEach(value, function(arrayValue) {
  1281. parts.push(encodeUriQuery(key, true) +
  1282. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1283. });
  1284. } else {
  1285. parts.push(encodeUriQuery(key, true) +
  1286. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1287. }
  1288. });
  1289. return parts.length ? parts.join('&') : '';
  1290. }
  1291. /**
  1292. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1293. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1294. * segments:
  1295. * segment = *pchar
  1296. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1297. * pct-encoded = "%" HEXDIG HEXDIG
  1298. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1299. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1300. * / "*" / "+" / "," / ";" / "="
  1301. */
  1302. function encodeUriSegment(val) {
  1303. return encodeUriQuery(val, true).
  1304. replace(/%26/gi, '&').
  1305. replace(/%3D/gi, '=').
  1306. replace(/%2B/gi, '+');
  1307. }
  1308. /**
  1309. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1310. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1311. * encoded per http://tools.ietf.org/html/rfc3986:
  1312. * query = *( pchar / "/" / "?" )
  1313. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1314. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1315. * pct-encoded = "%" HEXDIG HEXDIG
  1316. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1317. * / "*" / "+" / "," / ";" / "="
  1318. */
  1319. function encodeUriQuery(val, pctEncodeSpaces) {
  1320. return encodeURIComponent(val).
  1321. replace(/%40/gi, '@').
  1322. replace(/%3A/gi, ':').
  1323. replace(/%24/g, '$').
  1324. replace(/%2C/gi, ',').
  1325. replace(/%3B/gi, ';').
  1326. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1327. }
  1328. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1329. function getNgAttribute(element, ngAttr) {
  1330. var attr, i, ii = ngAttrPrefixes.length;
  1331. for (i = 0; i < ii; ++i) {
  1332. attr = ngAttrPrefixes[i] + ngAttr;
  1333. if (isString(attr = element.getAttribute(attr))) {
  1334. return attr;
  1335. }
  1336. }
  1337. return null;
  1338. }
  1339. /**
  1340. * @ngdoc directive
  1341. * @name ngApp
  1342. * @module ng
  1343. *
  1344. * @element ANY
  1345. * @param {angular.Module} ngApp an optional application
  1346. * {@link angular.module module} name to load.
  1347. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1348. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1349. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1350. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1351. * tracking down the root of these bugs.
  1352. *
  1353. * @description
  1354. *
  1355. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1356. * designates the **root element** of the application and is typically placed near the root element
  1357. * of the page - e.g. on the `<body>` or `<html>` tags.
  1358. *
  1359. * There are a few things to keep in mind when using `ngApp`:
  1360. * - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1361. * found in the document will be used to define the root element to auto-bootstrap as an
  1362. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1363. * {@link angular.bootstrap} instead.
  1364. * - AngularJS applications cannot be nested within each other.
  1365. * - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`.
  1366. * This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and
  1367. * {@link ngRoute.ngView `ngView`}.
  1368. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1369. * causing animations to stop working and making the injector inaccessible from outside the app.
  1370. *
  1371. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1372. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1373. * should contain the application code needed or have dependencies on other modules that will
  1374. * contain the code. See {@link angular.module} for more information.
  1375. *
  1376. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1377. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1378. * would not be resolved to `3`.
  1379. *
  1380. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1381. *
  1382. <example module="ngAppDemo" name="ng-app">
  1383. <file name="index.html">
  1384. <div ng-controller="ngAppDemoController">
  1385. I can add: {{a}} + {{b}} = {{ a+b }}
  1386. </div>
  1387. </file>
  1388. <file name="script.js">
  1389. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1390. $scope.a = 1;
  1391. $scope.b = 2;
  1392. });
  1393. </file>
  1394. </example>
  1395. *
  1396. * Using `ngStrictDi`, you would see something like this:
  1397. *
  1398. <example ng-app-included="true" name="strict-di">
  1399. <file name="index.html">
  1400. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1401. <div ng-controller="GoodController1">
  1402. I can add: {{a}} + {{b}} = {{ a+b }}
  1403. <p>This renders because the controller does not fail to
  1404. instantiate, by using explicit annotation style (see
  1405. script.js for details)
  1406. </p>
  1407. </div>
  1408. <div ng-controller="GoodController2">
  1409. Name: <input ng-model="name"><br />
  1410. Hello, {{name}}!
  1411. <p>This renders because the controller does not fail to
  1412. instantiate, by using explicit annotation style
  1413. (see script.js for details)
  1414. </p>
  1415. </div>
  1416. <div ng-controller="BadController">
  1417. I can add: {{a}} + {{b}} = {{ a+b }}
  1418. <p>The controller could not be instantiated, due to relying
  1419. on automatic function annotations (which are disabled in
  1420. strict mode). As such, the content of this section is not
  1421. interpolated, and there should be an error in your web console.
  1422. </p>
  1423. </div>
  1424. </div>
  1425. </file>
  1426. <file name="script.js">
  1427. angular.module('ngAppStrictDemo', [])
  1428. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1429. // rather than an explicit annotation
  1430. .controller('BadController', function($scope) {
  1431. $scope.a = 1;
  1432. $scope.b = 2;
  1433. })
  1434. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1435. // due to using explicit annotations using the array style and $inject property, respectively.
  1436. .controller('GoodController1', ['$scope', function($scope) {
  1437. $scope.a = 1;
  1438. $scope.b = 2;
  1439. }])
  1440. .controller('GoodController2', GoodController2);
  1441. function GoodController2($scope) {
  1442. $scope.name = 'World';
  1443. }
  1444. GoodController2.$inject = ['$scope'];
  1445. </file>
  1446. <file name="style.css">
  1447. div[ng-controller] {
  1448. margin-bottom: 1em;
  1449. -webkit-border-radius: 4px;
  1450. border-radius: 4px;
  1451. border: 1px solid;
  1452. padding: .5em;
  1453. }
  1454. div[ng-controller^=Good] {
  1455. border-color: #d6e9c6;
  1456. background-color: #dff0d8;
  1457. color: #3c763d;
  1458. }
  1459. div[ng-controller^=Bad] {
  1460. border-color: #ebccd1;
  1461. background-color: #f2dede;
  1462. color: #a94442;
  1463. margin-bottom: 0;
  1464. }
  1465. </file>
  1466. </example>
  1467. */
  1468. function angularInit(element, bootstrap) {
  1469. var appElement,
  1470. module,
  1471. config = {};
  1472. // The element `element` has priority over any other element.
  1473. forEach(ngAttrPrefixes, function(prefix) {
  1474. var name = prefix + 'app';
  1475. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1476. appElement = element;
  1477. module = element.getAttribute(name);
  1478. }
  1479. });
  1480. forEach(ngAttrPrefixes, function(prefix) {
  1481. var name = prefix + 'app';
  1482. var candidate;
  1483. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1484. appElement = candidate;
  1485. module = candidate.getAttribute(name);
  1486. }
  1487. });
  1488. if (appElement) {
  1489. config.strictDi = getNgAttribute(appElement, 'strict-di') !== null;
  1490. bootstrap(appElement, module ? [module] : [], config);
  1491. }
  1492. }
  1493. /**
  1494. * @ngdoc function
  1495. * @name angular.bootstrap
  1496. * @module ng
  1497. * @description
  1498. * Use this function to manually start up angular application.
  1499. *
  1500. * For more information, see the {@link guide/bootstrap Bootstrap guide}.
  1501. *
  1502. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1503. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1504. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1505. * multiple instances of Angular try to work on the DOM.
  1506. *
  1507. * <div class="alert alert-warning">
  1508. * **Note:** Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1509. * They must use {@link ng.directive:ngApp ngApp}.
  1510. * </div>
  1511. *
  1512. * <div class="alert alert-warning">
  1513. * **Note:** Do not bootstrap the app on an element with a directive that uses {@link ng.$compile#transclusion transclusion},
  1514. * such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and {@link ngRoute.ngView `ngView`}.
  1515. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1516. * causing animations to stop working and making the injector inaccessible from outside the app.
  1517. * </div>
  1518. *
  1519. * ```html
  1520. * <!doctype html>
  1521. * <html>
  1522. * <body>
  1523. * <div ng-controller="WelcomeController">
  1524. * {{greeting}}
  1525. * </div>
  1526. *
  1527. * <script src="angular.js"></script>
  1528. * <script>
  1529. * var app = angular.module('demo', [])
  1530. * .controller('WelcomeController', function($scope) {
  1531. * $scope.greeting = 'Welcome!';
  1532. * });
  1533. * angular.bootstrap(document, ['demo']);
  1534. * </script>
  1535. * </body>
  1536. * </html>
  1537. * ```
  1538. *
  1539. * @param {DOMElement} element DOM element which is the root of angular application.
  1540. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1541. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1542. * function that will be invoked by the injector as a `config` block.
  1543. * See: {@link angular.module modules}
  1544. * @param {Object=} config an object for defining configuration options for the application. The
  1545. * following keys are supported:
  1546. *
  1547. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1548. * assist in finding bugs which break minified code. Defaults to `false`.
  1549. *
  1550. * @returns {auto.$injector} Returns the newly created injector for this app.
  1551. */
  1552. function bootstrap(element, modules, config) {
  1553. if (!isObject(config)) config = {};
  1554. var defaultConfig = {
  1555. strictDi: false
  1556. };
  1557. config = extend(defaultConfig, config);
  1558. var doBootstrap = function() {
  1559. element = jqLite(element);
  1560. if (element.injector()) {
  1561. var tag = (element[0] === window.document) ? 'document' : startingTag(element);
  1562. // Encode angle brackets to prevent input from being sanitized to empty string #8683.
  1563. throw ngMinErr(
  1564. 'btstrpd',
  1565. 'App already bootstrapped with this element \'{0}\'',
  1566. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1567. }
  1568. modules = modules || [];
  1569. modules.unshift(['$provide', function($provide) {
  1570. $provide.value('$rootElement', element);
  1571. }]);
  1572. if (config.debugInfoEnabled) {
  1573. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1574. modules.push(['$compileProvider', function($compileProvider) {
  1575. $compileProvider.debugInfoEnabled(true);
  1576. }]);
  1577. }
  1578. modules.unshift('ng');
  1579. var injector = createInjector(modules, config.strictDi);
  1580. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1581. function bootstrapApply(scope, element, compile, injector) {
  1582. scope.$apply(function() {
  1583. element.data('$injector', injector);
  1584. compile(element)(scope);
  1585. });
  1586. }]
  1587. );
  1588. return injector;
  1589. };
  1590. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1591. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1592. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1593. config.debugInfoEnabled = true;
  1594. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1595. }
  1596. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1597. return doBootstrap();
  1598. }
  1599. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1600. angular.resumeBootstrap = function(extraModules) {
  1601. forEach(extraModules, function(module) {
  1602. modules.push(module);
  1603. });
  1604. return doBootstrap();
  1605. };
  1606. if (isFunction(angular.resumeDeferredBootstrap)) {
  1607. angular.resumeDeferredBootstrap();
  1608. }
  1609. }
  1610. /**
  1611. * @ngdoc function
  1612. * @name angular.reloadWithDebugInfo
  1613. * @module ng
  1614. * @description
  1615. * Use this function to reload the current application with debug information turned on.
  1616. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1617. *
  1618. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1619. */
  1620. function reloadWithDebugInfo() {
  1621. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1622. window.location.reload();
  1623. }
  1624. /**
  1625. * @name angular.getTestability
  1626. * @module ng
  1627. * @description
  1628. * Get the testability service for the instance of Angular on the given
  1629. * element.
  1630. * @param {DOMElement} element DOM element which is the root of angular application.
  1631. */
  1632. function getTestability(rootElement) {
  1633. var injector = angular.element(rootElement).injector();
  1634. if (!injector) {
  1635. throw ngMinErr('test',
  1636. 'no injector found for element argument to getTestability');
  1637. }
  1638. return injector.get('$$testability');
  1639. }
  1640. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1641. function snake_case(name, separator) {
  1642. separator = separator || '_';
  1643. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1644. return (pos ? separator : '') + letter.toLowerCase();
  1645. });
  1646. }
  1647. var bindJQueryFired = false;
  1648. function bindJQuery() {
  1649. var originalCleanData;
  1650. if (bindJQueryFired) {
  1651. return;
  1652. }
  1653. // bind to jQuery if present;
  1654. var jqName = jq();
  1655. jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
  1656. !jqName ? undefined : // use jqLite
  1657. window[jqName]; // use jQuery specified by `ngJq`
  1658. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1659. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1660. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1661. // versions. It will not work for sure with jQuery <1.7, though.
  1662. if (jQuery && jQuery.fn.on) {
  1663. jqLite = jQuery;
  1664. extend(jQuery.fn, {
  1665. scope: JQLitePrototype.scope,
  1666. isolateScope: JQLitePrototype.isolateScope,
  1667. controller: JQLitePrototype.controller,
  1668. injector: JQLitePrototype.injector,
  1669. inheritedData: JQLitePrototype.inheritedData
  1670. });
  1671. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1672. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1673. // the $destroy event on all removed nodes.
  1674. originalCleanData = jQuery.cleanData;
  1675. jQuery.cleanData = function(elems) {
  1676. var events;
  1677. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1678. events = jQuery._data(elem, 'events');
  1679. if (events && events.$destroy) {
  1680. jQuery(elem).triggerHandler('$destroy');
  1681. }
  1682. }
  1683. originalCleanData(elems);
  1684. };
  1685. } else {
  1686. jqLite = JQLite;
  1687. }
  1688. angular.element = jqLite;
  1689. // Prevent double-proxying.
  1690. bindJQueryFired = true;
  1691. }
  1692. /**
  1693. * throw error if the argument is falsy.
  1694. */
  1695. function assertArg(arg, name, reason) {
  1696. if (!arg) {
  1697. throw ngMinErr('areq', 'Argument \'{0}\' is {1}', (name || '?'), (reason || 'required'));
  1698. }
  1699. return arg;
  1700. }
  1701. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1702. if (acceptArrayAnnotation && isArray(arg)) {
  1703. arg = arg[arg.length - 1];
  1704. }
  1705. assertArg(isFunction(arg), name, 'not a function, got ' +
  1706. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1707. return arg;
  1708. }
  1709. /**
  1710. * throw error if the name given is hasOwnProperty
  1711. * @param {String} name the name to test
  1712. * @param {String} context the context in which the name is used, such as module or directive
  1713. */
  1714. function assertNotHasOwnProperty(name, context) {
  1715. if (name === 'hasOwnProperty') {
  1716. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1717. }
  1718. }
  1719. /**
  1720. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1721. * @param {Object} obj starting object
  1722. * @param {String} path path to traverse
  1723. * @param {boolean} [bindFnToScope=true]
  1724. * @returns {Object} value as accessible by path
  1725. */
  1726. //TODO(misko): this function needs to be removed
  1727. function getter(obj, path, bindFnToScope) {
  1728. if (!path) return obj;
  1729. var keys = path.split('.');
  1730. var key;
  1731. var lastInstance = obj;
  1732. var len = keys.length;
  1733. for (var i = 0; i < len; i++) {
  1734. key = keys[i];
  1735. if (obj) {
  1736. obj = (lastInstance = obj)[key];
  1737. }
  1738. }
  1739. if (!bindFnToScope && isFunction(obj)) {
  1740. return bind(lastInstance, obj);
  1741. }
  1742. return obj;
  1743. }
  1744. /**
  1745. * Return the DOM siblings between the first and last node in the given array.
  1746. * @param {Array} array like object
  1747. * @returns {Array} the inputted object or a jqLite collection containing the nodes
  1748. */
  1749. function getBlockNodes(nodes) {
  1750. // TODO(perf): update `nodes` instead of creating a new object?
  1751. var node = nodes[0];
  1752. var endNode = nodes[nodes.length - 1];
  1753. var blockNodes;
  1754. for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
  1755. if (blockNodes || nodes[i] !== node) {
  1756. if (!blockNodes) {
  1757. blockNodes = jqLite(slice.call(nodes, 0, i));
  1758. }
  1759. blockNodes.push(node);
  1760. }
  1761. }
  1762. return blockNodes || nodes;
  1763. }
  1764. /**
  1765. * Creates a new object without a prototype. This object is useful for lookup without having to
  1766. * guard against prototypically inherited properties via hasOwnProperty.
  1767. *
  1768. * Related micro-benchmarks:
  1769. * - http://jsperf.com/object-create2
  1770. * - http://jsperf.com/proto-map-lookup/2
  1771. * - http://jsperf.com/for-in-vs-object-keys2
  1772. *
  1773. * @returns {Object}
  1774. */
  1775. function createMap() {
  1776. return Object.create(null);
  1777. }
  1778. function stringify(value) {
  1779. if (value == null) { // null || undefined
  1780. return '';
  1781. }
  1782. switch (typeof value) {
  1783. case 'string':
  1784. break;
  1785. case 'number':
  1786. value = '' + value;
  1787. break;
  1788. default:
  1789. if (hasCustomToString(value) && !isArray(value) && !isDate(value)) {
  1790. value = value.toString();
  1791. } else {
  1792. value = toJson(value);
  1793. }
  1794. }
  1795. return value;
  1796. }
  1797. var NODE_TYPE_ELEMENT = 1;
  1798. var NODE_TYPE_ATTRIBUTE = 2;
  1799. var NODE_TYPE_TEXT = 3;
  1800. var NODE_TYPE_COMMENT = 8;
  1801. var NODE_TYPE_DOCUMENT = 9;
  1802. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1803. /**
  1804. * @ngdoc type
  1805. * @name angular.Module
  1806. * @module ng
  1807. * @description
  1808. *
  1809. * Interface for configuring angular {@link angular.module modules}.
  1810. */
  1811. function setupModuleLoader(window) {
  1812. var $injectorMinErr = minErr('$injector');
  1813. var ngMinErr = minErr('ng');
  1814. function ensure(obj, name, factory) {
  1815. return obj[name] || (obj[name] = factory());
  1816. }
  1817. var angular = ensure(window, 'angular', Object);
  1818. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1819. angular.$$minErr = angular.$$minErr || minErr;
  1820. return ensure(angular, 'module', function() {
  1821. /** @type {Object.<string, angular.Module>} */
  1822. var modules = {};
  1823. /**
  1824. * @ngdoc function
  1825. * @name angular.module
  1826. * @module ng
  1827. * @description
  1828. *
  1829. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1830. * modules.
  1831. * All modules (angular core or 3rd party) that should be available to an application must be
  1832. * registered using this mechanism.
  1833. *
  1834. * Passing one argument retrieves an existing {@link angular.Module},
  1835. * whereas passing more than one argument creates a new {@link angular.Module}
  1836. *
  1837. *
  1838. * # Module
  1839. *
  1840. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1841. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1842. *
  1843. * ```js
  1844. * // Create a new module
  1845. * var myModule = angular.module('myModule', []);
  1846. *
  1847. * // register a new service
  1848. * myModule.value('appName', 'MyCoolApp');
  1849. *
  1850. * // configure existing services inside initialization blocks.
  1851. * myModule.config(['$locationProvider', function($locationProvider) {
  1852. * // Configure existing providers
  1853. * $locationProvider.hashPrefix('!');
  1854. * }]);
  1855. * ```
  1856. *
  1857. * Then you can create an injector and load your modules like this:
  1858. *
  1859. * ```js
  1860. * var injector = angular.injector(['ng', 'myModule'])
  1861. * ```
  1862. *
  1863. * However it's more likely that you'll just use
  1864. * {@link ng.directive:ngApp ngApp} or
  1865. * {@link angular.bootstrap} to simplify this process for you.
  1866. *
  1867. * @param {!string} name The name of the module to create or retrieve.
  1868. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1869. * unspecified then the module is being retrieved for further configuration.
  1870. * @param {Function=} configFn Optional configuration function for the module. Same as
  1871. * {@link angular.Module#config Module#config()}.
  1872. * @returns {angular.Module} new module with the {@link angular.Module} api.
  1873. */
  1874. return function module(name, requires, configFn) {
  1875. var assertNotHasOwnProperty = function(name, context) {
  1876. if (name === 'hasOwnProperty') {
  1877. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1878. }
  1879. };
  1880. assertNotHasOwnProperty(name, 'module');
  1881. if (requires && modules.hasOwnProperty(name)) {
  1882. modules[name] = null;
  1883. }
  1884. return ensure(modules, name, function() {
  1885. if (!requires) {
  1886. throw $injectorMinErr('nomod', 'Module \'{0}\' is not available! You either misspelled ' +
  1887. 'the module name or forgot to load it. If registering a module ensure that you ' +
  1888. 'specify the dependencies as the second argument.', name);
  1889. }
  1890. /** @type {!Array.<Array.<*>>} */
  1891. var invokeQueue = [];
  1892. /** @type {!Array.<Function>} */
  1893. var configBlocks = [];
  1894. /** @type {!Array.<Function>} */
  1895. var runBlocks = [];
  1896. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  1897. /** @type {angular.Module} */
  1898. var moduleInstance = {
  1899. // Private state
  1900. _invokeQueue: invokeQueue,
  1901. _configBlocks: configBlocks,
  1902. _runBlocks: runBlocks,
  1903. /**
  1904. * @ngdoc property
  1905. * @name angular.Module#requires
  1906. * @module ng
  1907. *
  1908. * @description
  1909. * Holds the list of modules which the injector will load before the current module is
  1910. * loaded.
  1911. */
  1912. requires: requires,
  1913. /**
  1914. * @ngdoc property
  1915. * @name angular.Module#name
  1916. * @module ng
  1917. *
  1918. * @description
  1919. * Name of the module.
  1920. */
  1921. name: name,
  1922. /**
  1923. * @ngdoc method
  1924. * @name angular.Module#provider
  1925. * @module ng
  1926. * @param {string} name service name
  1927. * @param {Function} providerType Construction function for creating new instance of the
  1928. * service.
  1929. * @description
  1930. * See {@link auto.$provide#provider $provide.provider()}.
  1931. */
  1932. provider: invokeLaterAndSetModuleName('$provide', 'provider'),
  1933. /**
  1934. * @ngdoc method
  1935. * @name angular.Module#factory
  1936. * @module ng
  1937. * @param {string} name service name
  1938. * @param {Function} providerFunction Function for creating new instance of the service.
  1939. * @description
  1940. * See {@link auto.$provide#factory $provide.factory()}.
  1941. */
  1942. factory: invokeLaterAndSetModuleName('$provide', 'factory'),
  1943. /**
  1944. * @ngdoc method
  1945. * @name angular.Module#service
  1946. * @module ng
  1947. * @param {string} name service name
  1948. * @param {Function} constructor A constructor function that will be instantiated.
  1949. * @description
  1950. * See {@link auto.$provide#service $provide.service()}.
  1951. */
  1952. service: invokeLaterAndSetModuleName('$provide', 'service'),
  1953. /**
  1954. * @ngdoc method
  1955. * @name angular.Module#value
  1956. * @module ng
  1957. * @param {string} name service name
  1958. * @param {*} object Service instance object.
  1959. * @description
  1960. * See {@link auto.$provide#value $provide.value()}.
  1961. */
  1962. value: invokeLater('$provide', 'value'),
  1963. /**
  1964. * @ngdoc method
  1965. * @name angular.Module#constant
  1966. * @module ng
  1967. * @param {string} name constant name
  1968. * @param {*} object Constant value.
  1969. * @description
  1970. * Because the constants are fixed, they get applied before other provide methods.
  1971. * See {@link auto.$provide#constant $provide.constant()}.
  1972. */
  1973. constant: invokeLater('$provide', 'constant', 'unshift'),
  1974. /**
  1975. * @ngdoc method
  1976. * @name angular.Module#decorator
  1977. * @module ng
  1978. * @param {string} name The name of the service to decorate.
  1979. * @param {Function} decorFn This function will be invoked when the service needs to be
  1980. * instantiated and should return the decorated service instance.
  1981. * @description
  1982. * See {@link auto.$provide#decorator $provide.decorator()}.
  1983. */
  1984. decorator: invokeLaterAndSetModuleName('$provide', 'decorator', configBlocks),
  1985. /**
  1986. * @ngdoc method
  1987. * @name angular.Module#animation
  1988. * @module ng
  1989. * @param {string} name animation name
  1990. * @param {Function} animationFactory Factory function for creating new instance of an
  1991. * animation.
  1992. * @description
  1993. *
  1994. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1995. *
  1996. *
  1997. * Defines an animation hook that can be later used with
  1998. * {@link $animate $animate} service and directives that use this service.
  1999. *
  2000. * ```js
  2001. * module.animation('.animation-name', function($inject1, $inject2) {
  2002. * return {
  2003. * eventName : function(element, done) {
  2004. * //code to run the animation
  2005. * //once complete, then run done()
  2006. * return function cancellationFunction(element) {
  2007. * //code to cancel the animation
  2008. * }
  2009. * }
  2010. * }
  2011. * })
  2012. * ```
  2013. *
  2014. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  2015. * {@link ngAnimate ngAnimate module} for more information.
  2016. */
  2017. animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
  2018. /**
  2019. * @ngdoc method
  2020. * @name angular.Module#filter
  2021. * @module ng
  2022. * @param {string} name Filter name - this must be a valid angular expression identifier
  2023. * @param {Function} filterFactory Factory function for creating new instance of filter.
  2024. * @description
  2025. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  2026. *
  2027. * <div class="alert alert-warning">
  2028. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  2029. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  2030. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  2031. * (`myapp_subsection_filterx`).
  2032. * </div>
  2033. */
  2034. filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
  2035. /**
  2036. * @ngdoc method
  2037. * @name angular.Module#controller
  2038. * @module ng
  2039. * @param {string|Object} name Controller name, or an object map of controllers where the
  2040. * keys are the names and the values are the constructors.
  2041. * @param {Function} constructor Controller constructor function.
  2042. * @description
  2043. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  2044. */
  2045. controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
  2046. /**
  2047. * @ngdoc method
  2048. * @name angular.Module#directive
  2049. * @module ng
  2050. * @param {string|Object} name Directive name, or an object map of directives where the
  2051. * keys are the names and the values are the factories.
  2052. * @param {Function} directiveFactory Factory function for creating new instance of
  2053. * directives.
  2054. * @description
  2055. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  2056. */
  2057. directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
  2058. /**
  2059. * @ngdoc method
  2060. * @name angular.Module#component
  2061. * @module ng
  2062. * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp)
  2063. * @param {Object} options Component definition object (a simplified
  2064. * {@link ng.$compile#directive-definition-object directive definition object})
  2065. *
  2066. * @description
  2067. * See {@link ng.$compileProvider#component $compileProvider.component()}.
  2068. */
  2069. component: invokeLaterAndSetModuleName('$compileProvider', 'component'),
  2070. /**
  2071. * @ngdoc method
  2072. * @name angular.Module#config
  2073. * @module ng
  2074. * @param {Function} configFn Execute this function on module load. Useful for service
  2075. * configuration.
  2076. * @description
  2077. * Use this method to register work which needs to be performed on module loading.
  2078. * For more about how to configure services, see
  2079. * {@link providers#provider-recipe Provider Recipe}.
  2080. */
  2081. config: config,
  2082. /**
  2083. * @ngdoc method
  2084. * @name angular.Module#run
  2085. * @module ng
  2086. * @param {Function} initializationFn Execute this function after injector creation.
  2087. * Useful for application initialization.
  2088. * @description
  2089. * Use this method to register work which should be performed when the injector is done
  2090. * loading all modules.
  2091. */
  2092. run: function(block) {
  2093. runBlocks.push(block);
  2094. return this;
  2095. }
  2096. };
  2097. if (configFn) {
  2098. config(configFn);
  2099. }
  2100. return moduleInstance;
  2101. /**
  2102. * @param {string} provider
  2103. * @param {string} method
  2104. * @param {String=} insertMethod
  2105. * @returns {angular.Module}
  2106. */
  2107. function invokeLater(provider, method, insertMethod, queue) {
  2108. if (!queue) queue = invokeQueue;
  2109. return function() {
  2110. queue[insertMethod || 'push']([provider, method, arguments]);
  2111. return moduleInstance;
  2112. };
  2113. }
  2114. /**
  2115. * @param {string} provider
  2116. * @param {string} method
  2117. * @returns {angular.Module}
  2118. */
  2119. function invokeLaterAndSetModuleName(provider, method, queue) {
  2120. if (!queue) queue = invokeQueue;
  2121. return function(recipeName, factoryFunction) {
  2122. if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
  2123. queue.push([provider, method, arguments]);
  2124. return moduleInstance;
  2125. };
  2126. }
  2127. });
  2128. };
  2129. });
  2130. }
  2131. /* global shallowCopy: true */
  2132. /**
  2133. * Creates a shallow copy of an object, an array or a primitive.
  2134. *
  2135. * Assumes that there are no proto properties for objects.
  2136. */
  2137. function shallowCopy(src, dst) {
  2138. if (isArray(src)) {
  2139. dst = dst || [];
  2140. for (var i = 0, ii = src.length; i < ii; i++) {
  2141. dst[i] = src[i];
  2142. }
  2143. } else if (isObject(src)) {
  2144. dst = dst || {};
  2145. for (var key in src) {
  2146. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  2147. dst[key] = src[key];
  2148. }
  2149. }
  2150. }
  2151. return dst || src;
  2152. }
  2153. /* global toDebugString: true */
  2154. function serializeObject(obj) {
  2155. var seen = [];
  2156. return JSON.stringify(obj, function(key, val) {
  2157. val = toJsonReplacer(key, val);
  2158. if (isObject(val)) {
  2159. if (seen.indexOf(val) >= 0) return '...';
  2160. seen.push(val);
  2161. }
  2162. return val;
  2163. });
  2164. }
  2165. function toDebugString(obj) {
  2166. if (typeof obj === 'function') {
  2167. return obj.toString().replace(/ \{[\s\S]*$/, '');
  2168. } else if (isUndefined(obj)) {
  2169. return 'undefined';
  2170. } else if (typeof obj !== 'string') {
  2171. return serializeObject(obj);
  2172. }
  2173. return obj;
  2174. }
  2175. /* global angularModule: true,
  2176. version: true,
  2177. $CompileProvider,
  2178. htmlAnchorDirective,
  2179. inputDirective,
  2180. inputDirective,
  2181. formDirective,
  2182. scriptDirective,
  2183. selectDirective,
  2184. optionDirective,
  2185. ngBindDirective,
  2186. ngBindHtmlDirective,
  2187. ngBindTemplateDirective,
  2188. ngClassDirective,
  2189. ngClassEvenDirective,
  2190. ngClassOddDirective,
  2191. ngCloakDirective,
  2192. ngControllerDirective,
  2193. ngFormDirective,
  2194. ngHideDirective,
  2195. ngIfDirective,
  2196. ngIncludeDirective,
  2197. ngIncludeFillContentDirective,
  2198. ngInitDirective,
  2199. ngNonBindableDirective,
  2200. ngPluralizeDirective,
  2201. ngRepeatDirective,
  2202. ngShowDirective,
  2203. ngStyleDirective,
  2204. ngSwitchDirective,
  2205. ngSwitchWhenDirective,
  2206. ngSwitchDefaultDirective,
  2207. ngOptionsDirective,
  2208. ngTranscludeDirective,
  2209. ngModelDirective,
  2210. ngListDirective,
  2211. ngChangeDirective,
  2212. patternDirective,
  2213. patternDirective,
  2214. requiredDirective,
  2215. requiredDirective,
  2216. minlengthDirective,
  2217. minlengthDirective,
  2218. maxlengthDirective,
  2219. maxlengthDirective,
  2220. ngValueDirective,
  2221. ngModelOptionsDirective,
  2222. ngAttributeAliasDirectives,
  2223. ngEventDirectives,
  2224. $AnchorScrollProvider,
  2225. $AnimateProvider,
  2226. $CoreAnimateCssProvider,
  2227. $$CoreAnimateJsProvider,
  2228. $$CoreAnimateQueueProvider,
  2229. $$AnimateRunnerFactoryProvider,
  2230. $$AnimateAsyncRunFactoryProvider,
  2231. $BrowserProvider,
  2232. $CacheFactoryProvider,
  2233. $ControllerProvider,
  2234. $DateProvider,
  2235. $DocumentProvider,
  2236. $$IsDocumentHiddenProvider,
  2237. $ExceptionHandlerProvider,
  2238. $FilterProvider,
  2239. $$ForceReflowProvider,
  2240. $InterpolateProvider,
  2241. $IntervalProvider,
  2242. $$HashMapProvider,
  2243. $HttpProvider,
  2244. $HttpParamSerializerProvider,
  2245. $HttpParamSerializerJQLikeProvider,
  2246. $HttpBackendProvider,
  2247. $xhrFactoryProvider,
  2248. $jsonpCallbacksProvider,
  2249. $LocationProvider,
  2250. $LogProvider,
  2251. $ModelOptionsProvider,
  2252. $ParseProvider,
  2253. $RootScopeProvider,
  2254. $QProvider,
  2255. $$QProvider,
  2256. $$SanitizeUriProvider,
  2257. $SceProvider,
  2258. $SceDelegateProvider,
  2259. $SnifferProvider,
  2260. $TemplateCacheProvider,
  2261. $TemplateRequestProvider,
  2262. $$TestabilityProvider,
  2263. $TimeoutProvider,
  2264. $$RAFProvider,
  2265. $WindowProvider,
  2266. $$jqLiteProvider,
  2267. $$CookieReaderProvider
  2268. */
  2269. /**
  2270. * @ngdoc object
  2271. * @name angular.version
  2272. * @module ng
  2273. * @description
  2274. * An object that contains information about the current AngularJS version.
  2275. *
  2276. * This object has the following properties:
  2277. *
  2278. * - `full` – `{string}` – Full version string, such as "0.9.18".
  2279. * - `major` – `{number}` – Major version number, such as "0".
  2280. * - `minor` – `{number}` – Minor version number, such as "9".
  2281. * - `dot` – `{number}` – Dot version number, such as "18".
  2282. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  2283. */
  2284. var version = {
  2285. // These placeholder strings will be replaced by grunt's `build` task.
  2286. // They need to be double- or single-quoted.
  2287. full: '1.5.9-build.5020+sha.0784977',
  2288. major: 1,
  2289. minor: 5,
  2290. dot: 9,
  2291. codeName: 'snapshot'
  2292. };
  2293. function publishExternalAPI(angular) {
  2294. extend(angular, {
  2295. 'bootstrap': bootstrap,
  2296. 'copy': copy,
  2297. 'extend': extend,
  2298. 'merge': merge,
  2299. 'equals': equals,
  2300. 'element': jqLite,
  2301. 'forEach': forEach,
  2302. 'injector': createInjector,
  2303. 'noop': noop,
  2304. 'bind': bind,
  2305. 'toJson': toJson,
  2306. 'fromJson': fromJson,
  2307. 'identity': identity,
  2308. 'isUndefined': isUndefined,
  2309. 'isDefined': isDefined,
  2310. 'isString': isString,
  2311. 'isFunction': isFunction,
  2312. 'isObject': isObject,
  2313. 'isNumber': isNumber,
  2314. 'isElement': isElement,
  2315. 'isArray': isArray,
  2316. 'version': version,
  2317. 'isDate': isDate,
  2318. 'lowercase': lowercase,
  2319. 'uppercase': uppercase,
  2320. 'callbacks': {$$counter: 0},
  2321. 'getTestability': getTestability,
  2322. 'reloadWithDebugInfo': reloadWithDebugInfo,
  2323. '$$minErr': minErr,
  2324. '$$csp': csp,
  2325. '$$encodeUriSegment': encodeUriSegment,
  2326. '$$encodeUriQuery': encodeUriQuery,
  2327. '$$stringify': stringify
  2328. });
  2329. angularModule = setupModuleLoader(window);
  2330. angularModule('ng', ['ngLocale'], ['$provide',
  2331. function ngModule($provide) {
  2332. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  2333. $provide.provider({
  2334. $$sanitizeUri: $$SanitizeUriProvider
  2335. });
  2336. $provide.provider('$compile', $CompileProvider).
  2337. directive({
  2338. a: htmlAnchorDirective,
  2339. input: inputDirective,
  2340. textarea: inputDirective,
  2341. form: formDirective,
  2342. script: scriptDirective,
  2343. select: selectDirective,
  2344. option: optionDirective,
  2345. ngBind: ngBindDirective,
  2346. ngBindHtml: ngBindHtmlDirective,
  2347. ngBindTemplate: ngBindTemplateDirective,
  2348. ngClass: ngClassDirective,
  2349. ngClassEven: ngClassEvenDirective,
  2350. ngClassOdd: ngClassOddDirective,
  2351. ngCloak: ngCloakDirective,
  2352. ngController: ngControllerDirective,
  2353. ngForm: ngFormDirective,
  2354. ngHide: ngHideDirective,
  2355. ngIf: ngIfDirective,
  2356. ngInclude: ngIncludeDirective,
  2357. ngInit: ngInitDirective,
  2358. ngNonBindable: ngNonBindableDirective,
  2359. ngPluralize: ngPluralizeDirective,
  2360. ngRepeat: ngRepeatDirective,
  2361. ngShow: ngShowDirective,
  2362. ngStyle: ngStyleDirective,
  2363. ngSwitch: ngSwitchDirective,
  2364. ngSwitchWhen: ngSwitchWhenDirective,
  2365. ngSwitchDefault: ngSwitchDefaultDirective,
  2366. ngOptions: ngOptionsDirective,
  2367. ngTransclude: ngTranscludeDirective,
  2368. ngModel: ngModelDirective,
  2369. ngList: ngListDirective,
  2370. ngChange: ngChangeDirective,
  2371. pattern: patternDirective,
  2372. ngPattern: patternDirective,
  2373. required: requiredDirective,
  2374. ngRequired: requiredDirective,
  2375. minlength: minlengthDirective,
  2376. ngMinlength: minlengthDirective,
  2377. maxlength: maxlengthDirective,
  2378. ngMaxlength: maxlengthDirective,
  2379. ngValue: ngValueDirective,
  2380. ngModelOptions: ngModelOptionsDirective
  2381. }).
  2382. directive({
  2383. ngInclude: ngIncludeFillContentDirective
  2384. }).
  2385. directive(ngAttributeAliasDirectives).
  2386. directive(ngEventDirectives);
  2387. $provide.provider({
  2388. $anchorScroll: $AnchorScrollProvider,
  2389. $animate: $AnimateProvider,
  2390. $animateCss: $CoreAnimateCssProvider,
  2391. $$animateJs: $$CoreAnimateJsProvider,
  2392. $$animateQueue: $$CoreAnimateQueueProvider,
  2393. $$AnimateRunner: $$AnimateRunnerFactoryProvider,
  2394. $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,
  2395. $browser: $BrowserProvider,
  2396. $cacheFactory: $CacheFactoryProvider,
  2397. $controller: $ControllerProvider,
  2398. $document: $DocumentProvider,
  2399. $$isDocumentHidden: $$IsDocumentHiddenProvider,
  2400. $exceptionHandler: $ExceptionHandlerProvider,
  2401. $filter: $FilterProvider,
  2402. $$forceReflow: $$ForceReflowProvider,
  2403. $interpolate: $InterpolateProvider,
  2404. $interval: $IntervalProvider,
  2405. $http: $HttpProvider,
  2406. $httpParamSerializer: $HttpParamSerializerProvider,
  2407. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  2408. $httpBackend: $HttpBackendProvider,
  2409. $xhrFactory: $xhrFactoryProvider,
  2410. $jsonpCallbacks: $jsonpCallbacksProvider,
  2411. $location: $LocationProvider,
  2412. $log: $LogProvider,
  2413. $modelOptions: $ModelOptionsProvider,
  2414. $parse: $ParseProvider,
  2415. $rootScope: $RootScopeProvider,
  2416. $q: $QProvider,
  2417. $$q: $$QProvider,
  2418. $sce: $SceProvider,
  2419. $sceDelegate: $SceDelegateProvider,
  2420. $sniffer: $SnifferProvider,
  2421. $templateCache: $TemplateCacheProvider,
  2422. $templateRequest: $TemplateRequestProvider,
  2423. $$testability: $$TestabilityProvider,
  2424. $timeout: $TimeoutProvider,
  2425. $window: $WindowProvider,
  2426. $$rAF: $$RAFProvider,
  2427. $$jqLite: $$jqLiteProvider,
  2428. $$HashMap: $$HashMapProvider,
  2429. $$cookieReader: $$CookieReaderProvider
  2430. });
  2431. }
  2432. ]);
  2433. }
  2434. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2435. * Any commits to this file should be reviewed with security in mind. *
  2436. * Changes to this file can potentially create security vulnerabilities. *
  2437. * An approval from 2 Core members with history of modifying *
  2438. * this file is required. *
  2439. * *
  2440. * Does the change somehow allow for arbitrary javascript to be executed? *
  2441. * Or allows for someone to change the prototype of built-in objects? *
  2442. * Or gives undesired access to variables likes document or window? *
  2443. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2444. /* global
  2445. JQLitePrototype: true,
  2446. BOOLEAN_ATTR: true,
  2447. ALIASED_ATTR: true
  2448. */
  2449. //////////////////////////////////
  2450. //JQLite
  2451. //////////////////////////////////
  2452. /**
  2453. * @ngdoc function
  2454. * @name angular.element
  2455. * @module ng
  2456. * @kind function
  2457. *
  2458. * @description
  2459. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2460. *
  2461. * If jQuery is available, `angular.element` is an alias for the
  2462. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2463. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
  2464. *
  2465. * jqLite is a tiny, API-compatible subset of jQuery that allows
  2466. * Angular to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
  2467. * commonly needed functionality with the goal of having a very small footprint.
  2468. *
  2469. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
  2470. * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
  2471. * specific version of jQuery if multiple versions exist on the page.
  2472. *
  2473. * <div class="alert alert-info">**Note:** All element references in Angular are always wrapped with jQuery or
  2474. * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div>
  2475. *
  2476. * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements
  2477. * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
  2478. * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.</div>
  2479. *
  2480. * ## Angular's jqLite
  2481. * jqLite provides only the following jQuery methods:
  2482. *
  2483. * - [`addClass()`](http://api.jquery.com/addClass/) - Does not support a function as first argument
  2484. * - [`after()`](http://api.jquery.com/after/)
  2485. * - [`append()`](http://api.jquery.com/append/)
  2486. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2487. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  2488. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2489. * - [`clone()`](http://api.jquery.com/clone/)
  2490. * - [`contents()`](http://api.jquery.com/contents/)
  2491. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
  2492. * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
  2493. * - [`data()`](http://api.jquery.com/data/)
  2494. * - [`detach()`](http://api.jquery.com/detach/)
  2495. * - [`empty()`](http://api.jquery.com/empty/)
  2496. * - [`eq()`](http://api.jquery.com/eq/)
  2497. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2498. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2499. * - [`html()`](http://api.jquery.com/html/)
  2500. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2501. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2502. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
  2503. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2504. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2505. * - [`prepend()`](http://api.jquery.com/prepend/)
  2506. * - [`prop()`](http://api.jquery.com/prop/)
  2507. * - [`ready()`](http://api.jquery.com/ready/)
  2508. * - [`remove()`](http://api.jquery.com/remove/)
  2509. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  2510. * - [`removeClass()`](http://api.jquery.com/removeClass/) - Does not support a function as first argument
  2511. * - [`removeData()`](http://api.jquery.com/removeData/)
  2512. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2513. * - [`text()`](http://api.jquery.com/text/)
  2514. * - [`toggleClass()`](http://api.jquery.com/toggleClass/) - Does not support a function as first argument
  2515. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers
  2516. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces or event object as parameter
  2517. * - [`val()`](http://api.jquery.com/val/)
  2518. * - [`wrap()`](http://api.jquery.com/wrap/)
  2519. *
  2520. * ## jQuery/jqLite Extras
  2521. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2522. *
  2523. * ### Events
  2524. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2525. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2526. * element before it is removed.
  2527. *
  2528. * ### Methods
  2529. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2530. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2531. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2532. * `'ngModel'`).
  2533. * - `injector()` - retrieves the injector of the current element or its parent.
  2534. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2535. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2536. * be enabled.
  2537. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2538. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2539. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2540. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2541. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2542. * parent element is reached.
  2543. *
  2544. * @knownIssue You cannot spy on `angular.element` if you are using Jasmine version 1.x. See
  2545. * https://github.com/angular/angular.js/issues/14251 for more information.
  2546. *
  2547. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2548. * @returns {Object} jQuery object.
  2549. */
  2550. JQLite.expando = 'ng339';
  2551. var jqCache = JQLite.cache = {},
  2552. jqId = 1;
  2553. /*
  2554. * !!! This is an undocumented "private" function !!!
  2555. */
  2556. JQLite._data = function(node) {
  2557. //jQuery always returns an object on cache miss
  2558. return this.cache[node[this.expando]] || {};
  2559. };
  2560. function jqNextId() { return ++jqId; }
  2561. var SPECIAL_CHARS_REGEXP = /([:\-_]+(.))/g;
  2562. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  2563. var MOUSE_EVENT_MAP = { mouseleave: 'mouseout', mouseenter: 'mouseover' };
  2564. var jqLiteMinErr = minErr('jqLite');
  2565. /**
  2566. * Converts snake_case to camelCase.
  2567. * Also there is special case for Moz prefix starting with upper case letter.
  2568. * @param name Name to normalize
  2569. */
  2570. function camelCase(name) {
  2571. return name.
  2572. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2573. return offset ? letter.toUpperCase() : letter;
  2574. }).
  2575. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2576. }
  2577. var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
  2578. var HTML_REGEXP = /<|&#?\w+;/;
  2579. var TAG_NAME_REGEXP = /<([\w:-]+)/;
  2580. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
  2581. var wrapMap = {
  2582. 'option': [1, '<select multiple="multiple">', '</select>'],
  2583. 'thead': [1, '<table>', '</table>'],
  2584. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2585. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2586. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2587. '_default': [0, '', '']
  2588. };
  2589. wrapMap.optgroup = wrapMap.option;
  2590. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2591. wrapMap.th = wrapMap.td;
  2592. function jqLiteIsTextNode(html) {
  2593. return !HTML_REGEXP.test(html);
  2594. }
  2595. function jqLiteAcceptsData(node) {
  2596. // The window object can accept data but has no nodeType
  2597. // Otherwise we are only interested in elements (1) and documents (9)
  2598. var nodeType = node.nodeType;
  2599. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2600. }
  2601. function jqLiteHasData(node) {
  2602. for (var key in jqCache[node.ng339]) {
  2603. return true;
  2604. }
  2605. return false;
  2606. }
  2607. function jqLiteCleanData(nodes) {
  2608. for (var i = 0, ii = nodes.length; i < ii; i++) {
  2609. jqLiteRemoveData(nodes[i]);
  2610. }
  2611. }
  2612. function jqLiteBuildFragment(html, context) {
  2613. var tmp, tag, wrap,
  2614. fragment = context.createDocumentFragment(),
  2615. nodes = [], i;
  2616. if (jqLiteIsTextNode(html)) {
  2617. // Convert non-html into a text node
  2618. nodes.push(context.createTextNode(html));
  2619. } else {
  2620. // Convert html into DOM nodes
  2621. tmp = fragment.appendChild(context.createElement('div'));
  2622. tag = (TAG_NAME_REGEXP.exec(html) || ['', ''])[1].toLowerCase();
  2623. wrap = wrapMap[tag] || wrapMap._default;
  2624. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, '<$1></$2>') + wrap[2];
  2625. // Descend through wrappers to the right content
  2626. i = wrap[0];
  2627. while (i--) {
  2628. tmp = tmp.lastChild;
  2629. }
  2630. nodes = concat(nodes, tmp.childNodes);
  2631. tmp = fragment.firstChild;
  2632. tmp.textContent = '';
  2633. }
  2634. // Remove wrapper from fragment
  2635. fragment.textContent = '';
  2636. fragment.innerHTML = ''; // Clear inner HTML
  2637. forEach(nodes, function(node) {
  2638. fragment.appendChild(node);
  2639. });
  2640. return fragment;
  2641. }
  2642. function jqLiteParseHTML(html, context) {
  2643. context = context || window.document;
  2644. var parsed;
  2645. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2646. return [context.createElement(parsed[1])];
  2647. }
  2648. if ((parsed = jqLiteBuildFragment(html, context))) {
  2649. return parsed.childNodes;
  2650. }
  2651. return [];
  2652. }
  2653. function jqLiteWrapNode(node, wrapper) {
  2654. var parent = node.parentNode;
  2655. if (parent) {
  2656. parent.replaceChild(wrapper, node);
  2657. }
  2658. wrapper.appendChild(node);
  2659. }
  2660. // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
  2661. var jqLiteContains = window.Node.prototype.contains || /** @this */ function(arg) {
  2662. // eslint-disable-next-line no-bitwise
  2663. return !!(this.compareDocumentPosition(arg) & 16);
  2664. };
  2665. /////////////////////////////////////////////
  2666. function JQLite(element) {
  2667. if (element instanceof JQLite) {
  2668. return element;
  2669. }
  2670. var argIsString;
  2671. if (isString(element)) {
  2672. element = trim(element);
  2673. argIsString = true;
  2674. }
  2675. if (!(this instanceof JQLite)) {
  2676. if (argIsString && element.charAt(0) !== '<') {
  2677. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2678. }
  2679. return new JQLite(element);
  2680. }
  2681. if (argIsString) {
  2682. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2683. } else {
  2684. jqLiteAddNodes(this, element);
  2685. }
  2686. }
  2687. function jqLiteClone(element) {
  2688. return element.cloneNode(true);
  2689. }
  2690. function jqLiteDealoc(element, onlyDescendants) {
  2691. if (!onlyDescendants) jqLiteRemoveData(element);
  2692. if (element.querySelectorAll) {
  2693. var descendants = element.querySelectorAll('*');
  2694. for (var i = 0, l = descendants.length; i < l; i++) {
  2695. jqLiteRemoveData(descendants[i]);
  2696. }
  2697. }
  2698. }
  2699. function jqLiteOff(element, type, fn, unsupported) {
  2700. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2701. var expandoStore = jqLiteExpandoStore(element);
  2702. var events = expandoStore && expandoStore.events;
  2703. var handle = expandoStore && expandoStore.handle;
  2704. if (!handle) return; //no listeners registered
  2705. if (!type) {
  2706. for (type in events) {
  2707. if (type !== '$destroy') {
  2708. element.removeEventListener(type, handle);
  2709. }
  2710. delete events[type];
  2711. }
  2712. } else {
  2713. var removeHandler = function(type) {
  2714. var listenerFns = events[type];
  2715. if (isDefined(fn)) {
  2716. arrayRemove(listenerFns || [], fn);
  2717. }
  2718. if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
  2719. element.removeEventListener(type, handle);
  2720. delete events[type];
  2721. }
  2722. };
  2723. forEach(type.split(' '), function(type) {
  2724. removeHandler(type);
  2725. if (MOUSE_EVENT_MAP[type]) {
  2726. removeHandler(MOUSE_EVENT_MAP[type]);
  2727. }
  2728. });
  2729. }
  2730. }
  2731. function jqLiteRemoveData(element, name) {
  2732. var expandoId = element.ng339;
  2733. var expandoStore = expandoId && jqCache[expandoId];
  2734. if (expandoStore) {
  2735. if (name) {
  2736. delete expandoStore.data[name];
  2737. return;
  2738. }
  2739. if (expandoStore.handle) {
  2740. if (expandoStore.events.$destroy) {
  2741. expandoStore.handle({}, '$destroy');
  2742. }
  2743. jqLiteOff(element);
  2744. }
  2745. delete jqCache[expandoId];
  2746. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2747. }
  2748. }
  2749. function jqLiteExpandoStore(element, createIfNecessary) {
  2750. var expandoId = element.ng339,
  2751. expandoStore = expandoId && jqCache[expandoId];
  2752. if (createIfNecessary && !expandoStore) {
  2753. element.ng339 = expandoId = jqNextId();
  2754. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2755. }
  2756. return expandoStore;
  2757. }
  2758. function jqLiteData(element, key, value) {
  2759. if (jqLiteAcceptsData(element)) {
  2760. var isSimpleSetter = isDefined(value);
  2761. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2762. var massGetter = !key;
  2763. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2764. var data = expandoStore && expandoStore.data;
  2765. if (isSimpleSetter) { // data('key', value)
  2766. data[key] = value;
  2767. } else {
  2768. if (massGetter) { // data()
  2769. return data;
  2770. } else {
  2771. if (isSimpleGetter) { // data('key')
  2772. // don't force creation of expandoStore if it doesn't exist yet
  2773. return data && data[key];
  2774. } else { // mass-setter: data({key1: val1, key2: val2})
  2775. extend(data, key);
  2776. }
  2777. }
  2778. }
  2779. }
  2780. }
  2781. function jqLiteHasClass(element, selector) {
  2782. if (!element.getAttribute) return false;
  2783. return ((' ' + (element.getAttribute('class') || '') + ' ').replace(/[\n\t]/g, ' ').
  2784. indexOf(' ' + selector + ' ') > -1);
  2785. }
  2786. function jqLiteRemoveClass(element, cssClasses) {
  2787. if (cssClasses && element.setAttribute) {
  2788. forEach(cssClasses.split(' '), function(cssClass) {
  2789. element.setAttribute('class', trim(
  2790. (' ' + (element.getAttribute('class') || '') + ' ')
  2791. .replace(/[\n\t]/g, ' ')
  2792. .replace(' ' + trim(cssClass) + ' ', ' '))
  2793. );
  2794. });
  2795. }
  2796. }
  2797. function jqLiteAddClass(element, cssClasses) {
  2798. if (cssClasses && element.setAttribute) {
  2799. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2800. .replace(/[\n\t]/g, ' ');
  2801. forEach(cssClasses.split(' '), function(cssClass) {
  2802. cssClass = trim(cssClass);
  2803. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2804. existingClasses += cssClass + ' ';
  2805. }
  2806. });
  2807. element.setAttribute('class', trim(existingClasses));
  2808. }
  2809. }
  2810. function jqLiteAddNodes(root, elements) {
  2811. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2812. if (elements) {
  2813. // if a Node (the most common case)
  2814. if (elements.nodeType) {
  2815. root[root.length++] = elements;
  2816. } else {
  2817. var length = elements.length;
  2818. // if an Array or NodeList and not a Window
  2819. if (typeof length === 'number' && elements.window !== elements) {
  2820. if (length) {
  2821. for (var i = 0; i < length; i++) {
  2822. root[root.length++] = elements[i];
  2823. }
  2824. }
  2825. } else {
  2826. root[root.length++] = elements;
  2827. }
  2828. }
  2829. }
  2830. }
  2831. function jqLiteController(element, name) {
  2832. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  2833. }
  2834. function jqLiteInheritedData(element, name, value) {
  2835. // if element is the document object work with the html element instead
  2836. // this makes $(document).scope() possible
  2837. if (element.nodeType === NODE_TYPE_DOCUMENT) {
  2838. element = element.documentElement;
  2839. }
  2840. var names = isArray(name) ? name : [name];
  2841. while (element) {
  2842. for (var i = 0, ii = names.length; i < ii; i++) {
  2843. if (isDefined(value = jqLite.data(element, names[i]))) return value;
  2844. }
  2845. // If dealing with a document fragment node with a host element, and no parent, use the host
  2846. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2847. // to lookup parent controllers.
  2848. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  2849. }
  2850. }
  2851. function jqLiteEmpty(element) {
  2852. jqLiteDealoc(element, true);
  2853. while (element.firstChild) {
  2854. element.removeChild(element.firstChild);
  2855. }
  2856. }
  2857. function jqLiteRemove(element, keepData) {
  2858. if (!keepData) jqLiteDealoc(element);
  2859. var parent = element.parentNode;
  2860. if (parent) parent.removeChild(element);
  2861. }
  2862. function jqLiteDocumentLoaded(action, win) {
  2863. win = win || window;
  2864. if (win.document.readyState === 'complete') {
  2865. // Force the action to be run async for consistent behavior
  2866. // from the action's point of view
  2867. // i.e. it will definitely not be in a $apply
  2868. win.setTimeout(action);
  2869. } else {
  2870. // No need to unbind this handler as load is only ever called once
  2871. jqLite(win).on('load', action);
  2872. }
  2873. }
  2874. //////////////////////////////////////////
  2875. // Functions which are declared directly.
  2876. //////////////////////////////////////////
  2877. var JQLitePrototype = JQLite.prototype = {
  2878. ready: function(fn) {
  2879. var fired = false;
  2880. function trigger() {
  2881. if (fired) return;
  2882. fired = true;
  2883. fn();
  2884. }
  2885. // check if document is already loaded
  2886. if (window.document.readyState === 'complete') {
  2887. window.setTimeout(trigger);
  2888. } else {
  2889. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2890. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2891. // eslint-disable-next-line new-cap
  2892. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2893. }
  2894. },
  2895. toString: function() {
  2896. var value = [];
  2897. forEach(this, function(e) { value.push('' + e);});
  2898. return '[' + value.join(', ') + ']';
  2899. },
  2900. eq: function(index) {
  2901. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2902. },
  2903. length: 0,
  2904. push: push,
  2905. sort: [].sort,
  2906. splice: [].splice
  2907. };
  2908. //////////////////////////////////////////
  2909. // Functions iterating getter/setters.
  2910. // these functions return self on setter and
  2911. // value on get.
  2912. //////////////////////////////////////////
  2913. var BOOLEAN_ATTR = {};
  2914. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2915. BOOLEAN_ATTR[lowercase(value)] = value;
  2916. });
  2917. var BOOLEAN_ELEMENTS = {};
  2918. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2919. BOOLEAN_ELEMENTS[value] = true;
  2920. });
  2921. var ALIASED_ATTR = {
  2922. 'ngMinlength': 'minlength',
  2923. 'ngMaxlength': 'maxlength',
  2924. 'ngMin': 'min',
  2925. 'ngMax': 'max',
  2926. 'ngPattern': 'pattern',
  2927. 'ngStep': 'step'
  2928. };
  2929. function getBooleanAttrName(element, name) {
  2930. // check dom last since we will most likely fail on name
  2931. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2932. // booleanAttr is here twice to minimize DOM access
  2933. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  2934. }
  2935. function getAliasedAttrName(name) {
  2936. return ALIASED_ATTR[name];
  2937. }
  2938. forEach({
  2939. data: jqLiteData,
  2940. removeData: jqLiteRemoveData,
  2941. hasData: jqLiteHasData,
  2942. cleanData: jqLiteCleanData
  2943. }, function(fn, name) {
  2944. JQLite[name] = fn;
  2945. });
  2946. forEach({
  2947. data: jqLiteData,
  2948. inheritedData: jqLiteInheritedData,
  2949. scope: function(element) {
  2950. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2951. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2952. },
  2953. isolateScope: function(element) {
  2954. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2955. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  2956. },
  2957. controller: jqLiteController,
  2958. injector: function(element) {
  2959. return jqLiteInheritedData(element, '$injector');
  2960. },
  2961. removeAttr: function(element, name) {
  2962. element.removeAttribute(name);
  2963. },
  2964. hasClass: jqLiteHasClass,
  2965. css: function(element, name, value) {
  2966. name = camelCase(name);
  2967. if (isDefined(value)) {
  2968. element.style[name] = value;
  2969. } else {
  2970. return element.style[name];
  2971. }
  2972. },
  2973. attr: function(element, name, value) {
  2974. var nodeType = element.nodeType;
  2975. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
  2976. return;
  2977. }
  2978. var lowercasedName = lowercase(name);
  2979. if (BOOLEAN_ATTR[lowercasedName]) {
  2980. if (isDefined(value)) {
  2981. if (value) {
  2982. element[name] = true;
  2983. element.setAttribute(name, lowercasedName);
  2984. } else {
  2985. element[name] = false;
  2986. element.removeAttribute(lowercasedName);
  2987. }
  2988. } else {
  2989. return (element[name] ||
  2990. (element.attributes.getNamedItem(name) || noop).specified)
  2991. ? lowercasedName
  2992. : undefined;
  2993. }
  2994. } else if (isDefined(value)) {
  2995. element.setAttribute(name, value);
  2996. } else if (element.getAttribute) {
  2997. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2998. // some elements (e.g. Document) don't have get attribute, so return undefined
  2999. var ret = element.getAttribute(name, 2);
  3000. // normalize non-existing attributes to undefined (as jQuery)
  3001. return ret === null ? undefined : ret;
  3002. }
  3003. },
  3004. prop: function(element, name, value) {
  3005. if (isDefined(value)) {
  3006. element[name] = value;
  3007. } else {
  3008. return element[name];
  3009. }
  3010. },
  3011. text: (function() {
  3012. getText.$dv = '';
  3013. return getText;
  3014. function getText(element, value) {
  3015. if (isUndefined(value)) {
  3016. var nodeType = element.nodeType;
  3017. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  3018. }
  3019. element.textContent = value;
  3020. }
  3021. })(),
  3022. val: function(element, value) {
  3023. if (isUndefined(value)) {
  3024. if (element.multiple && nodeName_(element) === 'select') {
  3025. var result = [];
  3026. forEach(element.options, function(option) {
  3027. if (option.selected) {
  3028. result.push(option.value || option.text);
  3029. }
  3030. });
  3031. return result;
  3032. }
  3033. return element.value;
  3034. }
  3035. element.value = value;
  3036. },
  3037. html: function(element, value) {
  3038. if (isUndefined(value)) {
  3039. return element.innerHTML;
  3040. }
  3041. jqLiteDealoc(element, true);
  3042. element.innerHTML = value;
  3043. },
  3044. empty: jqLiteEmpty
  3045. }, function(fn, name) {
  3046. /**
  3047. * Properties: writes return selection, reads return first value
  3048. */
  3049. JQLite.prototype[name] = function(arg1, arg2) {
  3050. var i, key;
  3051. var nodeCount = this.length;
  3052. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  3053. // in a way that survives minification.
  3054. // jqLiteEmpty takes no arguments but is a setter.
  3055. if (fn !== jqLiteEmpty &&
  3056. (isUndefined((fn.length === 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
  3057. if (isObject(arg1)) {
  3058. // we are a write, but the object properties are the key/values
  3059. for (i = 0; i < nodeCount; i++) {
  3060. if (fn === jqLiteData) {
  3061. // data() takes the whole object in jQuery
  3062. fn(this[i], arg1);
  3063. } else {
  3064. for (key in arg1) {
  3065. fn(this[i], key, arg1[key]);
  3066. }
  3067. }
  3068. }
  3069. // return self for chaining
  3070. return this;
  3071. } else {
  3072. // we are a read, so read the first child.
  3073. // TODO: do we still need this?
  3074. var value = fn.$dv;
  3075. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  3076. var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
  3077. for (var j = 0; j < jj; j++) {
  3078. var nodeValue = fn(this[j], arg1, arg2);
  3079. value = value ? value + nodeValue : nodeValue;
  3080. }
  3081. return value;
  3082. }
  3083. } else {
  3084. // we are a write, so apply to all children
  3085. for (i = 0; i < nodeCount; i++) {
  3086. fn(this[i], arg1, arg2);
  3087. }
  3088. // return self for chaining
  3089. return this;
  3090. }
  3091. };
  3092. });
  3093. function createEventHandler(element, events) {
  3094. var eventHandler = function(event, type) {
  3095. // jQuery specific api
  3096. event.isDefaultPrevented = function() {
  3097. return event.defaultPrevented;
  3098. };
  3099. var eventFns = events[type || event.type];
  3100. var eventFnsLength = eventFns ? eventFns.length : 0;
  3101. if (!eventFnsLength) return;
  3102. if (isUndefined(event.immediatePropagationStopped)) {
  3103. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  3104. event.stopImmediatePropagation = function() {
  3105. event.immediatePropagationStopped = true;
  3106. if (event.stopPropagation) {
  3107. event.stopPropagation();
  3108. }
  3109. if (originalStopImmediatePropagation) {
  3110. originalStopImmediatePropagation.call(event);
  3111. }
  3112. };
  3113. }
  3114. event.isImmediatePropagationStopped = function() {
  3115. return event.immediatePropagationStopped === true;
  3116. };
  3117. // Some events have special handlers that wrap the real handler
  3118. var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
  3119. // Copy event handlers in case event handlers array is modified during execution.
  3120. if ((eventFnsLength > 1)) {
  3121. eventFns = shallowCopy(eventFns);
  3122. }
  3123. for (var i = 0; i < eventFnsLength; i++) {
  3124. if (!event.isImmediatePropagationStopped()) {
  3125. handlerWrapper(element, event, eventFns[i]);
  3126. }
  3127. }
  3128. };
  3129. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  3130. // events on `element`
  3131. eventHandler.elem = element;
  3132. return eventHandler;
  3133. }
  3134. function defaultHandlerWrapper(element, event, handler) {
  3135. handler.call(element, event);
  3136. }
  3137. function specialMouseHandlerWrapper(target, event, handler) {
  3138. // Refer to jQuery's implementation of mouseenter & mouseleave
  3139. // Read about mouseenter and mouseleave:
  3140. // http://www.quirksmode.org/js/events_mouse.html#link8
  3141. var related = event.relatedTarget;
  3142. // For mousenter/leave call the handler if related is outside the target.
  3143. // NB: No relatedTarget if the mouse left/entered the browser window
  3144. if (!related || (related !== target && !jqLiteContains.call(target, related))) {
  3145. handler.call(target, event);
  3146. }
  3147. }
  3148. //////////////////////////////////////////
  3149. // Functions iterating traversal.
  3150. // These functions chain results into a single
  3151. // selector.
  3152. //////////////////////////////////////////
  3153. forEach({
  3154. removeData: jqLiteRemoveData,
  3155. on: function jqLiteOn(element, type, fn, unsupported) {
  3156. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  3157. // Do not add event handlers to non-elements because they will not be cleaned up.
  3158. if (!jqLiteAcceptsData(element)) {
  3159. return;
  3160. }
  3161. var expandoStore = jqLiteExpandoStore(element, true);
  3162. var events = expandoStore.events;
  3163. var handle = expandoStore.handle;
  3164. if (!handle) {
  3165. handle = expandoStore.handle = createEventHandler(element, events);
  3166. }
  3167. // http://jsperf.com/string-indexof-vs-split
  3168. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  3169. var i = types.length;
  3170. var addHandler = function(type, specialHandlerWrapper, noEventListener) {
  3171. var eventFns = events[type];
  3172. if (!eventFns) {
  3173. eventFns = events[type] = [];
  3174. eventFns.specialHandlerWrapper = specialHandlerWrapper;
  3175. if (type !== '$destroy' && !noEventListener) {
  3176. element.addEventListener(type, handle);
  3177. }
  3178. }
  3179. eventFns.push(fn);
  3180. };
  3181. while (i--) {
  3182. type = types[i];
  3183. if (MOUSE_EVENT_MAP[type]) {
  3184. addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
  3185. addHandler(type, undefined, true);
  3186. } else {
  3187. addHandler(type);
  3188. }
  3189. }
  3190. },
  3191. off: jqLiteOff,
  3192. one: function(element, type, fn) {
  3193. element = jqLite(element);
  3194. //add the listener twice so that when it is called
  3195. //you can remove the original function and still be
  3196. //able to call element.off(ev, fn) normally
  3197. element.on(type, function onFn() {
  3198. element.off(type, fn);
  3199. element.off(type, onFn);
  3200. });
  3201. element.on(type, fn);
  3202. },
  3203. replaceWith: function(element, replaceNode) {
  3204. var index, parent = element.parentNode;
  3205. jqLiteDealoc(element);
  3206. forEach(new JQLite(replaceNode), function(node) {
  3207. if (index) {
  3208. parent.insertBefore(node, index.nextSibling);
  3209. } else {
  3210. parent.replaceChild(node, element);
  3211. }
  3212. index = node;
  3213. });
  3214. },
  3215. children: function(element) {
  3216. var children = [];
  3217. forEach(element.childNodes, function(element) {
  3218. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3219. children.push(element);
  3220. }
  3221. });
  3222. return children;
  3223. },
  3224. contents: function(element) {
  3225. return element.contentDocument || element.childNodes || [];
  3226. },
  3227. append: function(element, node) {
  3228. var nodeType = element.nodeType;
  3229. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  3230. node = new JQLite(node);
  3231. for (var i = 0, ii = node.length; i < ii; i++) {
  3232. var child = node[i];
  3233. element.appendChild(child);
  3234. }
  3235. },
  3236. prepend: function(element, node) {
  3237. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3238. var index = element.firstChild;
  3239. forEach(new JQLite(node), function(child) {
  3240. element.insertBefore(child, index);
  3241. });
  3242. }
  3243. },
  3244. wrap: function(element, wrapNode) {
  3245. jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);
  3246. },
  3247. remove: jqLiteRemove,
  3248. detach: function(element) {
  3249. jqLiteRemove(element, true);
  3250. },
  3251. after: function(element, newElement) {
  3252. var index = element, parent = element.parentNode;
  3253. newElement = new JQLite(newElement);
  3254. for (var i = 0, ii = newElement.length; i < ii; i++) {
  3255. var node = newElement[i];
  3256. parent.insertBefore(node, index.nextSibling);
  3257. index = node;
  3258. }
  3259. },
  3260. addClass: jqLiteAddClass,
  3261. removeClass: jqLiteRemoveClass,
  3262. toggleClass: function(element, selector, condition) {
  3263. if (selector) {
  3264. forEach(selector.split(' '), function(className) {
  3265. var classCondition = condition;
  3266. if (isUndefined(classCondition)) {
  3267. classCondition = !jqLiteHasClass(element, className);
  3268. }
  3269. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  3270. });
  3271. }
  3272. },
  3273. parent: function(element) {
  3274. var parent = element.parentNode;
  3275. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  3276. },
  3277. next: function(element) {
  3278. return element.nextElementSibling;
  3279. },
  3280. find: function(element, selector) {
  3281. if (element.getElementsByTagName) {
  3282. return element.getElementsByTagName(selector);
  3283. } else {
  3284. return [];
  3285. }
  3286. },
  3287. clone: jqLiteClone,
  3288. triggerHandler: function(element, event, extraParameters) {
  3289. var dummyEvent, eventFnsCopy, handlerArgs;
  3290. var eventName = event.type || event;
  3291. var expandoStore = jqLiteExpandoStore(element);
  3292. var events = expandoStore && expandoStore.events;
  3293. var eventFns = events && events[eventName];
  3294. if (eventFns) {
  3295. // Create a dummy event to pass to the handlers
  3296. dummyEvent = {
  3297. preventDefault: function() { this.defaultPrevented = true; },
  3298. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  3299. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  3300. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  3301. stopPropagation: noop,
  3302. type: eventName,
  3303. target: element
  3304. };
  3305. // If a custom event was provided then extend our dummy event with it
  3306. if (event.type) {
  3307. dummyEvent = extend(dummyEvent, event);
  3308. }
  3309. // Copy event handlers in case event handlers array is modified during execution.
  3310. eventFnsCopy = shallowCopy(eventFns);
  3311. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  3312. forEach(eventFnsCopy, function(fn) {
  3313. if (!dummyEvent.isImmediatePropagationStopped()) {
  3314. fn.apply(element, handlerArgs);
  3315. }
  3316. });
  3317. }
  3318. }
  3319. }, function(fn, name) {
  3320. /**
  3321. * chaining functions
  3322. */
  3323. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  3324. var value;
  3325. for (var i = 0, ii = this.length; i < ii; i++) {
  3326. if (isUndefined(value)) {
  3327. value = fn(this[i], arg1, arg2, arg3);
  3328. if (isDefined(value)) {
  3329. // any function which returns a value needs to be wrapped
  3330. value = jqLite(value);
  3331. }
  3332. } else {
  3333. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  3334. }
  3335. }
  3336. return isDefined(value) ? value : this;
  3337. };
  3338. // bind legacy bind/unbind to on/off
  3339. JQLite.prototype.bind = JQLite.prototype.on;
  3340. JQLite.prototype.unbind = JQLite.prototype.off;
  3341. });
  3342. // Provider for private $$jqLite service
  3343. /** @this */
  3344. function $$jqLiteProvider() {
  3345. this.$get = function $$jqLite() {
  3346. return extend(JQLite, {
  3347. hasClass: function(node, classes) {
  3348. if (node.attr) node = node[0];
  3349. return jqLiteHasClass(node, classes);
  3350. },
  3351. addClass: function(node, classes) {
  3352. if (node.attr) node = node[0];
  3353. return jqLiteAddClass(node, classes);
  3354. },
  3355. removeClass: function(node, classes) {
  3356. if (node.attr) node = node[0];
  3357. return jqLiteRemoveClass(node, classes);
  3358. }
  3359. });
  3360. };
  3361. }
  3362. /**
  3363. * Computes a hash of an 'obj'.
  3364. * Hash of a:
  3365. * string is string
  3366. * number is number as string
  3367. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  3368. * that is also assigned to the $$hashKey property of the object.
  3369. *
  3370. * @param obj
  3371. * @returns {string} hash string such that the same input will have the same hash string.
  3372. * The resulting string key is in 'type:hashKey' format.
  3373. */
  3374. function hashKey(obj, nextUidFn) {
  3375. var key = obj && obj.$$hashKey;
  3376. if (key) {
  3377. if (typeof key === 'function') {
  3378. key = obj.$$hashKey();
  3379. }
  3380. return key;
  3381. }
  3382. var objType = typeof obj;
  3383. if (objType === 'function' || (objType === 'object' && obj !== null)) {
  3384. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  3385. } else {
  3386. key = objType + ':' + obj;
  3387. }
  3388. return key;
  3389. }
  3390. /**
  3391. * HashMap which can use objects as keys
  3392. */
  3393. function HashMap(array, isolatedUid) {
  3394. if (isolatedUid) {
  3395. var uid = 0;
  3396. this.nextUid = function() {
  3397. return ++uid;
  3398. };
  3399. }
  3400. forEach(array, this.put, this);
  3401. }
  3402. HashMap.prototype = {
  3403. /**
  3404. * Store key value pair
  3405. * @param key key to store can be any type
  3406. * @param value value to store can be any type
  3407. */
  3408. put: function(key, value) {
  3409. this[hashKey(key, this.nextUid)] = value;
  3410. },
  3411. /**
  3412. * @param key
  3413. * @returns {Object} the value for the key
  3414. */
  3415. get: function(key) {
  3416. return this[hashKey(key, this.nextUid)];
  3417. },
  3418. /**
  3419. * Remove the key/value pair
  3420. * @param key
  3421. */
  3422. remove: function(key) {
  3423. var value = this[key = hashKey(key, this.nextUid)];
  3424. delete this[key];
  3425. return value;
  3426. }
  3427. };
  3428. var $$HashMapProvider = [/** @this */function() {
  3429. this.$get = [function() {
  3430. return HashMap;
  3431. }];
  3432. }];
  3433. /**
  3434. * @ngdoc function
  3435. * @module ng
  3436. * @name angular.injector
  3437. * @kind function
  3438. *
  3439. * @description
  3440. * Creates an injector object that can be used for retrieving services as well as for
  3441. * dependency injection (see {@link guide/di dependency injection}).
  3442. *
  3443. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3444. * {@link angular.module}. The `ng` module must be explicitly added.
  3445. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3446. * disallows argument name annotation inference.
  3447. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3448. *
  3449. * @example
  3450. * Typical usage
  3451. * ```js
  3452. * // create an injector
  3453. * var $injector = angular.injector(['ng']);
  3454. *
  3455. * // use the injector to kick off your application
  3456. * // use the type inference to auto inject arguments, or use implicit injection
  3457. * $injector.invoke(function($rootScope, $compile, $document) {
  3458. * $compile($document)($rootScope);
  3459. * $rootScope.$digest();
  3460. * });
  3461. * ```
  3462. *
  3463. * Sometimes you want to get access to the injector of a currently running Angular app
  3464. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  3465. * application has been bootstrapped. You can do this using the extra `injector()` added
  3466. * to JQuery/jqLite elements. See {@link angular.element}.
  3467. *
  3468. * *This is fairly rare but could be the case if a third party library is injecting the
  3469. * markup.*
  3470. *
  3471. * In the following example a new block of HTML containing a `ng-controller`
  3472. * directive is added to the end of the document body by JQuery. We then compile and link
  3473. * it into the current AngularJS scope.
  3474. *
  3475. * ```js
  3476. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3477. * $(document.body).append($div);
  3478. *
  3479. * angular.element(document).injector().invoke(function($compile) {
  3480. * var scope = angular.element($div).scope();
  3481. * $compile($div)(scope);
  3482. * });
  3483. * ```
  3484. */
  3485. /**
  3486. * @ngdoc module
  3487. * @name auto
  3488. * @installation
  3489. * @description
  3490. *
  3491. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3492. */
  3493. var ARROW_ARG = /^([^\(]+?)=>/;
  3494. var FN_ARGS = /^[^\(]*\(\s*([^\)]*)\)/m;
  3495. var FN_ARG_SPLIT = /,/;
  3496. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3497. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3498. var $injectorMinErr = minErr('$injector');
  3499. function stringifyFn(fn) {
  3500. // Support: Chrome 50-51 only
  3501. // Creating a new string by adding `' '` at the end, to hack around some bug in Chrome v50/51
  3502. // (See https://github.com/angular/angular.js/issues/14487.)
  3503. // TODO (gkalpak): Remove workaround when Chrome v52 is released
  3504. return Function.prototype.toString.call(fn) + ' ';
  3505. }
  3506. function extractArgs(fn) {
  3507. var fnText = stringifyFn(fn).replace(STRIP_COMMENTS, ''),
  3508. args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
  3509. return args;
  3510. }
  3511. function anonFn(fn) {
  3512. // For anonymous functions, showing at the very least the function signature can help in
  3513. // debugging.
  3514. var args = extractArgs(fn);
  3515. if (args) {
  3516. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3517. }
  3518. return 'fn';
  3519. }
  3520. function annotate(fn, strictDi, name) {
  3521. var $inject,
  3522. argDecl,
  3523. last;
  3524. if (typeof fn === 'function') {
  3525. if (!($inject = fn.$inject)) {
  3526. $inject = [];
  3527. if (fn.length) {
  3528. if (strictDi) {
  3529. if (!isString(name) || !name) {
  3530. name = fn.name || anonFn(fn);
  3531. }
  3532. throw $injectorMinErr('strictdi',
  3533. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3534. }
  3535. argDecl = extractArgs(fn);
  3536. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3537. arg.replace(FN_ARG, function(all, underscore, name) {
  3538. $inject.push(name);
  3539. });
  3540. });
  3541. }
  3542. fn.$inject = $inject;
  3543. }
  3544. } else if (isArray(fn)) {
  3545. last = fn.length - 1;
  3546. assertArgFn(fn[last], 'fn');
  3547. $inject = fn.slice(0, last);
  3548. } else {
  3549. assertArgFn(fn, 'fn', true);
  3550. }
  3551. return $inject;
  3552. }
  3553. ///////////////////////////////////////
  3554. /**
  3555. * @ngdoc service
  3556. * @name $injector
  3557. *
  3558. * @description
  3559. *
  3560. * `$injector` is used to retrieve object instances as defined by
  3561. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3562. * and load modules.
  3563. *
  3564. * The following always holds true:
  3565. *
  3566. * ```js
  3567. * var $injector = angular.injector();
  3568. * expect($injector.get('$injector')).toBe($injector);
  3569. * expect($injector.invoke(function($injector) {
  3570. * return $injector;
  3571. * })).toBe($injector);
  3572. * ```
  3573. *
  3574. * # Injection Function Annotation
  3575. *
  3576. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3577. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3578. *
  3579. * ```js
  3580. * // inferred (only works if code not minified/obfuscated)
  3581. * $injector.invoke(function(serviceA){});
  3582. *
  3583. * // annotated
  3584. * function explicit(serviceA) {};
  3585. * explicit.$inject = ['serviceA'];
  3586. * $injector.invoke(explicit);
  3587. *
  3588. * // inline
  3589. * $injector.invoke(['serviceA', function(serviceA){}]);
  3590. * ```
  3591. *
  3592. * ## Inference
  3593. *
  3594. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3595. * can then be parsed and the function arguments can be extracted. This method of discovering
  3596. * annotations is disallowed when the injector is in strict mode.
  3597. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3598. * argument names.
  3599. *
  3600. * ## `$inject` Annotation
  3601. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3602. *
  3603. * ## Inline
  3604. * As an array of injection names, where the last item in the array is the function to call.
  3605. */
  3606. /**
  3607. * @ngdoc method
  3608. * @name $injector#get
  3609. *
  3610. * @description
  3611. * Return an instance of the service.
  3612. *
  3613. * @param {string} name The name of the instance to retrieve.
  3614. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  3615. * @return {*} The instance.
  3616. */
  3617. /**
  3618. * @ngdoc method
  3619. * @name $injector#invoke
  3620. *
  3621. * @description
  3622. * Invoke the method and supply the method arguments from the `$injector`.
  3623. *
  3624. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  3625. * injected according to the {@link guide/di $inject Annotation} rules.
  3626. * @param {Object=} self The `this` for the invoked method.
  3627. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3628. * object first, before the `$injector` is consulted.
  3629. * @returns {*} the value returned by the invoked `fn` function.
  3630. */
  3631. /**
  3632. * @ngdoc method
  3633. * @name $injector#has
  3634. *
  3635. * @description
  3636. * Allows the user to query if the particular service exists.
  3637. *
  3638. * @param {string} name Name of the service to query.
  3639. * @returns {boolean} `true` if injector has given service.
  3640. */
  3641. /**
  3642. * @ngdoc method
  3643. * @name $injector#instantiate
  3644. * @description
  3645. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3646. * operator, and supplies all of the arguments to the constructor function as specified by the
  3647. * constructor annotation.
  3648. *
  3649. * @param {Function} Type Annotated constructor function.
  3650. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3651. * object first, before the `$injector` is consulted.
  3652. * @returns {Object} new instance of `Type`.
  3653. */
  3654. /**
  3655. * @ngdoc method
  3656. * @name $injector#annotate
  3657. *
  3658. * @description
  3659. * Returns an array of service names which the function is requesting for injection. This API is
  3660. * used by the injector to determine which services need to be injected into the function when the
  3661. * function is invoked. There are three ways in which the function can be annotated with the needed
  3662. * dependencies.
  3663. *
  3664. * # Argument names
  3665. *
  3666. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3667. * by converting the function into a string using `toString()` method and extracting the argument
  3668. * names.
  3669. * ```js
  3670. * // Given
  3671. * function MyController($scope, $route) {
  3672. * // ...
  3673. * }
  3674. *
  3675. * // Then
  3676. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3677. * ```
  3678. *
  3679. * You can disallow this method by using strict injection mode.
  3680. *
  3681. * This method does not work with code minification / obfuscation. For this reason the following
  3682. * annotation strategies are supported.
  3683. *
  3684. * # The `$inject` property
  3685. *
  3686. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3687. * represent names of services to be injected into the function.
  3688. * ```js
  3689. * // Given
  3690. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3691. * // ...
  3692. * }
  3693. * // Define function dependencies
  3694. * MyController['$inject'] = ['$scope', '$route'];
  3695. *
  3696. * // Then
  3697. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3698. * ```
  3699. *
  3700. * # The array notation
  3701. *
  3702. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3703. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3704. * a way that survives minification is a better choice:
  3705. *
  3706. * ```js
  3707. * // We wish to write this (not minification / obfuscation safe)
  3708. * injector.invoke(function($compile, $rootScope) {
  3709. * // ...
  3710. * });
  3711. *
  3712. * // We are forced to write break inlining
  3713. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3714. * // ...
  3715. * };
  3716. * tmpFn.$inject = ['$compile', '$rootScope'];
  3717. * injector.invoke(tmpFn);
  3718. *
  3719. * // To better support inline function the inline annotation is supported
  3720. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3721. * // ...
  3722. * }]);
  3723. *
  3724. * // Therefore
  3725. * expect(injector.annotate(
  3726. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3727. * ).toEqual(['$compile', '$rootScope']);
  3728. * ```
  3729. *
  3730. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3731. * be retrieved as described above.
  3732. *
  3733. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3734. *
  3735. * @returns {Array.<string>} The names of the services which the function requires.
  3736. */
  3737. /**
  3738. * @ngdoc service
  3739. * @name $provide
  3740. *
  3741. * @description
  3742. *
  3743. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3744. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3745. * {@link angular.Module}.
  3746. *
  3747. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3748. * factories** are functions which, in turn, are created by a **service provider**.
  3749. * The **service providers** are constructor functions. When instantiated they must contain a
  3750. * property called `$get`, which holds the **service factory** function.
  3751. *
  3752. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3753. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3754. * function to get the instance of the **service**.
  3755. *
  3756. * Often services have no configuration options and there is no need to add methods to the service
  3757. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3758. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3759. * services without specifying a provider.
  3760. *
  3761. * * {@link auto.$provide#provider provider(name, provider)} - registers a **service provider** with the
  3762. * {@link auto.$injector $injector}
  3763. * * {@link auto.$provide#constant constant(name, obj)} - registers a value/object that can be accessed by
  3764. * providers and services.
  3765. * * {@link auto.$provide#value value(name, obj)} - registers a value/object that can only be accessed by
  3766. * services, not providers.
  3767. * * {@link auto.$provide#factory factory(name, fn)} - registers a service **factory function**
  3768. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3769. * given factory function.
  3770. * * {@link auto.$provide#service service(name, Fn)} - registers a **constructor function**
  3771. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3772. * a new object using the given constructor function.
  3773. * * {@link auto.$provide#decorator decorator(name, decorFn)} - registers a **decorator function** that
  3774. * will be able to modify or replace the implementation of another service.
  3775. *
  3776. * See the individual methods for more information and examples.
  3777. */
  3778. /**
  3779. * @ngdoc method
  3780. * @name $provide#provider
  3781. * @description
  3782. *
  3783. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3784. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3785. * service.
  3786. *
  3787. * Service provider names start with the name of the service they provide followed by `Provider`.
  3788. * For example, the {@link ng.$log $log} service has a provider called
  3789. * {@link ng.$logProvider $logProvider}.
  3790. *
  3791. * Service provider objects can have additional methods which allow configuration of the provider
  3792. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3793. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3794. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3795. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3796. * console or not.
  3797. *
  3798. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3799. 'Provider'` key.
  3800. * @param {(Object|function())} provider If the provider is:
  3801. *
  3802. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3803. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3804. * - `Constructor`: a new instance of the provider will be created using
  3805. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3806. *
  3807. * @returns {Object} registered provider instance
  3808. * @example
  3809. *
  3810. * The following example shows how to create a simple event tracking service and register it using
  3811. * {@link auto.$provide#provider $provide.provider()}.
  3812. *
  3813. * ```js
  3814. * // Define the eventTracker provider
  3815. * function EventTrackerProvider() {
  3816. * var trackingUrl = '/track';
  3817. *
  3818. * // A provider method for configuring where the tracked events should been saved
  3819. * this.setTrackingUrl = function(url) {
  3820. * trackingUrl = url;
  3821. * };
  3822. *
  3823. * // The service factory function
  3824. * this.$get = ['$http', function($http) {
  3825. * var trackedEvents = {};
  3826. * return {
  3827. * // Call this to track an event
  3828. * event: function(event) {
  3829. * var count = trackedEvents[event] || 0;
  3830. * count += 1;
  3831. * trackedEvents[event] = count;
  3832. * return count;
  3833. * },
  3834. * // Call this to save the tracked events to the trackingUrl
  3835. * save: function() {
  3836. * $http.post(trackingUrl, trackedEvents);
  3837. * }
  3838. * };
  3839. * }];
  3840. * }
  3841. *
  3842. * describe('eventTracker', function() {
  3843. * var postSpy;
  3844. *
  3845. * beforeEach(module(function($provide) {
  3846. * // Register the eventTracker provider
  3847. * $provide.provider('eventTracker', EventTrackerProvider);
  3848. * }));
  3849. *
  3850. * beforeEach(module(function(eventTrackerProvider) {
  3851. * // Configure eventTracker provider
  3852. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3853. * }));
  3854. *
  3855. * it('tracks events', inject(function(eventTracker) {
  3856. * expect(eventTracker.event('login')).toEqual(1);
  3857. * expect(eventTracker.event('login')).toEqual(2);
  3858. * }));
  3859. *
  3860. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3861. * postSpy = spyOn($http, 'post');
  3862. * eventTracker.event('login');
  3863. * eventTracker.save();
  3864. * expect(postSpy).toHaveBeenCalled();
  3865. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3866. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3867. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3868. * }));
  3869. * });
  3870. * ```
  3871. */
  3872. /**
  3873. * @ngdoc method
  3874. * @name $provide#factory
  3875. * @description
  3876. *
  3877. * Register a **service factory**, which will be called to return the service instance.
  3878. * This is short for registering a service where its provider consists of only a `$get` property,
  3879. * which is the given service factory function.
  3880. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3881. * configure your service in a provider.
  3882. *
  3883. * @param {string} name The name of the instance.
  3884. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  3885. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  3886. * @returns {Object} registered provider instance
  3887. *
  3888. * @example
  3889. * Here is an example of registering a service
  3890. * ```js
  3891. * $provide.factory('ping', ['$http', function($http) {
  3892. * return function ping() {
  3893. * return $http.send('/ping');
  3894. * };
  3895. * }]);
  3896. * ```
  3897. * You would then inject and use this service like this:
  3898. * ```js
  3899. * someModule.controller('Ctrl', ['ping', function(ping) {
  3900. * ping();
  3901. * }]);
  3902. * ```
  3903. */
  3904. /**
  3905. * @ngdoc method
  3906. * @name $provide#service
  3907. * @description
  3908. *
  3909. * Register a **service constructor**, which will be invoked with `new` to create the service
  3910. * instance.
  3911. * This is short for registering a service where its provider's `$get` property is a factory
  3912. * function that returns an instance instantiated by the injector from the service constructor
  3913. * function.
  3914. *
  3915. * Internally it looks a bit like this:
  3916. *
  3917. * ```
  3918. * {
  3919. * $get: function() {
  3920. * return $injector.instantiate(constructor);
  3921. * }
  3922. * }
  3923. * ```
  3924. *
  3925. *
  3926. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3927. * as a type/class.
  3928. *
  3929. * @param {string} name The name of the instance.
  3930. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  3931. * that will be instantiated.
  3932. * @returns {Object} registered provider instance
  3933. *
  3934. * @example
  3935. * Here is an example of registering a service using
  3936. * {@link auto.$provide#service $provide.service(class)}.
  3937. * ```js
  3938. * var Ping = function($http) {
  3939. * this.$http = $http;
  3940. * };
  3941. *
  3942. * Ping.$inject = ['$http'];
  3943. *
  3944. * Ping.prototype.send = function() {
  3945. * return this.$http.get('/ping');
  3946. * };
  3947. * $provide.service('ping', Ping);
  3948. * ```
  3949. * You would then inject and use this service like this:
  3950. * ```js
  3951. * someModule.controller('Ctrl', ['ping', function(ping) {
  3952. * ping.send();
  3953. * }]);
  3954. * ```
  3955. */
  3956. /**
  3957. * @ngdoc method
  3958. * @name $provide#value
  3959. * @description
  3960. *
  3961. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3962. * number, an array, an object or a function. This is short for registering a service where its
  3963. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3964. * service**. That also means it is not possible to inject other services into a value service.
  3965. *
  3966. * Value services are similar to constant services, except that they cannot be injected into a
  3967. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3968. * an Angular {@link auto.$provide#decorator decorator}.
  3969. *
  3970. * @param {string} name The name of the instance.
  3971. * @param {*} value The value.
  3972. * @returns {Object} registered provider instance
  3973. *
  3974. * @example
  3975. * Here are some examples of creating value services.
  3976. * ```js
  3977. * $provide.value('ADMIN_USER', 'admin');
  3978. *
  3979. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3980. *
  3981. * $provide.value('halfOf', function(value) {
  3982. * return value / 2;
  3983. * });
  3984. * ```
  3985. */
  3986. /**
  3987. * @ngdoc method
  3988. * @name $provide#constant
  3989. * @description
  3990. *
  3991. * Register a **constant service** with the {@link auto.$injector $injector}, such as a string,
  3992. * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not
  3993. * possible to inject other services into a constant.
  3994. *
  3995. * But unlike {@link auto.$provide#value value}, a constant can be
  3996. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3997. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3998. *
  3999. * @param {string} name The name of the constant.
  4000. * @param {*} value The constant value.
  4001. * @returns {Object} registered instance
  4002. *
  4003. * @example
  4004. * Here a some examples of creating constants:
  4005. * ```js
  4006. * $provide.constant('SHARD_HEIGHT', 306);
  4007. *
  4008. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  4009. *
  4010. * $provide.constant('double', function(value) {
  4011. * return value * 2;
  4012. * });
  4013. * ```
  4014. */
  4015. /**
  4016. * @ngdoc method
  4017. * @name $provide#decorator
  4018. * @description
  4019. *
  4020. * Register a **decorator function** with the {@link auto.$injector $injector}. A decorator function
  4021. * intercepts the creation of a service, allowing it to override or modify the behavior of the
  4022. * service. The return value of the decorator function may be the original service, or a new service
  4023. * that replaces (or wraps and delegates to) the original service.
  4024. *
  4025. * You can find out more about using decorators in the {@link guide/decorators} guide.
  4026. *
  4027. * @param {string} name The name of the service to decorate.
  4028. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  4029. * provided and should return the decorated service instance. The function is called using
  4030. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  4031. * Local injection arguments:
  4032. *
  4033. * * `$delegate` - The original service instance, which can be replaced, monkey patched, configured,
  4034. * decorated or delegated to.
  4035. *
  4036. * @example
  4037. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  4038. * calls to {@link ng.$log#error $log.warn()}.
  4039. * ```js
  4040. * $provide.decorator('$log', ['$delegate', function($delegate) {
  4041. * $delegate.warn = $delegate.error;
  4042. * return $delegate;
  4043. * }]);
  4044. * ```
  4045. */
  4046. function createInjector(modulesToLoad, strictDi) {
  4047. strictDi = (strictDi === true);
  4048. var INSTANTIATING = {},
  4049. providerSuffix = 'Provider',
  4050. path = [],
  4051. loadedModules = new HashMap([], true),
  4052. providerCache = {
  4053. $provide: {
  4054. provider: supportObject(provider),
  4055. factory: supportObject(factory),
  4056. service: supportObject(service),
  4057. value: supportObject(value),
  4058. constant: supportObject(constant),
  4059. decorator: decorator
  4060. }
  4061. },
  4062. providerInjector = (providerCache.$injector =
  4063. createInternalInjector(providerCache, function(serviceName, caller) {
  4064. if (angular.isString(caller)) {
  4065. path.push(caller);
  4066. }
  4067. throw $injectorMinErr('unpr', 'Unknown provider: {0}', path.join(' <- '));
  4068. })),
  4069. instanceCache = {},
  4070. protoInstanceInjector =
  4071. createInternalInjector(instanceCache, function(serviceName, caller) {
  4072. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  4073. return instanceInjector.invoke(
  4074. provider.$get, provider, undefined, serviceName);
  4075. }),
  4076. instanceInjector = protoInstanceInjector;
  4077. providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
  4078. var runBlocks = loadModules(modulesToLoad);
  4079. instanceInjector = protoInstanceInjector.get('$injector');
  4080. instanceInjector.strictDi = strictDi;
  4081. forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
  4082. return instanceInjector;
  4083. ////////////////////////////////////
  4084. // $provider
  4085. ////////////////////////////////////
  4086. function supportObject(delegate) {
  4087. return function(key, value) {
  4088. if (isObject(key)) {
  4089. forEach(key, reverseParams(delegate));
  4090. } else {
  4091. return delegate(key, value);
  4092. }
  4093. };
  4094. }
  4095. function provider(name, provider_) {
  4096. assertNotHasOwnProperty(name, 'service');
  4097. if (isFunction(provider_) || isArray(provider_)) {
  4098. provider_ = providerInjector.instantiate(provider_);
  4099. }
  4100. if (!provider_.$get) {
  4101. throw $injectorMinErr('pget', 'Provider \'{0}\' must define $get factory method.', name);
  4102. }
  4103. return (providerCache[name + providerSuffix] = provider_);
  4104. }
  4105. function enforceReturnValue(name, factory) {
  4106. return /** @this */ function enforcedReturnValue() {
  4107. var result = instanceInjector.invoke(factory, this);
  4108. if (isUndefined(result)) {
  4109. throw $injectorMinErr('undef', 'Provider \'{0}\' must return a value from $get factory method.', name);
  4110. }
  4111. return result;
  4112. };
  4113. }
  4114. function factory(name, factoryFn, enforce) {
  4115. return provider(name, {
  4116. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  4117. });
  4118. }
  4119. function service(name, constructor) {
  4120. return factory(name, ['$injector', function($injector) {
  4121. return $injector.instantiate(constructor);
  4122. }]);
  4123. }
  4124. function value(name, val) { return factory(name, valueFn(val), false); }
  4125. function constant(name, value) {
  4126. assertNotHasOwnProperty(name, 'constant');
  4127. providerCache[name] = value;
  4128. instanceCache[name] = value;
  4129. }
  4130. function decorator(serviceName, decorFn) {
  4131. var origProvider = providerInjector.get(serviceName + providerSuffix),
  4132. orig$get = origProvider.$get;
  4133. origProvider.$get = function() {
  4134. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  4135. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  4136. };
  4137. }
  4138. ////////////////////////////////////
  4139. // Module Loading
  4140. ////////////////////////////////////
  4141. function loadModules(modulesToLoad) {
  4142. assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
  4143. var runBlocks = [], moduleFn;
  4144. forEach(modulesToLoad, function(module) {
  4145. if (loadedModules.get(module)) return;
  4146. loadedModules.put(module, true);
  4147. function runInvokeQueue(queue) {
  4148. var i, ii;
  4149. for (i = 0, ii = queue.length; i < ii; i++) {
  4150. var invokeArgs = queue[i],
  4151. provider = providerInjector.get(invokeArgs[0]);
  4152. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  4153. }
  4154. }
  4155. try {
  4156. if (isString(module)) {
  4157. moduleFn = angularModule(module);
  4158. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  4159. runInvokeQueue(moduleFn._invokeQueue);
  4160. runInvokeQueue(moduleFn._configBlocks);
  4161. } else if (isFunction(module)) {
  4162. runBlocks.push(providerInjector.invoke(module));
  4163. } else if (isArray(module)) {
  4164. runBlocks.push(providerInjector.invoke(module));
  4165. } else {
  4166. assertArgFn(module, 'module');
  4167. }
  4168. } catch (e) {
  4169. if (isArray(module)) {
  4170. module = module[module.length - 1];
  4171. }
  4172. if (e.message && e.stack && e.stack.indexOf(e.message) === -1) {
  4173. // Safari & FF's stack traces don't contain error.message content
  4174. // unlike those of Chrome and IE
  4175. // So if stack doesn't contain message, we create a new string that contains both.
  4176. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  4177. // eslint-disable-next-line no-ex-assign
  4178. e = e.message + '\n' + e.stack;
  4179. }
  4180. throw $injectorMinErr('modulerr', 'Failed to instantiate module {0} due to:\n{1}',
  4181. module, e.stack || e.message || e);
  4182. }
  4183. });
  4184. return runBlocks;
  4185. }
  4186. ////////////////////////////////////
  4187. // internal Injector
  4188. ////////////////////////////////////
  4189. function createInternalInjector(cache, factory) {
  4190. function getService(serviceName, caller) {
  4191. if (cache.hasOwnProperty(serviceName)) {
  4192. if (cache[serviceName] === INSTANTIATING) {
  4193. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  4194. serviceName + ' <- ' + path.join(' <- '));
  4195. }
  4196. return cache[serviceName];
  4197. } else {
  4198. try {
  4199. path.unshift(serviceName);
  4200. cache[serviceName] = INSTANTIATING;
  4201. cache[serviceName] = factory(serviceName, caller);
  4202. return cache[serviceName];
  4203. } catch (err) {
  4204. if (cache[serviceName] === INSTANTIATING) {
  4205. delete cache[serviceName];
  4206. }
  4207. throw err;
  4208. } finally {
  4209. path.shift();
  4210. }
  4211. }
  4212. }
  4213. function injectionArgs(fn, locals, serviceName) {
  4214. var args = [],
  4215. $inject = createInjector.$$annotate(fn, strictDi, serviceName);
  4216. for (var i = 0, length = $inject.length; i < length; i++) {
  4217. var key = $inject[i];
  4218. if (typeof key !== 'string') {
  4219. throw $injectorMinErr('itkn',
  4220. 'Incorrect injection token! Expected service name as string, got {0}', key);
  4221. }
  4222. args.push(locals && locals.hasOwnProperty(key) ? locals[key] :
  4223. getService(key, serviceName));
  4224. }
  4225. return args;
  4226. }
  4227. function isClass(func) {
  4228. // IE 9-11 do not support classes and IE9 leaks with the code below.
  4229. if (msie <= 11 || typeof func !== 'function') {
  4230. return false;
  4231. }
  4232. var result = func.$$ngIsClass;
  4233. if (!isBoolean(result)) {
  4234. // Support: Edge 12-13 only
  4235. // See: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/6156135/
  4236. result = func.$$ngIsClass = /^(?:class\b|constructor\()/.test(stringifyFn(func));
  4237. }
  4238. return result;
  4239. }
  4240. function invoke(fn, self, locals, serviceName) {
  4241. if (typeof locals === 'string') {
  4242. serviceName = locals;
  4243. locals = null;
  4244. }
  4245. var args = injectionArgs(fn, locals, serviceName);
  4246. if (isArray(fn)) {
  4247. fn = fn[fn.length - 1];
  4248. }
  4249. if (!isClass(fn)) {
  4250. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  4251. // #5388
  4252. return fn.apply(self, args);
  4253. } else {
  4254. args.unshift(null);
  4255. return new (Function.prototype.bind.apply(fn, args))();
  4256. }
  4257. }
  4258. function instantiate(Type, locals, serviceName) {
  4259. // Check if Type is annotated and use just the given function at n-1 as parameter
  4260. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  4261. var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
  4262. var args = injectionArgs(Type, locals, serviceName);
  4263. // Empty object at position 0 is ignored for invocation with `new`, but required.
  4264. args.unshift(null);
  4265. return new (Function.prototype.bind.apply(ctor, args))();
  4266. }
  4267. return {
  4268. invoke: invoke,
  4269. instantiate: instantiate,
  4270. get: getService,
  4271. annotate: createInjector.$$annotate,
  4272. has: function(name) {
  4273. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  4274. }
  4275. };
  4276. }
  4277. }
  4278. createInjector.$$annotate = annotate;
  4279. /**
  4280. * @ngdoc provider
  4281. * @name $anchorScrollProvider
  4282. * @this
  4283. *
  4284. * @description
  4285. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  4286. * {@link ng.$location#hash $location.hash()} changes.
  4287. */
  4288. function $AnchorScrollProvider() {
  4289. var autoScrollingEnabled = true;
  4290. /**
  4291. * @ngdoc method
  4292. * @name $anchorScrollProvider#disableAutoScrolling
  4293. *
  4294. * @description
  4295. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  4296. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  4297. * Use this method to disable automatic scrolling.
  4298. *
  4299. * If automatic scrolling is disabled, one must explicitly call
  4300. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  4301. * current hash.
  4302. */
  4303. this.disableAutoScrolling = function() {
  4304. autoScrollingEnabled = false;
  4305. };
  4306. /**
  4307. * @ngdoc service
  4308. * @name $anchorScroll
  4309. * @kind function
  4310. * @requires $window
  4311. * @requires $location
  4312. * @requires $rootScope
  4313. *
  4314. * @description
  4315. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  4316. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  4317. * in the
  4318. * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#an-indicated-part-of-the-document).
  4319. *
  4320. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  4321. * match any anchor whenever it changes. This can be disabled by calling
  4322. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  4323. *
  4324. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  4325. * vertical scroll-offset (either fixed or dynamic).
  4326. *
  4327. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  4328. * {@link ng.$location#hash $location.hash()} will be used.
  4329. *
  4330. * @property {(number|function|jqLite)} yOffset
  4331. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  4332. * positioned elements at the top of the page, such as navbars, headers etc.
  4333. *
  4334. * `yOffset` can be specified in various ways:
  4335. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  4336. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  4337. * a number representing the offset (in pixels).<br /><br />
  4338. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  4339. * the top of the page to the element's bottom will be used as offset.<br />
  4340. * **Note**: The element will be taken into account only as long as its `position` is set to
  4341. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  4342. * their height and/or positioning according to the viewport's size.
  4343. *
  4344. * <br />
  4345. * <div class="alert alert-warning">
  4346. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  4347. * not some child element.
  4348. * </div>
  4349. *
  4350. * @example
  4351. <example module="anchorScrollExample" name="anchor-scroll">
  4352. <file name="index.html">
  4353. <div id="scrollArea" ng-controller="ScrollController">
  4354. <a ng-click="gotoBottom()">Go to bottom</a>
  4355. <a id="bottom"></a> You're at the bottom!
  4356. </div>
  4357. </file>
  4358. <file name="script.js">
  4359. angular.module('anchorScrollExample', [])
  4360. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  4361. function($scope, $location, $anchorScroll) {
  4362. $scope.gotoBottom = function() {
  4363. // set the location.hash to the id of
  4364. // the element you wish to scroll to.
  4365. $location.hash('bottom');
  4366. // call $anchorScroll()
  4367. $anchorScroll();
  4368. };
  4369. }]);
  4370. </file>
  4371. <file name="style.css">
  4372. #scrollArea {
  4373. height: 280px;
  4374. overflow: auto;
  4375. }
  4376. #bottom {
  4377. display: block;
  4378. margin-top: 2000px;
  4379. }
  4380. </file>
  4381. </example>
  4382. *
  4383. * <hr />
  4384. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  4385. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  4386. *
  4387. * @example
  4388. <example module="anchorScrollOffsetExample" name="anchor-scroll-offset">
  4389. <file name="index.html">
  4390. <div class="fixed-header" ng-controller="headerCtrl">
  4391. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  4392. Go to anchor {{x}}
  4393. </a>
  4394. </div>
  4395. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  4396. Anchor {{x}} of 5
  4397. </div>
  4398. </file>
  4399. <file name="script.js">
  4400. angular.module('anchorScrollOffsetExample', [])
  4401. .run(['$anchorScroll', function($anchorScroll) {
  4402. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  4403. }])
  4404. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  4405. function($anchorScroll, $location, $scope) {
  4406. $scope.gotoAnchor = function(x) {
  4407. var newHash = 'anchor' + x;
  4408. if ($location.hash() !== newHash) {
  4409. // set the $location.hash to `newHash` and
  4410. // $anchorScroll will automatically scroll to it
  4411. $location.hash('anchor' + x);
  4412. } else {
  4413. // call $anchorScroll() explicitly,
  4414. // since $location.hash hasn't changed
  4415. $anchorScroll();
  4416. }
  4417. };
  4418. }
  4419. ]);
  4420. </file>
  4421. <file name="style.css">
  4422. body {
  4423. padding-top: 50px;
  4424. }
  4425. .anchor {
  4426. border: 2px dashed DarkOrchid;
  4427. padding: 10px 10px 200px 10px;
  4428. }
  4429. .fixed-header {
  4430. background-color: rgba(0, 0, 0, 0.2);
  4431. height: 50px;
  4432. position: fixed;
  4433. top: 0; left: 0; right: 0;
  4434. }
  4435. .fixed-header > a {
  4436. display: inline-block;
  4437. margin: 5px 15px;
  4438. }
  4439. </file>
  4440. </example>
  4441. */
  4442. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  4443. var document = $window.document;
  4444. // Helper function to get first anchor from a NodeList
  4445. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  4446. // and working in all supported browsers.)
  4447. function getFirstAnchor(list) {
  4448. var result = null;
  4449. Array.prototype.some.call(list, function(element) {
  4450. if (nodeName_(element) === 'a') {
  4451. result = element;
  4452. return true;
  4453. }
  4454. });
  4455. return result;
  4456. }
  4457. function getYOffset() {
  4458. var offset = scroll.yOffset;
  4459. if (isFunction(offset)) {
  4460. offset = offset();
  4461. } else if (isElement(offset)) {
  4462. var elem = offset[0];
  4463. var style = $window.getComputedStyle(elem);
  4464. if (style.position !== 'fixed') {
  4465. offset = 0;
  4466. } else {
  4467. offset = elem.getBoundingClientRect().bottom;
  4468. }
  4469. } else if (!isNumber(offset)) {
  4470. offset = 0;
  4471. }
  4472. return offset;
  4473. }
  4474. function scrollTo(elem) {
  4475. if (elem) {
  4476. elem.scrollIntoView();
  4477. var offset = getYOffset();
  4478. if (offset) {
  4479. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  4480. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  4481. // top of the viewport.
  4482. //
  4483. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  4484. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  4485. // way down the page.
  4486. //
  4487. // This is often the case for elements near the bottom of the page.
  4488. //
  4489. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  4490. // the top of the element and the offset, which is enough to align the top of `elem` at the
  4491. // desired position.
  4492. var elemTop = elem.getBoundingClientRect().top;
  4493. $window.scrollBy(0, elemTop - offset);
  4494. }
  4495. } else {
  4496. $window.scrollTo(0, 0);
  4497. }
  4498. }
  4499. function scroll(hash) {
  4500. hash = isString(hash) ? hash : $location.hash();
  4501. var elm;
  4502. // empty hash, scroll to the top of the page
  4503. if (!hash) scrollTo(null);
  4504. // element with given id
  4505. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4506. // first anchor with given name :-D
  4507. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4508. // no element and hash === 'top', scroll to the top of the page
  4509. else if (hash === 'top') scrollTo(null);
  4510. }
  4511. // does not scroll when user clicks on anchor link that is currently on
  4512. // (no url change, no $location.hash() change), browser native does scroll
  4513. if (autoScrollingEnabled) {
  4514. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4515. function autoScrollWatchAction(newVal, oldVal) {
  4516. // skip the initial scroll if $location.hash is empty
  4517. if (newVal === oldVal && newVal === '') return;
  4518. jqLiteDocumentLoaded(function() {
  4519. $rootScope.$evalAsync(scroll);
  4520. });
  4521. });
  4522. }
  4523. return scroll;
  4524. }];
  4525. }
  4526. var $animateMinErr = minErr('$animate');
  4527. var ELEMENT_NODE = 1;
  4528. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  4529. function mergeClasses(a,b) {
  4530. if (!a && !b) return '';
  4531. if (!a) return b;
  4532. if (!b) return a;
  4533. if (isArray(a)) a = a.join(' ');
  4534. if (isArray(b)) b = b.join(' ');
  4535. return a + ' ' + b;
  4536. }
  4537. function extractElementNode(element) {
  4538. for (var i = 0; i < element.length; i++) {
  4539. var elm = element[i];
  4540. if (elm.nodeType === ELEMENT_NODE) {
  4541. return elm;
  4542. }
  4543. }
  4544. }
  4545. function splitClasses(classes) {
  4546. if (isString(classes)) {
  4547. classes = classes.split(' ');
  4548. }
  4549. // Use createMap() to prevent class assumptions involving property names in
  4550. // Object.prototype
  4551. var obj = createMap();
  4552. forEach(classes, function(klass) {
  4553. // sometimes the split leaves empty string values
  4554. // incase extra spaces were applied to the options
  4555. if (klass.length) {
  4556. obj[klass] = true;
  4557. }
  4558. });
  4559. return obj;
  4560. }
  4561. // if any other type of options value besides an Object value is
  4562. // passed into the $animate.method() animation then this helper code
  4563. // will be run which will ignore it. While this patch is not the
  4564. // greatest solution to this, a lot of existing plugins depend on
  4565. // $animate to either call the callback (< 1.2) or return a promise
  4566. // that can be changed. This helper function ensures that the options
  4567. // are wiped clean incase a callback function is provided.
  4568. function prepareAnimateOptions(options) {
  4569. return isObject(options)
  4570. ? options
  4571. : {};
  4572. }
  4573. var $$CoreAnimateJsProvider = /** @this */ function() {
  4574. this.$get = noop;
  4575. };
  4576. // this is prefixed with Core since it conflicts with
  4577. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  4578. var $$CoreAnimateQueueProvider = /** @this */ function() {
  4579. var postDigestQueue = new HashMap();
  4580. var postDigestElements = [];
  4581. this.$get = ['$$AnimateRunner', '$rootScope',
  4582. function($$AnimateRunner, $rootScope) {
  4583. return {
  4584. enabled: noop,
  4585. on: noop,
  4586. off: noop,
  4587. pin: noop,
  4588. push: function(element, event, options, domOperation) {
  4589. if (domOperation) {
  4590. domOperation();
  4591. }
  4592. options = options || {};
  4593. if (options.from) {
  4594. element.css(options.from);
  4595. }
  4596. if (options.to) {
  4597. element.css(options.to);
  4598. }
  4599. if (options.addClass || options.removeClass) {
  4600. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  4601. }
  4602. var runner = new $$AnimateRunner();
  4603. // since there are no animations to run the runner needs to be
  4604. // notified that the animation call is complete.
  4605. runner.complete();
  4606. return runner;
  4607. }
  4608. };
  4609. function updateData(data, classes, value) {
  4610. var changed = false;
  4611. if (classes) {
  4612. classes = isString(classes) ? classes.split(' ') :
  4613. isArray(classes) ? classes : [];
  4614. forEach(classes, function(className) {
  4615. if (className) {
  4616. changed = true;
  4617. data[className] = value;
  4618. }
  4619. });
  4620. }
  4621. return changed;
  4622. }
  4623. function handleCSSClassChanges() {
  4624. forEach(postDigestElements, function(element) {
  4625. var data = postDigestQueue.get(element);
  4626. if (data) {
  4627. var existing = splitClasses(element.attr('class'));
  4628. var toAdd = '';
  4629. var toRemove = '';
  4630. forEach(data, function(status, className) {
  4631. var hasClass = !!existing[className];
  4632. if (status !== hasClass) {
  4633. if (status) {
  4634. toAdd += (toAdd.length ? ' ' : '') + className;
  4635. } else {
  4636. toRemove += (toRemove.length ? ' ' : '') + className;
  4637. }
  4638. }
  4639. });
  4640. forEach(element, function(elm) {
  4641. if (toAdd) {
  4642. jqLiteAddClass(elm, toAdd);
  4643. }
  4644. if (toRemove) {
  4645. jqLiteRemoveClass(elm, toRemove);
  4646. }
  4647. });
  4648. postDigestQueue.remove(element);
  4649. }
  4650. });
  4651. postDigestElements.length = 0;
  4652. }
  4653. function addRemoveClassesPostDigest(element, add, remove) {
  4654. var data = postDigestQueue.get(element) || {};
  4655. var classesAdded = updateData(data, add, true);
  4656. var classesRemoved = updateData(data, remove, false);
  4657. if (classesAdded || classesRemoved) {
  4658. postDigestQueue.put(element, data);
  4659. postDigestElements.push(element);
  4660. if (postDigestElements.length === 1) {
  4661. $rootScope.$$postDigest(handleCSSClassChanges);
  4662. }
  4663. }
  4664. }
  4665. }];
  4666. };
  4667. /**
  4668. * @ngdoc provider
  4669. * @name $animateProvider
  4670. *
  4671. * @description
  4672. * Default implementation of $animate that doesn't perform any animations, instead just
  4673. * synchronously performs DOM updates and resolves the returned runner promise.
  4674. *
  4675. * In order to enable animations the `ngAnimate` module has to be loaded.
  4676. *
  4677. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  4678. */
  4679. var $AnimateProvider = ['$provide', /** @this */ function($provide) {
  4680. var provider = this;
  4681. this.$$registeredAnimations = Object.create(null);
  4682. /**
  4683. * @ngdoc method
  4684. * @name $animateProvider#register
  4685. *
  4686. * @description
  4687. * Registers a new injectable animation factory function. The factory function produces the
  4688. * animation object which contains callback functions for each event that is expected to be
  4689. * animated.
  4690. *
  4691. * * `eventFn`: `function(element, ... , doneFunction, options)`
  4692. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  4693. * on the type of animation additional arguments will be injected into the animation function. The
  4694. * list below explains the function signatures for the different animation methods:
  4695. *
  4696. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  4697. * - addClass: function(element, addedClasses, doneFunction, options)
  4698. * - removeClass: function(element, removedClasses, doneFunction, options)
  4699. * - enter, leave, move: function(element, doneFunction, options)
  4700. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  4701. *
  4702. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  4703. *
  4704. * ```js
  4705. * return {
  4706. * //enter, leave, move signature
  4707. * eventFn : function(element, done, options) {
  4708. * //code to run the animation
  4709. * //once complete, then run done()
  4710. * return function endFunction(wasCancelled) {
  4711. * //code to cancel the animation
  4712. * }
  4713. * }
  4714. * }
  4715. * ```
  4716. *
  4717. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  4718. * @param {Function} factory The factory function that will be executed to return the animation
  4719. * object.
  4720. */
  4721. this.register = function(name, factory) {
  4722. if (name && name.charAt(0) !== '.') {
  4723. throw $animateMinErr('notcsel', 'Expecting class selector starting with \'.\' got \'{0}\'.', name);
  4724. }
  4725. var key = name + '-animation';
  4726. provider.$$registeredAnimations[name.substr(1)] = key;
  4727. $provide.factory(key, factory);
  4728. };
  4729. /**
  4730. * @ngdoc method
  4731. * @name $animateProvider#classNameFilter
  4732. *
  4733. * @description
  4734. * Sets and/or returns the CSS class regular expression that is checked when performing
  4735. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4736. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  4737. * When setting the `classNameFilter` value, animations will only be performed on elements
  4738. * that successfully match the filter expression. This in turn can boost performance
  4739. * for low-powered devices as well as applications containing a lot of structural operations.
  4740. * @param {RegExp=} expression The className expression which will be checked against all animations
  4741. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4742. */
  4743. this.classNameFilter = function(expression) {
  4744. if (arguments.length === 1) {
  4745. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  4746. if (this.$$classNameFilter) {
  4747. var reservedRegex = new RegExp('(\\s+|\\/)' + NG_ANIMATE_CLASSNAME + '(\\s+|\\/)');
  4748. if (reservedRegex.test(this.$$classNameFilter.toString())) {
  4749. throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  4750. }
  4751. }
  4752. }
  4753. return this.$$classNameFilter;
  4754. };
  4755. this.$get = ['$$animateQueue', function($$animateQueue) {
  4756. function domInsert(element, parentElement, afterElement) {
  4757. // if for some reason the previous element was removed
  4758. // from the dom sometime before this code runs then let's
  4759. // just stick to using the parent element as the anchor
  4760. if (afterElement) {
  4761. var afterNode = extractElementNode(afterElement);
  4762. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  4763. afterElement = null;
  4764. }
  4765. }
  4766. if (afterElement) {
  4767. afterElement.after(element);
  4768. } else {
  4769. parentElement.prepend(element);
  4770. }
  4771. }
  4772. /**
  4773. * @ngdoc service
  4774. * @name $animate
  4775. * @description The $animate service exposes a series of DOM utility methods that provide support
  4776. * for animation hooks. The default behavior is the application of DOM operations, however,
  4777. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  4778. * to ensure that animation runs with the triggered DOM operation.
  4779. *
  4780. * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
  4781. * included and only when it is active then the animation hooks that `$animate` triggers will be
  4782. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  4783. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  4784. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  4785. *
  4786. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  4787. *
  4788. * To learn more about enabling animation support, click here to visit the
  4789. * {@link ngAnimate ngAnimate module page}.
  4790. */
  4791. return {
  4792. // we don't call it directly since non-existant arguments may
  4793. // be interpreted as null within the sub enabled function
  4794. /**
  4795. *
  4796. * @ngdoc method
  4797. * @name $animate#on
  4798. * @kind function
  4799. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  4800. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  4801. * is fired with the following params:
  4802. *
  4803. * ```js
  4804. * $animate.on('enter', container,
  4805. * function callback(element, phase) {
  4806. * // cool we detected an enter animation within the container
  4807. * }
  4808. * );
  4809. * ```
  4810. *
  4811. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  4812. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  4813. * as well as among its children
  4814. * @param {Function} callback the callback function that will be fired when the listener is triggered
  4815. *
  4816. * The arguments present in the callback function are:
  4817. * * `element` - The captured DOM element that the animation was fired on.
  4818. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  4819. */
  4820. on: $$animateQueue.on,
  4821. /**
  4822. *
  4823. * @ngdoc method
  4824. * @name $animate#off
  4825. * @kind function
  4826. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  4827. * can be used in three different ways depending on the arguments:
  4828. *
  4829. * ```js
  4830. * // remove all the animation event listeners listening for `enter`
  4831. * $animate.off('enter');
  4832. *
  4833. * // remove listeners for all animation events from the container element
  4834. * $animate.off(container);
  4835. *
  4836. * // remove all the animation event listeners listening for `enter` on the given element and its children
  4837. * $animate.off('enter', container);
  4838. *
  4839. * // remove the event listener function provided by `callback` that is set
  4840. * // to listen for `enter` on the given `container` as well as its children
  4841. * $animate.off('enter', container, callback);
  4842. * ```
  4843. *
  4844. * @param {string|DOMElement} event|container the animation event (e.g. enter, leave, move,
  4845. * addClass, removeClass, etc...), or the container element. If it is the element, all other
  4846. * arguments are ignored.
  4847. * @param {DOMElement=} container the container element the event listener was placed on
  4848. * @param {Function=} callback the callback function that was registered as the listener
  4849. */
  4850. off: $$animateQueue.off,
  4851. /**
  4852. * @ngdoc method
  4853. * @name $animate#pin
  4854. * @kind function
  4855. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  4856. * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
  4857. * element despite being outside the realm of the application or within another application. Say for example if the application
  4858. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  4859. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  4860. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  4861. *
  4862. * Note that this feature is only active when the `ngAnimate` module is used.
  4863. *
  4864. * @param {DOMElement} element the external element that will be pinned
  4865. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  4866. */
  4867. pin: $$animateQueue.pin,
  4868. /**
  4869. *
  4870. * @ngdoc method
  4871. * @name $animate#enabled
  4872. * @kind function
  4873. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  4874. * function can be called in four ways:
  4875. *
  4876. * ```js
  4877. * // returns true or false
  4878. * $animate.enabled();
  4879. *
  4880. * // changes the enabled state for all animations
  4881. * $animate.enabled(false);
  4882. * $animate.enabled(true);
  4883. *
  4884. * // returns true or false if animations are enabled for an element
  4885. * $animate.enabled(element);
  4886. *
  4887. * // changes the enabled state for an element and its children
  4888. * $animate.enabled(element, true);
  4889. * $animate.enabled(element, false);
  4890. * ```
  4891. *
  4892. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  4893. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  4894. *
  4895. * @return {boolean} whether or not animations are enabled
  4896. */
  4897. enabled: $$animateQueue.enabled,
  4898. /**
  4899. * @ngdoc method
  4900. * @name $animate#cancel
  4901. * @kind function
  4902. * @description Cancels the provided animation.
  4903. *
  4904. * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
  4905. */
  4906. cancel: function(runner) {
  4907. if (runner.end) {
  4908. runner.end();
  4909. }
  4910. },
  4911. /**
  4912. *
  4913. * @ngdoc method
  4914. * @name $animate#enter
  4915. * @kind function
  4916. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  4917. * as the first child within the `parent` element and then triggers an animation.
  4918. * A promise is returned that will be resolved during the next digest once the animation
  4919. * has completed.
  4920. *
  4921. * @param {DOMElement} element the element which will be inserted into the DOM
  4922. * @param {DOMElement} parent the parent element which will append the element as
  4923. * a child (so long as the after element is not present)
  4924. * @param {DOMElement=} after the sibling element after which the element will be appended
  4925. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  4926. * The object can have the following properties:
  4927. *
  4928. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  4929. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  4930. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  4931. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  4932. *
  4933. * @return {Promise} the animation callback promise
  4934. */
  4935. enter: function(element, parent, after, options) {
  4936. parent = parent && jqLite(parent);
  4937. after = after && jqLite(after);
  4938. parent = parent || after.parent();
  4939. domInsert(element, parent, after);
  4940. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  4941. },
  4942. /**
  4943. *
  4944. * @ngdoc method
  4945. * @name $animate#move
  4946. * @kind function
  4947. * @description Inserts (moves) the element into its new position in the DOM either after
  4948. * the `after` element (if provided) or as the first child within the `parent` element
  4949. * and then triggers an animation. A promise is returned that will be resolved
  4950. * during the next digest once the animation has completed.
  4951. *
  4952. * @param {DOMElement} element the element which will be moved into the new DOM position
  4953. * @param {DOMElement} parent the parent element which will append the element as
  4954. * a child (so long as the after element is not present)
  4955. * @param {DOMElement=} after the sibling element after which the element will be appended
  4956. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  4957. * The object can have the following properties:
  4958. *
  4959. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  4960. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  4961. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  4962. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  4963. *
  4964. * @return {Promise} the animation callback promise
  4965. */
  4966. move: function(element, parent, after, options) {
  4967. parent = parent && jqLite(parent);
  4968. after = after && jqLite(after);
  4969. parent = parent || after.parent();
  4970. domInsert(element, parent, after);
  4971. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  4972. },
  4973. /**
  4974. * @ngdoc method
  4975. * @name $animate#leave
  4976. * @kind function
  4977. * @description Triggers an animation and then removes the element from the DOM.
  4978. * When the function is called a promise is returned that will be resolved during the next
  4979. * digest once the animation has completed.
  4980. *
  4981. * @param {DOMElement} element the element which will be removed from the DOM
  4982. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  4983. * The object can have the following properties:
  4984. *
  4985. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  4986. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  4987. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  4988. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  4989. *
  4990. * @return {Promise} the animation callback promise
  4991. */
  4992. leave: function(element, options) {
  4993. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  4994. element.remove();
  4995. });
  4996. },
  4997. /**
  4998. * @ngdoc method
  4999. * @name $animate#addClass
  5000. * @kind function
  5001. *
  5002. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  5003. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  5004. * animation if element already contains the CSS class or if the class is removed at a later step.
  5005. * Note that class-based animations are treated differently compared to structural animations
  5006. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5007. * depending if CSS or JavaScript animations are used.
  5008. *
  5009. * @param {DOMElement} element the element which the CSS classes will be applied to
  5010. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  5011. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5012. * The object can have the following properties:
  5013. *
  5014. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5015. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5016. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5017. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5018. *
  5019. * @return {Promise} the animation callback promise
  5020. */
  5021. addClass: function(element, className, options) {
  5022. options = prepareAnimateOptions(options);
  5023. options.addClass = mergeClasses(options.addclass, className);
  5024. return $$animateQueue.push(element, 'addClass', options);
  5025. },
  5026. /**
  5027. * @ngdoc method
  5028. * @name $animate#removeClass
  5029. * @kind function
  5030. *
  5031. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  5032. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  5033. * animation if element does not contain the CSS class or if the class is added at a later step.
  5034. * Note that class-based animations are treated differently compared to structural animations
  5035. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5036. * depending if CSS or JavaScript animations are used.
  5037. *
  5038. * @param {DOMElement} element the element which the CSS classes will be applied to
  5039. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  5040. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5041. * The object can have the following properties:
  5042. *
  5043. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5044. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5045. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5046. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5047. *
  5048. * @return {Promise} the animation callback promise
  5049. */
  5050. removeClass: function(element, className, options) {
  5051. options = prepareAnimateOptions(options);
  5052. options.removeClass = mergeClasses(options.removeClass, className);
  5053. return $$animateQueue.push(element, 'removeClass', options);
  5054. },
  5055. /**
  5056. * @ngdoc method
  5057. * @name $animate#setClass
  5058. * @kind function
  5059. *
  5060. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  5061. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  5062. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  5063. * passed. Note that class-based animations are treated differently compared to structural animations
  5064. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5065. * depending if CSS or JavaScript animations are used.
  5066. *
  5067. * @param {DOMElement} element the element which the CSS classes will be applied to
  5068. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  5069. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  5070. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5071. * The object can have the following properties:
  5072. *
  5073. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5074. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5075. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5076. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5077. *
  5078. * @return {Promise} the animation callback promise
  5079. */
  5080. setClass: function(element, add, remove, options) {
  5081. options = prepareAnimateOptions(options);
  5082. options.addClass = mergeClasses(options.addClass, add);
  5083. options.removeClass = mergeClasses(options.removeClass, remove);
  5084. return $$animateQueue.push(element, 'setClass', options);
  5085. },
  5086. /**
  5087. * @ngdoc method
  5088. * @name $animate#animate
  5089. * @kind function
  5090. *
  5091. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  5092. * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take
  5093. * on the provided styles. For example, if a transition animation is set for the given classNamem, then the provided `from` and
  5094. * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding
  5095. * style in `to`, the style in `from` is applied immediately, and no animation is run.
  5096. * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`
  5097. * method (or as part of the `options` parameter):
  5098. *
  5099. * ```js
  5100. * ngModule.animation('.my-inline-animation', function() {
  5101. * return {
  5102. * animate : function(element, from, to, done, options) {
  5103. * //animation
  5104. * done();
  5105. * }
  5106. * }
  5107. * });
  5108. * ```
  5109. *
  5110. * @param {DOMElement} element the element which the CSS styles will be applied to
  5111. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  5112. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  5113. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  5114. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  5115. * (Note that if no animation is detected then this value will not be applied to the element.)
  5116. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5117. * The object can have the following properties:
  5118. *
  5119. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5120. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5121. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5122. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5123. *
  5124. * @return {Promise} the animation callback promise
  5125. */
  5126. animate: function(element, from, to, className, options) {
  5127. options = prepareAnimateOptions(options);
  5128. options.from = options.from ? extend(options.from, from) : from;
  5129. options.to = options.to ? extend(options.to, to) : to;
  5130. className = className || 'ng-inline-animate';
  5131. options.tempClasses = mergeClasses(options.tempClasses, className);
  5132. return $$animateQueue.push(element, 'animate', options);
  5133. }
  5134. };
  5135. }];
  5136. }];
  5137. var $$AnimateAsyncRunFactoryProvider = /** @this */ function() {
  5138. this.$get = ['$$rAF', function($$rAF) {
  5139. var waitQueue = [];
  5140. function waitForTick(fn) {
  5141. waitQueue.push(fn);
  5142. if (waitQueue.length > 1) return;
  5143. $$rAF(function() {
  5144. for (var i = 0; i < waitQueue.length; i++) {
  5145. waitQueue[i]();
  5146. }
  5147. waitQueue = [];
  5148. });
  5149. }
  5150. return function() {
  5151. var passed = false;
  5152. waitForTick(function() {
  5153. passed = true;
  5154. });
  5155. return function(callback) {
  5156. if (passed) {
  5157. callback();
  5158. } else {
  5159. waitForTick(callback);
  5160. }
  5161. };
  5162. };
  5163. }];
  5164. };
  5165. var $$AnimateRunnerFactoryProvider = /** @this */ function() {
  5166. this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$$isDocumentHidden', '$timeout',
  5167. function($q, $sniffer, $$animateAsyncRun, $$isDocumentHidden, $timeout) {
  5168. var INITIAL_STATE = 0;
  5169. var DONE_PENDING_STATE = 1;
  5170. var DONE_COMPLETE_STATE = 2;
  5171. AnimateRunner.chain = function(chain, callback) {
  5172. var index = 0;
  5173. next();
  5174. function next() {
  5175. if (index === chain.length) {
  5176. callback(true);
  5177. return;
  5178. }
  5179. chain[index](function(response) {
  5180. if (response === false) {
  5181. callback(false);
  5182. return;
  5183. }
  5184. index++;
  5185. next();
  5186. });
  5187. }
  5188. };
  5189. AnimateRunner.all = function(runners, callback) {
  5190. var count = 0;
  5191. var status = true;
  5192. forEach(runners, function(runner) {
  5193. runner.done(onProgress);
  5194. });
  5195. function onProgress(response) {
  5196. status = status && response;
  5197. if (++count === runners.length) {
  5198. callback(status);
  5199. }
  5200. }
  5201. };
  5202. function AnimateRunner(host) {
  5203. this.setHost(host);
  5204. var rafTick = $$animateAsyncRun();
  5205. var timeoutTick = function(fn) {
  5206. $timeout(fn, 0, false);
  5207. };
  5208. this._doneCallbacks = [];
  5209. this._tick = function(fn) {
  5210. if ($$isDocumentHidden()) {
  5211. timeoutTick(fn);
  5212. } else {
  5213. rafTick(fn);
  5214. }
  5215. };
  5216. this._state = 0;
  5217. }
  5218. AnimateRunner.prototype = {
  5219. setHost: function(host) {
  5220. this.host = host || {};
  5221. },
  5222. done: function(fn) {
  5223. if (this._state === DONE_COMPLETE_STATE) {
  5224. fn();
  5225. } else {
  5226. this._doneCallbacks.push(fn);
  5227. }
  5228. },
  5229. progress: noop,
  5230. getPromise: function() {
  5231. if (!this.promise) {
  5232. var self = this;
  5233. this.promise = $q(function(resolve, reject) {
  5234. self.done(function(status) {
  5235. if (status === false) {
  5236. reject();
  5237. } else {
  5238. resolve();
  5239. }
  5240. });
  5241. });
  5242. }
  5243. return this.promise;
  5244. },
  5245. then: function(resolveHandler, rejectHandler) {
  5246. return this.getPromise().then(resolveHandler, rejectHandler);
  5247. },
  5248. 'catch': function(handler) {
  5249. return this.getPromise()['catch'](handler);
  5250. },
  5251. 'finally': function(handler) {
  5252. return this.getPromise()['finally'](handler);
  5253. },
  5254. pause: function() {
  5255. if (this.host.pause) {
  5256. this.host.pause();
  5257. }
  5258. },
  5259. resume: function() {
  5260. if (this.host.resume) {
  5261. this.host.resume();
  5262. }
  5263. },
  5264. end: function() {
  5265. if (this.host.end) {
  5266. this.host.end();
  5267. }
  5268. this._resolve(true);
  5269. },
  5270. cancel: function() {
  5271. if (this.host.cancel) {
  5272. this.host.cancel();
  5273. }
  5274. this._resolve(false);
  5275. },
  5276. complete: function(response) {
  5277. var self = this;
  5278. if (self._state === INITIAL_STATE) {
  5279. self._state = DONE_PENDING_STATE;
  5280. self._tick(function() {
  5281. self._resolve(response);
  5282. });
  5283. }
  5284. },
  5285. _resolve: function(response) {
  5286. if (this._state !== DONE_COMPLETE_STATE) {
  5287. forEach(this._doneCallbacks, function(fn) {
  5288. fn(response);
  5289. });
  5290. this._doneCallbacks.length = 0;
  5291. this._state = DONE_COMPLETE_STATE;
  5292. }
  5293. }
  5294. };
  5295. return AnimateRunner;
  5296. }];
  5297. };
  5298. /* exported $CoreAnimateCssProvider */
  5299. /**
  5300. * @ngdoc service
  5301. * @name $animateCss
  5302. * @kind object
  5303. * @this
  5304. *
  5305. * @description
  5306. * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
  5307. * then the `$animateCss` service will actually perform animations.
  5308. *
  5309. * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
  5310. */
  5311. var $CoreAnimateCssProvider = function() {
  5312. this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
  5313. return function(element, initialOptions) {
  5314. // all of the animation functions should create
  5315. // a copy of the options data, however, if a
  5316. // parent service has already created a copy then
  5317. // we should stick to using that
  5318. var options = initialOptions || {};
  5319. if (!options.$$prepared) {
  5320. options = copy(options);
  5321. }
  5322. // there is no point in applying the styles since
  5323. // there is no animation that goes on at all in
  5324. // this version of $animateCss.
  5325. if (options.cleanupStyles) {
  5326. options.from = options.to = null;
  5327. }
  5328. if (options.from) {
  5329. element.css(options.from);
  5330. options.from = null;
  5331. }
  5332. var closed, runner = new $$AnimateRunner();
  5333. return {
  5334. start: run,
  5335. end: run
  5336. };
  5337. function run() {
  5338. $$rAF(function() {
  5339. applyAnimationContents();
  5340. if (!closed) {
  5341. runner.complete();
  5342. }
  5343. closed = true;
  5344. });
  5345. return runner;
  5346. }
  5347. function applyAnimationContents() {
  5348. if (options.addClass) {
  5349. element.addClass(options.addClass);
  5350. options.addClass = null;
  5351. }
  5352. if (options.removeClass) {
  5353. element.removeClass(options.removeClass);
  5354. options.removeClass = null;
  5355. }
  5356. if (options.to) {
  5357. element.css(options.to);
  5358. options.to = null;
  5359. }
  5360. }
  5361. };
  5362. }];
  5363. };
  5364. /* global stripHash: true */
  5365. /**
  5366. * ! This is a private undocumented service !
  5367. *
  5368. * @name $browser
  5369. * @requires $log
  5370. * @description
  5371. * This object has two goals:
  5372. *
  5373. * - hide all the global state in the browser caused by the window object
  5374. * - abstract away all the browser specific features and inconsistencies
  5375. *
  5376. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  5377. * service, which can be used for convenient testing of the application without the interaction with
  5378. * the real browser apis.
  5379. */
  5380. /**
  5381. * @param {object} window The global window object.
  5382. * @param {object} document jQuery wrapped document.
  5383. * @param {object} $log window.console or an object with the same interface.
  5384. * @param {object} $sniffer $sniffer service
  5385. */
  5386. function Browser(window, document, $log, $sniffer) {
  5387. var self = this,
  5388. location = window.location,
  5389. history = window.history,
  5390. setTimeout = window.setTimeout,
  5391. clearTimeout = window.clearTimeout,
  5392. pendingDeferIds = {};
  5393. self.isMock = false;
  5394. var outstandingRequestCount = 0;
  5395. var outstandingRequestCallbacks = [];
  5396. // TODO(vojta): remove this temporary api
  5397. self.$$completeOutstandingRequest = completeOutstandingRequest;
  5398. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  5399. /**
  5400. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  5401. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  5402. */
  5403. function completeOutstandingRequest(fn) {
  5404. try {
  5405. fn.apply(null, sliceArgs(arguments, 1));
  5406. } finally {
  5407. outstandingRequestCount--;
  5408. if (outstandingRequestCount === 0) {
  5409. while (outstandingRequestCallbacks.length) {
  5410. try {
  5411. outstandingRequestCallbacks.pop()();
  5412. } catch (e) {
  5413. $log.error(e);
  5414. }
  5415. }
  5416. }
  5417. }
  5418. }
  5419. function getHash(url) {
  5420. var index = url.indexOf('#');
  5421. return index === -1 ? '' : url.substr(index);
  5422. }
  5423. /**
  5424. * @private
  5425. * Note: this method is used only by scenario runner
  5426. * TODO(vojta): prefix this method with $$ ?
  5427. * @param {function()} callback Function that will be called when no outstanding request
  5428. */
  5429. self.notifyWhenNoOutstandingRequests = function(callback) {
  5430. if (outstandingRequestCount === 0) {
  5431. callback();
  5432. } else {
  5433. outstandingRequestCallbacks.push(callback);
  5434. }
  5435. };
  5436. //////////////////////////////////////////////////////////////
  5437. // URL API
  5438. //////////////////////////////////////////////////////////////
  5439. var cachedState, lastHistoryState,
  5440. lastBrowserUrl = location.href,
  5441. baseElement = document.find('base'),
  5442. pendingLocation = null,
  5443. getCurrentState = !$sniffer.history ? noop : function getCurrentState() {
  5444. try {
  5445. return history.state;
  5446. } catch (e) {
  5447. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  5448. }
  5449. };
  5450. cacheState();
  5451. lastHistoryState = cachedState;
  5452. /**
  5453. * @name $browser#url
  5454. *
  5455. * @description
  5456. * GETTER:
  5457. * Without any argument, this method just returns current value of location.href.
  5458. *
  5459. * SETTER:
  5460. * With at least one argument, this method sets url to new value.
  5461. * If html5 history api supported, pushState/replaceState is used, otherwise
  5462. * location.href/location.replace is used.
  5463. * Returns its own instance to allow chaining
  5464. *
  5465. * NOTE: this api is intended for use only by the $location service. Please use the
  5466. * {@link ng.$location $location service} to change url.
  5467. *
  5468. * @param {string} url New url (when used as setter)
  5469. * @param {boolean=} replace Should new url replace current history record?
  5470. * @param {object=} state object to use with pushState/replaceState
  5471. */
  5472. self.url = function(url, replace, state) {
  5473. // In modern browsers `history.state` is `null` by default; treating it separately
  5474. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  5475. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  5476. if (isUndefined(state)) {
  5477. state = null;
  5478. }
  5479. // Android Browser BFCache causes location, history reference to become stale.
  5480. if (location !== window.location) location = window.location;
  5481. if (history !== window.history) history = window.history;
  5482. // setter
  5483. if (url) {
  5484. var sameState = lastHistoryState === state;
  5485. // Don't change anything if previous and current URLs and states match. This also prevents
  5486. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  5487. // See https://github.com/angular/angular.js/commit/ffb2701
  5488. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  5489. return self;
  5490. }
  5491. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  5492. lastBrowserUrl = url;
  5493. lastHistoryState = state;
  5494. // Don't use history API if only the hash changed
  5495. // due to a bug in IE10/IE11 which leads
  5496. // to not firing a `hashchange` nor `popstate` event
  5497. // in some cases (see #9143).
  5498. if ($sniffer.history && (!sameBase || !sameState)) {
  5499. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  5500. cacheState();
  5501. // Do the assignment again so that those two variables are referentially identical.
  5502. lastHistoryState = cachedState;
  5503. } else {
  5504. if (!sameBase) {
  5505. pendingLocation = url;
  5506. }
  5507. if (replace) {
  5508. location.replace(url);
  5509. } else if (!sameBase) {
  5510. location.href = url;
  5511. } else {
  5512. location.hash = getHash(url);
  5513. }
  5514. if (location.href !== url) {
  5515. pendingLocation = url;
  5516. }
  5517. }
  5518. if (pendingLocation) {
  5519. pendingLocation = url;
  5520. }
  5521. return self;
  5522. // getter
  5523. } else {
  5524. // - pendingLocation is needed as browsers don't allow to read out
  5525. // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
  5526. // https://openradar.appspot.com/22186109).
  5527. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  5528. return pendingLocation || location.href.replace(/%27/g,'\'');
  5529. }
  5530. };
  5531. /**
  5532. * @name $browser#state
  5533. *
  5534. * @description
  5535. * This method is a getter.
  5536. *
  5537. * Return history.state or null if history.state is undefined.
  5538. *
  5539. * @returns {object} state
  5540. */
  5541. self.state = function() {
  5542. return cachedState;
  5543. };
  5544. var urlChangeListeners = [],
  5545. urlChangeInit = false;
  5546. function cacheStateAndFireUrlChange() {
  5547. pendingLocation = null;
  5548. cacheState();
  5549. fireUrlChange();
  5550. }
  5551. // This variable should be used *only* inside the cacheState function.
  5552. var lastCachedState = null;
  5553. function cacheState() {
  5554. // This should be the only place in $browser where `history.state` is read.
  5555. cachedState = getCurrentState();
  5556. cachedState = isUndefined(cachedState) ? null : cachedState;
  5557. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  5558. if (equals(cachedState, lastCachedState)) {
  5559. cachedState = lastCachedState;
  5560. }
  5561. lastCachedState = cachedState;
  5562. }
  5563. function fireUrlChange() {
  5564. if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
  5565. return;
  5566. }
  5567. lastBrowserUrl = self.url();
  5568. lastHistoryState = cachedState;
  5569. forEach(urlChangeListeners, function(listener) {
  5570. listener(self.url(), cachedState);
  5571. });
  5572. }
  5573. /**
  5574. * @name $browser#onUrlChange
  5575. *
  5576. * @description
  5577. * Register callback function that will be called, when url changes.
  5578. *
  5579. * It's only called when the url is changed from outside of angular:
  5580. * - user types different url into address bar
  5581. * - user clicks on history (forward/back) button
  5582. * - user clicks on a link
  5583. *
  5584. * It's not called when url is changed by $browser.url() method
  5585. *
  5586. * The listener gets called with new url as parameter.
  5587. *
  5588. * NOTE: this api is intended for use only by the $location service. Please use the
  5589. * {@link ng.$location $location service} to monitor url changes in angular apps.
  5590. *
  5591. * @param {function(string)} listener Listener function to be called when url changes.
  5592. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  5593. */
  5594. self.onUrlChange = function(callback) {
  5595. // TODO(vojta): refactor to use node's syntax for events
  5596. if (!urlChangeInit) {
  5597. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  5598. // don't fire popstate when user change the address bar and don't fire hashchange when url
  5599. // changed by push/replaceState
  5600. // html5 history api - popstate event
  5601. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  5602. // hashchange event
  5603. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  5604. urlChangeInit = true;
  5605. }
  5606. urlChangeListeners.push(callback);
  5607. return callback;
  5608. };
  5609. /**
  5610. * @private
  5611. * Remove popstate and hashchange handler from window.
  5612. *
  5613. * NOTE: this api is intended for use only by $rootScope.
  5614. */
  5615. self.$$applicationDestroyed = function() {
  5616. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  5617. };
  5618. /**
  5619. * Checks whether the url has changed outside of Angular.
  5620. * Needs to be exported to be able to check for changes that have been done in sync,
  5621. * as hashchange/popstate events fire in async.
  5622. */
  5623. self.$$checkUrlChange = fireUrlChange;
  5624. //////////////////////////////////////////////////////////////
  5625. // Misc API
  5626. //////////////////////////////////////////////////////////////
  5627. /**
  5628. * @name $browser#baseHref
  5629. *
  5630. * @description
  5631. * Returns current <base href>
  5632. * (always relative - without domain)
  5633. *
  5634. * @returns {string} The current base href
  5635. */
  5636. self.baseHref = function() {
  5637. var href = baseElement.attr('href');
  5638. return href ? href.replace(/^(https?:)?\/\/[^\/]*/, '') : '';
  5639. };
  5640. /**
  5641. * @name $browser#defer
  5642. * @param {function()} fn A function, who's execution should be deferred.
  5643. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  5644. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  5645. *
  5646. * @description
  5647. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  5648. *
  5649. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  5650. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  5651. * via `$browser.defer.flush()`.
  5652. *
  5653. */
  5654. self.defer = function(fn, delay) {
  5655. var timeoutId;
  5656. outstandingRequestCount++;
  5657. timeoutId = setTimeout(function() {
  5658. delete pendingDeferIds[timeoutId];
  5659. completeOutstandingRequest(fn);
  5660. }, delay || 0);
  5661. pendingDeferIds[timeoutId] = true;
  5662. return timeoutId;
  5663. };
  5664. /**
  5665. * @name $browser#defer.cancel
  5666. *
  5667. * @description
  5668. * Cancels a deferred task identified with `deferId`.
  5669. *
  5670. * @param {*} deferId Token returned by the `$browser.defer` function.
  5671. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  5672. * canceled.
  5673. */
  5674. self.defer.cancel = function(deferId) {
  5675. if (pendingDeferIds[deferId]) {
  5676. delete pendingDeferIds[deferId];
  5677. clearTimeout(deferId);
  5678. completeOutstandingRequest(noop);
  5679. return true;
  5680. }
  5681. return false;
  5682. };
  5683. }
  5684. /** @this */
  5685. function $BrowserProvider() {
  5686. this.$get = ['$window', '$log', '$sniffer', '$document',
  5687. function($window, $log, $sniffer, $document) {
  5688. return new Browser($window, $document, $log, $sniffer);
  5689. }];
  5690. }
  5691. /**
  5692. * @ngdoc service
  5693. * @name $cacheFactory
  5694. * @this
  5695. *
  5696. * @description
  5697. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  5698. * them.
  5699. *
  5700. * ```js
  5701. *
  5702. * var cache = $cacheFactory('cacheId');
  5703. * expect($cacheFactory.get('cacheId')).toBe(cache);
  5704. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  5705. *
  5706. * cache.put("key", "value");
  5707. * cache.put("another key", "another value");
  5708. *
  5709. * // We've specified no options on creation
  5710. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  5711. *
  5712. * ```
  5713. *
  5714. *
  5715. * @param {string} cacheId Name or id of the newly created cache.
  5716. * @param {object=} options Options object that specifies the cache behavior. Properties:
  5717. *
  5718. * - `{number=}` `capacity` — turns the cache into LRU cache.
  5719. *
  5720. * @returns {object} Newly created cache object with the following set of methods:
  5721. *
  5722. * - `{object}` `info()` — Returns id, size, and options of cache.
  5723. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  5724. * it.
  5725. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  5726. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  5727. * - `{void}` `removeAll()` — Removes all cached values.
  5728. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  5729. *
  5730. * @example
  5731. <example module="cacheExampleApp" name="cache-factory">
  5732. <file name="index.html">
  5733. <div ng-controller="CacheController">
  5734. <input ng-model="newCacheKey" placeholder="Key">
  5735. <input ng-model="newCacheValue" placeholder="Value">
  5736. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  5737. <p ng-if="keys.length">Cached Values</p>
  5738. <div ng-repeat="key in keys">
  5739. <span ng-bind="key"></span>
  5740. <span>: </span>
  5741. <b ng-bind="cache.get(key)"></b>
  5742. </div>
  5743. <p>Cache Info</p>
  5744. <div ng-repeat="(key, value) in cache.info()">
  5745. <span ng-bind="key"></span>
  5746. <span>: </span>
  5747. <b ng-bind="value"></b>
  5748. </div>
  5749. </div>
  5750. </file>
  5751. <file name="script.js">
  5752. angular.module('cacheExampleApp', []).
  5753. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  5754. $scope.keys = [];
  5755. $scope.cache = $cacheFactory('cacheId');
  5756. $scope.put = function(key, value) {
  5757. if (angular.isUndefined($scope.cache.get(key))) {
  5758. $scope.keys.push(key);
  5759. }
  5760. $scope.cache.put(key, angular.isUndefined(value) ? null : value);
  5761. };
  5762. }]);
  5763. </file>
  5764. <file name="style.css">
  5765. p {
  5766. margin: 10px 0 3px;
  5767. }
  5768. </file>
  5769. </example>
  5770. */
  5771. function $CacheFactoryProvider() {
  5772. this.$get = function() {
  5773. var caches = {};
  5774. function cacheFactory(cacheId, options) {
  5775. if (cacheId in caches) {
  5776. throw minErr('$cacheFactory')('iid', 'CacheId \'{0}\' is already taken!', cacheId);
  5777. }
  5778. var size = 0,
  5779. stats = extend({}, options, {id: cacheId}),
  5780. data = createMap(),
  5781. capacity = (options && options.capacity) || Number.MAX_VALUE,
  5782. lruHash = createMap(),
  5783. freshEnd = null,
  5784. staleEnd = null;
  5785. /**
  5786. * @ngdoc type
  5787. * @name $cacheFactory.Cache
  5788. *
  5789. * @description
  5790. * A cache object used to store and retrieve data, primarily used by
  5791. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  5792. * templates and other data.
  5793. *
  5794. * ```js
  5795. * angular.module('superCache')
  5796. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  5797. * return $cacheFactory('super-cache');
  5798. * }]);
  5799. * ```
  5800. *
  5801. * Example test:
  5802. *
  5803. * ```js
  5804. * it('should behave like a cache', inject(function(superCache) {
  5805. * superCache.put('key', 'value');
  5806. * superCache.put('another key', 'another value');
  5807. *
  5808. * expect(superCache.info()).toEqual({
  5809. * id: 'super-cache',
  5810. * size: 2
  5811. * });
  5812. *
  5813. * superCache.remove('another key');
  5814. * expect(superCache.get('another key')).toBeUndefined();
  5815. *
  5816. * superCache.removeAll();
  5817. * expect(superCache.info()).toEqual({
  5818. * id: 'super-cache',
  5819. * size: 0
  5820. * });
  5821. * }));
  5822. * ```
  5823. */
  5824. return (caches[cacheId] = {
  5825. /**
  5826. * @ngdoc method
  5827. * @name $cacheFactory.Cache#put
  5828. * @kind function
  5829. *
  5830. * @description
  5831. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  5832. * retrieved later, and incrementing the size of the cache if the key was not already
  5833. * present in the cache. If behaving like an LRU cache, it will also remove stale
  5834. * entries from the set.
  5835. *
  5836. * It will not insert undefined values into the cache.
  5837. *
  5838. * @param {string} key the key under which the cached data is stored.
  5839. * @param {*} value the value to store alongside the key. If it is undefined, the key
  5840. * will not be stored.
  5841. * @returns {*} the value stored.
  5842. */
  5843. put: function(key, value) {
  5844. if (isUndefined(value)) return;
  5845. if (capacity < Number.MAX_VALUE) {
  5846. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  5847. refresh(lruEntry);
  5848. }
  5849. if (!(key in data)) size++;
  5850. data[key] = value;
  5851. if (size > capacity) {
  5852. this.remove(staleEnd.key);
  5853. }
  5854. return value;
  5855. },
  5856. /**
  5857. * @ngdoc method
  5858. * @name $cacheFactory.Cache#get
  5859. * @kind function
  5860. *
  5861. * @description
  5862. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  5863. *
  5864. * @param {string} key the key of the data to be retrieved
  5865. * @returns {*} the value stored.
  5866. */
  5867. get: function(key) {
  5868. if (capacity < Number.MAX_VALUE) {
  5869. var lruEntry = lruHash[key];
  5870. if (!lruEntry) return;
  5871. refresh(lruEntry);
  5872. }
  5873. return data[key];
  5874. },
  5875. /**
  5876. * @ngdoc method
  5877. * @name $cacheFactory.Cache#remove
  5878. * @kind function
  5879. *
  5880. * @description
  5881. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  5882. *
  5883. * @param {string} key the key of the entry to be removed
  5884. */
  5885. remove: function(key) {
  5886. if (capacity < Number.MAX_VALUE) {
  5887. var lruEntry = lruHash[key];
  5888. if (!lruEntry) return;
  5889. if (lruEntry === freshEnd) freshEnd = lruEntry.p;
  5890. if (lruEntry === staleEnd) staleEnd = lruEntry.n;
  5891. link(lruEntry.n,lruEntry.p);
  5892. delete lruHash[key];
  5893. }
  5894. if (!(key in data)) return;
  5895. delete data[key];
  5896. size--;
  5897. },
  5898. /**
  5899. * @ngdoc method
  5900. * @name $cacheFactory.Cache#removeAll
  5901. * @kind function
  5902. *
  5903. * @description
  5904. * Clears the cache object of any entries.
  5905. */
  5906. removeAll: function() {
  5907. data = createMap();
  5908. size = 0;
  5909. lruHash = createMap();
  5910. freshEnd = staleEnd = null;
  5911. },
  5912. /**
  5913. * @ngdoc method
  5914. * @name $cacheFactory.Cache#destroy
  5915. * @kind function
  5916. *
  5917. * @description
  5918. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  5919. * removing it from the {@link $cacheFactory $cacheFactory} set.
  5920. */
  5921. destroy: function() {
  5922. data = null;
  5923. stats = null;
  5924. lruHash = null;
  5925. delete caches[cacheId];
  5926. },
  5927. /**
  5928. * @ngdoc method
  5929. * @name $cacheFactory.Cache#info
  5930. * @kind function
  5931. *
  5932. * @description
  5933. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  5934. *
  5935. * @returns {object} an object with the following properties:
  5936. * <ul>
  5937. * <li>**id**: the id of the cache instance</li>
  5938. * <li>**size**: the number of entries kept in the cache instance</li>
  5939. * <li>**...**: any additional properties from the options object when creating the
  5940. * cache.</li>
  5941. * </ul>
  5942. */
  5943. info: function() {
  5944. return extend({}, stats, {size: size});
  5945. }
  5946. });
  5947. /**
  5948. * makes the `entry` the freshEnd of the LRU linked list
  5949. */
  5950. function refresh(entry) {
  5951. if (entry !== freshEnd) {
  5952. if (!staleEnd) {
  5953. staleEnd = entry;
  5954. } else if (staleEnd === entry) {
  5955. staleEnd = entry.n;
  5956. }
  5957. link(entry.n, entry.p);
  5958. link(entry, freshEnd);
  5959. freshEnd = entry;
  5960. freshEnd.n = null;
  5961. }
  5962. }
  5963. /**
  5964. * bidirectionally links two entries of the LRU linked list
  5965. */
  5966. function link(nextEntry, prevEntry) {
  5967. if (nextEntry !== prevEntry) {
  5968. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  5969. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  5970. }
  5971. }
  5972. }
  5973. /**
  5974. * @ngdoc method
  5975. * @name $cacheFactory#info
  5976. *
  5977. * @description
  5978. * Get information about all the caches that have been created
  5979. *
  5980. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  5981. */
  5982. cacheFactory.info = function() {
  5983. var info = {};
  5984. forEach(caches, function(cache, cacheId) {
  5985. info[cacheId] = cache.info();
  5986. });
  5987. return info;
  5988. };
  5989. /**
  5990. * @ngdoc method
  5991. * @name $cacheFactory#get
  5992. *
  5993. * @description
  5994. * Get access to a cache object by the `cacheId` used when it was created.
  5995. *
  5996. * @param {string} cacheId Name or id of a cache to access.
  5997. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  5998. */
  5999. cacheFactory.get = function(cacheId) {
  6000. return caches[cacheId];
  6001. };
  6002. return cacheFactory;
  6003. };
  6004. }
  6005. /**
  6006. * @ngdoc service
  6007. * @name $templateCache
  6008. * @this
  6009. *
  6010. * @description
  6011. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  6012. * can load templates directly into the cache in a `script` tag, or by consuming the
  6013. * `$templateCache` service directly.
  6014. *
  6015. * Adding via the `script` tag:
  6016. *
  6017. * ```html
  6018. * <script type="text/ng-template" id="templateId.html">
  6019. * <p>This is the content of the template</p>
  6020. * </script>
  6021. * ```
  6022. *
  6023. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  6024. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  6025. * element with ng-app attribute), otherwise the template will be ignored.
  6026. *
  6027. * Adding via the `$templateCache` service:
  6028. *
  6029. * ```js
  6030. * var myApp = angular.module('myApp', []);
  6031. * myApp.run(function($templateCache) {
  6032. * $templateCache.put('templateId.html', 'This is the content of the template');
  6033. * });
  6034. * ```
  6035. *
  6036. * To retrieve the template later, simply use it in your HTML:
  6037. * ```html
  6038. * <div ng-include=" 'templateId.html' "></div>
  6039. * ```
  6040. *
  6041. * or get it via Javascript:
  6042. * ```js
  6043. * $templateCache.get('templateId.html')
  6044. * ```
  6045. *
  6046. * See {@link ng.$cacheFactory $cacheFactory}.
  6047. *
  6048. */
  6049. function $TemplateCacheProvider() {
  6050. this.$get = ['$cacheFactory', function($cacheFactory) {
  6051. return $cacheFactory('templates');
  6052. }];
  6053. }
  6054. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  6055. * Any commits to this file should be reviewed with security in mind. *
  6056. * Changes to this file can potentially create security vulnerabilities. *
  6057. * An approval from 2 Core members with history of modifying *
  6058. * this file is required. *
  6059. * *
  6060. * Does the change somehow allow for arbitrary javascript to be executed? *
  6061. * Or allows for someone to change the prototype of built-in objects? *
  6062. * Or gives undesired access to variables likes document or window? *
  6063. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  6064. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  6065. *
  6066. * DOM-related variables:
  6067. *
  6068. * - "node" - DOM Node
  6069. * - "element" - DOM Element or Node
  6070. * - "$node" or "$element" - jqLite-wrapped node or element
  6071. *
  6072. *
  6073. * Compiler related stuff:
  6074. *
  6075. * - "linkFn" - linking fn of a single directive
  6076. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  6077. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  6078. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  6079. */
  6080. /**
  6081. * @ngdoc service
  6082. * @name $compile
  6083. * @kind function
  6084. *
  6085. * @description
  6086. * Compiles an HTML string or DOM into a template and produces a template function, which
  6087. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  6088. *
  6089. * The compilation is a process of walking the DOM tree and matching DOM elements to
  6090. * {@link ng.$compileProvider#directive directives}.
  6091. *
  6092. * <div class="alert alert-warning">
  6093. * **Note:** This document is an in-depth reference of all directive options.
  6094. * For a gentle introduction to directives with examples of common use cases,
  6095. * see the {@link guide/directive directive guide}.
  6096. * </div>
  6097. *
  6098. * ## Comprehensive Directive API
  6099. *
  6100. * There are many different options for a directive.
  6101. *
  6102. * The difference resides in the return value of the factory function.
  6103. * You can either return a {@link $compile#directive-definition-object Directive Definition Object (see below)}
  6104. * that defines the directive properties, or just the `postLink` function (all other properties will have
  6105. * the default values).
  6106. *
  6107. * <div class="alert alert-success">
  6108. * **Best Practice:** It's recommended to use the "directive definition object" form.
  6109. * </div>
  6110. *
  6111. * Here's an example directive declared with a Directive Definition Object:
  6112. *
  6113. * ```js
  6114. * var myModule = angular.module(...);
  6115. *
  6116. * myModule.directive('directiveName', function factory(injectables) {
  6117. * var directiveDefinitionObject = {
  6118. * {@link $compile#-priority- priority}: 0,
  6119. * {@link $compile#-template- template}: '<div></div>', // or // function(tElement, tAttrs) { ... },
  6120. * // or
  6121. * // {@link $compile#-templateurl- templateUrl}: 'directive.html', // or // function(tElement, tAttrs) { ... },
  6122. * {@link $compile#-transclude- transclude}: false,
  6123. * {@link $compile#-restrict- restrict}: 'A',
  6124. * {@link $compile#-templatenamespace- templateNamespace}: 'html',
  6125. * {@link $compile#-scope- scope}: false,
  6126. * {@link $compile#-controller- controller}: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  6127. * {@link $compile#-controlleras- controllerAs}: 'stringIdentifier',
  6128. * {@link $compile#-bindtocontroller- bindToController}: false,
  6129. * {@link $compile#-require- require}: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  6130. * {@link $compile#-multielement- multiElement}: false,
  6131. * {@link $compile#-compile- compile}: function compile(tElement, tAttrs, transclude) {
  6132. * return {
  6133. * {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
  6134. * {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
  6135. * }
  6136. * // or
  6137. * // return function postLink( ... ) { ... }
  6138. * },
  6139. * // or
  6140. * // {@link $compile#-link- link}: {
  6141. * // {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
  6142. * // {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
  6143. * // }
  6144. * // or
  6145. * // {@link $compile#-link- link}: function postLink( ... ) { ... }
  6146. * };
  6147. * return directiveDefinitionObject;
  6148. * });
  6149. * ```
  6150. *
  6151. * <div class="alert alert-warning">
  6152. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  6153. * </div>
  6154. *
  6155. * Therefore the above can be simplified as:
  6156. *
  6157. * ```js
  6158. * var myModule = angular.module(...);
  6159. *
  6160. * myModule.directive('directiveName', function factory(injectables) {
  6161. * var directiveDefinitionObject = {
  6162. * link: function postLink(scope, iElement, iAttrs) { ... }
  6163. * };
  6164. * return directiveDefinitionObject;
  6165. * // or
  6166. * // return function postLink(scope, iElement, iAttrs) { ... }
  6167. * });
  6168. * ```
  6169. *
  6170. * ### Life-cycle hooks
  6171. * Directive controllers can provide the following methods that are called by Angular at points in the life-cycle of the
  6172. * directive:
  6173. * * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and
  6174. * had their bindings initialized (and before the pre &amp; post linking functions for the directives on
  6175. * this element). This is a good place to put initialization code for your controller.
  6176. * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The
  6177. * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an
  6178. * object of the form `{ currentValue, previousValue, isFirstChange() }`. Use this hook to trigger updates within a
  6179. * component such as cloning the bound value to prevent accidental mutation of the outer value.
  6180. * * `$doCheck()` - Called on each turn of the digest cycle. Provides an opportunity to detect and act on
  6181. * changes. Any actions that you wish to take in response to the changes that you detect must be
  6182. * invoked from this hook; implementing this has no effect on when `$onChanges` is called. For example, this hook
  6183. * could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not
  6184. * be detected by Angular's change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments;
  6185. * if detecting changes, you must store the previous value(s) for comparison to the current values.
  6186. * * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing
  6187. * external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in
  6188. * the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent
  6189. * components will have their `$onDestroy()` hook called before child components.
  6190. * * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link
  6191. * function this hook can be used to set up DOM event handlers and do direct DOM manipulation.
  6192. * Note that child elements that contain `templateUrl` directives will not have been compiled and linked since
  6193. * they are waiting for their template to load asynchronously and their own compilation and linking has been
  6194. * suspended until that occurs.
  6195. *
  6196. * #### Comparison with Angular 2 life-cycle hooks
  6197. * Angular 2 also uses life-cycle hooks for its components. While the Angular 1 life-cycle hooks are similar there are
  6198. * some differences that you should be aware of, especially when it comes to moving your code from Angular 1 to Angular 2:
  6199. *
  6200. * * Angular 1 hooks are prefixed with `$`, such as `$onInit`. Angular 2 hooks are prefixed with `ng`, such as `ngOnInit`.
  6201. * * Angular 1 hooks can be defined on the controller prototype or added to the controller inside its constructor.
  6202. * In Angular 2 you can only define hooks on the prototype of the Component class.
  6203. * * Due to the differences in change-detection, you may get many more calls to `$doCheck` in Angular 1 than you would to
  6204. * `ngDoCheck` in Angular 2
  6205. * * Changes to the model inside `$doCheck` will trigger new turns of the digest loop, which will cause the changes to be
  6206. * propagated throughout the application.
  6207. * Angular 2 does not allow the `ngDoCheck` hook to trigger a change outside of the component. It will either throw an
  6208. * error or do nothing depending upon the state of `enableProdMode()`.
  6209. *
  6210. * #### Life-cycle hook examples
  6211. *
  6212. * This example shows how you can check for mutations to a Date object even though the identity of the object
  6213. * has not changed.
  6214. *
  6215. * <example name="doCheckDateExample" module="do-check-module">
  6216. * <file name="app.js">
  6217. * angular.module('do-check-module', [])
  6218. * .component('app', {
  6219. * template:
  6220. * 'Month: <input ng-model="$ctrl.month" ng-change="$ctrl.updateDate()">' +
  6221. * 'Date: {{ $ctrl.date }}' +
  6222. * '<test date="$ctrl.date"></test>',
  6223. * controller: function() {
  6224. * this.date = new Date();
  6225. * this.month = this.date.getMonth();
  6226. * this.updateDate = function() {
  6227. * this.date.setMonth(this.month);
  6228. * };
  6229. * }
  6230. * })
  6231. * .component('test', {
  6232. * bindings: { date: '<' },
  6233. * template:
  6234. * '<pre>{{ $ctrl.log | json }}</pre>',
  6235. * controller: function() {
  6236. * var previousValue;
  6237. * this.log = [];
  6238. * this.$doCheck = function() {
  6239. * var currentValue = this.date && this.date.valueOf();
  6240. * if (previousValue !== currentValue) {
  6241. * this.log.push('doCheck: date mutated: ' + this.date);
  6242. * previousValue = currentValue;
  6243. * }
  6244. * };
  6245. * }
  6246. * });
  6247. * </file>
  6248. * <file name="index.html">
  6249. * <app></app>
  6250. * </file>
  6251. * </example>
  6252. *
  6253. * This example show how you might use `$doCheck` to trigger changes in your component's inputs even if the
  6254. * actual identity of the component doesn't change. (Be aware that cloning and deep equality checks on large
  6255. * arrays or objects can have a negative impact on your application performance)
  6256. *
  6257. * <example name="doCheckArrayExample" module="do-check-module">
  6258. * <file name="index.html">
  6259. * <div ng-init="items = []">
  6260. * <button ng-click="items.push(items.length)">Add Item</button>
  6261. * <button ng-click="items = []">Reset Items</button>
  6262. * <pre>{{ items }}</pre>
  6263. * <test items="items"></test>
  6264. * </div>
  6265. * </file>
  6266. * <file name="app.js">
  6267. * angular.module('do-check-module', [])
  6268. * .component('test', {
  6269. * bindings: { items: '<' },
  6270. * template:
  6271. * '<pre>{{ $ctrl.log | json }}</pre>',
  6272. * controller: function() {
  6273. * this.log = [];
  6274. *
  6275. * this.$doCheck = function() {
  6276. * if (this.items_ref !== this.items) {
  6277. * this.log.push('doCheck: items changed');
  6278. * this.items_ref = this.items;
  6279. * }
  6280. * if (!angular.equals(this.items_clone, this.items)) {
  6281. * this.log.push('doCheck: items mutated');
  6282. * this.items_clone = angular.copy(this.items);
  6283. * }
  6284. * };
  6285. * }
  6286. * });
  6287. * </file>
  6288. * </example>
  6289. *
  6290. *
  6291. * ### Directive Definition Object
  6292. *
  6293. * The directive definition object provides instructions to the {@link ng.$compile
  6294. * compiler}. The attributes are:
  6295. *
  6296. * #### `multiElement`
  6297. * When this property is set to true (default is `false`), the HTML compiler will collect DOM nodes between
  6298. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  6299. * together as the directive elements. It is recommended that this feature be used on directives
  6300. * which are not strictly behavioral (such as {@link ngClick}), and which
  6301. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  6302. *
  6303. * #### `priority`
  6304. * When there are multiple directives defined on a single DOM element, sometimes it
  6305. * is necessary to specify the order in which the directives are applied. The `priority` is used
  6306. * to sort the directives before their `compile` functions get called. Priority is defined as a
  6307. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  6308. * are also run in priority order, but post-link functions are run in reverse order. The order
  6309. * of directives with the same priority is undefined. The default priority is `0`.
  6310. *
  6311. * #### `terminal`
  6312. * If set to true then the current `priority` will be the last set of directives
  6313. * which will execute (any directives at the current priority will still execute
  6314. * as the order of execution on same `priority` is undefined). Note that expressions
  6315. * and other directives used in the directive's template will also be excluded from execution.
  6316. *
  6317. * #### `scope`
  6318. * The scope property can be `false`, `true`, or an object:
  6319. *
  6320. * * **`false` (default):** No scope will be created for the directive. The directive will use its
  6321. * parent's scope.
  6322. *
  6323. * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
  6324. * the directive's element. If multiple directives on the same element request a new scope,
  6325. * only one new scope is created.
  6326. *
  6327. * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's element. The
  6328. * 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent
  6329. * scope. This is useful when creating reusable components, which should not accidentally read or modify
  6330. * data in the parent scope.
  6331. *
  6332. * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
  6333. * directive's element. These local properties are useful for aliasing values for templates. The keys in
  6334. * the object hash map to the name of the property on the isolate scope; the values define how the property
  6335. * is bound to the parent scope, via matching attributes on the directive's element:
  6336. *
  6337. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  6338. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  6339. * attribute name is assumed to be the same as the local name. Given `<my-component
  6340. * my-attr="hello {{name}}">` and the isolate scope definition `scope: { localName:'@myAttr' }`,
  6341. * the directive's scope property `localName` will reflect the interpolated value of `hello
  6342. * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's
  6343. * scope. The `name` is read from the parent scope (not the directive's scope).
  6344. *
  6345. * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression
  6346. * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.
  6347. * If no `attr` name is specified then the attribute name is assumed to be the same as the local
  6348. * name. Given `<my-component my-attr="parentModel">` and the isolate scope definition `scope: {
  6349. * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the
  6350. * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in
  6351. * `localModel` and vice versa. Optional attributes should be marked as such with a question mark:
  6352. * `=?` or `=?attr`. If the binding expression is non-assignable, or if the attribute isn't
  6353. * optional and doesn't exist, an exception ({@link error/$compile/nonassign `$compile:nonassign`})
  6354. * will be thrown upon discovering changes to the local value, since it will be impossible to sync
  6355. * them back to the parent scope. By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
  6356. * method is used for tracking changes, and the equality check is based on object identity.
  6357. * However, if an object literal or an array literal is passed as the binding expression, the
  6358. * equality check is done by value (using the {@link angular.equals} function). It's also possible
  6359. * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection
  6360. * `$watchCollection`}: use `=*` or `=*attr` (`=*?` or `=*?attr` if the attribute is optional).
  6361. *
  6362. * * `<` or `<attr` - set up a one-way (one-directional) binding between a local scope property and an
  6363. * expression passed via the attribute `attr`. The expression is evaluated in the context of the
  6364. * parent scope. If no `attr` name is specified then the attribute name is assumed to be the same as the
  6365. * local name. You can also make the binding optional by adding `?`: `<?` or `<?attr`.
  6366. *
  6367. * For example, given `<my-component my-attr="parentModel">` and directive definition of
  6368. * `scope: { localModel:'<myAttr' }`, then the isolated scope property `localModel` will reflect the
  6369. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  6370. * in `localModel`, but changes in `localModel` will not reflect in `parentModel`. There are however
  6371. * two caveats:
  6372. * 1. one-way binding does not copy the value from the parent to the isolate scope, it simply
  6373. * sets the same value. That means if your bound value is an object, changes to its properties
  6374. * in the isolated scope will be reflected in the parent scope (because both reference the same object).
  6375. * 2. one-way binding watches changes to the **identity** of the parent value. That means the
  6376. * {@link ng.$rootScope.Scope#$watch `$watch`} on the parent value only fires if the reference
  6377. * to the value has changed. In most cases, this should not be of concern, but can be important
  6378. * to know if you one-way bind to an object, and then replace that object in the isolated scope.
  6379. * If you now change a property of the object in your parent scope, the change will not be
  6380. * propagated to the isolated scope, because the identity of the object on the parent scope
  6381. * has not changed. Instead you must assign a new object.
  6382. *
  6383. * One-way binding is useful if you do not plan to propagate changes to your isolated scope bindings
  6384. * back to the parent. However, it does not make this completely impossible.
  6385. *
  6386. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. If
  6387. * no `attr` name is specified then the attribute name is assumed to be the same as the local name.
  6388. * Given `<my-component my-attr="count = count + value">` and the isolate scope definition `scope: {
  6389. * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for
  6390. * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope
  6391. * via an expression to the parent scope. This can be done by passing a map of local variable names
  6392. * and values into the expression wrapper fn. For example, if the expression is `increment(amount)`
  6393. * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.
  6394. *
  6395. * In general it's possible to apply more than one directive to one element, but there might be limitations
  6396. * depending on the type of scope required by the directives. The following points will help explain these limitations.
  6397. * For simplicity only two directives are taken into account, but it is also applicable for several directives:
  6398. *
  6399. * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
  6400. * * **child scope** + **no scope** => Both directives will share one single child scope
  6401. * * **child scope** + **child scope** => Both directives will share one single child scope
  6402. * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
  6403. * its parent's scope
  6404. * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
  6405. * be applied to the same element.
  6406. * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
  6407. * cannot be applied to the same element.
  6408. *
  6409. *
  6410. * #### `bindToController`
  6411. * This property is used to bind scope properties directly to the controller. It can be either
  6412. * `true` or an object hash with the same format as the `scope` property. Additionally, a controller
  6413. * alias must be set, either by using `controllerAs: 'myAlias'` or by specifying the alias in the controller
  6414. * definition: `controller: 'myCtrl as myAlias'`.
  6415. *
  6416. * When an isolate scope is used for a directive (see above), `bindToController: true` will
  6417. * allow a component to have its properties bound to the controller, rather than to scope.
  6418. *
  6419. * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller
  6420. * properties. You can access these bindings once they have been initialized by providing a controller method called
  6421. * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings
  6422. * initialized.
  6423. *
  6424. * <div class="alert alert-warning">
  6425. * **Deprecation warning:** although bindings for non-ES6 class controllers are currently
  6426. * bound to `this` before the controller constructor is called, this use is now deprecated. Please place initialization
  6427. * code that relies upon bindings inside a `$onInit` method on the controller, instead.
  6428. * </div>
  6429. *
  6430. * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.
  6431. * This will set up the scope bindings to the controller directly. Note that `scope` can still be used
  6432. * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate
  6433. * scope (useful for component directives).
  6434. *
  6435. * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.
  6436. *
  6437. *
  6438. * #### `controller`
  6439. * Controller constructor function. The controller is instantiated before the
  6440. * pre-linking phase and can be accessed by other directives (see
  6441. * `require` attribute). This allows the directives to communicate with each other and augment
  6442. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  6443. *
  6444. * * `$scope` - Current scope associated with the element
  6445. * * `$element` - Current element
  6446. * * `$attrs` - Current attributes object for the element
  6447. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  6448. * `function([scope], cloneLinkingFn, futureParentElement, slotName)`:
  6449. * * `scope`: (optional) override the scope.
  6450. * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.
  6451. * * `futureParentElement` (optional):
  6452. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  6453. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  6454. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  6455. * and when the `cloneLinkinFn` is passed,
  6456. * as those elements need to created and cloned in a special way when they are defined outside their
  6457. * usual containers (e.g. like `<svg>`).
  6458. * * See also the `directive.templateNamespace` property.
  6459. * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`)
  6460. * then the default translusion is provided.
  6461. * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns
  6462. * `true` if the specified slot contains content (i.e. one or more DOM nodes).
  6463. *
  6464. * #### `require`
  6465. * Require another directive and inject its controller as the fourth argument to the linking function. The
  6466. * `require` property can be a string, an array or an object:
  6467. * * a **string** containing the name of the directive to pass to the linking function
  6468. * * an **array** containing the names of directives to pass to the linking function. The argument passed to the
  6469. * linking function will be an array of controllers in the same order as the names in the `require` property
  6470. * * an **object** whose property values are the names of the directives to pass to the linking function. The argument
  6471. * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding
  6472. * controllers.
  6473. *
  6474. * If the `require` property is an object and `bindToController` is truthy, then the required controllers are
  6475. * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers
  6476. * have been constructed but before `$onInit` is called.
  6477. * If the name of the required controller is the same as the local name (the key), the name can be
  6478. * omitted. For example, `{parentDir: '^^'}` is equivalent to `{parentDir: '^^parentDir'}`.
  6479. * See the {@link $compileProvider#component} helper for an example of how this can be used.
  6480. * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is
  6481. * raised (unless no link function is specified and the required controllers are not being bound to the directive
  6482. * controller, in which case error checking is skipped). The name can be prefixed with:
  6483. *
  6484. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  6485. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  6486. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  6487. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  6488. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  6489. * `null` to the `link` fn if not found.
  6490. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  6491. * `null` to the `link` fn if not found.
  6492. *
  6493. *
  6494. * #### `controllerAs`
  6495. * Identifier name for a reference to the controller in the directive's scope.
  6496. * This allows the controller to be referenced from the directive template. This is especially
  6497. * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
  6498. * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
  6499. * `controllerAs` reference might overwrite a property that already exists on the parent scope.
  6500. *
  6501. *
  6502. * #### `restrict`
  6503. * String of subset of `EACM` which restricts the directive to a specific directive
  6504. * declaration style. If omitted, the defaults (elements and attributes) are used.
  6505. *
  6506. * * `E` - Element name (default): `<my-directive></my-directive>`
  6507. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  6508. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  6509. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  6510. *
  6511. *
  6512. * #### `templateNamespace`
  6513. * String representing the document type used by the markup in the template.
  6514. * AngularJS needs this information as those elements need to be created and cloned
  6515. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  6516. *
  6517. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  6518. * top-level elements such as `<svg>` or `<math>`.
  6519. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  6520. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  6521. *
  6522. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  6523. *
  6524. * #### `template`
  6525. * HTML markup that may:
  6526. * * Replace the contents of the directive's element (default).
  6527. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  6528. * * Wrap the contents of the directive's element (if `transclude` is true).
  6529. *
  6530. * Value may be:
  6531. *
  6532. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  6533. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  6534. * function api below) and returns a string value.
  6535. *
  6536. *
  6537. * #### `templateUrl`
  6538. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  6539. *
  6540. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  6541. * for later when the template has been resolved. In the meantime it will continue to compile and link
  6542. * sibling and parent elements as though this element had not contained any directives.
  6543. *
  6544. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  6545. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  6546. * case when only one deeply nested directive has `templateUrl`.
  6547. *
  6548. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  6549. *
  6550. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  6551. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  6552. * a string value representing the url. In either case, the template URL is passed through {@link
  6553. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  6554. *
  6555. *
  6556. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  6557. * specify what the template should replace. Defaults to `false`.
  6558. *
  6559. * * `true` - the template will replace the directive's element.
  6560. * * `false` - the template will replace the contents of the directive's element.
  6561. *
  6562. * The replacement process migrates all of the attributes / classes from the old element to the new
  6563. * one. See the {@link guide/directive#template-expanding-directive
  6564. * Directives Guide} for an example.
  6565. *
  6566. * There are very few scenarios where element replacement is required for the application function,
  6567. * the main one being reusable custom components that are used within SVG contexts
  6568. * (because SVG doesn't work with custom elements in the DOM tree).
  6569. *
  6570. * #### `transclude`
  6571. * Extract the contents of the element where the directive appears and make it available to the directive.
  6572. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  6573. * {@link $compile#transclusion Transclusion} section below.
  6574. *
  6575. *
  6576. * #### `compile`
  6577. *
  6578. * ```js
  6579. * function compile(tElement, tAttrs, transclude) { ... }
  6580. * ```
  6581. *
  6582. * The compile function deals with transforming the template DOM. Since most directives do not do
  6583. * template transformation, it is not used often. The compile function takes the following arguments:
  6584. *
  6585. * * `tElement` - template element - The element where the directive has been declared. It is
  6586. * safe to do template transformation on the element and child elements only.
  6587. *
  6588. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  6589. * between all directive compile functions.
  6590. *
  6591. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  6592. *
  6593. * <div class="alert alert-warning">
  6594. * **Note:** The template instance and the link instance may be different objects if the template has
  6595. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  6596. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  6597. * should be done in a linking function rather than in a compile function.
  6598. * </div>
  6599. * <div class="alert alert-warning">
  6600. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  6601. * own templates or compile functions. Compiling these directives results in an infinite loop and
  6602. * stack overflow errors.
  6603. *
  6604. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  6605. * a directive's template instead of relying on automatic template compilation via `template` or
  6606. * `templateUrl` declaration or manual compilation inside the compile function.
  6607. * </div>
  6608. *
  6609. * <div class="alert alert-danger">
  6610. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  6611. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  6612. * to the link function instead.
  6613. * </div>
  6614. * A compile function can have a return value which can be either a function or an object.
  6615. *
  6616. * * returning a (post-link) function - is equivalent to registering the linking function via the
  6617. * `link` property of the config object when the compile function is empty.
  6618. *
  6619. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  6620. * control when a linking function should be called during the linking phase. See info about
  6621. * pre-linking and post-linking functions below.
  6622. *
  6623. *
  6624. * #### `link`
  6625. * This property is used only if the `compile` property is not defined.
  6626. *
  6627. * ```js
  6628. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  6629. * ```
  6630. *
  6631. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  6632. * executed after the template has been cloned. This is where most of the directive logic will be
  6633. * put.
  6634. *
  6635. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  6636. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  6637. *
  6638. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  6639. * manipulate the children of the element only in `postLink` function since the children have
  6640. * already been linked.
  6641. *
  6642. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  6643. * between all directive linking functions.
  6644. *
  6645. * * `controller` - the directive's required controller instance(s) - Instances are shared
  6646. * among all directives, which allows the directives to use the controllers as a communication
  6647. * channel. The exact value depends on the directive's `require` property:
  6648. * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
  6649. * * `string`: the controller instance
  6650. * * `array`: array of controller instances
  6651. *
  6652. * If a required controller cannot be found, and it is optional, the instance is `null`,
  6653. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  6654. *
  6655. * Note that you can also require the directive's own controller - it will be made available like
  6656. * any other controller.
  6657. *
  6658. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  6659. * This is the same as the `$transclude` parameter of directive controllers,
  6660. * see {@link ng.$compile#-controller- the controller section for details}.
  6661. * `function([scope], cloneLinkingFn, futureParentElement)`.
  6662. *
  6663. * #### Pre-linking function
  6664. *
  6665. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  6666. * compiler linking function will fail to locate the correct elements for linking.
  6667. *
  6668. * #### Post-linking function
  6669. *
  6670. * Executed after the child elements are linked.
  6671. *
  6672. * Note that child elements that contain `templateUrl` directives will not have been compiled
  6673. * and linked since they are waiting for their template to load asynchronously and their own
  6674. * compilation and linking has been suspended until that occurs.
  6675. *
  6676. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  6677. * for their async templates to be resolved.
  6678. *
  6679. *
  6680. * ### Transclusion
  6681. *
  6682. * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
  6683. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  6684. * scope from where they were taken.
  6685. *
  6686. * Transclusion is used (often with {@link ngTransclude}) to insert the
  6687. * original contents of a directive's element into a specified place in the template of the directive.
  6688. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  6689. * content has access to the properties on the scope from which it was taken, even if the directive
  6690. * has isolated scope.
  6691. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  6692. *
  6693. * This makes it possible for the widget to have private state for its template, while the transcluded
  6694. * content has access to its originating scope.
  6695. *
  6696. * <div class="alert alert-warning">
  6697. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  6698. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  6699. * Testing Transclusion Directives}.
  6700. * </div>
  6701. *
  6702. * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the
  6703. * directive's element, the entire element or multiple parts of the element contents:
  6704. *
  6705. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  6706. * * `'element'` - transclude the whole of the directive's element including any directives on this
  6707. * element that defined at a lower priority than this directive. When used, the `template`
  6708. * property is ignored.
  6709. * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template.
  6710. *
  6711. * **Mult-slot transclusion** is declared by providing an object for the `transclude` property.
  6712. *
  6713. * This object is a map where the keys are the name of the slot to fill and the value is an element selector
  6714. * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`)
  6715. * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc).
  6716. *
  6717. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  6718. *
  6719. * If the element selector is prefixed with a `?` then that slot is optional.
  6720. *
  6721. * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `<my-custom-element>` elements to
  6722. * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive.
  6723. *
  6724. * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements
  6725. * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call
  6726. * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and
  6727. * injectable into the directive's controller.
  6728. *
  6729. *
  6730. * #### Transclusion Functions
  6731. *
  6732. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  6733. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  6734. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  6735. *
  6736. * <div class="alert alert-info">
  6737. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  6738. * ngTransclude will deal with it for us.
  6739. * </div>
  6740. *
  6741. * If you want to manually control the insertion and removal of the transcluded content in your directive
  6742. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  6743. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  6744. *
  6745. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  6746. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  6747. * content and the `scope` is the newly created transclusion scope, which the clone will be linked to.
  6748. *
  6749. * <div class="alert alert-info">
  6750. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function
  6751. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  6752. * </div>
  6753. *
  6754. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  6755. * attach function**:
  6756. *
  6757. * ```js
  6758. * var transcludedContent, transclusionScope;
  6759. *
  6760. * $transclude(function(clone, scope) {
  6761. * element.append(clone);
  6762. * transcludedContent = clone;
  6763. * transclusionScope = scope;
  6764. * });
  6765. * ```
  6766. *
  6767. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  6768. * associated transclusion scope:
  6769. *
  6770. * ```js
  6771. * transcludedContent.remove();
  6772. * transclusionScope.$destroy();
  6773. * ```
  6774. *
  6775. * <div class="alert alert-info">
  6776. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  6777. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  6778. * then you are also responsible for calling `$destroy` on the transclusion scope.
  6779. * </div>
  6780. *
  6781. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  6782. * automatically destroy their transcluded clones as necessary so you do not need to worry about this if
  6783. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  6784. *
  6785. *
  6786. * #### Transclusion Scopes
  6787. *
  6788. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  6789. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  6790. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  6791. * was taken.
  6792. *
  6793. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  6794. * like this:
  6795. *
  6796. * ```html
  6797. * <div ng-app>
  6798. * <div isolate>
  6799. * <div transclusion>
  6800. * </div>
  6801. * </div>
  6802. * </div>
  6803. * ```
  6804. *
  6805. * The `$parent` scope hierarchy will look like this:
  6806. *
  6807. ```
  6808. - $rootScope
  6809. - isolate
  6810. - transclusion
  6811. ```
  6812. *
  6813. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  6814. *
  6815. ```
  6816. - $rootScope
  6817. - transclusion
  6818. - isolate
  6819. ```
  6820. *
  6821. *
  6822. * ### Attributes
  6823. *
  6824. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  6825. * `link()` or `compile()` functions. It has a variety of uses.
  6826. *
  6827. * * *Accessing normalized attribute names:* Directives like 'ngBind' can be expressed in many ways:
  6828. * 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. The attributes object allows for normalized access
  6829. * to the attributes.
  6830. *
  6831. * * *Directive inter-communication:* All directives share the same instance of the attributes
  6832. * object which allows the directives to use the attributes object as inter directive
  6833. * communication.
  6834. *
  6835. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  6836. * allowing other directives to read the interpolated value.
  6837. *
  6838. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  6839. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  6840. * the only way to easily get the actual value because during the linking phase the interpolation
  6841. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  6842. *
  6843. * ```js
  6844. * function linkingFn(scope, elm, attrs, ctrl) {
  6845. * // get the attribute value
  6846. * console.log(attrs.ngModel);
  6847. *
  6848. * // change the attribute
  6849. * attrs.$set('ngModel', 'new value');
  6850. *
  6851. * // observe changes to interpolated attribute
  6852. * attrs.$observe('ngModel', function(value) {
  6853. * console.log('ngModel has changed value to ' + value);
  6854. * });
  6855. * }
  6856. * ```
  6857. *
  6858. * ## Example
  6859. *
  6860. * <div class="alert alert-warning">
  6861. * **Note**: Typically directives are registered with `module.directive`. The example below is
  6862. * to illustrate how `$compile` works.
  6863. * </div>
  6864. *
  6865. <example module="compileExample" name="compile">
  6866. <file name="index.html">
  6867. <script>
  6868. angular.module('compileExample', [], function($compileProvider) {
  6869. // configure new 'compile' directive by passing a directive
  6870. // factory function. The factory function injects the '$compile'
  6871. $compileProvider.directive('compile', function($compile) {
  6872. // directive factory creates a link function
  6873. return function(scope, element, attrs) {
  6874. scope.$watch(
  6875. function(scope) {
  6876. // watch the 'compile' expression for changes
  6877. return scope.$eval(attrs.compile);
  6878. },
  6879. function(value) {
  6880. // when the 'compile' expression changes
  6881. // assign it into the current DOM
  6882. element.html(value);
  6883. // compile the new DOM and link it to the current
  6884. // scope.
  6885. // NOTE: we only compile .childNodes so that
  6886. // we don't get into infinite loop compiling ourselves
  6887. $compile(element.contents())(scope);
  6888. }
  6889. );
  6890. };
  6891. });
  6892. })
  6893. .controller('GreeterController', ['$scope', function($scope) {
  6894. $scope.name = 'Angular';
  6895. $scope.html = 'Hello {{name}}';
  6896. }]);
  6897. </script>
  6898. <div ng-controller="GreeterController">
  6899. <input ng-model="name"> <br/>
  6900. <textarea ng-model="html"></textarea> <br/>
  6901. <div compile="html"></div>
  6902. </div>
  6903. </file>
  6904. <file name="protractor.js" type="protractor">
  6905. it('should auto compile', function() {
  6906. var textarea = $('textarea');
  6907. var output = $('div[compile]');
  6908. // The initial state reads 'Hello Angular'.
  6909. expect(output.getText()).toBe('Hello Angular');
  6910. textarea.clear();
  6911. textarea.sendKeys('{{name}}!');
  6912. expect(output.getText()).toBe('Angular!');
  6913. });
  6914. </file>
  6915. </example>
  6916. *
  6917. *
  6918. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  6919. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  6920. *
  6921. * <div class="alert alert-danger">
  6922. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  6923. * e.g. will not use the right outer scope. Please pass the transclude function as a
  6924. * `parentBoundTranscludeFn` to the link function instead.
  6925. * </div>
  6926. *
  6927. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  6928. * root element(s), not their children)
  6929. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  6930. * (a DOM element/tree) to a scope. Where:
  6931. *
  6932. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  6933. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  6934. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  6935. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  6936. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  6937. *
  6938. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  6939. * * `scope` - is the current scope with which the linking function is working with.
  6940. *
  6941. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  6942. * keys may be used to control linking behavior:
  6943. *
  6944. * * `parentBoundTranscludeFn` - the transclude function made available to
  6945. * directives; if given, it will be passed through to the link functions of
  6946. * directives found in `element` during compilation.
  6947. * * `transcludeControllers` - an object hash with keys that map controller names
  6948. * to a hash with the key `instance`, which maps to the controller instance;
  6949. * if given, it will make the controllers available to directives on the compileNode:
  6950. * ```
  6951. * {
  6952. * parent: {
  6953. * instance: parentControllerInstance
  6954. * }
  6955. * }
  6956. * ```
  6957. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  6958. * the cloned elements; only needed for transcludes that are allowed to contain non html
  6959. * elements (e.g. SVG elements). See also the directive.controller property.
  6960. *
  6961. * Calling the linking function returns the element of the template. It is either the original
  6962. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  6963. *
  6964. * After linking the view is not updated until after a call to $digest which typically is done by
  6965. * Angular automatically.
  6966. *
  6967. * If you need access to the bound view, there are two ways to do it:
  6968. *
  6969. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  6970. * before you send them to the compiler and keep this reference around.
  6971. * ```js
  6972. * var element = $compile('<p>{{total}}</p>')(scope);
  6973. * ```
  6974. *
  6975. * - if on the other hand, you need the element to be cloned, the view reference from the original
  6976. * example would not point to the clone, but rather to the original template that was cloned. In
  6977. * this case, you can access the clone via the cloneAttachFn:
  6978. * ```js
  6979. * var templateElement = angular.element('<p>{{total}}</p>'),
  6980. * scope = ....;
  6981. *
  6982. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  6983. * //attach the clone to DOM document at the right place
  6984. * });
  6985. *
  6986. * //now we have reference to the cloned DOM via `clonedElement`
  6987. * ```
  6988. *
  6989. *
  6990. * For information on how the compiler works, see the
  6991. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  6992. */
  6993. var $compileMinErr = minErr('$compile');
  6994. function UNINITIALIZED_VALUE() {}
  6995. var _UNINITIALIZED_VALUE = new UNINITIALIZED_VALUE();
  6996. /**
  6997. * @ngdoc provider
  6998. * @name $compileProvider
  6999. *
  7000. * @description
  7001. */
  7002. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  7003. /** @this */
  7004. function $CompileProvider($provide, $$sanitizeUriProvider) {
  7005. var hasDirectives = {},
  7006. Suffix = 'Directive',
  7007. COMMENT_DIRECTIVE_REGEXP = /^\s*directive:\s*([\w\-]+)\s+(.*)$/,
  7008. CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?::([^;]+))?;?)/,
  7009. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  7010. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  7011. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  7012. // The assumption is that future DOM event attribute names will begin with
  7013. // 'on' and be composed of only English letters.
  7014. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  7015. var bindingCache = createMap();
  7016. function parseIsolateBindings(scope, directiveName, isController) {
  7017. var LOCAL_REGEXP = /^\s*([@&<]|=(\*?))(\??)\s*(\w*)\s*$/;
  7018. var bindings = createMap();
  7019. forEach(scope, function(definition, scopeName) {
  7020. if (definition in bindingCache) {
  7021. bindings[scopeName] = bindingCache[definition];
  7022. return;
  7023. }
  7024. var match = definition.match(LOCAL_REGEXP);
  7025. if (!match) {
  7026. throw $compileMinErr('iscp',
  7027. 'Invalid {3} for directive \'{0}\'.' +
  7028. ' Definition: {... {1}: \'{2}\' ...}',
  7029. directiveName, scopeName, definition,
  7030. (isController ? 'controller bindings definition' :
  7031. 'isolate scope definition'));
  7032. }
  7033. bindings[scopeName] = {
  7034. mode: match[1][0],
  7035. collection: match[2] === '*',
  7036. optional: match[3] === '?',
  7037. attrName: match[4] || scopeName
  7038. };
  7039. if (match[4]) {
  7040. bindingCache[definition] = bindings[scopeName];
  7041. }
  7042. });
  7043. return bindings;
  7044. }
  7045. function parseDirectiveBindings(directive, directiveName) {
  7046. var bindings = {
  7047. isolateScope: null,
  7048. bindToController: null
  7049. };
  7050. if (isObject(directive.scope)) {
  7051. if (directive.bindToController === true) {
  7052. bindings.bindToController = parseIsolateBindings(directive.scope,
  7053. directiveName, true);
  7054. bindings.isolateScope = {};
  7055. } else {
  7056. bindings.isolateScope = parseIsolateBindings(directive.scope,
  7057. directiveName, false);
  7058. }
  7059. }
  7060. if (isObject(directive.bindToController)) {
  7061. bindings.bindToController =
  7062. parseIsolateBindings(directive.bindToController, directiveName, true);
  7063. }
  7064. if (isObject(bindings.bindToController)) {
  7065. var controller = directive.controller;
  7066. var controllerAs = directive.controllerAs;
  7067. if (!controller) {
  7068. // There is no controller, there may or may not be a controllerAs property
  7069. throw $compileMinErr('noctrl',
  7070. 'Cannot bind to controller without directive \'{0}\'s controller.',
  7071. directiveName);
  7072. } else if (!identifierForController(controller, controllerAs)) {
  7073. // There is a controller, but no identifier or controllerAs property
  7074. throw $compileMinErr('noident',
  7075. 'Cannot bind to controller without identifier for directive \'{0}\'.',
  7076. directiveName);
  7077. }
  7078. }
  7079. return bindings;
  7080. }
  7081. function assertValidDirectiveName(name) {
  7082. var letter = name.charAt(0);
  7083. if (!letter || letter !== lowercase(letter)) {
  7084. throw $compileMinErr('baddir', 'Directive/Component name \'{0}\' is invalid. The first character must be a lowercase letter', name);
  7085. }
  7086. if (name !== name.trim()) {
  7087. throw $compileMinErr('baddir',
  7088. 'Directive/Component name \'{0}\' is invalid. The name should not contain leading or trailing whitespaces',
  7089. name);
  7090. }
  7091. }
  7092. function getDirectiveRequire(directive) {
  7093. var require = directive.require || (directive.controller && directive.name);
  7094. if (!isArray(require) && isObject(require)) {
  7095. forEach(require, function(value, key) {
  7096. var match = value.match(REQUIRE_PREFIX_REGEXP);
  7097. var name = value.substring(match[0].length);
  7098. if (!name) require[key] = match[0] + key;
  7099. });
  7100. }
  7101. return require;
  7102. }
  7103. function getDirectiveRestrict(restrict, name) {
  7104. if (restrict && !(isString(restrict) && /[EACM]/.test(restrict))) {
  7105. throw $compileMinErr('badrestrict',
  7106. 'Restrict property \'{0}\' of directive \'{1}\' is invalid',
  7107. restrict,
  7108. name);
  7109. }
  7110. return restrict || 'EA';
  7111. }
  7112. /**
  7113. * @ngdoc method
  7114. * @name $compileProvider#directive
  7115. * @kind function
  7116. *
  7117. * @description
  7118. * Register a new directive with the compiler.
  7119. *
  7120. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  7121. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  7122. * names and the values are the factories.
  7123. * @param {Function|Array} directiveFactory An injectable directive factory function. See the
  7124. * {@link guide/directive directive guide} and the {@link $compile compile API} for more info.
  7125. * @returns {ng.$compileProvider} Self for chaining.
  7126. */
  7127. this.directive = function registerDirective(name, directiveFactory) {
  7128. assertArg(name, 'name');
  7129. assertNotHasOwnProperty(name, 'directive');
  7130. if (isString(name)) {
  7131. assertValidDirectiveName(name);
  7132. assertArg(directiveFactory, 'directiveFactory');
  7133. if (!hasDirectives.hasOwnProperty(name)) {
  7134. hasDirectives[name] = [];
  7135. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  7136. function($injector, $exceptionHandler) {
  7137. var directives = [];
  7138. forEach(hasDirectives[name], function(directiveFactory, index) {
  7139. try {
  7140. var directive = $injector.invoke(directiveFactory);
  7141. if (isFunction(directive)) {
  7142. directive = { compile: valueFn(directive) };
  7143. } else if (!directive.compile && directive.link) {
  7144. directive.compile = valueFn(directive.link);
  7145. }
  7146. directive.priority = directive.priority || 0;
  7147. directive.index = index;
  7148. directive.name = directive.name || name;
  7149. directive.require = getDirectiveRequire(directive);
  7150. directive.restrict = getDirectiveRestrict(directive.restrict, name);
  7151. directive.$$moduleName = directiveFactory.$$moduleName;
  7152. directives.push(directive);
  7153. } catch (e) {
  7154. $exceptionHandler(e);
  7155. }
  7156. });
  7157. return directives;
  7158. }]);
  7159. }
  7160. hasDirectives[name].push(directiveFactory);
  7161. } else {
  7162. forEach(name, reverseParams(registerDirective));
  7163. }
  7164. return this;
  7165. };
  7166. /**
  7167. * @ngdoc method
  7168. * @name $compileProvider#component
  7169. * @module ng
  7170. * @param {string} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`)
  7171. * @param {Object} options Component definition object (a simplified
  7172. * {@link ng.$compile#directive-definition-object directive definition object}),
  7173. * with the following properties (all optional):
  7174. *
  7175. * - `controller` – `{(string|function()=}` – controller constructor function that should be
  7176. * associated with newly created scope or the name of a {@link ng.$compile#-controller-
  7177. * registered controller} if passed as a string. An empty `noop` function by default.
  7178. * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope.
  7179. * If present, the controller will be published to scope under the `controllerAs` name.
  7180. * If not present, this will default to be `$ctrl`.
  7181. * - `template` – `{string=|function()=}` – html template as a string or a function that
  7182. * returns an html template as a string which should be used as the contents of this component.
  7183. * Empty string by default.
  7184. *
  7185. * If `template` is a function, then it is {@link auto.$injector#invoke injected} with
  7186. * the following locals:
  7187. *
  7188. * - `$element` - Current element
  7189. * - `$attrs` - Current attributes object for the element
  7190. *
  7191. * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
  7192. * template that should be used as the contents of this component.
  7193. *
  7194. * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
  7195. * the following locals:
  7196. *
  7197. * - `$element` - Current element
  7198. * - `$attrs` - Current attributes object for the element
  7199. *
  7200. * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties.
  7201. * Component properties are always bound to the component controller and not to the scope.
  7202. * See {@link ng.$compile#-bindtocontroller- `bindToController`}.
  7203. * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled.
  7204. * Disabled by default.
  7205. * - `require` - `{Object<string, string>=}` - requires the controllers of other directives and binds them to
  7206. * this component's controller. The object keys specify the property names under which the required
  7207. * controllers (object values) will be bound. See {@link ng.$compile#-require- `require`}.
  7208. * - `$...` – additional properties to attach to the directive factory function and the controller
  7209. * constructor function. (This is used by the component router to annotate)
  7210. *
  7211. * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls.
  7212. * @description
  7213. * Register a **component definition** with the compiler. This is a shorthand for registering a special
  7214. * type of directive, which represents a self-contained UI component in your application. Such components
  7215. * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`).
  7216. *
  7217. * Component definitions are very simple and do not require as much configuration as defining general
  7218. * directives. Component definitions usually consist only of a template and a controller backing it.
  7219. *
  7220. * In order to make the definition easier, components enforce best practices like use of `controllerAs`,
  7221. * `bindToController`. They always have **isolate scope** and are restricted to elements.
  7222. *
  7223. * Here are a few examples of how you would usually define components:
  7224. *
  7225. * ```js
  7226. * var myMod = angular.module(...);
  7227. * myMod.component('myComp', {
  7228. * template: '<div>My name is {{$ctrl.name}}</div>',
  7229. * controller: function() {
  7230. * this.name = 'shahar';
  7231. * }
  7232. * });
  7233. *
  7234. * myMod.component('myComp', {
  7235. * template: '<div>My name is {{$ctrl.name}}</div>',
  7236. * bindings: {name: '@'}
  7237. * });
  7238. *
  7239. * myMod.component('myComp', {
  7240. * templateUrl: 'views/my-comp.html',
  7241. * controller: 'MyCtrl',
  7242. * controllerAs: 'ctrl',
  7243. * bindings: {name: '@'}
  7244. * });
  7245. *
  7246. * ```
  7247. * For more examples, and an in-depth guide, see the {@link guide/component component guide}.
  7248. *
  7249. * <br />
  7250. * See also {@link ng.$compileProvider#directive $compileProvider.directive()}.
  7251. */
  7252. this.component = function registerComponent(name, options) {
  7253. var controller = options.controller || function() {};
  7254. function factory($injector) {
  7255. function makeInjectable(fn) {
  7256. if (isFunction(fn) || isArray(fn)) {
  7257. return /** @this */ function(tElement, tAttrs) {
  7258. return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
  7259. };
  7260. } else {
  7261. return fn;
  7262. }
  7263. }
  7264. var template = (!options.template && !options.templateUrl ? '' : options.template);
  7265. var ddo = {
  7266. controller: controller,
  7267. controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',
  7268. template: makeInjectable(template),
  7269. templateUrl: makeInjectable(options.templateUrl),
  7270. transclude: options.transclude,
  7271. scope: {},
  7272. bindToController: options.bindings || {},
  7273. restrict: 'E',
  7274. require: options.require
  7275. };
  7276. // Copy annotations (starting with $) over to the DDO
  7277. forEach(options, function(val, key) {
  7278. if (key.charAt(0) === '$') ddo[key] = val;
  7279. });
  7280. return ddo;
  7281. }
  7282. // TODO(pete) remove the following `forEach` before we release 1.6.0
  7283. // The component-router@0.2.0 looks for the annotations on the controller constructor
  7284. // Nothing in Angular looks for annotations on the factory function but we can't remove
  7285. // it from 1.5.x yet.
  7286. // Copy any annotation properties (starting with $) over to the factory and controller constructor functions
  7287. // These could be used by libraries such as the new component router
  7288. forEach(options, function(val, key) {
  7289. if (key.charAt(0) === '$') {
  7290. factory[key] = val;
  7291. // Don't try to copy over annotations to named controller
  7292. if (isFunction(controller)) controller[key] = val;
  7293. }
  7294. });
  7295. factory.$inject = ['$injector'];
  7296. return this.directive(name, factory);
  7297. };
  7298. /**
  7299. * @ngdoc method
  7300. * @name $compileProvider#aHrefSanitizationWhitelist
  7301. * @kind function
  7302. *
  7303. * @description
  7304. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  7305. * urls during a[href] sanitization.
  7306. *
  7307. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  7308. *
  7309. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  7310. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  7311. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  7312. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  7313. *
  7314. * @param {RegExp=} regexp New regexp to whitelist urls with.
  7315. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  7316. * chaining otherwise.
  7317. */
  7318. this.aHrefSanitizationWhitelist = function(regexp) {
  7319. if (isDefined(regexp)) {
  7320. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  7321. return this;
  7322. } else {
  7323. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  7324. }
  7325. };
  7326. /**
  7327. * @ngdoc method
  7328. * @name $compileProvider#imgSrcSanitizationWhitelist
  7329. * @kind function
  7330. *
  7331. * @description
  7332. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  7333. * urls during img[src] sanitization.
  7334. *
  7335. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  7336. *
  7337. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  7338. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  7339. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  7340. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  7341. *
  7342. * @param {RegExp=} regexp New regexp to whitelist urls with.
  7343. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  7344. * chaining otherwise.
  7345. */
  7346. this.imgSrcSanitizationWhitelist = function(regexp) {
  7347. if (isDefined(regexp)) {
  7348. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  7349. return this;
  7350. } else {
  7351. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  7352. }
  7353. };
  7354. /**
  7355. * @ngdoc method
  7356. * @name $compileProvider#debugInfoEnabled
  7357. *
  7358. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  7359. * current debugInfoEnabled state
  7360. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  7361. *
  7362. * @kind function
  7363. *
  7364. * @description
  7365. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  7366. * binding information and a reference to the current scope on to DOM elements.
  7367. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  7368. * * `ng-binding` CSS class
  7369. * * `$binding` data property containing an array of the binding expressions
  7370. *
  7371. * You may want to disable this in production for a significant performance boost. See
  7372. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  7373. *
  7374. * The default value is true.
  7375. */
  7376. var debugInfoEnabled = true;
  7377. this.debugInfoEnabled = function(enabled) {
  7378. if (isDefined(enabled)) {
  7379. debugInfoEnabled = enabled;
  7380. return this;
  7381. }
  7382. return debugInfoEnabled;
  7383. };
  7384. /**
  7385. * @ngdoc method
  7386. * @name $compileProvider#preAssignBindingsEnabled
  7387. *
  7388. * @param {boolean=} enabled update the preAssignBindingsEnabled state if provided, otherwise just return the
  7389. * current preAssignBindingsEnabled state
  7390. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  7391. *
  7392. * @kind function
  7393. *
  7394. * @description
  7395. * Call this method to enable/disable whether directive controllers are assigned bindings before
  7396. * calling the controller's constructor.
  7397. * If enabled (true), the compiler assigns the value of each of the bindings to the
  7398. * properties of the controller object before the constructor of this object is called.
  7399. *
  7400. * If disabled (false), the compiler calls the constructor first before assigning bindings.
  7401. *
  7402. * The default value is true in Angular 1.5.x but will switch to false in Angular 1.6.x.
  7403. */
  7404. var preAssignBindingsEnabled = true;
  7405. this.preAssignBindingsEnabled = function(enabled) {
  7406. if (isDefined(enabled)) {
  7407. preAssignBindingsEnabled = enabled;
  7408. return this;
  7409. }
  7410. return preAssignBindingsEnabled;
  7411. };
  7412. var TTL = 10;
  7413. /**
  7414. * @ngdoc method
  7415. * @name $compileProvider#onChangesTtl
  7416. * @description
  7417. *
  7418. * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and
  7419. * assuming that the model is unstable.
  7420. *
  7421. * The current default is 10 iterations.
  7422. *
  7423. * In complex applications it's possible that dependencies between `$onChanges` hooks and bindings will result
  7424. * in several iterations of calls to these hooks. However if an application needs more than the default 10
  7425. * iterations to stabilize then you should investigate what is causing the model to continuously change during
  7426. * the `$onChanges` hook execution.
  7427. *
  7428. * Increasing the TTL could have performance implications, so you should not change it without proper justification.
  7429. *
  7430. * @param {number} limit The number of `$onChanges` hook iterations.
  7431. * @returns {number|object} the current limit (or `this` if called as a setter for chaining)
  7432. */
  7433. this.onChangesTtl = function(value) {
  7434. if (arguments.length) {
  7435. TTL = value;
  7436. return this;
  7437. }
  7438. return TTL;
  7439. };
  7440. var commentDirectivesEnabledConfig = true;
  7441. /**
  7442. * @ngdoc method
  7443. * @name $compileProvider#commentDirectivesEnabled
  7444. * @description
  7445. *
  7446. * It indicates to the compiler
  7447. * whether or not directives on comments should be compiled.
  7448. * Defaults to `true`.
  7449. *
  7450. * Calling this function with false disables the compilation of directives
  7451. * on comments for the whole application.
  7452. * This results in a compilation performance gain,
  7453. * as the compiler doesn't have to check comments when looking for directives.
  7454. * This should however only be used if you are sure that no comment directives are used in
  7455. * the application (including any 3rd party directives).
  7456. *
  7457. * @param {boolean} enabled `false` if the compiler may ignore directives on comments
  7458. * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
  7459. */
  7460. this.commentDirectivesEnabled = function(value) {
  7461. if (arguments.length) {
  7462. commentDirectivesEnabledConfig = value;
  7463. return this;
  7464. }
  7465. return commentDirectivesEnabledConfig;
  7466. };
  7467. var cssClassDirectivesEnabledConfig = true;
  7468. /**
  7469. * @ngdoc method
  7470. * @name $compileProvider#cssClassDirectivesEnabled
  7471. * @description
  7472. *
  7473. * It indicates to the compiler
  7474. * whether or not directives on element classes should be compiled.
  7475. * Defaults to `true`.
  7476. *
  7477. * Calling this function with false disables the compilation of directives
  7478. * on element classes for the whole application.
  7479. * This results in a compilation performance gain,
  7480. * as the compiler doesn't have to check element classes when looking for directives.
  7481. * This should however only be used if you are sure that no class directives are used in
  7482. * the application (including any 3rd party directives).
  7483. *
  7484. * @param {boolean} enabled `false` if the compiler may ignore directives on element classes
  7485. * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
  7486. */
  7487. this.cssClassDirectivesEnabled = function(value) {
  7488. if (arguments.length) {
  7489. cssClassDirectivesEnabledConfig = value;
  7490. return this;
  7491. }
  7492. return cssClassDirectivesEnabledConfig;
  7493. };
  7494. this.$get = [
  7495. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  7496. '$controller', '$rootScope', '$sce', '$animate', '$$sanitizeUri',
  7497. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  7498. $controller, $rootScope, $sce, $animate, $$sanitizeUri) {
  7499. var SIMPLE_ATTR_NAME = /^\w/;
  7500. var specialAttrHolder = window.document.createElement('div');
  7501. var commentDirectivesEnabled = commentDirectivesEnabledConfig;
  7502. var cssClassDirectivesEnabled = cssClassDirectivesEnabledConfig;
  7503. var onChangesTtl = TTL;
  7504. // The onChanges hooks should all be run together in a single digest
  7505. // When changes occur, the call to trigger their hooks will be added to this queue
  7506. var onChangesQueue;
  7507. // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest
  7508. function flushOnChangesQueue() {
  7509. try {
  7510. if (!(--onChangesTtl)) {
  7511. // We have hit the TTL limit so reset everything
  7512. onChangesQueue = undefined;
  7513. throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\n', TTL);
  7514. }
  7515. // We must run this hook in an apply since the $$postDigest runs outside apply
  7516. $rootScope.$apply(function() {
  7517. var errors = [];
  7518. for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) {
  7519. try {
  7520. onChangesQueue[i]();
  7521. } catch (e) {
  7522. errors.push(e);
  7523. }
  7524. }
  7525. // Reset the queue to trigger a new schedule next time there is a change
  7526. onChangesQueue = undefined;
  7527. if (errors.length) {
  7528. throw errors;
  7529. }
  7530. });
  7531. } finally {
  7532. onChangesTtl++;
  7533. }
  7534. }
  7535. function Attributes(element, attributesToCopy) {
  7536. if (attributesToCopy) {
  7537. var keys = Object.keys(attributesToCopy);
  7538. var i, l, key;
  7539. for (i = 0, l = keys.length; i < l; i++) {
  7540. key = keys[i];
  7541. this[key] = attributesToCopy[key];
  7542. }
  7543. } else {
  7544. this.$attr = {};
  7545. }
  7546. this.$$element = element;
  7547. }
  7548. Attributes.prototype = {
  7549. /**
  7550. * @ngdoc method
  7551. * @name $compile.directive.Attributes#$normalize
  7552. * @kind function
  7553. *
  7554. * @description
  7555. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  7556. * `data-`) to its normalized, camelCase form.
  7557. *
  7558. * Also there is special case for Moz prefix starting with upper case letter.
  7559. *
  7560. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  7561. *
  7562. * @param {string} name Name to normalize
  7563. */
  7564. $normalize: directiveNormalize,
  7565. /**
  7566. * @ngdoc method
  7567. * @name $compile.directive.Attributes#$addClass
  7568. * @kind function
  7569. *
  7570. * @description
  7571. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  7572. * are enabled then an animation will be triggered for the class addition.
  7573. *
  7574. * @param {string} classVal The className value that will be added to the element
  7575. */
  7576. $addClass: function(classVal) {
  7577. if (classVal && classVal.length > 0) {
  7578. $animate.addClass(this.$$element, classVal);
  7579. }
  7580. },
  7581. /**
  7582. * @ngdoc method
  7583. * @name $compile.directive.Attributes#$removeClass
  7584. * @kind function
  7585. *
  7586. * @description
  7587. * Removes the CSS class value specified by the classVal parameter from the element. If
  7588. * animations are enabled then an animation will be triggered for the class removal.
  7589. *
  7590. * @param {string} classVal The className value that will be removed from the element
  7591. */
  7592. $removeClass: function(classVal) {
  7593. if (classVal && classVal.length > 0) {
  7594. $animate.removeClass(this.$$element, classVal);
  7595. }
  7596. },
  7597. /**
  7598. * @ngdoc method
  7599. * @name $compile.directive.Attributes#$updateClass
  7600. * @kind function
  7601. *
  7602. * @description
  7603. * Adds and removes the appropriate CSS class values to the element based on the difference
  7604. * between the new and old CSS class values (specified as newClasses and oldClasses).
  7605. *
  7606. * @param {string} newClasses The current CSS className value
  7607. * @param {string} oldClasses The former CSS className value
  7608. */
  7609. $updateClass: function(newClasses, oldClasses) {
  7610. var toAdd = tokenDifference(newClasses, oldClasses);
  7611. if (toAdd && toAdd.length) {
  7612. $animate.addClass(this.$$element, toAdd);
  7613. }
  7614. var toRemove = tokenDifference(oldClasses, newClasses);
  7615. if (toRemove && toRemove.length) {
  7616. $animate.removeClass(this.$$element, toRemove);
  7617. }
  7618. },
  7619. /**
  7620. * Set a normalized attribute on the element in a way such that all directives
  7621. * can share the attribute. This function properly handles boolean attributes.
  7622. * @param {string} key Normalized key. (ie ngAttribute)
  7623. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  7624. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  7625. * Defaults to true.
  7626. * @param {string=} attrName Optional none normalized name. Defaults to key.
  7627. */
  7628. $set: function(key, value, writeAttr, attrName) {
  7629. // TODO: decide whether or not to throw an error if "class"
  7630. //is set through this function since it may cause $updateClass to
  7631. //become unstable.
  7632. var node = this.$$element[0],
  7633. booleanKey = getBooleanAttrName(node, key),
  7634. aliasedKey = getAliasedAttrName(key),
  7635. observer = key,
  7636. nodeName;
  7637. if (booleanKey) {
  7638. this.$$element.prop(key, value);
  7639. attrName = booleanKey;
  7640. } else if (aliasedKey) {
  7641. this[aliasedKey] = value;
  7642. observer = aliasedKey;
  7643. }
  7644. this[key] = value;
  7645. // translate normalized key to actual key
  7646. if (attrName) {
  7647. this.$attr[key] = attrName;
  7648. } else {
  7649. attrName = this.$attr[key];
  7650. if (!attrName) {
  7651. this.$attr[key] = attrName = snake_case(key, '-');
  7652. }
  7653. }
  7654. nodeName = nodeName_(this.$$element);
  7655. if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) ||
  7656. (nodeName === 'img' && key === 'src')) {
  7657. // sanitize a[href] and img[src] values
  7658. this[key] = value = $$sanitizeUri(value, key === 'src');
  7659. } else if (nodeName === 'img' && key === 'srcset' && isDefined(value)) {
  7660. // sanitize img[srcset] values
  7661. var result = '';
  7662. // first check if there are spaces because it's not the same pattern
  7663. var trimmedSrcset = trim(value);
  7664. // ( 999x ,| 999w ,| ,|, )
  7665. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  7666. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  7667. // split srcset into tuple of uri and descriptor except for the last item
  7668. var rawUris = trimmedSrcset.split(pattern);
  7669. // for each tuples
  7670. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  7671. for (var i = 0; i < nbrUrisWith2parts; i++) {
  7672. var innerIdx = i * 2;
  7673. // sanitize the uri
  7674. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  7675. // add the descriptor
  7676. result += (' ' + trim(rawUris[innerIdx + 1]));
  7677. }
  7678. // split the last item into uri and descriptor
  7679. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  7680. // sanitize the last uri
  7681. result += $$sanitizeUri(trim(lastTuple[0]), true);
  7682. // and add the last descriptor if any
  7683. if (lastTuple.length === 2) {
  7684. result += (' ' + trim(lastTuple[1]));
  7685. }
  7686. this[key] = value = result;
  7687. }
  7688. if (writeAttr !== false) {
  7689. if (value === null || isUndefined(value)) {
  7690. this.$$element.removeAttr(attrName);
  7691. } else {
  7692. if (SIMPLE_ATTR_NAME.test(attrName)) {
  7693. this.$$element.attr(attrName, value);
  7694. } else {
  7695. setSpecialAttr(this.$$element[0], attrName, value);
  7696. }
  7697. }
  7698. }
  7699. // fire observers
  7700. var $$observers = this.$$observers;
  7701. if ($$observers) {
  7702. forEach($$observers[observer], function(fn) {
  7703. try {
  7704. fn(value);
  7705. } catch (e) {
  7706. $exceptionHandler(e);
  7707. }
  7708. });
  7709. }
  7710. },
  7711. /**
  7712. * @ngdoc method
  7713. * @name $compile.directive.Attributes#$observe
  7714. * @kind function
  7715. *
  7716. * @description
  7717. * Observes an interpolated attribute.
  7718. *
  7719. * The observer function will be invoked once during the next `$digest` following
  7720. * compilation. The observer is then invoked whenever the interpolated value
  7721. * changes.
  7722. *
  7723. * @param {string} key Normalized key. (ie ngAttribute) .
  7724. * @param {function(interpolatedValue)} fn Function that will be called whenever
  7725. the interpolated value of the attribute changes.
  7726. * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation
  7727. * guide} for more info.
  7728. * @returns {function()} Returns a deregistration function for this observer.
  7729. */
  7730. $observe: function(key, fn) {
  7731. var attrs = this,
  7732. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  7733. listeners = ($$observers[key] || ($$observers[key] = []));
  7734. listeners.push(fn);
  7735. $rootScope.$evalAsync(function() {
  7736. if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
  7737. // no one registered attribute interpolation function, so lets call it manually
  7738. fn(attrs[key]);
  7739. }
  7740. });
  7741. return function() {
  7742. arrayRemove(listeners, fn);
  7743. };
  7744. }
  7745. };
  7746. function setSpecialAttr(element, attrName, value) {
  7747. // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute`
  7748. // so we have to jump through some hoops to get such an attribute
  7749. // https://github.com/angular/angular.js/pull/13318
  7750. specialAttrHolder.innerHTML = '<span ' + attrName + '>';
  7751. var attributes = specialAttrHolder.firstChild.attributes;
  7752. var attribute = attributes[0];
  7753. // We have to remove the attribute from its container element before we can add it to the destination element
  7754. attributes.removeNamedItem(attribute.name);
  7755. attribute.value = value;
  7756. element.attributes.setNamedItem(attribute);
  7757. }
  7758. function safeAddClass($element, className) {
  7759. try {
  7760. $element.addClass(className);
  7761. } catch (e) {
  7762. // ignore, since it means that we are trying to set class on
  7763. // SVG element, where class name is read-only.
  7764. }
  7765. }
  7766. var startSymbol = $interpolate.startSymbol(),
  7767. endSymbol = $interpolate.endSymbol(),
  7768. denormalizeTemplate = (startSymbol === '{{' && endSymbol === '}}')
  7769. ? identity
  7770. : function denormalizeTemplate(template) {
  7771. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  7772. },
  7773. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  7774. var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
  7775. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  7776. var bindings = $element.data('$binding') || [];
  7777. if (isArray(binding)) {
  7778. bindings = bindings.concat(binding);
  7779. } else {
  7780. bindings.push(binding);
  7781. }
  7782. $element.data('$binding', bindings);
  7783. } : noop;
  7784. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  7785. safeAddClass($element, 'ng-binding');
  7786. } : noop;
  7787. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  7788. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  7789. $element.data(dataName, scope);
  7790. } : noop;
  7791. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  7792. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  7793. } : noop;
  7794. compile.$$createComment = function(directiveName, comment) {
  7795. var content = '';
  7796. if (debugInfoEnabled) {
  7797. content = ' ' + (directiveName || '') + ': ';
  7798. if (comment) content += comment + ' ';
  7799. }
  7800. return window.document.createComment(content);
  7801. };
  7802. return compile;
  7803. //================================
  7804. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  7805. previousCompileContext) {
  7806. if (!($compileNodes instanceof jqLite)) {
  7807. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  7808. // modify it.
  7809. $compileNodes = jqLite($compileNodes);
  7810. }
  7811. var compositeLinkFn =
  7812. compileNodes($compileNodes, transcludeFn, $compileNodes,
  7813. maxPriority, ignoreDirective, previousCompileContext);
  7814. compile.$$addScopeClass($compileNodes);
  7815. var namespace = null;
  7816. return function publicLinkFn(scope, cloneConnectFn, options) {
  7817. if (!$compileNodes) {
  7818. throw $compileMinErr('multilink', 'This element has already been linked.');
  7819. }
  7820. assertArg(scope, 'scope');
  7821. if (previousCompileContext && previousCompileContext.needsNewScope) {
  7822. // A parent directive did a replace and a directive on this element asked
  7823. // for transclusion, which caused us to lose a layer of element on which
  7824. // we could hold the new transclusion scope, so we will create it manually
  7825. // here.
  7826. scope = scope.$parent.$new();
  7827. }
  7828. options = options || {};
  7829. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  7830. transcludeControllers = options.transcludeControllers,
  7831. futureParentElement = options.futureParentElement;
  7832. // When `parentBoundTranscludeFn` is passed, it is a
  7833. // `controllersBoundTransclude` function (it was previously passed
  7834. // as `transclude` to directive.link) so we must unwrap it to get
  7835. // its `boundTranscludeFn`
  7836. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  7837. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  7838. }
  7839. if (!namespace) {
  7840. namespace = detectNamespaceForChildElements(futureParentElement);
  7841. }
  7842. var $linkNode;
  7843. if (namespace !== 'html') {
  7844. // When using a directive with replace:true and templateUrl the $compileNodes
  7845. // (or a child element inside of them)
  7846. // might change, so we need to recreate the namespace adapted compileNodes
  7847. // for call to the link function.
  7848. // Note: This will already clone the nodes...
  7849. $linkNode = jqLite(
  7850. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  7851. );
  7852. } else if (cloneConnectFn) {
  7853. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  7854. // and sometimes changes the structure of the DOM.
  7855. $linkNode = JQLitePrototype.clone.call($compileNodes);
  7856. } else {
  7857. $linkNode = $compileNodes;
  7858. }
  7859. if (transcludeControllers) {
  7860. for (var controllerName in transcludeControllers) {
  7861. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  7862. }
  7863. }
  7864. compile.$$addScopeInfo($linkNode, scope);
  7865. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  7866. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  7867. if (!cloneConnectFn) {
  7868. $compileNodes = compositeLinkFn = null;
  7869. }
  7870. return $linkNode;
  7871. };
  7872. }
  7873. function detectNamespaceForChildElements(parentElement) {
  7874. // TODO: Make this detect MathML as well...
  7875. var node = parentElement && parentElement[0];
  7876. if (!node) {
  7877. return 'html';
  7878. } else {
  7879. return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html';
  7880. }
  7881. }
  7882. /**
  7883. * Compile function matches each node in nodeList against the directives. Once all directives
  7884. * for a particular node are collected their compile functions are executed. The compile
  7885. * functions return values - the linking functions - are combined into a composite linking
  7886. * function, which is the a linking function for the node.
  7887. *
  7888. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  7889. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  7890. * scope argument is auto-generated to the new child of the transcluded parent scope.
  7891. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  7892. * the rootElement must be set the jqLite collection of the compile root. This is
  7893. * needed so that the jqLite collection items can be replaced with widgets.
  7894. * @param {number=} maxPriority Max directive priority.
  7895. * @returns {Function} A composite linking function of all of the matched directives or null.
  7896. */
  7897. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  7898. previousCompileContext) {
  7899. var linkFns = [],
  7900. // `nodeList` can be either an element's `.childNodes` (live NodeList)
  7901. // or a jqLite/jQuery collection or an array
  7902. notLiveList = isArray(nodeList) || (nodeList instanceof jqLite),
  7903. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  7904. for (var i = 0; i < nodeList.length; i++) {
  7905. attrs = new Attributes();
  7906. // Workaround for #11781 and #14924
  7907. if (msie === 11) {
  7908. mergeConsecutiveTextNodes(nodeList, i, notLiveList);
  7909. }
  7910. // We must always refer to `nodeList[i]` hereafter,
  7911. // since the nodes can be replaced underneath us.
  7912. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  7913. ignoreDirective);
  7914. nodeLinkFn = (directives.length)
  7915. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  7916. null, [], [], previousCompileContext)
  7917. : null;
  7918. if (nodeLinkFn && nodeLinkFn.scope) {
  7919. compile.$$addScopeClass(attrs.$$element);
  7920. }
  7921. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  7922. !(childNodes = nodeList[i].childNodes) ||
  7923. !childNodes.length)
  7924. ? null
  7925. : compileNodes(childNodes,
  7926. nodeLinkFn ? (
  7927. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  7928. && nodeLinkFn.transclude) : transcludeFn);
  7929. if (nodeLinkFn || childLinkFn) {
  7930. linkFns.push(i, nodeLinkFn, childLinkFn);
  7931. linkFnFound = true;
  7932. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  7933. }
  7934. //use the previous context only for the first element in the virtual group
  7935. previousCompileContext = null;
  7936. }
  7937. // return a linking function if we have found anything, null otherwise
  7938. return linkFnFound ? compositeLinkFn : null;
  7939. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  7940. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  7941. var stableNodeList;
  7942. if (nodeLinkFnFound) {
  7943. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  7944. // offsets don't get screwed up
  7945. var nodeListLength = nodeList.length;
  7946. stableNodeList = new Array(nodeListLength);
  7947. // create a sparse array by only copying the elements which have a linkFn
  7948. for (i = 0; i < linkFns.length; i += 3) {
  7949. idx = linkFns[i];
  7950. stableNodeList[idx] = nodeList[idx];
  7951. }
  7952. } else {
  7953. stableNodeList = nodeList;
  7954. }
  7955. for (i = 0, ii = linkFns.length; i < ii;) {
  7956. node = stableNodeList[linkFns[i++]];
  7957. nodeLinkFn = linkFns[i++];
  7958. childLinkFn = linkFns[i++];
  7959. if (nodeLinkFn) {
  7960. if (nodeLinkFn.scope) {
  7961. childScope = scope.$new();
  7962. compile.$$addScopeInfo(jqLite(node), childScope);
  7963. } else {
  7964. childScope = scope;
  7965. }
  7966. if (nodeLinkFn.transcludeOnThisElement) {
  7967. childBoundTranscludeFn = createBoundTranscludeFn(
  7968. scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  7969. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  7970. childBoundTranscludeFn = parentBoundTranscludeFn;
  7971. } else if (!parentBoundTranscludeFn && transcludeFn) {
  7972. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  7973. } else {
  7974. childBoundTranscludeFn = null;
  7975. }
  7976. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  7977. } else if (childLinkFn) {
  7978. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  7979. }
  7980. }
  7981. }
  7982. }
  7983. function mergeConsecutiveTextNodes(nodeList, idx, notLiveList) {
  7984. var node = nodeList[idx];
  7985. var parent = node.parentNode;
  7986. var sibling;
  7987. if (node.nodeType !== NODE_TYPE_TEXT) {
  7988. return;
  7989. }
  7990. while (true) {
  7991. sibling = parent ? node.nextSibling : nodeList[idx + 1];
  7992. if (!sibling || sibling.nodeType !== NODE_TYPE_TEXT) {
  7993. break;
  7994. }
  7995. node.nodeValue = node.nodeValue + sibling.nodeValue;
  7996. if (sibling.parentNode) {
  7997. sibling.parentNode.removeChild(sibling);
  7998. }
  7999. if (notLiveList && sibling === nodeList[idx + 1]) {
  8000. nodeList.splice(idx + 1, 1);
  8001. }
  8002. }
  8003. }
  8004. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  8005. function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  8006. if (!transcludedScope) {
  8007. transcludedScope = scope.$new(false, containingScope);
  8008. transcludedScope.$$transcluded = true;
  8009. }
  8010. return transcludeFn(transcludedScope, cloneFn, {
  8011. parentBoundTranscludeFn: previousBoundTranscludeFn,
  8012. transcludeControllers: controllers,
  8013. futureParentElement: futureParentElement
  8014. });
  8015. }
  8016. // We need to attach the transclusion slots onto the `boundTranscludeFn`
  8017. // so that they are available inside the `controllersBoundTransclude` function
  8018. var boundSlots = boundTranscludeFn.$$slots = createMap();
  8019. for (var slotName in transcludeFn.$$slots) {
  8020. if (transcludeFn.$$slots[slotName]) {
  8021. boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);
  8022. } else {
  8023. boundSlots[slotName] = null;
  8024. }
  8025. }
  8026. return boundTranscludeFn;
  8027. }
  8028. /**
  8029. * Looks for directives on the given node and adds them to the directive collection which is
  8030. * sorted.
  8031. *
  8032. * @param node Node to search.
  8033. * @param directives An array to which the directives are added to. This array is sorted before
  8034. * the function returns.
  8035. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  8036. * @param {number=} maxPriority Max directive priority.
  8037. */
  8038. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  8039. var nodeType = node.nodeType,
  8040. attrsMap = attrs.$attr,
  8041. match,
  8042. className;
  8043. switch (nodeType) {
  8044. case NODE_TYPE_ELEMENT: /* Element */
  8045. // use the node name: <directive>
  8046. addDirective(directives,
  8047. directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
  8048. // iterate over the attributes
  8049. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  8050. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  8051. var attrStartName = false;
  8052. var attrEndName = false;
  8053. attr = nAttrs[j];
  8054. name = attr.name;
  8055. value = attr.value;
  8056. // support ngAttr attribute binding
  8057. ngAttrName = directiveNormalize(name);
  8058. isNgAttr = NG_ATTR_BINDING.test(ngAttrName);
  8059. if (isNgAttr) {
  8060. name = name.replace(PREFIX_REGEXP, '')
  8061. .substr(8).replace(/_(.)/g, function(match, letter) {
  8062. return letter.toUpperCase();
  8063. });
  8064. }
  8065. var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);
  8066. if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {
  8067. attrStartName = name;
  8068. attrEndName = name.substr(0, name.length - 5) + 'end';
  8069. name = name.substr(0, name.length - 6);
  8070. }
  8071. nName = directiveNormalize(name.toLowerCase());
  8072. attrsMap[nName] = name;
  8073. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  8074. attrs[nName] = value;
  8075. if (getBooleanAttrName(node, nName)) {
  8076. attrs[nName] = true; // presence means true
  8077. }
  8078. }
  8079. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  8080. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  8081. attrEndName);
  8082. }
  8083. // use class as directive
  8084. if (!cssClassDirectivesEnabled) break;
  8085. className = node.className;
  8086. if (isObject(className)) {
  8087. // Maybe SVGAnimatedString
  8088. className = className.animVal;
  8089. }
  8090. if (isString(className) && className !== '') {
  8091. while ((match = CLASS_DIRECTIVE_REGEXP.exec(className))) {
  8092. nName = directiveNormalize(match[2]);
  8093. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  8094. attrs[nName] = trim(match[3]);
  8095. }
  8096. className = className.substr(match.index + match[0].length);
  8097. }
  8098. }
  8099. break;
  8100. case NODE_TYPE_TEXT: /* Text Node */
  8101. addTextInterpolateDirective(directives, node.nodeValue);
  8102. break;
  8103. case NODE_TYPE_COMMENT: /* Comment */
  8104. if (!commentDirectivesEnabled) break;
  8105. collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective);
  8106. break;
  8107. }
  8108. directives.sort(byPriority);
  8109. return directives;
  8110. }
  8111. function collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  8112. // function created because of performance, try/catch disables
  8113. // the optimization of the whole function #14848
  8114. try {
  8115. var match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  8116. if (match) {
  8117. var nName = directiveNormalize(match[1]);
  8118. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  8119. attrs[nName] = trim(match[2]);
  8120. }
  8121. }
  8122. } catch (e) {
  8123. // turns out that under some circumstances IE9 throws errors when one attempts to read
  8124. // comment's node value.
  8125. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  8126. }
  8127. }
  8128. /**
  8129. * Given a node with an directive-start it collects all of the siblings until it finds
  8130. * directive-end.
  8131. * @param node
  8132. * @param attrStart
  8133. * @param attrEnd
  8134. * @returns {*}
  8135. */
  8136. function groupScan(node, attrStart, attrEnd) {
  8137. var nodes = [];
  8138. var depth = 0;
  8139. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  8140. do {
  8141. if (!node) {
  8142. throw $compileMinErr('uterdir',
  8143. 'Unterminated attribute, found \'{0}\' but no matching \'{1}\' found.',
  8144. attrStart, attrEnd);
  8145. }
  8146. if (node.nodeType === NODE_TYPE_ELEMENT) {
  8147. if (node.hasAttribute(attrStart)) depth++;
  8148. if (node.hasAttribute(attrEnd)) depth--;
  8149. }
  8150. nodes.push(node);
  8151. node = node.nextSibling;
  8152. } while (depth > 0);
  8153. } else {
  8154. nodes.push(node);
  8155. }
  8156. return jqLite(nodes);
  8157. }
  8158. /**
  8159. * Wrapper for linking function which converts normal linking function into a grouped
  8160. * linking function.
  8161. * @param linkFn
  8162. * @param attrStart
  8163. * @param attrEnd
  8164. * @returns {Function}
  8165. */
  8166. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  8167. return function groupedElementsLink(scope, element, attrs, controllers, transcludeFn) {
  8168. element = groupScan(element[0], attrStart, attrEnd);
  8169. return linkFn(scope, element, attrs, controllers, transcludeFn);
  8170. };
  8171. }
  8172. /**
  8173. * A function generator that is used to support both eager and lazy compilation
  8174. * linking function.
  8175. * @param eager
  8176. * @param $compileNodes
  8177. * @param transcludeFn
  8178. * @param maxPriority
  8179. * @param ignoreDirective
  8180. * @param previousCompileContext
  8181. * @returns {Function}
  8182. */
  8183. function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
  8184. var compiled;
  8185. if (eager) {
  8186. return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  8187. }
  8188. return /** @this */ function lazyCompilation() {
  8189. if (!compiled) {
  8190. compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  8191. // Null out all of these references in order to make them eligible for garbage collection
  8192. // since this is a potentially long lived closure
  8193. $compileNodes = transcludeFn = previousCompileContext = null;
  8194. }
  8195. return compiled.apply(this, arguments);
  8196. };
  8197. }
  8198. /**
  8199. * Once the directives have been collected, their compile functions are executed. This method
  8200. * is responsible for inlining directive templates as well as terminating the application
  8201. * of the directives if the terminal directive has been reached.
  8202. *
  8203. * @param {Array} directives Array of collected directives to execute their compile function.
  8204. * this needs to be pre-sorted by priority order.
  8205. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  8206. * @param {Object} templateAttrs The shared attribute function
  8207. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  8208. * scope argument is auto-generated to the new
  8209. * child of the transcluded parent scope.
  8210. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  8211. * argument has the root jqLite array so that we can replace nodes
  8212. * on it.
  8213. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  8214. * compiling the transclusion.
  8215. * @param {Array.<Function>} preLinkFns
  8216. * @param {Array.<Function>} postLinkFns
  8217. * @param {Object} previousCompileContext Context used for previous compilation of the current
  8218. * node
  8219. * @returns {Function} linkFn
  8220. */
  8221. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  8222. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  8223. previousCompileContext) {
  8224. previousCompileContext = previousCompileContext || {};
  8225. var terminalPriority = -Number.MAX_VALUE,
  8226. newScopeDirective = previousCompileContext.newScopeDirective,
  8227. controllerDirectives = previousCompileContext.controllerDirectives,
  8228. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  8229. templateDirective = previousCompileContext.templateDirective,
  8230. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  8231. hasTranscludeDirective = false,
  8232. hasTemplate = false,
  8233. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  8234. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  8235. directive,
  8236. directiveName,
  8237. $template,
  8238. replaceDirective = originalReplaceDirective,
  8239. childTranscludeFn = transcludeFn,
  8240. linkFn,
  8241. didScanForMultipleTransclusion = false,
  8242. mightHaveMultipleTransclusionError = false,
  8243. directiveValue;
  8244. // executes all directives on the current element
  8245. for (var i = 0, ii = directives.length; i < ii; i++) {
  8246. directive = directives[i];
  8247. var attrStart = directive.$$start;
  8248. var attrEnd = directive.$$end;
  8249. // collect multiblock sections
  8250. if (attrStart) {
  8251. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  8252. }
  8253. $template = undefined;
  8254. if (terminalPriority > directive.priority) {
  8255. break; // prevent further processing of directives
  8256. }
  8257. directiveValue = directive.scope;
  8258. if (directiveValue) {
  8259. // skip the check for directives with async templates, we'll check the derived sync
  8260. // directive when the template arrives
  8261. if (!directive.templateUrl) {
  8262. if (isObject(directiveValue)) {
  8263. // This directive is trying to add an isolated scope.
  8264. // Check that there is no scope of any kind already
  8265. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  8266. directive, $compileNode);
  8267. newIsolateScopeDirective = directive;
  8268. } else {
  8269. // This directive is trying to add a child scope.
  8270. // Check that there is no isolated scope already
  8271. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  8272. $compileNode);
  8273. }
  8274. }
  8275. newScopeDirective = newScopeDirective || directive;
  8276. }
  8277. directiveName = directive.name;
  8278. // If we encounter a condition that can result in transclusion on the directive,
  8279. // then scan ahead in the remaining directives for others that may cause a multiple
  8280. // transclusion error to be thrown during the compilation process. If a matching directive
  8281. // is found, then we know that when we encounter a transcluded directive, we need to eagerly
  8282. // compile the `transclude` function rather than doing it lazily in order to throw
  8283. // exceptions at the correct time
  8284. if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))
  8285. || (directive.transclude && !directive.$$tlb))) {
  8286. var candidateDirective;
  8287. for (var scanningIndex = i + 1; (candidateDirective = directives[scanningIndex++]);) {
  8288. if ((candidateDirective.transclude && !candidateDirective.$$tlb)
  8289. || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {
  8290. mightHaveMultipleTransclusionError = true;
  8291. break;
  8292. }
  8293. }
  8294. didScanForMultipleTransclusion = true;
  8295. }
  8296. if (!directive.templateUrl && directive.controller) {
  8297. directiveValue = directive.controller;
  8298. controllerDirectives = controllerDirectives || createMap();
  8299. assertNoDuplicate('\'' + directiveName + '\' controller',
  8300. controllerDirectives[directiveName], directive, $compileNode);
  8301. controllerDirectives[directiveName] = directive;
  8302. }
  8303. directiveValue = directive.transclude;
  8304. if (directiveValue) {
  8305. hasTranscludeDirective = true;
  8306. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  8307. // This option should only be used by directives that know how to safely handle element transclusion,
  8308. // where the transcluded nodes are added or replaced after linking.
  8309. if (!directive.$$tlb) {
  8310. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  8311. nonTlbTranscludeDirective = directive;
  8312. }
  8313. if (directiveValue === 'element') {
  8314. hasElementTranscludeDirective = true;
  8315. terminalPriority = directive.priority;
  8316. $template = $compileNode;
  8317. $compileNode = templateAttrs.$$element =
  8318. jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName]));
  8319. compileNode = $compileNode[0];
  8320. replaceWith(jqCollection, sliceArgs($template), compileNode);
  8321. // Support: Chrome < 50
  8322. // https://github.com/angular/angular.js/issues/14041
  8323. // In the versions of V8 prior to Chrome 50, the document fragment that is created
  8324. // in the `replaceWith` function is improperly garbage collected despite still
  8325. // being referenced by the `parentNode` property of all of the child nodes. By adding
  8326. // a reference to the fragment via a different property, we can avoid that incorrect
  8327. // behavior.
  8328. // TODO: remove this line after Chrome 50 has been released
  8329. $template[0].$$parentNode = $template[0].parentNode;
  8330. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
  8331. replaceDirective && replaceDirective.name, {
  8332. // Don't pass in:
  8333. // - controllerDirectives - otherwise we'll create duplicates controllers
  8334. // - newIsolateScopeDirective or templateDirective - combining templates with
  8335. // element transclusion doesn't make sense.
  8336. //
  8337. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  8338. // on the same element more than once.
  8339. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  8340. });
  8341. } else {
  8342. var slots = createMap();
  8343. if (!isObject(directiveValue)) {
  8344. $template = jqLite(jqLiteClone(compileNode)).contents();
  8345. } else {
  8346. // We have transclusion slots,
  8347. // collect them up, compile them and store their transclusion functions
  8348. $template = [];
  8349. var slotMap = createMap();
  8350. var filledSlots = createMap();
  8351. // Parse the element selectors
  8352. forEach(directiveValue, function(elementSelector, slotName) {
  8353. // If an element selector starts with a ? then it is optional
  8354. var optional = (elementSelector.charAt(0) === '?');
  8355. elementSelector = optional ? elementSelector.substring(1) : elementSelector;
  8356. slotMap[elementSelector] = slotName;
  8357. // We explicitly assign `null` since this implies that a slot was defined but not filled.
  8358. // Later when calling boundTransclusion functions with a slot name we only error if the
  8359. // slot is `undefined`
  8360. slots[slotName] = null;
  8361. // filledSlots contains `true` for all slots that are either optional or have been
  8362. // filled. This is used to check that we have not missed any required slots
  8363. filledSlots[slotName] = optional;
  8364. });
  8365. // Add the matching elements into their slot
  8366. forEach($compileNode.contents(), function(node) {
  8367. var slotName = slotMap[directiveNormalize(nodeName_(node))];
  8368. if (slotName) {
  8369. filledSlots[slotName] = true;
  8370. slots[slotName] = slots[slotName] || [];
  8371. slots[slotName].push(node);
  8372. } else {
  8373. $template.push(node);
  8374. }
  8375. });
  8376. // Check for required slots that were not filled
  8377. forEach(filledSlots, function(filled, slotName) {
  8378. if (!filled) {
  8379. throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
  8380. }
  8381. });
  8382. for (var slotName in slots) {
  8383. if (slots[slotName]) {
  8384. // Only define a transclusion function if the slot was filled
  8385. slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn);
  8386. }
  8387. }
  8388. }
  8389. $compileNode.empty(); // clear contents
  8390. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
  8391. undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
  8392. childTranscludeFn.$$slots = slots;
  8393. }
  8394. }
  8395. if (directive.template) {
  8396. hasTemplate = true;
  8397. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  8398. templateDirective = directive;
  8399. directiveValue = (isFunction(directive.template))
  8400. ? directive.template($compileNode, templateAttrs)
  8401. : directive.template;
  8402. directiveValue = denormalizeTemplate(directiveValue);
  8403. if (directive.replace) {
  8404. replaceDirective = directive;
  8405. if (jqLiteIsTextNode(directiveValue)) {
  8406. $template = [];
  8407. } else {
  8408. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  8409. }
  8410. compileNode = $template[0];
  8411. if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  8412. throw $compileMinErr('tplrt',
  8413. 'Template for directive \'{0}\' must have exactly one root element. {1}',
  8414. directiveName, '');
  8415. }
  8416. replaceWith(jqCollection, $compileNode, compileNode);
  8417. var newTemplateAttrs = {$attr: {}};
  8418. // combine directives from the original node and from the template:
  8419. // - take the array of directives for this element
  8420. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  8421. // - collect directives from the template and sort them by priority
  8422. // - combine directives as: processed + template + unprocessed
  8423. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  8424. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  8425. if (newIsolateScopeDirective || newScopeDirective) {
  8426. // The original directive caused the current element to be replaced but this element
  8427. // also needs to have a new scope, so we need to tell the template directives
  8428. // that they would need to get their scope from further up, if they require transclusion
  8429. markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
  8430. }
  8431. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  8432. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  8433. ii = directives.length;
  8434. } else {
  8435. $compileNode.html(directiveValue);
  8436. }
  8437. }
  8438. if (directive.templateUrl) {
  8439. hasTemplate = true;
  8440. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  8441. templateDirective = directive;
  8442. if (directive.replace) {
  8443. replaceDirective = directive;
  8444. }
  8445. // eslint-disable-next-line no-func-assign
  8446. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  8447. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  8448. controllerDirectives: controllerDirectives,
  8449. newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
  8450. newIsolateScopeDirective: newIsolateScopeDirective,
  8451. templateDirective: templateDirective,
  8452. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  8453. });
  8454. ii = directives.length;
  8455. } else if (directive.compile) {
  8456. try {
  8457. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  8458. var context = directive.$$originalDirective || directive;
  8459. if (isFunction(linkFn)) {
  8460. addLinkFns(null, bind(context, linkFn), attrStart, attrEnd);
  8461. } else if (linkFn) {
  8462. addLinkFns(bind(context, linkFn.pre), bind(context, linkFn.post), attrStart, attrEnd);
  8463. }
  8464. } catch (e) {
  8465. $exceptionHandler(e, startingTag($compileNode));
  8466. }
  8467. }
  8468. if (directive.terminal) {
  8469. nodeLinkFn.terminal = true;
  8470. terminalPriority = Math.max(terminalPriority, directive.priority);
  8471. }
  8472. }
  8473. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  8474. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  8475. nodeLinkFn.templateOnThisElement = hasTemplate;
  8476. nodeLinkFn.transclude = childTranscludeFn;
  8477. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  8478. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  8479. return nodeLinkFn;
  8480. ////////////////////
  8481. function addLinkFns(pre, post, attrStart, attrEnd) {
  8482. if (pre) {
  8483. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  8484. pre.require = directive.require;
  8485. pre.directiveName = directiveName;
  8486. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  8487. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  8488. }
  8489. preLinkFns.push(pre);
  8490. }
  8491. if (post) {
  8492. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  8493. post.require = directive.require;
  8494. post.directiveName = directiveName;
  8495. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  8496. post = cloneAndAnnotateFn(post, {isolateScope: true});
  8497. }
  8498. postLinkFns.push(post);
  8499. }
  8500. }
  8501. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  8502. var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
  8503. attrs, scopeBindingInfo;
  8504. if (compileNode === linkNode) {
  8505. attrs = templateAttrs;
  8506. $element = templateAttrs.$$element;
  8507. } else {
  8508. $element = jqLite(linkNode);
  8509. attrs = new Attributes($element, templateAttrs);
  8510. }
  8511. controllerScope = scope;
  8512. if (newIsolateScopeDirective) {
  8513. isolateScope = scope.$new(true);
  8514. } else if (newScopeDirective) {
  8515. controllerScope = scope.$parent;
  8516. }
  8517. if (boundTranscludeFn) {
  8518. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  8519. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  8520. transcludeFn = controllersBoundTransclude;
  8521. transcludeFn.$$boundTransclude = boundTranscludeFn;
  8522. // expose the slots on the `$transclude` function
  8523. transcludeFn.isSlotFilled = function(slotName) {
  8524. return !!boundTranscludeFn.$$slots[slotName];
  8525. };
  8526. }
  8527. if (controllerDirectives) {
  8528. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective);
  8529. }
  8530. if (newIsolateScopeDirective) {
  8531. // Initialize isolate scope bindings for new isolate scope directive.
  8532. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  8533. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  8534. compile.$$addScopeClass($element, true);
  8535. isolateScope.$$isolateBindings =
  8536. newIsolateScopeDirective.$$isolateBindings;
  8537. scopeBindingInfo = initializeDirectiveBindings(scope, attrs, isolateScope,
  8538. isolateScope.$$isolateBindings,
  8539. newIsolateScopeDirective);
  8540. if (scopeBindingInfo.removeWatches) {
  8541. isolateScope.$on('$destroy', scopeBindingInfo.removeWatches);
  8542. }
  8543. }
  8544. // Initialize bindToController bindings
  8545. for (var name in elementControllers) {
  8546. var controllerDirective = controllerDirectives[name];
  8547. var controller = elementControllers[name];
  8548. var bindings = controllerDirective.$$bindings.bindToController;
  8549. if (preAssignBindingsEnabled) {
  8550. if (controller.identifier && bindings) {
  8551. controller.bindingInfo =
  8552. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8553. } else {
  8554. controller.bindingInfo = {};
  8555. }
  8556. var controllerResult = controller();
  8557. if (controllerResult !== controller.instance) {
  8558. // If the controller constructor has a return value, overwrite the instance
  8559. // from setupControllers
  8560. controller.instance = controllerResult;
  8561. $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
  8562. if (controller.bindingInfo.removeWatches) {
  8563. controller.bindingInfo.removeWatches();
  8564. }
  8565. controller.bindingInfo =
  8566. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8567. }
  8568. } else {
  8569. controller.instance = controller();
  8570. $element.data('$' + controllerDirective.name + 'Controller', controller.instance);
  8571. controller.bindingInfo =
  8572. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8573. }
  8574. }
  8575. // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy
  8576. forEach(controllerDirectives, function(controllerDirective, name) {
  8577. var require = controllerDirective.require;
  8578. if (controllerDirective.bindToController && !isArray(require) && isObject(require)) {
  8579. extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers));
  8580. }
  8581. });
  8582. // Handle the init and destroy lifecycle hooks on all controllers that have them
  8583. forEach(elementControllers, function(controller) {
  8584. var controllerInstance = controller.instance;
  8585. if (isFunction(controllerInstance.$onChanges)) {
  8586. try {
  8587. controllerInstance.$onChanges(controller.bindingInfo.initialChanges);
  8588. } catch (e) {
  8589. $exceptionHandler(e);
  8590. }
  8591. }
  8592. if (isFunction(controllerInstance.$onInit)) {
  8593. try {
  8594. controllerInstance.$onInit();
  8595. } catch (e) {
  8596. $exceptionHandler(e);
  8597. }
  8598. }
  8599. if (isFunction(controllerInstance.$doCheck)) {
  8600. controllerScope.$watch(function() { controllerInstance.$doCheck(); });
  8601. controllerInstance.$doCheck();
  8602. }
  8603. if (isFunction(controllerInstance.$onDestroy)) {
  8604. controllerScope.$on('$destroy', function callOnDestroyHook() {
  8605. controllerInstance.$onDestroy();
  8606. });
  8607. }
  8608. });
  8609. // PRELINKING
  8610. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  8611. linkFn = preLinkFns[i];
  8612. invokeLinkFn(linkFn,
  8613. linkFn.isolateScope ? isolateScope : scope,
  8614. $element,
  8615. attrs,
  8616. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  8617. transcludeFn
  8618. );
  8619. }
  8620. // RECURSION
  8621. // We only pass the isolate scope, if the isolate directive has a template,
  8622. // otherwise the child elements do not belong to the isolate directive.
  8623. var scopeToChild = scope;
  8624. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  8625. scopeToChild = isolateScope;
  8626. }
  8627. if (childLinkFn) {
  8628. childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  8629. }
  8630. // POSTLINKING
  8631. for (i = postLinkFns.length - 1; i >= 0; i--) {
  8632. linkFn = postLinkFns[i];
  8633. invokeLinkFn(linkFn,
  8634. linkFn.isolateScope ? isolateScope : scope,
  8635. $element,
  8636. attrs,
  8637. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  8638. transcludeFn
  8639. );
  8640. }
  8641. // Trigger $postLink lifecycle hooks
  8642. forEach(elementControllers, function(controller) {
  8643. var controllerInstance = controller.instance;
  8644. if (isFunction(controllerInstance.$postLink)) {
  8645. controllerInstance.$postLink();
  8646. }
  8647. });
  8648. // This is the function that is injected as `$transclude`.
  8649. // Note: all arguments are optional!
  8650. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
  8651. var transcludeControllers;
  8652. // No scope passed in:
  8653. if (!isScope(scope)) {
  8654. slotName = futureParentElement;
  8655. futureParentElement = cloneAttachFn;
  8656. cloneAttachFn = scope;
  8657. scope = undefined;
  8658. }
  8659. if (hasElementTranscludeDirective) {
  8660. transcludeControllers = elementControllers;
  8661. }
  8662. if (!futureParentElement) {
  8663. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  8664. }
  8665. if (slotName) {
  8666. // slotTranscludeFn can be one of three things:
  8667. // * a transclude function - a filled slot
  8668. // * `null` - an optional slot that was not filled
  8669. // * `undefined` - a slot that was not declared (i.e. invalid)
  8670. var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];
  8671. if (slotTranscludeFn) {
  8672. return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  8673. } else if (isUndefined(slotTranscludeFn)) {
  8674. throw $compileMinErr('noslot',
  8675. 'No parent directive that requires a transclusion with slot name "{0}". ' +
  8676. 'Element: {1}',
  8677. slotName, startingTag($element));
  8678. }
  8679. } else {
  8680. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  8681. }
  8682. }
  8683. }
  8684. }
  8685. function getControllers(directiveName, require, $element, elementControllers) {
  8686. var value;
  8687. if (isString(require)) {
  8688. var match = require.match(REQUIRE_PREFIX_REGEXP);
  8689. var name = require.substring(match[0].length);
  8690. var inheritType = match[1] || match[3];
  8691. var optional = match[2] === '?';
  8692. //If only parents then start at the parent element
  8693. if (inheritType === '^^') {
  8694. $element = $element.parent();
  8695. //Otherwise attempt getting the controller from elementControllers in case
  8696. //the element is transcluded (and has no data) and to avoid .data if possible
  8697. } else {
  8698. value = elementControllers && elementControllers[name];
  8699. value = value && value.instance;
  8700. }
  8701. if (!value) {
  8702. var dataName = '$' + name + 'Controller';
  8703. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  8704. }
  8705. if (!value && !optional) {
  8706. throw $compileMinErr('ctreq',
  8707. 'Controller \'{0}\', required by directive \'{1}\', can\'t be found!',
  8708. name, directiveName);
  8709. }
  8710. } else if (isArray(require)) {
  8711. value = [];
  8712. for (var i = 0, ii = require.length; i < ii; i++) {
  8713. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  8714. }
  8715. } else if (isObject(require)) {
  8716. value = {};
  8717. forEach(require, function(controller, property) {
  8718. value[property] = getControllers(directiveName, controller, $element, elementControllers);
  8719. });
  8720. }
  8721. return value || null;
  8722. }
  8723. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective) {
  8724. var elementControllers = createMap();
  8725. for (var controllerKey in controllerDirectives) {
  8726. var directive = controllerDirectives[controllerKey];
  8727. var locals = {
  8728. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  8729. $element: $element,
  8730. $attrs: attrs,
  8731. $transclude: transcludeFn
  8732. };
  8733. var controller = directive.controller;
  8734. if (controller === '@') {
  8735. controller = attrs[directive.name];
  8736. }
  8737. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  8738. // For directives with element transclusion the element is a comment.
  8739. // In this case .data will not attach any data.
  8740. // Instead, we save the controllers for the element in a local hash and attach to .data
  8741. // later, once we have the actual element.
  8742. elementControllers[directive.name] = controllerInstance;
  8743. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  8744. }
  8745. return elementControllers;
  8746. }
  8747. // Depending upon the context in which a directive finds itself it might need to have a new isolated
  8748. // or child scope created. For instance:
  8749. // * if the directive has been pulled into a template because another directive with a higher priority
  8750. // asked for element transclusion
  8751. // * if the directive itself asks for transclusion but it is at the root of a template and the original
  8752. // element was replaced. See https://github.com/angular/angular.js/issues/12936
  8753. function markDirectiveScope(directives, isolateScope, newScope) {
  8754. for (var j = 0, jj = directives.length; j < jj; j++) {
  8755. directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
  8756. }
  8757. }
  8758. /**
  8759. * looks up the directive and decorates it with exception handling and proper parameters. We
  8760. * call this the boundDirective.
  8761. *
  8762. * @param {string} name name of the directive to look up.
  8763. * @param {string} location The directive must be found in specific format.
  8764. * String containing any of theses characters:
  8765. *
  8766. * * `E`: element name
  8767. * * `A': attribute
  8768. * * `C`: class
  8769. * * `M`: comment
  8770. * @returns {boolean} true if directive was added.
  8771. */
  8772. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  8773. endAttrName) {
  8774. if (name === ignoreDirective) return null;
  8775. var match = null;
  8776. if (hasDirectives.hasOwnProperty(name)) {
  8777. for (var directive, directives = $injector.get(name + Suffix),
  8778. i = 0, ii = directives.length; i < ii; i++) {
  8779. directive = directives[i];
  8780. if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
  8781. directive.restrict.indexOf(location) !== -1) {
  8782. if (startAttrName) {
  8783. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  8784. }
  8785. if (!directive.$$bindings) {
  8786. var bindings = directive.$$bindings =
  8787. parseDirectiveBindings(directive, directive.name);
  8788. if (isObject(bindings.isolateScope)) {
  8789. directive.$$isolateBindings = bindings.isolateScope;
  8790. }
  8791. }
  8792. tDirectives.push(directive);
  8793. match = directive;
  8794. }
  8795. }
  8796. }
  8797. return match;
  8798. }
  8799. /**
  8800. * looks up the directive and returns true if it is a multi-element directive,
  8801. * and therefore requires DOM nodes between -start and -end markers to be grouped
  8802. * together.
  8803. *
  8804. * @param {string} name name of the directive to look up.
  8805. * @returns true if directive was registered as multi-element.
  8806. */
  8807. function directiveIsMultiElement(name) {
  8808. if (hasDirectives.hasOwnProperty(name)) {
  8809. for (var directive, directives = $injector.get(name + Suffix),
  8810. i = 0, ii = directives.length; i < ii; i++) {
  8811. directive = directives[i];
  8812. if (directive.multiElement) {
  8813. return true;
  8814. }
  8815. }
  8816. }
  8817. return false;
  8818. }
  8819. /**
  8820. * When the element is replaced with HTML template then the new attributes
  8821. * on the template need to be merged with the existing attributes in the DOM.
  8822. * The desired effect is to have both of the attributes present.
  8823. *
  8824. * @param {object} dst destination attributes (original DOM)
  8825. * @param {object} src source attributes (from the directive template)
  8826. */
  8827. function mergeTemplateAttributes(dst, src) {
  8828. var srcAttr = src.$attr,
  8829. dstAttr = dst.$attr;
  8830. // reapply the old attributes to the new element
  8831. forEach(dst, function(value, key) {
  8832. if (key.charAt(0) !== '$') {
  8833. if (src[key] && src[key] !== value) {
  8834. if (value.length) {
  8835. value += (key === 'style' ? ';' : ' ') + src[key];
  8836. } else {
  8837. value = src[key];
  8838. }
  8839. }
  8840. dst.$set(key, value, true, srcAttr[key]);
  8841. }
  8842. });
  8843. // copy the new attributes on the old attrs object
  8844. forEach(src, function(value, key) {
  8845. // Check if we already set this attribute in the loop above.
  8846. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  8847. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  8848. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  8849. if (!dst.hasOwnProperty(key) && key.charAt(0) !== '$') {
  8850. dst[key] = value;
  8851. if (key !== 'class' && key !== 'style') {
  8852. dstAttr[key] = srcAttr[key];
  8853. }
  8854. }
  8855. });
  8856. }
  8857. function compileTemplateUrl(directives, $compileNode, tAttrs,
  8858. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  8859. var linkQueue = [],
  8860. afterTemplateNodeLinkFn,
  8861. afterTemplateChildLinkFn,
  8862. beforeTemplateCompileNode = $compileNode[0],
  8863. origAsyncDirective = directives.shift(),
  8864. derivedSyncDirective = inherit(origAsyncDirective, {
  8865. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  8866. }),
  8867. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  8868. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  8869. : origAsyncDirective.templateUrl,
  8870. templateNamespace = origAsyncDirective.templateNamespace;
  8871. $compileNode.empty();
  8872. $templateRequest(templateUrl)
  8873. .then(function(content) {
  8874. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  8875. content = denormalizeTemplate(content);
  8876. if (origAsyncDirective.replace) {
  8877. if (jqLiteIsTextNode(content)) {
  8878. $template = [];
  8879. } else {
  8880. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  8881. }
  8882. compileNode = $template[0];
  8883. if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  8884. throw $compileMinErr('tplrt',
  8885. 'Template for directive \'{0}\' must have exactly one root element. {1}',
  8886. origAsyncDirective.name, templateUrl);
  8887. }
  8888. tempTemplateAttrs = {$attr: {}};
  8889. replaceWith($rootElement, $compileNode, compileNode);
  8890. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  8891. if (isObject(origAsyncDirective.scope)) {
  8892. // the original directive that caused the template to be loaded async required
  8893. // an isolate scope
  8894. markDirectiveScope(templateDirectives, true);
  8895. }
  8896. directives = templateDirectives.concat(directives);
  8897. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  8898. } else {
  8899. compileNode = beforeTemplateCompileNode;
  8900. $compileNode.html(content);
  8901. }
  8902. directives.unshift(derivedSyncDirective);
  8903. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  8904. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  8905. previousCompileContext);
  8906. forEach($rootElement, function(node, i) {
  8907. if (node === compileNode) {
  8908. $rootElement[i] = $compileNode[0];
  8909. }
  8910. });
  8911. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  8912. while (linkQueue.length) {
  8913. var scope = linkQueue.shift(),
  8914. beforeTemplateLinkNode = linkQueue.shift(),
  8915. linkRootElement = linkQueue.shift(),
  8916. boundTranscludeFn = linkQueue.shift(),
  8917. linkNode = $compileNode[0];
  8918. if (scope.$$destroyed) continue;
  8919. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  8920. var oldClasses = beforeTemplateLinkNode.className;
  8921. if (!(previousCompileContext.hasElementTranscludeDirective &&
  8922. origAsyncDirective.replace)) {
  8923. // it was cloned therefore we have to clone as well.
  8924. linkNode = jqLiteClone(compileNode);
  8925. }
  8926. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  8927. // Copy in CSS classes from original node
  8928. safeAddClass(jqLite(linkNode), oldClasses);
  8929. }
  8930. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  8931. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  8932. } else {
  8933. childBoundTranscludeFn = boundTranscludeFn;
  8934. }
  8935. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  8936. childBoundTranscludeFn);
  8937. }
  8938. linkQueue = null;
  8939. }).catch(noop);
  8940. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  8941. var childBoundTranscludeFn = boundTranscludeFn;
  8942. if (scope.$$destroyed) return;
  8943. if (linkQueue) {
  8944. linkQueue.push(scope,
  8945. node,
  8946. rootElement,
  8947. childBoundTranscludeFn);
  8948. } else {
  8949. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  8950. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  8951. }
  8952. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  8953. }
  8954. };
  8955. }
  8956. /**
  8957. * Sorting function for bound directives.
  8958. */
  8959. function byPriority(a, b) {
  8960. var diff = b.priority - a.priority;
  8961. if (diff !== 0) return diff;
  8962. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  8963. return a.index - b.index;
  8964. }
  8965. function assertNoDuplicate(what, previousDirective, directive, element) {
  8966. function wrapModuleNameIfDefined(moduleName) {
  8967. return moduleName ?
  8968. (' (module: ' + moduleName + ')') :
  8969. '';
  8970. }
  8971. if (previousDirective) {
  8972. throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
  8973. previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
  8974. directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
  8975. }
  8976. }
  8977. function addTextInterpolateDirective(directives, text) {
  8978. var interpolateFn = $interpolate(text, true);
  8979. if (interpolateFn) {
  8980. directives.push({
  8981. priority: 0,
  8982. compile: function textInterpolateCompileFn(templateNode) {
  8983. var templateNodeParent = templateNode.parent(),
  8984. hasCompileParent = !!templateNodeParent.length;
  8985. // When transcluding a template that has bindings in the root
  8986. // we don't have a parent and thus need to add the class during linking fn.
  8987. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  8988. return function textInterpolateLinkFn(scope, node) {
  8989. var parent = node.parent();
  8990. if (!hasCompileParent) compile.$$addBindingClass(parent);
  8991. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  8992. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  8993. node[0].nodeValue = value;
  8994. });
  8995. };
  8996. }
  8997. });
  8998. }
  8999. }
  9000. function wrapTemplate(type, template) {
  9001. type = lowercase(type || 'html');
  9002. switch (type) {
  9003. case 'svg':
  9004. case 'math':
  9005. var wrapper = window.document.createElement('div');
  9006. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  9007. return wrapper.childNodes[0].childNodes;
  9008. default:
  9009. return template;
  9010. }
  9011. }
  9012. function getTrustedContext(node, attrNormalizedName) {
  9013. if (attrNormalizedName === 'srcdoc') {
  9014. return $sce.HTML;
  9015. }
  9016. var tag = nodeName_(node);
  9017. // All tags with src attributes require a RESOURCE_URL value, except for
  9018. // img and various html5 media tags.
  9019. if (attrNormalizedName === 'src' || attrNormalizedName === 'ngSrc') {
  9020. if (['img', 'video', 'audio', 'source', 'track'].indexOf(tag) === -1) {
  9021. return $sce.RESOURCE_URL;
  9022. }
  9023. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  9024. } else if (attrNormalizedName === 'xlinkHref' ||
  9025. (tag === 'form' && attrNormalizedName === 'action') ||
  9026. // links can be stylesheets or imports, which can run script in the current origin
  9027. (tag === 'link' && attrNormalizedName === 'href')
  9028. ) {
  9029. return $sce.RESOURCE_URL;
  9030. }
  9031. }
  9032. function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  9033. var trustedContext = getTrustedContext(node, name);
  9034. allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
  9035. var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
  9036. // no interpolation found -> ignore
  9037. if (!interpolateFn) return;
  9038. if (name === 'multiple' && nodeName_(node) === 'select') {
  9039. throw $compileMinErr('selmulti',
  9040. 'Binding to the \'multiple\' attribute is not supported. Element: {0}',
  9041. startingTag(node));
  9042. }
  9043. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  9044. throw $compileMinErr('nodomevents',
  9045. 'Interpolations for HTML DOM event attributes are disallowed. Please use the ' +
  9046. 'ng- versions (such as ng-click instead of onclick) instead.');
  9047. }
  9048. directives.push({
  9049. priority: 100,
  9050. compile: function() {
  9051. return {
  9052. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  9053. var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
  9054. // If the attribute has changed since last $interpolate()ed
  9055. var newValue = attr[name];
  9056. if (newValue !== value) {
  9057. // we need to interpolate again since the attribute value has been updated
  9058. // (e.g. by another directive's compile function)
  9059. // ensure unset/empty values make interpolateFn falsy
  9060. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  9061. value = newValue;
  9062. }
  9063. // if attribute was updated so that there is no interpolation going on we don't want to
  9064. // register any observers
  9065. if (!interpolateFn) return;
  9066. // initialize attr object so that it's ready in case we need the value for isolate
  9067. // scope initialization, otherwise the value would not be available from isolate
  9068. // directive's linking fn during linking phase
  9069. attr[name] = interpolateFn(scope);
  9070. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  9071. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  9072. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  9073. //special case for class attribute addition + removal
  9074. //so that class changes can tap into the animation
  9075. //hooks provided by the $animate service. Be sure to
  9076. //skip animations when the first digest occurs (when
  9077. //both the new and the old values are the same) since
  9078. //the CSS classes are the non-interpolated values
  9079. if (name === 'class' && newValue !== oldValue) {
  9080. attr.$updateClass(newValue, oldValue);
  9081. } else {
  9082. attr.$set(name, newValue);
  9083. }
  9084. });
  9085. }
  9086. };
  9087. }
  9088. });
  9089. }
  9090. /**
  9091. * This is a special jqLite.replaceWith, which can replace items which
  9092. * have no parents, provided that the containing jqLite collection is provided.
  9093. *
  9094. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  9095. * in the root of the tree.
  9096. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  9097. * the shell, but replace its DOM node reference.
  9098. * @param {Node} newNode The new DOM node.
  9099. */
  9100. function replaceWith($rootElement, elementsToRemove, newNode) {
  9101. var firstElementToRemove = elementsToRemove[0],
  9102. removeCount = elementsToRemove.length,
  9103. parent = firstElementToRemove.parentNode,
  9104. i, ii;
  9105. if ($rootElement) {
  9106. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  9107. if ($rootElement[i] === firstElementToRemove) {
  9108. $rootElement[i++] = newNode;
  9109. for (var j = i, j2 = j + removeCount - 1,
  9110. jj = $rootElement.length;
  9111. j < jj; j++, j2++) {
  9112. if (j2 < jj) {
  9113. $rootElement[j] = $rootElement[j2];
  9114. } else {
  9115. delete $rootElement[j];
  9116. }
  9117. }
  9118. $rootElement.length -= removeCount - 1;
  9119. // If the replaced element is also the jQuery .context then replace it
  9120. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  9121. // http://api.jquery.com/context/
  9122. if ($rootElement.context === firstElementToRemove) {
  9123. $rootElement.context = newNode;
  9124. }
  9125. break;
  9126. }
  9127. }
  9128. }
  9129. if (parent) {
  9130. parent.replaceChild(newNode, firstElementToRemove);
  9131. }
  9132. // Append all the `elementsToRemove` to a fragment. This will...
  9133. // - remove them from the DOM
  9134. // - allow them to still be traversed with .nextSibling
  9135. // - allow a single fragment.qSA to fetch all elements being removed
  9136. var fragment = window.document.createDocumentFragment();
  9137. for (i = 0; i < removeCount; i++) {
  9138. fragment.appendChild(elementsToRemove[i]);
  9139. }
  9140. if (jqLite.hasData(firstElementToRemove)) {
  9141. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  9142. // data here because there's no public interface in jQuery to do that and copying over
  9143. // event listeners (which is the main use of private data) wouldn't work anyway.
  9144. jqLite.data(newNode, jqLite.data(firstElementToRemove));
  9145. // Remove $destroy event listeners from `firstElementToRemove`
  9146. jqLite(firstElementToRemove).off('$destroy');
  9147. }
  9148. // Cleanup any data/listeners on the elements and children.
  9149. // This includes invoking the $destroy event on any elements with listeners.
  9150. jqLite.cleanData(fragment.querySelectorAll('*'));
  9151. // Update the jqLite collection to only contain the `newNode`
  9152. for (i = 1; i < removeCount; i++) {
  9153. delete elementsToRemove[i];
  9154. }
  9155. elementsToRemove[0] = newNode;
  9156. elementsToRemove.length = 1;
  9157. }
  9158. function cloneAndAnnotateFn(fn, annotation) {
  9159. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  9160. }
  9161. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  9162. try {
  9163. linkFn(scope, $element, attrs, controllers, transcludeFn);
  9164. } catch (e) {
  9165. $exceptionHandler(e, startingTag($element));
  9166. }
  9167. }
  9168. // Set up $watches for isolate scope and controller bindings. This process
  9169. // only occurs for isolate scopes and new scopes with controllerAs.
  9170. function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
  9171. var removeWatchCollection = [];
  9172. var initialChanges = {};
  9173. var changes;
  9174. forEach(bindings, function initializeBinding(definition, scopeName) {
  9175. var attrName = definition.attrName,
  9176. optional = definition.optional,
  9177. mode = definition.mode, // @, =, <, or &
  9178. lastValue,
  9179. parentGet, parentSet, compare, removeWatch;
  9180. switch (mode) {
  9181. case '@':
  9182. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  9183. destination[scopeName] = attrs[attrName] = undefined;
  9184. }
  9185. attrs.$observe(attrName, function(value) {
  9186. if (isString(value) || isBoolean(value)) {
  9187. var oldValue = destination[scopeName];
  9188. recordChanges(scopeName, value, oldValue);
  9189. destination[scopeName] = value;
  9190. }
  9191. });
  9192. attrs.$$observers[attrName].$$scope = scope;
  9193. lastValue = attrs[attrName];
  9194. if (isString(lastValue)) {
  9195. // If the attribute has been provided then we trigger an interpolation to ensure
  9196. // the value is there for use in the link fn
  9197. destination[scopeName] = $interpolate(lastValue)(scope);
  9198. } else if (isBoolean(lastValue)) {
  9199. // If the attributes is one of the BOOLEAN_ATTR then Angular will have converted
  9200. // the value to boolean rather than a string, so we special case this situation
  9201. destination[scopeName] = lastValue;
  9202. }
  9203. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  9204. break;
  9205. case '=':
  9206. if (!hasOwnProperty.call(attrs, attrName)) {
  9207. if (optional) break;
  9208. attrs[attrName] = undefined;
  9209. }
  9210. if (optional && !attrs[attrName]) break;
  9211. parentGet = $parse(attrs[attrName]);
  9212. if (parentGet.literal) {
  9213. compare = equals;
  9214. } else {
  9215. // eslint-disable-next-line no-self-compare
  9216. compare = function simpleCompare(a, b) { return a === b || (a !== a && b !== b); };
  9217. }
  9218. parentSet = parentGet.assign || function() {
  9219. // reset the change, or we will throw this exception on every $digest
  9220. lastValue = destination[scopeName] = parentGet(scope);
  9221. throw $compileMinErr('nonassign',
  9222. 'Expression \'{0}\' in attribute \'{1}\' used with directive \'{2}\' is non-assignable!',
  9223. attrs[attrName], attrName, directive.name);
  9224. };
  9225. lastValue = destination[scopeName] = parentGet(scope);
  9226. var parentValueWatch = function parentValueWatch(parentValue) {
  9227. if (!compare(parentValue, destination[scopeName])) {
  9228. // we are out of sync and need to copy
  9229. if (!compare(parentValue, lastValue)) {
  9230. // parent changed and it has precedence
  9231. destination[scopeName] = parentValue;
  9232. } else {
  9233. // if the parent can be assigned then do so
  9234. parentSet(scope, parentValue = destination[scopeName]);
  9235. }
  9236. }
  9237. lastValue = parentValue;
  9238. return lastValue;
  9239. };
  9240. parentValueWatch.$stateful = true;
  9241. if (definition.collection) {
  9242. removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  9243. } else {
  9244. removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  9245. }
  9246. removeWatchCollection.push(removeWatch);
  9247. break;
  9248. case '<':
  9249. if (!hasOwnProperty.call(attrs, attrName)) {
  9250. if (optional) break;
  9251. attrs[attrName] = undefined;
  9252. }
  9253. if (optional && !attrs[attrName]) break;
  9254. parentGet = $parse(attrs[attrName]);
  9255. var initialValue = destination[scopeName] = parentGet(scope);
  9256. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  9257. removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newValue, oldValue) {
  9258. if (oldValue === newValue) {
  9259. if (oldValue === initialValue) return;
  9260. oldValue = initialValue;
  9261. }
  9262. recordChanges(scopeName, newValue, oldValue);
  9263. destination[scopeName] = newValue;
  9264. }, parentGet.literal);
  9265. removeWatchCollection.push(removeWatch);
  9266. break;
  9267. case '&':
  9268. // Don't assign Object.prototype method to scope
  9269. parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
  9270. // Don't assign noop to destination if expression is not valid
  9271. if (parentGet === noop && optional) break;
  9272. destination[scopeName] = function(locals) {
  9273. return parentGet(scope, locals);
  9274. };
  9275. break;
  9276. }
  9277. });
  9278. function recordChanges(key, currentValue, previousValue) {
  9279. if (isFunction(destination.$onChanges) && currentValue !== previousValue &&
  9280. // eslint-disable-next-line no-self-compare
  9281. (currentValue === currentValue || previousValue === previousValue)) {
  9282. // If we have not already scheduled the top level onChangesQueue handler then do so now
  9283. if (!onChangesQueue) {
  9284. scope.$$postDigest(flushOnChangesQueue);
  9285. onChangesQueue = [];
  9286. }
  9287. // If we have not already queued a trigger of onChanges for this controller then do so now
  9288. if (!changes) {
  9289. changes = {};
  9290. onChangesQueue.push(triggerOnChangesHook);
  9291. }
  9292. // If the has been a change on this property already then we need to reuse the previous value
  9293. if (changes[key]) {
  9294. previousValue = changes[key].previousValue;
  9295. }
  9296. // Store this change
  9297. changes[key] = new SimpleChange(previousValue, currentValue);
  9298. }
  9299. }
  9300. function triggerOnChangesHook() {
  9301. destination.$onChanges(changes);
  9302. // Now clear the changes so that we schedule onChanges when more changes arrive
  9303. changes = undefined;
  9304. }
  9305. return {
  9306. initialChanges: initialChanges,
  9307. removeWatches: removeWatchCollection.length && function removeWatches() {
  9308. for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
  9309. removeWatchCollection[i]();
  9310. }
  9311. }
  9312. };
  9313. }
  9314. }];
  9315. }
  9316. function SimpleChange(previous, current) {
  9317. this.previousValue = previous;
  9318. this.currentValue = current;
  9319. }
  9320. SimpleChange.prototype.isFirstChange = function() { return this.previousValue === _UNINITIALIZED_VALUE; };
  9321. var PREFIX_REGEXP = /^((?:x|data)[:\-_])/i;
  9322. /**
  9323. * Converts all accepted directives format into proper directive name.
  9324. * @param name Name to normalize
  9325. */
  9326. function directiveNormalize(name) {
  9327. return camelCase(name.replace(PREFIX_REGEXP, ''));
  9328. }
  9329. /**
  9330. * @ngdoc type
  9331. * @name $compile.directive.Attributes
  9332. *
  9333. * @description
  9334. * A shared object between directive compile / linking functions which contains normalized DOM
  9335. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  9336. * needed since all of these are treated as equivalent in Angular:
  9337. *
  9338. * ```
  9339. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  9340. * ```
  9341. */
  9342. /**
  9343. * @ngdoc property
  9344. * @name $compile.directive.Attributes#$attr
  9345. *
  9346. * @description
  9347. * A map of DOM element attribute names to the normalized name. This is
  9348. * needed to do reverse lookup from normalized name back to actual name.
  9349. */
  9350. /**
  9351. * @ngdoc method
  9352. * @name $compile.directive.Attributes#$set
  9353. * @kind function
  9354. *
  9355. * @description
  9356. * Set DOM element attribute value.
  9357. *
  9358. *
  9359. * @param {string} name Normalized element attribute name of the property to modify. The name is
  9360. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  9361. * property to the original name.
  9362. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  9363. */
  9364. /**
  9365. * Closure compiler type information
  9366. */
  9367. function nodesetLinkingFn(
  9368. /* angular.Scope */ scope,
  9369. /* NodeList */ nodeList,
  9370. /* Element */ rootElement,
  9371. /* function(Function) */ boundTranscludeFn
  9372. ) {}
  9373. function directiveLinkingFn(
  9374. /* nodesetLinkingFn */ nodesetLinkingFn,
  9375. /* angular.Scope */ scope,
  9376. /* Node */ node,
  9377. /* Element */ rootElement,
  9378. /* function(Function) */ boundTranscludeFn
  9379. ) {}
  9380. function tokenDifference(str1, str2) {
  9381. var values = '',
  9382. tokens1 = str1.split(/\s+/),
  9383. tokens2 = str2.split(/\s+/);
  9384. outer:
  9385. for (var i = 0; i < tokens1.length; i++) {
  9386. var token = tokens1[i];
  9387. for (var j = 0; j < tokens2.length; j++) {
  9388. if (token === tokens2[j]) continue outer;
  9389. }
  9390. values += (values.length > 0 ? ' ' : '') + token;
  9391. }
  9392. return values;
  9393. }
  9394. function removeComments(jqNodes) {
  9395. jqNodes = jqLite(jqNodes);
  9396. var i = jqNodes.length;
  9397. if (i <= 1) {
  9398. return jqNodes;
  9399. }
  9400. while (i--) {
  9401. var node = jqNodes[i];
  9402. if (node.nodeType === NODE_TYPE_COMMENT) {
  9403. splice.call(jqNodes, i, 1);
  9404. }
  9405. }
  9406. return jqNodes;
  9407. }
  9408. var $controllerMinErr = minErr('$controller');
  9409. var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/;
  9410. function identifierForController(controller, ident) {
  9411. if (ident && isString(ident)) return ident;
  9412. if (isString(controller)) {
  9413. var match = CNTRL_REG.exec(controller);
  9414. if (match) return match[3];
  9415. }
  9416. }
  9417. /**
  9418. * @ngdoc provider
  9419. * @name $controllerProvider
  9420. * @this
  9421. *
  9422. * @description
  9423. * The {@link ng.$controller $controller service} is used by Angular to create new
  9424. * controllers.
  9425. *
  9426. * This provider allows controller registration via the
  9427. * {@link ng.$controllerProvider#register register} method.
  9428. */
  9429. function $ControllerProvider() {
  9430. var controllers = {},
  9431. globals = false;
  9432. /**
  9433. * @ngdoc method
  9434. * @name $controllerProvider#has
  9435. * @param {string} name Controller name to check.
  9436. */
  9437. this.has = function(name) {
  9438. return controllers.hasOwnProperty(name);
  9439. };
  9440. /**
  9441. * @ngdoc method
  9442. * @name $controllerProvider#register
  9443. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  9444. * the names and the values are the constructors.
  9445. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  9446. * annotations in the array notation).
  9447. */
  9448. this.register = function(name, constructor) {
  9449. assertNotHasOwnProperty(name, 'controller');
  9450. if (isObject(name)) {
  9451. extend(controllers, name);
  9452. } else {
  9453. controllers[name] = constructor;
  9454. }
  9455. };
  9456. /**
  9457. * @ngdoc method
  9458. * @name $controllerProvider#allowGlobals
  9459. * @description If called, allows `$controller` to find controller constructors on `window`
  9460. */
  9461. this.allowGlobals = function() {
  9462. globals = true;
  9463. };
  9464. this.$get = ['$injector', '$window', function($injector, $window) {
  9465. /**
  9466. * @ngdoc service
  9467. * @name $controller
  9468. * @requires $injector
  9469. *
  9470. * @param {Function|string} constructor If called with a function then it's considered to be the
  9471. * controller constructor function. Otherwise it's considered to be a string which is used
  9472. * to retrieve the controller constructor using the following steps:
  9473. *
  9474. * * check if a controller with given name is registered via `$controllerProvider`
  9475. * * check if evaluating the string on the current scope returns a constructor
  9476. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  9477. * `window` object (not recommended)
  9478. *
  9479. * The string can use the `controller as property` syntax, where the controller instance is published
  9480. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  9481. * to work correctly.
  9482. *
  9483. * @param {Object} locals Injection locals for Controller.
  9484. * @return {Object} Instance of given controller.
  9485. *
  9486. * @description
  9487. * `$controller` service is responsible for instantiating controllers.
  9488. *
  9489. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  9490. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  9491. */
  9492. return function $controller(expression, locals, later, ident) {
  9493. // PRIVATE API:
  9494. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  9495. // If true, $controller will allocate the object with the correct
  9496. // prototype chain, but will not invoke the controller until a returned
  9497. // callback is invoked.
  9498. // param `ident` --- An optional label which overrides the label parsed from the controller
  9499. // expression, if any.
  9500. var instance, match, constructor, identifier;
  9501. later = later === true;
  9502. if (ident && isString(ident)) {
  9503. identifier = ident;
  9504. }
  9505. if (isString(expression)) {
  9506. match = expression.match(CNTRL_REG);
  9507. if (!match) {
  9508. throw $controllerMinErr('ctrlfmt',
  9509. 'Badly formed controller string \'{0}\'. ' +
  9510. 'Must match `__name__ as __id__` or `__name__`.', expression);
  9511. }
  9512. constructor = match[1];
  9513. identifier = identifier || match[3];
  9514. expression = controllers.hasOwnProperty(constructor)
  9515. ? controllers[constructor]
  9516. : getter(locals.$scope, constructor, true) ||
  9517. (globals ? getter($window, constructor, true) : undefined);
  9518. if (!expression) {
  9519. throw $controllerMinErr('ctrlreg',
  9520. 'The controller with the name \'{0}\' is not registered.', constructor);
  9521. }
  9522. assertArgFn(expression, constructor, true);
  9523. }
  9524. if (later) {
  9525. // Instantiate controller later:
  9526. // This machinery is used to create an instance of the object before calling the
  9527. // controller's constructor itself.
  9528. //
  9529. // This allows properties to be added to the controller before the constructor is
  9530. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  9531. //
  9532. // This feature is not intended for use by applications, and is thus not documented
  9533. // publicly.
  9534. // Object creation: http://jsperf.com/create-constructor/2
  9535. var controllerPrototype = (isArray(expression) ?
  9536. expression[expression.length - 1] : expression).prototype;
  9537. instance = Object.create(controllerPrototype || null);
  9538. if (identifier) {
  9539. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9540. }
  9541. return extend(function $controllerInit() {
  9542. var result = $injector.invoke(expression, instance, locals, constructor);
  9543. if (result !== instance && (isObject(result) || isFunction(result))) {
  9544. instance = result;
  9545. if (identifier) {
  9546. // If result changed, re-assign controllerAs value to scope.
  9547. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9548. }
  9549. }
  9550. return instance;
  9551. }, {
  9552. instance: instance,
  9553. identifier: identifier
  9554. });
  9555. }
  9556. instance = $injector.instantiate(expression, locals, constructor);
  9557. if (identifier) {
  9558. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9559. }
  9560. return instance;
  9561. };
  9562. function addIdentifier(locals, identifier, instance, name) {
  9563. if (!(locals && isObject(locals.$scope))) {
  9564. throw minErr('$controller')('noscp',
  9565. 'Cannot export controller \'{0}\' as \'{1}\'! No $scope object provided via `locals`.',
  9566. name, identifier);
  9567. }
  9568. locals.$scope[identifier] = instance;
  9569. }
  9570. }];
  9571. }
  9572. /**
  9573. * @ngdoc service
  9574. * @name $document
  9575. * @requires $window
  9576. * @this
  9577. *
  9578. * @description
  9579. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  9580. *
  9581. * @example
  9582. <example module="documentExample" name="document">
  9583. <file name="index.html">
  9584. <div ng-controller="ExampleController">
  9585. <p>$document title: <b ng-bind="title"></b></p>
  9586. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  9587. </div>
  9588. </file>
  9589. <file name="script.js">
  9590. angular.module('documentExample', [])
  9591. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  9592. $scope.title = $document[0].title;
  9593. $scope.windowTitle = angular.element(window.document)[0].title;
  9594. }]);
  9595. </file>
  9596. </example>
  9597. */
  9598. function $DocumentProvider() {
  9599. this.$get = ['$window', function(window) {
  9600. return jqLite(window.document);
  9601. }];
  9602. }
  9603. /**
  9604. * @private
  9605. * @this
  9606. * Listens for document visibility change and makes the current status accessible.
  9607. */
  9608. function $$IsDocumentHiddenProvider() {
  9609. this.$get = ['$document', '$rootScope', function($document, $rootScope) {
  9610. var doc = $document[0];
  9611. var hidden = doc && doc.hidden;
  9612. $document.on('visibilitychange', changeListener);
  9613. $rootScope.$on('$destroy', function() {
  9614. $document.off('visibilitychange', changeListener);
  9615. });
  9616. function changeListener() {
  9617. hidden = doc.hidden;
  9618. }
  9619. return function() {
  9620. return hidden;
  9621. };
  9622. }];
  9623. }
  9624. /**
  9625. * @ngdoc service
  9626. * @name $exceptionHandler
  9627. * @requires ng.$log
  9628. * @this
  9629. *
  9630. * @description
  9631. * Any uncaught exception in angular expressions is delegated to this service.
  9632. * The default implementation simply delegates to `$log.error` which logs it into
  9633. * the browser console.
  9634. *
  9635. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  9636. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  9637. *
  9638. * ## Example:
  9639. *
  9640. * The example below will overwrite the default `$exceptionHandler` in order to (a) log uncaught
  9641. * errors to the backend for later inspection by the developers and (b) to use `$log.warn()` instead
  9642. * of `$log.error()`.
  9643. *
  9644. * ```js
  9645. * angular.
  9646. * module('exceptionOverwrite', []).
  9647. * factory('$exceptionHandler', ['$log', 'logErrorsToBackend', function($log, logErrorsToBackend) {
  9648. * return function myExceptionHandler(exception, cause) {
  9649. * logErrorsToBackend(exception, cause);
  9650. * $log.warn(exception, cause);
  9651. * };
  9652. * }]);
  9653. * ```
  9654. *
  9655. * <hr />
  9656. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  9657. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  9658. * (unless executed during a digest).
  9659. *
  9660. * If you wish, you can manually delegate exceptions, e.g.
  9661. * `try { ... } catch(e) { $exceptionHandler(e); }`
  9662. *
  9663. * @param {Error} exception Exception associated with the error.
  9664. * @param {string=} cause Optional information about the context in which
  9665. * the error was thrown.
  9666. *
  9667. */
  9668. function $ExceptionHandlerProvider() {
  9669. this.$get = ['$log', function($log) {
  9670. return function(exception, cause) {
  9671. $log.error.apply($log, arguments);
  9672. };
  9673. }];
  9674. }
  9675. var $$ForceReflowProvider = /** @this */ function() {
  9676. this.$get = ['$document', function($document) {
  9677. return function(domNode) {
  9678. //the line below will force the browser to perform a repaint so
  9679. //that all the animated elements within the animation frame will
  9680. //be properly updated and drawn on screen. This is required to
  9681. //ensure that the preparation animation is properly flushed so that
  9682. //the active state picks up from there. DO NOT REMOVE THIS LINE.
  9683. //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
  9684. //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
  9685. //WILL TAKE YEARS AWAY FROM YOUR LIFE.
  9686. if (domNode) {
  9687. if (!domNode.nodeType && domNode instanceof jqLite) {
  9688. domNode = domNode[0];
  9689. }
  9690. } else {
  9691. domNode = $document[0].body;
  9692. }
  9693. return domNode.offsetWidth + 1;
  9694. };
  9695. }];
  9696. };
  9697. var APPLICATION_JSON = 'application/json';
  9698. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  9699. var JSON_START = /^\[|^\{(?!\{)/;
  9700. var JSON_ENDS = {
  9701. '[': /]$/,
  9702. '{': /}$/
  9703. };
  9704. var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
  9705. var $httpMinErr = minErr('$http');
  9706. var $httpMinErrLegacyFn = function(method) {
  9707. return function() {
  9708. throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method);
  9709. };
  9710. };
  9711. function serializeValue(v) {
  9712. if (isObject(v)) {
  9713. return isDate(v) ? v.toISOString() : toJson(v);
  9714. }
  9715. return v;
  9716. }
  9717. /** @this */
  9718. function $HttpParamSerializerProvider() {
  9719. /**
  9720. * @ngdoc service
  9721. * @name $httpParamSerializer
  9722. * @description
  9723. *
  9724. * Default {@link $http `$http`} params serializer that converts objects to strings
  9725. * according to the following rules:
  9726. *
  9727. * * `{'foo': 'bar'}` results in `foo=bar`
  9728. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  9729. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  9730. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D` (stringified and encoded representation of an object)
  9731. *
  9732. * Note that serializer will sort the request parameters alphabetically.
  9733. * */
  9734. this.$get = function() {
  9735. return function ngParamSerializer(params) {
  9736. if (!params) return '';
  9737. var parts = [];
  9738. forEachSorted(params, function(value, key) {
  9739. if (value === null || isUndefined(value)) return;
  9740. if (isArray(value)) {
  9741. forEach(value, function(v) {
  9742. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  9743. });
  9744. } else {
  9745. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  9746. }
  9747. });
  9748. return parts.join('&');
  9749. };
  9750. };
  9751. }
  9752. /** @this */
  9753. function $HttpParamSerializerJQLikeProvider() {
  9754. /**
  9755. * @ngdoc service
  9756. * @name $httpParamSerializerJQLike
  9757. *
  9758. * @description
  9759. *
  9760. * Alternative {@link $http `$http`} params serializer that follows
  9761. * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  9762. * The serializer will also sort the params alphabetically.
  9763. *
  9764. * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
  9765. *
  9766. * ```js
  9767. * $http({
  9768. * url: myUrl,
  9769. * method: 'GET',
  9770. * params: myParams,
  9771. * paramSerializer: '$httpParamSerializerJQLike'
  9772. * });
  9773. * ```
  9774. *
  9775. * It is also possible to set it as the default `paramSerializer` in the
  9776. * {@link $httpProvider#defaults `$httpProvider`}.
  9777. *
  9778. * Additionally, you can inject the serializer and use it explicitly, for example to serialize
  9779. * form data for submission:
  9780. *
  9781. * ```js
  9782. * .controller(function($http, $httpParamSerializerJQLike) {
  9783. * //...
  9784. *
  9785. * $http({
  9786. * url: myUrl,
  9787. * method: 'POST',
  9788. * data: $httpParamSerializerJQLike(myData),
  9789. * headers: {
  9790. * 'Content-Type': 'application/x-www-form-urlencoded'
  9791. * }
  9792. * });
  9793. *
  9794. * });
  9795. * ```
  9796. *
  9797. * */
  9798. this.$get = function() {
  9799. return function jQueryLikeParamSerializer(params) {
  9800. if (!params) return '';
  9801. var parts = [];
  9802. serialize(params, '', true);
  9803. return parts.join('&');
  9804. function serialize(toSerialize, prefix, topLevel) {
  9805. if (toSerialize === null || isUndefined(toSerialize)) return;
  9806. if (isArray(toSerialize)) {
  9807. forEach(toSerialize, function(value, index) {
  9808. serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
  9809. });
  9810. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  9811. forEachSorted(toSerialize, function(value, key) {
  9812. serialize(value, prefix +
  9813. (topLevel ? '' : '[') +
  9814. key +
  9815. (topLevel ? '' : ']'));
  9816. });
  9817. } else {
  9818. parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
  9819. }
  9820. }
  9821. };
  9822. };
  9823. }
  9824. function defaultHttpResponseTransform(data, headers) {
  9825. if (isString(data)) {
  9826. // Strip json vulnerability protection prefix and trim whitespace
  9827. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  9828. if (tempData) {
  9829. var contentType = headers('Content-Type');
  9830. if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
  9831. data = fromJson(tempData);
  9832. }
  9833. }
  9834. }
  9835. return data;
  9836. }
  9837. function isJsonLike(str) {
  9838. var jsonStart = str.match(JSON_START);
  9839. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  9840. }
  9841. /**
  9842. * Parse headers into key value object
  9843. *
  9844. * @param {string} headers Raw headers as a string
  9845. * @returns {Object} Parsed headers as key value object
  9846. */
  9847. function parseHeaders(headers) {
  9848. var parsed = createMap(), i;
  9849. function fillInParsed(key, val) {
  9850. if (key) {
  9851. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  9852. }
  9853. }
  9854. if (isString(headers)) {
  9855. forEach(headers.split('\n'), function(line) {
  9856. i = line.indexOf(':');
  9857. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  9858. });
  9859. } else if (isObject(headers)) {
  9860. forEach(headers, function(headerVal, headerKey) {
  9861. fillInParsed(lowercase(headerKey), trim(headerVal));
  9862. });
  9863. }
  9864. return parsed;
  9865. }
  9866. /**
  9867. * Returns a function that provides access to parsed headers.
  9868. *
  9869. * Headers are lazy parsed when first requested.
  9870. * @see parseHeaders
  9871. *
  9872. * @param {(string|Object)} headers Headers to provide access to.
  9873. * @returns {function(string=)} Returns a getter function which if called with:
  9874. *
  9875. * - if called with single an argument returns a single header value or null
  9876. * - if called with no arguments returns an object containing all headers.
  9877. */
  9878. function headersGetter(headers) {
  9879. var headersObj;
  9880. return function(name) {
  9881. if (!headersObj) headersObj = parseHeaders(headers);
  9882. if (name) {
  9883. var value = headersObj[lowercase(name)];
  9884. if (value === undefined) {
  9885. value = null;
  9886. }
  9887. return value;
  9888. }
  9889. return headersObj;
  9890. };
  9891. }
  9892. /**
  9893. * Chain all given functions
  9894. *
  9895. * This function is used for both request and response transforming
  9896. *
  9897. * @param {*} data Data to transform.
  9898. * @param {function(string=)} headers HTTP headers getter fn.
  9899. * @param {number} status HTTP status code of the response.
  9900. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  9901. * @returns {*} Transformed data.
  9902. */
  9903. function transformData(data, headers, status, fns) {
  9904. if (isFunction(fns)) {
  9905. return fns(data, headers, status);
  9906. }
  9907. forEach(fns, function(fn) {
  9908. data = fn(data, headers, status);
  9909. });
  9910. return data;
  9911. }
  9912. function isSuccess(status) {
  9913. return 200 <= status && status < 300;
  9914. }
  9915. /**
  9916. * @ngdoc provider
  9917. * @name $httpProvider
  9918. * @this
  9919. *
  9920. * @description
  9921. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  9922. * */
  9923. function $HttpProvider() {
  9924. /**
  9925. * @ngdoc property
  9926. * @name $httpProvider#defaults
  9927. * @description
  9928. *
  9929. * Object containing default values for all {@link ng.$http $http} requests.
  9930. *
  9931. * - **`defaults.cache`** - {boolean|Object} - A boolean value or object created with
  9932. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of HTTP responses
  9933. * by default. See {@link $http#caching $http Caching} for more information.
  9934. *
  9935. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  9936. * Defaults value is `'XSRF-TOKEN'`.
  9937. *
  9938. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  9939. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  9940. *
  9941. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  9942. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  9943. * setting default headers.
  9944. * - **`defaults.headers.common`**
  9945. * - **`defaults.headers.post`**
  9946. * - **`defaults.headers.put`**
  9947. * - **`defaults.headers.patch`**
  9948. *
  9949. *
  9950. * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
  9951. * used to the prepare string representation of request parameters (specified as an object).
  9952. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  9953. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  9954. *
  9955. **/
  9956. var defaults = this.defaults = {
  9957. // transform incoming response data
  9958. transformResponse: [defaultHttpResponseTransform],
  9959. // transform outgoing request data
  9960. transformRequest: [function(d) {
  9961. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  9962. }],
  9963. // default headers
  9964. headers: {
  9965. common: {
  9966. 'Accept': 'application/json, text/plain, */*'
  9967. },
  9968. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  9969. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  9970. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  9971. },
  9972. xsrfCookieName: 'XSRF-TOKEN',
  9973. xsrfHeaderName: 'X-XSRF-TOKEN',
  9974. paramSerializer: '$httpParamSerializer'
  9975. };
  9976. var useApplyAsync = false;
  9977. /**
  9978. * @ngdoc method
  9979. * @name $httpProvider#useApplyAsync
  9980. * @description
  9981. *
  9982. * Configure $http service to combine processing of multiple http responses received at around
  9983. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  9984. * significant performance improvement for bigger applications that make many HTTP requests
  9985. * concurrently (common during application bootstrap).
  9986. *
  9987. * Defaults to false. If no value is specified, returns the current configured value.
  9988. *
  9989. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  9990. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  9991. * to load and share the same digest cycle.
  9992. *
  9993. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  9994. * otherwise, returns the current configured value.
  9995. **/
  9996. this.useApplyAsync = function(value) {
  9997. if (isDefined(value)) {
  9998. useApplyAsync = !!value;
  9999. return this;
  10000. }
  10001. return useApplyAsync;
  10002. };
  10003. var useLegacyPromise = true;
  10004. /**
  10005. * @ngdoc method
  10006. * @name $httpProvider#useLegacyPromiseExtensions
  10007. * @description
  10008. *
  10009. * Configure `$http` service to return promises without the shorthand methods `success` and `error`.
  10010. * This should be used to make sure that applications work without these methods.
  10011. *
  10012. * Defaults to true. If no value is specified, returns the current configured value.
  10013. *
  10014. * @param {boolean=} value If true, `$http` will return a promise with the deprecated legacy `success` and `error` methods.
  10015. *
  10016. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  10017. * otherwise, returns the current configured value.
  10018. **/
  10019. this.useLegacyPromiseExtensions = function(value) {
  10020. if (isDefined(value)) {
  10021. useLegacyPromise = !!value;
  10022. return this;
  10023. }
  10024. return useLegacyPromise;
  10025. };
  10026. /**
  10027. * @ngdoc property
  10028. * @name $httpProvider#interceptors
  10029. * @description
  10030. *
  10031. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  10032. * pre-processing of request or postprocessing of responses.
  10033. *
  10034. * These service factories are ordered by request, i.e. they are applied in the same order as the
  10035. * array, on request, but reverse order, on response.
  10036. *
  10037. * {@link ng.$http#interceptors Interceptors detailed info}
  10038. **/
  10039. var interceptorFactories = this.interceptors = [];
  10040. this.$get = ['$browser', '$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
  10041. function($browser, $httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
  10042. var defaultCache = $cacheFactory('$http');
  10043. /**
  10044. * Make sure that default param serializer is exposed as a function
  10045. */
  10046. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  10047. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  10048. /**
  10049. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  10050. * The reversal is needed so that we can build up the interception chain around the
  10051. * server request.
  10052. */
  10053. var reversedInterceptors = [];
  10054. forEach(interceptorFactories, function(interceptorFactory) {
  10055. reversedInterceptors.unshift(isString(interceptorFactory)
  10056. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  10057. });
  10058. /**
  10059. * @ngdoc service
  10060. * @kind function
  10061. * @name $http
  10062. * @requires ng.$httpBackend
  10063. * @requires $cacheFactory
  10064. * @requires $rootScope
  10065. * @requires $q
  10066. * @requires $injector
  10067. *
  10068. * @description
  10069. * The `$http` service is a core Angular service that facilitates communication with the remote
  10070. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  10071. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  10072. *
  10073. * For unit testing applications that use `$http` service, see
  10074. * {@link ngMock.$httpBackend $httpBackend mock}.
  10075. *
  10076. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  10077. * $resource} service.
  10078. *
  10079. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  10080. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  10081. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  10082. *
  10083. *
  10084. * ## General usage
  10085. * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
  10086. * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
  10087. *
  10088. * ```js
  10089. * // Simple GET request example:
  10090. * $http({
  10091. * method: 'GET',
  10092. * url: '/someUrl'
  10093. * }).then(function successCallback(response) {
  10094. * // this callback will be called asynchronously
  10095. * // when the response is available
  10096. * }, function errorCallback(response) {
  10097. * // called asynchronously if an error occurs
  10098. * // or server returns response with an error status.
  10099. * });
  10100. * ```
  10101. *
  10102. * The response object has these properties:
  10103. *
  10104. * - **data** – `{string|Object}` – The response body transformed with the transform
  10105. * functions.
  10106. * - **status** – `{number}` – HTTP status code of the response.
  10107. * - **headers** – `{function([headerName])}` – Header getter function.
  10108. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  10109. * - **statusText** – `{string}` – HTTP status text of the response.
  10110. *
  10111. * A response status code between 200 and 299 is considered a success status and will result in
  10112. * the success callback being called. Any response status code outside of that range is
  10113. * considered an error status and will result in the error callback being called.
  10114. * Also, status codes less than -1 are normalized to zero. -1 usually means the request was
  10115. * aborted, e.g. using a `config.timeout`.
  10116. * Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning
  10117. * that the outcome (success or error) will be determined by the final response status code.
  10118. *
  10119. *
  10120. * ## Shortcut methods
  10121. *
  10122. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  10123. * request data must be passed in for POST/PUT requests. An optional config can be passed as the
  10124. * last argument.
  10125. *
  10126. * ```js
  10127. * $http.get('/someUrl', config).then(successCallback, errorCallback);
  10128. * $http.post('/someUrl', data, config).then(successCallback, errorCallback);
  10129. * ```
  10130. *
  10131. * Complete list of shortcut methods:
  10132. *
  10133. * - {@link ng.$http#get $http.get}
  10134. * - {@link ng.$http#head $http.head}
  10135. * - {@link ng.$http#post $http.post}
  10136. * - {@link ng.$http#put $http.put}
  10137. * - {@link ng.$http#delete $http.delete}
  10138. * - {@link ng.$http#jsonp $http.jsonp}
  10139. * - {@link ng.$http#patch $http.patch}
  10140. *
  10141. *
  10142. * ## Writing Unit Tests that use $http
  10143. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  10144. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  10145. * request using trained responses.
  10146. *
  10147. * ```
  10148. * $httpBackend.expectGET(...);
  10149. * $http.get(...);
  10150. * $httpBackend.flush();
  10151. * ```
  10152. *
  10153. * ## Deprecation Notice
  10154. * <div class="alert alert-danger">
  10155. * The `$http` legacy promise methods `success` and `error` have been deprecated.
  10156. * Use the standard `then` method instead.
  10157. * If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to
  10158. * `false` then these methods will throw {@link $http:legacy `$http/legacy`} error.
  10159. * </div>
  10160. *
  10161. * ## Setting HTTP Headers
  10162. *
  10163. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  10164. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  10165. * object, which currently contains this default configuration:
  10166. *
  10167. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  10168. * - `Accept: application/json, text/plain, * / *`
  10169. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  10170. * - `Content-Type: application/json`
  10171. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  10172. * - `Content-Type: application/json`
  10173. *
  10174. * To add or overwrite these defaults, simply add or remove a property from these configuration
  10175. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  10176. * with the lowercased HTTP method name as the key, e.g.
  10177. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  10178. *
  10179. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  10180. * fashion. For example:
  10181. *
  10182. * ```
  10183. * module.run(function($http) {
  10184. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
  10185. * });
  10186. * ```
  10187. *
  10188. * In addition, you can supply a `headers` property in the config object passed when
  10189. * calling `$http(config)`, which overrides the defaults without changing them globally.
  10190. *
  10191. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  10192. * Use the `headers` property, setting the desired header to `undefined`. For example:
  10193. *
  10194. * ```js
  10195. * var req = {
  10196. * method: 'POST',
  10197. * url: 'http://example.com',
  10198. * headers: {
  10199. * 'Content-Type': undefined
  10200. * },
  10201. * data: { test: 'test' }
  10202. * }
  10203. *
  10204. * $http(req).then(function(){...}, function(){...});
  10205. * ```
  10206. *
  10207. * ## Transforming Requests and Responses
  10208. *
  10209. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  10210. * and `transformResponse`. These properties can be a single function that returns
  10211. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  10212. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  10213. *
  10214. * <div class="alert alert-warning">
  10215. * **Note:** Angular does not make a copy of the `data` parameter before it is passed into the `transformRequest` pipeline.
  10216. * That means changes to the properties of `data` are not local to the transform function (since Javascript passes objects by reference).
  10217. * For example, when calling `$http.get(url, $scope.myObject)`, modifications to the object's properties in a transformRequest
  10218. * function will be reflected on the scope and in any templates where the object is data-bound.
  10219. * To prevent this, transform functions should have no side-effects.
  10220. * If you need to modify properties, it is recommended to make a copy of the data, or create new object to return.
  10221. * </div>
  10222. *
  10223. * ### Default Transformations
  10224. *
  10225. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  10226. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  10227. * then these will be applied.
  10228. *
  10229. * You can augment or replace the default transformations by modifying these properties by adding to or
  10230. * replacing the array.
  10231. *
  10232. * Angular provides the following default transformations:
  10233. *
  10234. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  10235. *
  10236. * - If the `data` property of the request configuration object contains an object, serialize it
  10237. * into JSON format.
  10238. *
  10239. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  10240. *
  10241. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  10242. * - If JSON response is detected, deserialize it using a JSON parser.
  10243. *
  10244. *
  10245. * ### Overriding the Default Transformations Per Request
  10246. *
  10247. * If you wish to override the request/response transformations only for a single request then provide
  10248. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  10249. * into `$http`.
  10250. *
  10251. * Note that if you provide these properties on the config object the default transformations will be
  10252. * overwritten. If you wish to augment the default transformations then you must include them in your
  10253. * local transformation array.
  10254. *
  10255. * The following code demonstrates adding a new response transformation to be run after the default response
  10256. * transformations have been run.
  10257. *
  10258. * ```js
  10259. * function appendTransform(defaults, transform) {
  10260. *
  10261. * // We can't guarantee that the default transformation is an array
  10262. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  10263. *
  10264. * // Append the new transformation to the defaults
  10265. * return defaults.concat(transform);
  10266. * }
  10267. *
  10268. * $http({
  10269. * url: '...',
  10270. * method: 'GET',
  10271. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  10272. * return doTransform(value);
  10273. * })
  10274. * });
  10275. * ```
  10276. *
  10277. *
  10278. * ## Caching
  10279. *
  10280. * {@link ng.$http `$http`} responses are not cached by default. To enable caching, you must
  10281. * set the config.cache value or the default cache value to TRUE or to a cache object (created
  10282. * with {@link ng.$cacheFactory `$cacheFactory`}). If defined, the value of config.cache takes
  10283. * precedence over the default cache value.
  10284. *
  10285. * In order to:
  10286. * * cache all responses - set the default cache value to TRUE or to a cache object
  10287. * * cache a specific response - set config.cache value to TRUE or to a cache object
  10288. *
  10289. * If caching is enabled, but neither the default cache nor config.cache are set to a cache object,
  10290. * then the default `$cacheFactory("$http")` object is used.
  10291. *
  10292. * The default cache value can be set by updating the
  10293. * {@link ng.$http#defaults `$http.defaults.cache`} property or the
  10294. * {@link $httpProvider#defaults `$httpProvider.defaults.cache`} property.
  10295. *
  10296. * When caching is enabled, {@link ng.$http `$http`} stores the response from the server using
  10297. * the relevant cache object. The next time the same request is made, the response is returned
  10298. * from the cache without sending a request to the server.
  10299. *
  10300. * Take note that:
  10301. *
  10302. * * Only GET and JSONP requests are cached.
  10303. * * The cache key is the request URL including search parameters; headers are not considered.
  10304. * * Cached responses are returned asynchronously, in the same way as responses from the server.
  10305. * * If multiple identical requests are made using the same cache, which is not yet populated,
  10306. * one request will be made to the server and remaining requests will return the same response.
  10307. * * A cache-control header on the response does not affect if or how responses are cached.
  10308. *
  10309. *
  10310. * ## Interceptors
  10311. *
  10312. * Before you start creating interceptors, be sure to understand the
  10313. * {@link ng.$q $q and deferred/promise APIs}.
  10314. *
  10315. * For purposes of global error handling, authentication, or any kind of synchronous or
  10316. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  10317. * able to intercept requests before they are handed to the server and
  10318. * responses before they are handed over to the application code that
  10319. * initiated these requests. The interceptors leverage the {@link ng.$q
  10320. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  10321. *
  10322. * The interceptors are service factories that are registered with the `$httpProvider` by
  10323. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  10324. * injected with dependencies (if specified) and returns the interceptor.
  10325. *
  10326. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  10327. *
  10328. * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
  10329. * modify the `config` object or create a new one. The function needs to return the `config`
  10330. * object directly, or a promise containing the `config` or a new `config` object.
  10331. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  10332. * resolved with a rejection.
  10333. * * `response`: interceptors get called with http `response` object. The function is free to
  10334. * modify the `response` object or create a new one. The function needs to return the `response`
  10335. * object directly, or as a promise containing the `response` or a new `response` object.
  10336. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  10337. * resolved with a rejection.
  10338. *
  10339. *
  10340. * ```js
  10341. * // register the interceptor as a service
  10342. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  10343. * return {
  10344. * // optional method
  10345. * 'request': function(config) {
  10346. * // do something on success
  10347. * return config;
  10348. * },
  10349. *
  10350. * // optional method
  10351. * 'requestError': function(rejection) {
  10352. * // do something on error
  10353. * if (canRecover(rejection)) {
  10354. * return responseOrNewPromise
  10355. * }
  10356. * return $q.reject(rejection);
  10357. * },
  10358. *
  10359. *
  10360. *
  10361. * // optional method
  10362. * 'response': function(response) {
  10363. * // do something on success
  10364. * return response;
  10365. * },
  10366. *
  10367. * // optional method
  10368. * 'responseError': function(rejection) {
  10369. * // do something on error
  10370. * if (canRecover(rejection)) {
  10371. * return responseOrNewPromise
  10372. * }
  10373. * return $q.reject(rejection);
  10374. * }
  10375. * };
  10376. * });
  10377. *
  10378. * $httpProvider.interceptors.push('myHttpInterceptor');
  10379. *
  10380. *
  10381. * // alternatively, register the interceptor via an anonymous factory
  10382. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  10383. * return {
  10384. * 'request': function(config) {
  10385. * // same as above
  10386. * },
  10387. *
  10388. * 'response': function(response) {
  10389. * // same as above
  10390. * }
  10391. * };
  10392. * });
  10393. * ```
  10394. *
  10395. * ## Security Considerations
  10396. *
  10397. * When designing web applications, consider security threats from:
  10398. *
  10399. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  10400. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  10401. *
  10402. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  10403. * pre-configured with strategies that address these issues, but for this to work backend server
  10404. * cooperation is required.
  10405. *
  10406. * ### JSON Vulnerability Protection
  10407. *
  10408. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  10409. * allows third party website to turn your JSON resource URL into
  10410. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  10411. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  10412. * Angular will automatically strip the prefix before processing it as JSON.
  10413. *
  10414. * For example if your server needs to return:
  10415. * ```js
  10416. * ['one','two']
  10417. * ```
  10418. *
  10419. * which is vulnerable to attack, your server can return:
  10420. * ```js
  10421. * )]}',
  10422. * ['one','two']
  10423. * ```
  10424. *
  10425. * Angular will strip the prefix, before processing the JSON.
  10426. *
  10427. *
  10428. * ### Cross Site Request Forgery (XSRF) Protection
  10429. *
  10430. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by
  10431. * which the attacker can trick an authenticated user into unknowingly executing actions on your
  10432. * website. Angular provides a mechanism to counter XSRF. When performing XHR requests, the
  10433. * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP
  10434. * header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the
  10435. * cookie, your server can be assured that the XHR came from JavaScript running on your domain.
  10436. * The header will not be set for cross-domain requests.
  10437. *
  10438. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  10439. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  10440. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  10441. * that only JavaScript running on your domain could have sent the request. The token must be
  10442. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  10443. * making up its own tokens). We recommend that the token is a digest of your site's
  10444. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  10445. * for added security.
  10446. *
  10447. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  10448. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  10449. * or the per-request config object.
  10450. *
  10451. * In order to prevent collisions in environments where multiple Angular apps share the
  10452. * same domain or subdomain, we recommend that each application uses unique cookie name.
  10453. *
  10454. * @param {object} config Object describing the request to be made and how it should be
  10455. * processed. The object has following properties:
  10456. *
  10457. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  10458. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  10459. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
  10460. * with the `paramSerializer` and appended as GET parameters.
  10461. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  10462. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  10463. * HTTP headers to send to the server. If the return value of a function is null, the
  10464. * header will not be sent. Functions accept a config object as an argument.
  10465. * - **eventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest object.
  10466. * To bind events to the XMLHttpRequest upload object, use `uploadEventHandlers`.
  10467. * The handler will be called in the context of a `$apply` block.
  10468. * - **uploadEventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest upload
  10469. * object. To bind events to the XMLHttpRequest object, use `eventHandlers`.
  10470. * The handler will be called in the context of a `$apply` block.
  10471. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  10472. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  10473. * - **transformRequest** –
  10474. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  10475. * transform function or an array of such functions. The transform function takes the http
  10476. * request body and headers and returns its transformed (typically serialized) version.
  10477. * See {@link ng.$http#overriding-the-default-transformations-per-request
  10478. * Overriding the Default Transformations}
  10479. * - **transformResponse** –
  10480. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  10481. * transform function or an array of such functions. The transform function takes the http
  10482. * response body, headers and status and returns its transformed (typically deserialized) version.
  10483. * See {@link ng.$http#overriding-the-default-transformations-per-request
  10484. * Overriding the Default Transformations}
  10485. * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
  10486. * prepare the string representation of request parameters (specified as an object).
  10487. * If specified as string, it is interpreted as function registered with the
  10488. * {@link $injector $injector}, which means you can create your own serializer
  10489. * by registering it as a {@link auto.$provide#service service}.
  10490. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
  10491. * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
  10492. * - **cache** – `{boolean|Object}` – A boolean value or object created with
  10493. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response.
  10494. * See {@link $http#caching $http Caching} for more information.
  10495. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  10496. * that should abort the request when resolved.
  10497. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  10498. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  10499. * for more information.
  10500. * - **responseType** - `{string}` - see
  10501. * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
  10502. *
  10503. * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
  10504. * when the request succeeds or fails.
  10505. *
  10506. *
  10507. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  10508. * requests. This is primarily meant to be used for debugging purposes.
  10509. *
  10510. *
  10511. * @example
  10512. <example module="httpExample" name="http-service">
  10513. <file name="index.html">
  10514. <div ng-controller="FetchController">
  10515. <select ng-model="method" aria-label="Request method">
  10516. <option>GET</option>
  10517. <option>JSONP</option>
  10518. </select>
  10519. <input type="text" ng-model="url" size="80" aria-label="URL" />
  10520. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  10521. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  10522. <button id="samplejsonpbtn"
  10523. ng-click="updateModel('JSONP',
  10524. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  10525. Sample JSONP
  10526. </button>
  10527. <button id="invalidjsonpbtn"
  10528. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  10529. Invalid JSONP
  10530. </button>
  10531. <pre>http status code: {{status}}</pre>
  10532. <pre>http response data: {{data}}</pre>
  10533. </div>
  10534. </file>
  10535. <file name="script.js">
  10536. angular.module('httpExample', [])
  10537. .controller('FetchController', ['$scope', '$http', '$templateCache',
  10538. function($scope, $http, $templateCache) {
  10539. $scope.method = 'GET';
  10540. $scope.url = 'http-hello.html';
  10541. $scope.fetch = function() {
  10542. $scope.code = null;
  10543. $scope.response = null;
  10544. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  10545. then(function(response) {
  10546. $scope.status = response.status;
  10547. $scope.data = response.data;
  10548. }, function(response) {
  10549. $scope.data = response.data || 'Request failed';
  10550. $scope.status = response.status;
  10551. });
  10552. };
  10553. $scope.updateModel = function(method, url) {
  10554. $scope.method = method;
  10555. $scope.url = url;
  10556. };
  10557. }]);
  10558. </file>
  10559. <file name="http-hello.html">
  10560. Hello, $http!
  10561. </file>
  10562. <file name="protractor.js" type="protractor">
  10563. var status = element(by.binding('status'));
  10564. var data = element(by.binding('data'));
  10565. var fetchBtn = element(by.id('fetchbtn'));
  10566. var sampleGetBtn = element(by.id('samplegetbtn'));
  10567. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  10568. it('should make an xhr GET request', function() {
  10569. sampleGetBtn.click();
  10570. fetchBtn.click();
  10571. expect(status.getText()).toMatch('200');
  10572. expect(data.getText()).toMatch(/Hello, \$http!/);
  10573. });
  10574. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  10575. // it('should make a JSONP request to angularjs.org', function() {
  10576. // var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  10577. // sampleJsonpBtn.click();
  10578. // fetchBtn.click();
  10579. // expect(status.getText()).toMatch('200');
  10580. // expect(data.getText()).toMatch(/Super Hero!/);
  10581. // });
  10582. it('should make JSONP request to invalid URL and invoke the error handler',
  10583. function() {
  10584. invalidJsonpBtn.click();
  10585. fetchBtn.click();
  10586. expect(status.getText()).toMatch('0');
  10587. expect(data.getText()).toMatch('Request failed');
  10588. });
  10589. </file>
  10590. </example>
  10591. */
  10592. function $http(requestConfig) {
  10593. if (!isObject(requestConfig)) {
  10594. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  10595. }
  10596. if (!isString(requestConfig.url)) {
  10597. throw minErr('$http')('badreq', 'Http request configuration url must be a string. Received: {0}', requestConfig.url);
  10598. }
  10599. var config = extend({
  10600. method: 'get',
  10601. transformRequest: defaults.transformRequest,
  10602. transformResponse: defaults.transformResponse,
  10603. paramSerializer: defaults.paramSerializer
  10604. }, requestConfig);
  10605. config.headers = mergeHeaders(requestConfig);
  10606. config.method = uppercase(config.method);
  10607. config.paramSerializer = isString(config.paramSerializer) ?
  10608. $injector.get(config.paramSerializer) : config.paramSerializer;
  10609. $browser.$$incOutstandingRequestCount();
  10610. var requestInterceptors = [];
  10611. var responseInterceptors = [];
  10612. var promise = $q.when(config);
  10613. // apply interceptors
  10614. forEach(reversedInterceptors, function(interceptor) {
  10615. if (interceptor.request || interceptor.requestError) {
  10616. requestInterceptors.unshift(interceptor.request, interceptor.requestError);
  10617. }
  10618. if (interceptor.response || interceptor.responseError) {
  10619. responseInterceptors.push(interceptor.response, interceptor.responseError);
  10620. }
  10621. });
  10622. promise = chainInterceptors(promise, requestInterceptors);
  10623. promise = promise.then(serverRequest);
  10624. promise = chainInterceptors(promise, responseInterceptors);
  10625. promise = promise.finally(completeOutstandingRequest);
  10626. if (useLegacyPromise) {
  10627. promise.success = function(fn) {
  10628. assertArgFn(fn, 'fn');
  10629. promise.then(function(response) {
  10630. fn(response.data, response.status, response.headers, config);
  10631. });
  10632. return promise;
  10633. };
  10634. promise.error = function(fn) {
  10635. assertArgFn(fn, 'fn');
  10636. promise.then(null, function(response) {
  10637. fn(response.data, response.status, response.headers, config);
  10638. });
  10639. return promise;
  10640. };
  10641. } else {
  10642. promise.success = $httpMinErrLegacyFn('success');
  10643. promise.error = $httpMinErrLegacyFn('error');
  10644. }
  10645. return promise;
  10646. function chainInterceptors(promise, interceptors) {
  10647. for (var i = 0, ii = interceptors.length; i < ii;) {
  10648. var thenFn = interceptors[i++];
  10649. var rejectFn = interceptors[i++];
  10650. promise = promise.then(thenFn, rejectFn);
  10651. }
  10652. interceptors.length = 0;
  10653. return promise;
  10654. }
  10655. function completeOutstandingRequest() {
  10656. $browser.$$completeOutstandingRequest(noop);
  10657. }
  10658. function executeHeaderFns(headers, config) {
  10659. var headerContent, processedHeaders = {};
  10660. forEach(headers, function(headerFn, header) {
  10661. if (isFunction(headerFn)) {
  10662. headerContent = headerFn(config);
  10663. if (headerContent != null) {
  10664. processedHeaders[header] = headerContent;
  10665. }
  10666. } else {
  10667. processedHeaders[header] = headerFn;
  10668. }
  10669. });
  10670. return processedHeaders;
  10671. }
  10672. function mergeHeaders(config) {
  10673. var defHeaders = defaults.headers,
  10674. reqHeaders = extend({}, config.headers),
  10675. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  10676. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  10677. // using for-in instead of forEach to avoid unnecessary iteration after header has been found
  10678. defaultHeadersIteration:
  10679. for (defHeaderName in defHeaders) {
  10680. lowercaseDefHeaderName = lowercase(defHeaderName);
  10681. for (reqHeaderName in reqHeaders) {
  10682. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  10683. continue defaultHeadersIteration;
  10684. }
  10685. }
  10686. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  10687. }
  10688. // execute if header value is a function for merged headers
  10689. return executeHeaderFns(reqHeaders, shallowCopy(config));
  10690. }
  10691. function serverRequest(config) {
  10692. var headers = config.headers;
  10693. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  10694. // strip content-type if data is undefined
  10695. if (isUndefined(reqData)) {
  10696. forEach(headers, function(value, header) {
  10697. if (lowercase(header) === 'content-type') {
  10698. delete headers[header];
  10699. }
  10700. });
  10701. }
  10702. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  10703. config.withCredentials = defaults.withCredentials;
  10704. }
  10705. // send request
  10706. return sendReq(config, reqData).then(transformResponse, transformResponse);
  10707. }
  10708. function transformResponse(response) {
  10709. // make a copy since the response must be cacheable
  10710. var resp = extend({}, response);
  10711. resp.data = transformData(response.data, response.headers, response.status,
  10712. config.transformResponse);
  10713. return (isSuccess(response.status))
  10714. ? resp
  10715. : $q.reject(resp);
  10716. }
  10717. }
  10718. $http.pendingRequests = [];
  10719. /**
  10720. * @ngdoc method
  10721. * @name $http#get
  10722. *
  10723. * @description
  10724. * Shortcut method to perform `GET` request.
  10725. *
  10726. * @param {string} url Relative or absolute URL specifying the destination of the request
  10727. * @param {Object=} config Optional configuration object
  10728. * @returns {HttpPromise} Future object
  10729. */
  10730. /**
  10731. * @ngdoc method
  10732. * @name $http#delete
  10733. *
  10734. * @description
  10735. * Shortcut method to perform `DELETE` request.
  10736. *
  10737. * @param {string} url Relative or absolute URL specifying the destination of the request
  10738. * @param {Object=} config Optional configuration object
  10739. * @returns {HttpPromise} Future object
  10740. */
  10741. /**
  10742. * @ngdoc method
  10743. * @name $http#head
  10744. *
  10745. * @description
  10746. * Shortcut method to perform `HEAD` request.
  10747. *
  10748. * @param {string} url Relative or absolute URL specifying the destination of the request
  10749. * @param {Object=} config Optional configuration object
  10750. * @returns {HttpPromise} Future object
  10751. */
  10752. /**
  10753. * @ngdoc method
  10754. * @name $http#jsonp
  10755. *
  10756. * @description
  10757. * Shortcut method to perform `JSONP` request.
  10758. * If you would like to customise where and how the callbacks are stored then try overriding
  10759. * or decorating the {@link $jsonpCallbacks} service.
  10760. *
  10761. * @param {string} url Relative or absolute URL specifying the destination of the request.
  10762. * The name of the callback should be the string `JSON_CALLBACK`.
  10763. * @param {Object=} config Optional configuration object
  10764. * @returns {HttpPromise} Future object
  10765. */
  10766. createShortMethods('get', 'delete', 'head', 'jsonp');
  10767. /**
  10768. * @ngdoc method
  10769. * @name $http#post
  10770. *
  10771. * @description
  10772. * Shortcut method to perform `POST` request.
  10773. *
  10774. * @param {string} url Relative or absolute URL specifying the destination of the request
  10775. * @param {*} data Request content
  10776. * @param {Object=} config Optional configuration object
  10777. * @returns {HttpPromise} Future object
  10778. */
  10779. /**
  10780. * @ngdoc method
  10781. * @name $http#put
  10782. *
  10783. * @description
  10784. * Shortcut method to perform `PUT` request.
  10785. *
  10786. * @param {string} url Relative or absolute URL specifying the destination of the request
  10787. * @param {*} data Request content
  10788. * @param {Object=} config Optional configuration object
  10789. * @returns {HttpPromise} Future object
  10790. */
  10791. /**
  10792. * @ngdoc method
  10793. * @name $http#patch
  10794. *
  10795. * @description
  10796. * Shortcut method to perform `PATCH` request.
  10797. *
  10798. * @param {string} url Relative or absolute URL specifying the destination of the request
  10799. * @param {*} data Request content
  10800. * @param {Object=} config Optional configuration object
  10801. * @returns {HttpPromise} Future object
  10802. */
  10803. createShortMethodsWithData('post', 'put', 'patch');
  10804. /**
  10805. * @ngdoc property
  10806. * @name $http#defaults
  10807. *
  10808. * @description
  10809. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  10810. * default headers, withCredentials as well as request and response transformations.
  10811. *
  10812. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  10813. */
  10814. $http.defaults = defaults;
  10815. return $http;
  10816. function createShortMethods(names) {
  10817. forEach(arguments, function(name) {
  10818. $http[name] = function(url, config) {
  10819. return $http(extend({}, config || {}, {
  10820. method: name,
  10821. url: url
  10822. }));
  10823. };
  10824. });
  10825. }
  10826. function createShortMethodsWithData(name) {
  10827. forEach(arguments, function(name) {
  10828. $http[name] = function(url, data, config) {
  10829. return $http(extend({}, config || {}, {
  10830. method: name,
  10831. url: url,
  10832. data: data
  10833. }));
  10834. };
  10835. });
  10836. }
  10837. /**
  10838. * Makes the request.
  10839. *
  10840. * !!! ACCESSES CLOSURE VARS:
  10841. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  10842. */
  10843. function sendReq(config, reqData) {
  10844. var deferred = $q.defer(),
  10845. promise = deferred.promise,
  10846. cache,
  10847. cachedResp,
  10848. reqHeaders = config.headers,
  10849. url = buildUrl(config.url, config.paramSerializer(config.params));
  10850. $http.pendingRequests.push(config);
  10851. promise.then(removePendingReq, removePendingReq);
  10852. if ((config.cache || defaults.cache) && config.cache !== false &&
  10853. (config.method === 'GET' || config.method === 'JSONP')) {
  10854. cache = isObject(config.cache) ? config.cache
  10855. : isObject(defaults.cache) ? defaults.cache
  10856. : defaultCache;
  10857. }
  10858. if (cache) {
  10859. cachedResp = cache.get(url);
  10860. if (isDefined(cachedResp)) {
  10861. if (isPromiseLike(cachedResp)) {
  10862. // cached request has already been sent, but there is no response yet
  10863. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  10864. } else {
  10865. // serving from cache
  10866. if (isArray(cachedResp)) {
  10867. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  10868. } else {
  10869. resolvePromise(cachedResp, 200, {}, 'OK');
  10870. }
  10871. }
  10872. } else {
  10873. // put the promise for the non-transformed response into cache as a placeholder
  10874. cache.put(url, promise);
  10875. }
  10876. }
  10877. // if we won't have the response in cache, set the xsrf headers and
  10878. // send the request to the backend
  10879. if (isUndefined(cachedResp)) {
  10880. var xsrfValue = urlIsSameOrigin(config.url)
  10881. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  10882. : undefined;
  10883. if (xsrfValue) {
  10884. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  10885. }
  10886. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  10887. config.withCredentials, config.responseType,
  10888. createApplyHandlers(config.eventHandlers),
  10889. createApplyHandlers(config.uploadEventHandlers));
  10890. }
  10891. return promise;
  10892. function createApplyHandlers(eventHandlers) {
  10893. if (eventHandlers) {
  10894. var applyHandlers = {};
  10895. forEach(eventHandlers, function(eventHandler, key) {
  10896. applyHandlers[key] = function(event) {
  10897. if (useApplyAsync) {
  10898. $rootScope.$applyAsync(callEventHandler);
  10899. } else if ($rootScope.$$phase) {
  10900. callEventHandler();
  10901. } else {
  10902. $rootScope.$apply(callEventHandler);
  10903. }
  10904. function callEventHandler() {
  10905. eventHandler(event);
  10906. }
  10907. };
  10908. });
  10909. return applyHandlers;
  10910. }
  10911. }
  10912. /**
  10913. * Callback registered to $httpBackend():
  10914. * - caches the response if desired
  10915. * - resolves the raw $http promise
  10916. * - calls $apply
  10917. */
  10918. function done(status, response, headersString, statusText) {
  10919. if (cache) {
  10920. if (isSuccess(status)) {
  10921. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  10922. } else {
  10923. // remove promise from the cache
  10924. cache.remove(url);
  10925. }
  10926. }
  10927. function resolveHttpPromise() {
  10928. resolvePromise(response, status, headersString, statusText);
  10929. }
  10930. if (useApplyAsync) {
  10931. $rootScope.$applyAsync(resolveHttpPromise);
  10932. } else {
  10933. resolveHttpPromise();
  10934. if (!$rootScope.$$phase) $rootScope.$apply();
  10935. }
  10936. }
  10937. /**
  10938. * Resolves the raw $http promise.
  10939. */
  10940. function resolvePromise(response, status, headers, statusText) {
  10941. //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
  10942. status = status >= -1 ? status : 0;
  10943. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  10944. data: response,
  10945. status: status,
  10946. headers: headersGetter(headers),
  10947. config: config,
  10948. statusText: statusText
  10949. });
  10950. }
  10951. function resolvePromiseWithResult(result) {
  10952. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
  10953. }
  10954. function removePendingReq() {
  10955. var idx = $http.pendingRequests.indexOf(config);
  10956. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  10957. }
  10958. }
  10959. function buildUrl(url, serializedParams) {
  10960. if (serializedParams.length > 0) {
  10961. url += ((url.indexOf('?') === -1) ? '?' : '&') + serializedParams;
  10962. }
  10963. return url;
  10964. }
  10965. }];
  10966. }
  10967. /**
  10968. * @ngdoc service
  10969. * @name $xhrFactory
  10970. * @this
  10971. *
  10972. * @description
  10973. * Factory function used to create XMLHttpRequest objects.
  10974. *
  10975. * Replace or decorate this service to create your own custom XMLHttpRequest objects.
  10976. *
  10977. * ```
  10978. * angular.module('myApp', [])
  10979. * .factory('$xhrFactory', function() {
  10980. * return function createXhr(method, url) {
  10981. * return new window.XMLHttpRequest({mozSystem: true});
  10982. * };
  10983. * });
  10984. * ```
  10985. *
  10986. * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
  10987. * @param {string} url URL of the request.
  10988. */
  10989. function $xhrFactoryProvider() {
  10990. this.$get = function() {
  10991. return function createXhr() {
  10992. return new window.XMLHttpRequest();
  10993. };
  10994. };
  10995. }
  10996. /**
  10997. * @ngdoc service
  10998. * @name $httpBackend
  10999. * @requires $jsonpCallbacks
  11000. * @requires $document
  11001. * @requires $xhrFactory
  11002. * @this
  11003. *
  11004. * @description
  11005. * HTTP backend used by the {@link ng.$http service} that delegates to
  11006. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  11007. *
  11008. * You should never need to use this service directly, instead use the higher-level abstractions:
  11009. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  11010. *
  11011. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  11012. * $httpBackend} which can be trained with responses.
  11013. */
  11014. function $HttpBackendProvider() {
  11015. this.$get = ['$browser', '$jsonpCallbacks', '$document', '$xhrFactory', function($browser, $jsonpCallbacks, $document, $xhrFactory) {
  11016. return createHttpBackend($browser, $xhrFactory, $browser.defer, $jsonpCallbacks, $document[0]);
  11017. }];
  11018. }
  11019. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  11020. // TODO(vojta): fix the signature
  11021. return function(method, url, post, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) {
  11022. url = url || $browser.url();
  11023. if (lowercase(method) === 'jsonp') {
  11024. var callbackPath = callbacks.createCallback(url);
  11025. var jsonpDone = jsonpReq(url, callbackPath, function(status, text) {
  11026. // jsonpReq only ever sets status to 200 (OK), 404 (ERROR) or -1 (WAITING)
  11027. var response = (status === 200) && callbacks.getResponse(callbackPath);
  11028. completeRequest(callback, status, response, '', text);
  11029. callbacks.removeCallback(callbackPath);
  11030. });
  11031. } else {
  11032. var xhr = createXhr(method, url);
  11033. xhr.open(method, url, true);
  11034. forEach(headers, function(value, key) {
  11035. if (isDefined(value)) {
  11036. xhr.setRequestHeader(key, value);
  11037. }
  11038. });
  11039. xhr.onload = function requestLoaded() {
  11040. var statusText = xhr.statusText || '';
  11041. // responseText is the old-school way of retrieving response (supported by IE9)
  11042. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  11043. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  11044. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  11045. var status = xhr.status === 1223 ? 204 : xhr.status;
  11046. // fix status code when it is 0 (0 status is undocumented).
  11047. // Occurs when accessing file resources or on Android 4.1 stock browser
  11048. // while retrieving files from application cache.
  11049. if (status === 0) {
  11050. status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0;
  11051. }
  11052. completeRequest(callback,
  11053. status,
  11054. response,
  11055. xhr.getAllResponseHeaders(),
  11056. statusText);
  11057. };
  11058. var requestError = function() {
  11059. // The response is always empty
  11060. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  11061. completeRequest(callback, -1, null, null, '');
  11062. };
  11063. xhr.onerror = requestError;
  11064. xhr.onabort = requestError;
  11065. xhr.ontimeout = requestError;
  11066. forEach(eventHandlers, function(value, key) {
  11067. xhr.addEventListener(key, value);
  11068. });
  11069. forEach(uploadEventHandlers, function(value, key) {
  11070. xhr.upload.addEventListener(key, value);
  11071. });
  11072. if (withCredentials) {
  11073. xhr.withCredentials = true;
  11074. }
  11075. if (responseType) {
  11076. try {
  11077. xhr.responseType = responseType;
  11078. } catch (e) {
  11079. // WebKit added support for the json responseType value on 09/03/2013
  11080. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  11081. // known to throw when setting the value "json" as the response type. Other older
  11082. // browsers implementing the responseType
  11083. //
  11084. // The json response type can be ignored if not supported, because JSON payloads are
  11085. // parsed on the client-side regardless.
  11086. if (responseType !== 'json') {
  11087. throw e;
  11088. }
  11089. }
  11090. }
  11091. xhr.send(isUndefined(post) ? null : post);
  11092. }
  11093. if (timeout > 0) {
  11094. var timeoutId = $browserDefer(timeoutRequest, timeout);
  11095. } else if (isPromiseLike(timeout)) {
  11096. timeout.then(timeoutRequest);
  11097. }
  11098. function timeoutRequest() {
  11099. if (jsonpDone) {
  11100. jsonpDone();
  11101. }
  11102. if (xhr) {
  11103. xhr.abort();
  11104. }
  11105. }
  11106. function completeRequest(callback, status, response, headersString, statusText) {
  11107. // cancel timeout and subsequent timeout promise resolution
  11108. if (isDefined(timeoutId)) {
  11109. $browserDefer.cancel(timeoutId);
  11110. }
  11111. jsonpDone = xhr = null;
  11112. callback(status, response, headersString, statusText);
  11113. }
  11114. };
  11115. function jsonpReq(url, callbackPath, done) {
  11116. url = url.replace('JSON_CALLBACK', callbackPath);
  11117. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  11118. // - fetches local scripts via XHR and evals them
  11119. // - adds and immediately removes script elements from the document
  11120. var script = rawDocument.createElement('script'), callback = null;
  11121. script.type = 'text/javascript';
  11122. script.src = url;
  11123. script.async = true;
  11124. callback = function(event) {
  11125. script.removeEventListener('load', callback);
  11126. script.removeEventListener('error', callback);
  11127. rawDocument.body.removeChild(script);
  11128. script = null;
  11129. var status = -1;
  11130. var text = 'unknown';
  11131. if (event) {
  11132. if (event.type === 'load' && !callbacks.wasCalled(callbackPath)) {
  11133. event = { type: 'error' };
  11134. }
  11135. text = event.type;
  11136. status = event.type === 'error' ? 404 : 200;
  11137. }
  11138. if (done) {
  11139. done(status, text);
  11140. }
  11141. };
  11142. script.addEventListener('load', callback);
  11143. script.addEventListener('error', callback);
  11144. rawDocument.body.appendChild(script);
  11145. return callback;
  11146. }
  11147. }
  11148. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  11149. $interpolateMinErr.throwNoconcat = function(text) {
  11150. throw $interpolateMinErr('noconcat',
  11151. 'Error while interpolating: {0}\nStrict Contextual Escaping disallows ' +
  11152. 'interpolations that concatenate multiple expressions when a trusted value is ' +
  11153. 'required. See http://docs.angularjs.org/api/ng.$sce', text);
  11154. };
  11155. $interpolateMinErr.interr = function(text, err) {
  11156. return $interpolateMinErr('interr', 'Can\'t interpolate: {0}\n{1}', text, err.toString());
  11157. };
  11158. /**
  11159. * @ngdoc provider
  11160. * @name $interpolateProvider
  11161. * @this
  11162. *
  11163. * @description
  11164. *
  11165. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  11166. *
  11167. * <div class="alert alert-danger">
  11168. * This feature is sometimes used to mix different markup languages, e.g. to wrap an Angular
  11169. * template within a Python Jinja template (or any other template language). Mixing templating
  11170. * languages is **very dangerous**. The embedding template language will not safely escape Angular
  11171. * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)
  11172. * security bugs!
  11173. * </div>
  11174. *
  11175. * @example
  11176. <example name="custom-interpolation-markup" module="customInterpolationApp">
  11177. <file name="index.html">
  11178. <script>
  11179. var customInterpolationApp = angular.module('customInterpolationApp', []);
  11180. customInterpolationApp.config(function($interpolateProvider) {
  11181. $interpolateProvider.startSymbol('//');
  11182. $interpolateProvider.endSymbol('//');
  11183. });
  11184. customInterpolationApp.controller('DemoController', function() {
  11185. this.label = "This binding is brought you by // interpolation symbols.";
  11186. });
  11187. </script>
  11188. <div ng-controller="DemoController as demo">
  11189. //demo.label//
  11190. </div>
  11191. </file>
  11192. <file name="protractor.js" type="protractor">
  11193. it('should interpolate binding with custom symbols', function() {
  11194. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  11195. });
  11196. </file>
  11197. </example>
  11198. */
  11199. function $InterpolateProvider() {
  11200. var startSymbol = '{{';
  11201. var endSymbol = '}}';
  11202. /**
  11203. * @ngdoc method
  11204. * @name $interpolateProvider#startSymbol
  11205. * @description
  11206. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  11207. *
  11208. * @param {string=} value new value to set the starting symbol to.
  11209. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  11210. */
  11211. this.startSymbol = function(value) {
  11212. if (value) {
  11213. startSymbol = value;
  11214. return this;
  11215. } else {
  11216. return startSymbol;
  11217. }
  11218. };
  11219. /**
  11220. * @ngdoc method
  11221. * @name $interpolateProvider#endSymbol
  11222. * @description
  11223. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  11224. *
  11225. * @param {string=} value new value to set the ending symbol to.
  11226. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  11227. */
  11228. this.endSymbol = function(value) {
  11229. if (value) {
  11230. endSymbol = value;
  11231. return this;
  11232. } else {
  11233. return endSymbol;
  11234. }
  11235. };
  11236. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  11237. var startSymbolLength = startSymbol.length,
  11238. endSymbolLength = endSymbol.length,
  11239. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  11240. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  11241. function escape(ch) {
  11242. return '\\\\\\' + ch;
  11243. }
  11244. function unescapeText(text) {
  11245. return text.replace(escapedStartRegexp, startSymbol).
  11246. replace(escapedEndRegexp, endSymbol);
  11247. }
  11248. // TODO: this is the same as the constantWatchDelegate in parse.js
  11249. function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {
  11250. var unwatch = scope.$watch(function constantInterpolateWatch(scope) {
  11251. unwatch();
  11252. return constantInterp(scope);
  11253. }, listener, objectEquality);
  11254. return unwatch;
  11255. }
  11256. /**
  11257. * @ngdoc service
  11258. * @name $interpolate
  11259. * @kind function
  11260. *
  11261. * @requires $parse
  11262. * @requires $sce
  11263. *
  11264. * @description
  11265. *
  11266. * Compiles a string with markup into an interpolation function. This service is used by the
  11267. * HTML {@link ng.$compile $compile} service for data binding. See
  11268. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  11269. * interpolation markup.
  11270. *
  11271. *
  11272. * ```js
  11273. * var $interpolate = ...; // injected
  11274. * var exp = $interpolate('Hello {{name | uppercase}}!');
  11275. * expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
  11276. * ```
  11277. *
  11278. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  11279. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  11280. * evaluate to a value other than `undefined`.
  11281. *
  11282. * ```js
  11283. * var $interpolate = ...; // injected
  11284. * var context = {greeting: 'Hello', name: undefined };
  11285. *
  11286. * // default "forgiving" mode
  11287. * var exp = $interpolate('{{greeting}} {{name}}!');
  11288. * expect(exp(context)).toEqual('Hello !');
  11289. *
  11290. * // "allOrNothing" mode
  11291. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  11292. * expect(exp(context)).toBeUndefined();
  11293. * context.name = 'Angular';
  11294. * expect(exp(context)).toEqual('Hello Angular!');
  11295. * ```
  11296. *
  11297. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  11298. *
  11299. * #### Escaped Interpolation
  11300. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  11301. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  11302. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  11303. * or binding.
  11304. *
  11305. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  11306. * degree, while also enabling code examples to work without relying on the
  11307. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  11308. *
  11309. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  11310. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  11311. * interpolation start/end markers with their escaped counterparts.**
  11312. *
  11313. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  11314. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  11315. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  11316. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  11317. * this is typically useful only when user-data is used in rendering a template from the server, or
  11318. * when otherwise untrusted data is used by a directive.
  11319. *
  11320. * <example name="interpolation">
  11321. * <file name="index.html">
  11322. * <div ng-init="username='A user'">
  11323. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  11324. * </p>
  11325. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  11326. * application, but fails to accomplish their task, because the server has correctly
  11327. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  11328. * characters.</p>
  11329. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  11330. * from the database by an administrator.</p>
  11331. * </div>
  11332. * </file>
  11333. * </example>
  11334. *
  11335. * @knownIssue
  11336. * It is currently not possible for an interpolated expression to contain the interpolation end
  11337. * symbol. For example, `{{ '}}' }}` will be incorrectly interpreted as `{{ ' }}` + `' }}`, i.e.
  11338. * an interpolated expression consisting of a single-quote (`'`) and the `' }}` string.
  11339. *
  11340. * @knownIssue
  11341. * All directives and components must use the standard `{{` `}}` interpolation symbols
  11342. * in their templates. If you change the application interpolation symbols the {@link $compile}
  11343. * service will attempt to denormalize the standard symbols to the custom symbols.
  11344. * The denormalization process is not clever enough to know not to replace instances of the standard
  11345. * symbols where they would not normally be treated as interpolation symbols. For example in the following
  11346. * code snippet the closing braces of the literal object will get incorrectly denormalized:
  11347. *
  11348. * ```
  11349. * <div data-context='{"context":{"id":3,"type":"page"}}">
  11350. * ```
  11351. *
  11352. * The workaround is to ensure that such instances are separated by whitespace:
  11353. * ```
  11354. * <div data-context='{"context":{"id":3,"type":"page"} }">
  11355. * ```
  11356. *
  11357. * See https://github.com/angular/angular.js/pull/14610#issuecomment-219401099 for more information.
  11358. *
  11359. * @param {string} text The text with markup to interpolate.
  11360. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  11361. * embedded expression in order to return an interpolation function. Strings with no
  11362. * embedded expression will return null for the interpolation function.
  11363. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  11364. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  11365. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  11366. * provides Strict Contextual Escaping for details.
  11367. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  11368. * unless all embedded expressions evaluate to a value other than `undefined`.
  11369. * @returns {function(context)} an interpolation function which is used to compute the
  11370. * interpolated string. The function has these parameters:
  11371. *
  11372. * - `context`: evaluation context for all expressions embedded in the interpolated text
  11373. */
  11374. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  11375. // Provide a quick exit and simplified result function for text with no interpolation
  11376. if (!text.length || text.indexOf(startSymbol) === -1) {
  11377. var constantInterp;
  11378. if (!mustHaveExpression) {
  11379. var unescapedText = unescapeText(text);
  11380. constantInterp = valueFn(unescapedText);
  11381. constantInterp.exp = text;
  11382. constantInterp.expressions = [];
  11383. constantInterp.$$watchDelegate = constantWatchDelegate;
  11384. }
  11385. return constantInterp;
  11386. }
  11387. allOrNothing = !!allOrNothing;
  11388. var startIndex,
  11389. endIndex,
  11390. index = 0,
  11391. expressions = [],
  11392. parseFns = [],
  11393. textLength = text.length,
  11394. exp,
  11395. concat = [],
  11396. expressionPositions = [];
  11397. while (index < textLength) {
  11398. if (((startIndex = text.indexOf(startSymbol, index)) !== -1) &&
  11399. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) !== -1)) {
  11400. if (index !== startIndex) {
  11401. concat.push(unescapeText(text.substring(index, startIndex)));
  11402. }
  11403. exp = text.substring(startIndex + startSymbolLength, endIndex);
  11404. expressions.push(exp);
  11405. parseFns.push($parse(exp, parseStringifyInterceptor));
  11406. index = endIndex + endSymbolLength;
  11407. expressionPositions.push(concat.length);
  11408. concat.push('');
  11409. } else {
  11410. // we did not find an interpolation, so we have to add the remainder to the separators array
  11411. if (index !== textLength) {
  11412. concat.push(unescapeText(text.substring(index)));
  11413. }
  11414. break;
  11415. }
  11416. }
  11417. // Concatenating expressions makes it hard to reason about whether some combination of
  11418. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  11419. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  11420. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  11421. // make it obvious that you bound the value to some user controlled value. This helps reduce
  11422. // the load when auditing for XSS issues.
  11423. if (trustedContext && concat.length > 1) {
  11424. $interpolateMinErr.throwNoconcat(text);
  11425. }
  11426. if (!mustHaveExpression || expressions.length) {
  11427. var compute = function(values) {
  11428. for (var i = 0, ii = expressions.length; i < ii; i++) {
  11429. if (allOrNothing && isUndefined(values[i])) return;
  11430. concat[expressionPositions[i]] = values[i];
  11431. }
  11432. return concat.join('');
  11433. };
  11434. var getValue = function(value) {
  11435. return trustedContext ?
  11436. $sce.getTrusted(trustedContext, value) :
  11437. $sce.valueOf(value);
  11438. };
  11439. return extend(function interpolationFn(context) {
  11440. var i = 0;
  11441. var ii = expressions.length;
  11442. var values = new Array(ii);
  11443. try {
  11444. for (; i < ii; i++) {
  11445. values[i] = parseFns[i](context);
  11446. }
  11447. return compute(values);
  11448. } catch (err) {
  11449. $exceptionHandler($interpolateMinErr.interr(text, err));
  11450. }
  11451. }, {
  11452. // all of these properties are undocumented for now
  11453. exp: text, //just for compatibility with regular watchers created via $watch
  11454. expressions: expressions,
  11455. $$watchDelegate: function(scope, listener) {
  11456. var lastValue;
  11457. return scope.$watchGroup(parseFns, /** @this */ function interpolateFnWatcher(values, oldValues) {
  11458. var currValue = compute(values);
  11459. if (isFunction(listener)) {
  11460. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  11461. }
  11462. lastValue = currValue;
  11463. });
  11464. }
  11465. });
  11466. }
  11467. function parseStringifyInterceptor(value) {
  11468. try {
  11469. value = getValue(value);
  11470. return allOrNothing && !isDefined(value) ? value : stringify(value);
  11471. } catch (err) {
  11472. $exceptionHandler($interpolateMinErr.interr(text, err));
  11473. }
  11474. }
  11475. }
  11476. /**
  11477. * @ngdoc method
  11478. * @name $interpolate#startSymbol
  11479. * @description
  11480. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  11481. *
  11482. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  11483. * the symbol.
  11484. *
  11485. * @returns {string} start symbol.
  11486. */
  11487. $interpolate.startSymbol = function() {
  11488. return startSymbol;
  11489. };
  11490. /**
  11491. * @ngdoc method
  11492. * @name $interpolate#endSymbol
  11493. * @description
  11494. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  11495. *
  11496. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  11497. * the symbol.
  11498. *
  11499. * @returns {string} end symbol.
  11500. */
  11501. $interpolate.endSymbol = function() {
  11502. return endSymbol;
  11503. };
  11504. return $interpolate;
  11505. }];
  11506. }
  11507. /** @this */
  11508. function $IntervalProvider() {
  11509. this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',
  11510. function($rootScope, $window, $q, $$q, $browser) {
  11511. var intervals = {};
  11512. /**
  11513. * @ngdoc service
  11514. * @name $interval
  11515. *
  11516. * @description
  11517. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  11518. * milliseconds.
  11519. *
  11520. * The return value of registering an interval function is a promise. This promise will be
  11521. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  11522. * run indefinitely if `count` is not defined. The value of the notification will be the
  11523. * number of iterations that have run.
  11524. * To cancel an interval, call `$interval.cancel(promise)`.
  11525. *
  11526. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  11527. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  11528. * time.
  11529. *
  11530. * <div class="alert alert-warning">
  11531. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  11532. * with them. In particular they are not automatically destroyed when a controller's scope or a
  11533. * directive's element are destroyed.
  11534. * You should take this into consideration and make sure to always cancel the interval at the
  11535. * appropriate moment. See the example below for more details on how and when to do this.
  11536. * </div>
  11537. *
  11538. * @param {function()} fn A function that should be called repeatedly.
  11539. * @param {number} delay Number of milliseconds between each function call.
  11540. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  11541. * indefinitely.
  11542. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  11543. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  11544. * @param {...*=} Pass additional parameters to the executed function.
  11545. * @returns {promise} A promise which will be notified on each iteration.
  11546. *
  11547. * @example
  11548. * <example module="intervalExample" name="interval-service">
  11549. * <file name="index.html">
  11550. * <script>
  11551. * angular.module('intervalExample', [])
  11552. * .controller('ExampleController', ['$scope', '$interval',
  11553. * function($scope, $interval) {
  11554. * $scope.format = 'M/d/yy h:mm:ss a';
  11555. * $scope.blood_1 = 100;
  11556. * $scope.blood_2 = 120;
  11557. *
  11558. * var stop;
  11559. * $scope.fight = function() {
  11560. * // Don't start a new fight if we are already fighting
  11561. * if ( angular.isDefined(stop) ) return;
  11562. *
  11563. * stop = $interval(function() {
  11564. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  11565. * $scope.blood_1 = $scope.blood_1 - 3;
  11566. * $scope.blood_2 = $scope.blood_2 - 4;
  11567. * } else {
  11568. * $scope.stopFight();
  11569. * }
  11570. * }, 100);
  11571. * };
  11572. *
  11573. * $scope.stopFight = function() {
  11574. * if (angular.isDefined(stop)) {
  11575. * $interval.cancel(stop);
  11576. * stop = undefined;
  11577. * }
  11578. * };
  11579. *
  11580. * $scope.resetFight = function() {
  11581. * $scope.blood_1 = 100;
  11582. * $scope.blood_2 = 120;
  11583. * };
  11584. *
  11585. * $scope.$on('$destroy', function() {
  11586. * // Make sure that the interval is destroyed too
  11587. * $scope.stopFight();
  11588. * });
  11589. * }])
  11590. * // Register the 'myCurrentTime' directive factory method.
  11591. * // We inject $interval and dateFilter service since the factory method is DI.
  11592. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  11593. * function($interval, dateFilter) {
  11594. * // return the directive link function. (compile function not needed)
  11595. * return function(scope, element, attrs) {
  11596. * var format, // date format
  11597. * stopTime; // so that we can cancel the time updates
  11598. *
  11599. * // used to update the UI
  11600. * function updateTime() {
  11601. * element.text(dateFilter(new Date(), format));
  11602. * }
  11603. *
  11604. * // watch the expression, and update the UI on change.
  11605. * scope.$watch(attrs.myCurrentTime, function(value) {
  11606. * format = value;
  11607. * updateTime();
  11608. * });
  11609. *
  11610. * stopTime = $interval(updateTime, 1000);
  11611. *
  11612. * // listen on DOM destroy (removal) event, and cancel the next UI update
  11613. * // to prevent updating time after the DOM element was removed.
  11614. * element.on('$destroy', function() {
  11615. * $interval.cancel(stopTime);
  11616. * });
  11617. * }
  11618. * }]);
  11619. * </script>
  11620. *
  11621. * <div>
  11622. * <div ng-controller="ExampleController">
  11623. * <label>Date format: <input ng-model="format"></label> <hr/>
  11624. * Current time is: <span my-current-time="format"></span>
  11625. * <hr/>
  11626. * Blood 1 : <font color='red'>{{blood_1}}</font>
  11627. * Blood 2 : <font color='red'>{{blood_2}}</font>
  11628. * <button type="button" data-ng-click="fight()">Fight</button>
  11629. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  11630. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  11631. * </div>
  11632. * </div>
  11633. *
  11634. * </file>
  11635. * </example>
  11636. */
  11637. function interval(fn, delay, count, invokeApply) {
  11638. var hasParams = arguments.length > 4,
  11639. args = hasParams ? sliceArgs(arguments, 4) : [],
  11640. setInterval = $window.setInterval,
  11641. clearInterval = $window.clearInterval,
  11642. iteration = 0,
  11643. skipApply = (isDefined(invokeApply) && !invokeApply),
  11644. deferred = (skipApply ? $$q : $q).defer(),
  11645. promise = deferred.promise;
  11646. count = isDefined(count) ? count : 0;
  11647. promise.$$intervalId = setInterval(function tick() {
  11648. if (skipApply) {
  11649. $browser.defer(callback);
  11650. } else {
  11651. $rootScope.$evalAsync(callback);
  11652. }
  11653. deferred.notify(iteration++);
  11654. if (count > 0 && iteration >= count) {
  11655. deferred.resolve(iteration);
  11656. clearInterval(promise.$$intervalId);
  11657. delete intervals[promise.$$intervalId];
  11658. }
  11659. if (!skipApply) $rootScope.$apply();
  11660. }, delay);
  11661. intervals[promise.$$intervalId] = deferred;
  11662. return promise;
  11663. function callback() {
  11664. if (!hasParams) {
  11665. fn(iteration);
  11666. } else {
  11667. fn.apply(null, args);
  11668. }
  11669. }
  11670. }
  11671. /**
  11672. * @ngdoc method
  11673. * @name $interval#cancel
  11674. *
  11675. * @description
  11676. * Cancels a task associated with the `promise`.
  11677. *
  11678. * @param {Promise=} promise returned by the `$interval` function.
  11679. * @returns {boolean} Returns `true` if the task was successfully canceled.
  11680. */
  11681. interval.cancel = function(promise) {
  11682. if (promise && promise.$$intervalId in intervals) {
  11683. // Interval cancels should not report as unhandled promise.
  11684. intervals[promise.$$intervalId].promise.catch(noop);
  11685. intervals[promise.$$intervalId].reject('canceled');
  11686. $window.clearInterval(promise.$$intervalId);
  11687. delete intervals[promise.$$intervalId];
  11688. return true;
  11689. }
  11690. return false;
  11691. };
  11692. return interval;
  11693. }];
  11694. }
  11695. /**
  11696. * @ngdoc service
  11697. * @name $jsonpCallbacks
  11698. * @requires $window
  11699. * @description
  11700. * This service handles the lifecycle of callbacks to handle JSONP requests.
  11701. * Override this service if you wish to customise where the callbacks are stored and
  11702. * how they vary compared to the requested url.
  11703. */
  11704. var $jsonpCallbacksProvider = /** @this */ function() {
  11705. this.$get = ['$window', function($window) {
  11706. var callbacks = $window.angular.callbacks;
  11707. var callbackMap = {};
  11708. function createCallback(callbackId) {
  11709. var callback = function(data) {
  11710. callback.data = data;
  11711. callback.called = true;
  11712. };
  11713. callback.id = callbackId;
  11714. return callback;
  11715. }
  11716. return {
  11717. /**
  11718. * @ngdoc method
  11719. * @name $jsonpCallbacks#createCallback
  11720. * @param {string} url the url of the JSONP request
  11721. * @returns {string} the callback path to send to the server as part of the JSONP request
  11722. * @description
  11723. * {@link $httpBackend} calls this method to create a callback and get hold of the path to the callback
  11724. * to pass to the server, which will be used to call the callback with its payload in the JSONP response.
  11725. */
  11726. createCallback: function(url) {
  11727. var callbackId = '_' + (callbacks.$$counter++).toString(36);
  11728. var callbackPath = 'angular.callbacks.' + callbackId;
  11729. var callback = createCallback(callbackId);
  11730. callbackMap[callbackPath] = callbacks[callbackId] = callback;
  11731. return callbackPath;
  11732. },
  11733. /**
  11734. * @ngdoc method
  11735. * @name $jsonpCallbacks#wasCalled
  11736. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  11737. * @returns {boolean} whether the callback has been called, as a result of the JSONP response
  11738. * @description
  11739. * {@link $httpBackend} calls this method to find out whether the JSONP response actually called the
  11740. * callback that was passed in the request.
  11741. */
  11742. wasCalled: function(callbackPath) {
  11743. return callbackMap[callbackPath].called;
  11744. },
  11745. /**
  11746. * @ngdoc method
  11747. * @name $jsonpCallbacks#getResponse
  11748. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  11749. * @returns {*} the data received from the response via the registered callback
  11750. * @description
  11751. * {@link $httpBackend} calls this method to get hold of the data that was provided to the callback
  11752. * in the JSONP response.
  11753. */
  11754. getResponse: function(callbackPath) {
  11755. return callbackMap[callbackPath].data;
  11756. },
  11757. /**
  11758. * @ngdoc method
  11759. * @name $jsonpCallbacks#removeCallback
  11760. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  11761. * @description
  11762. * {@link $httpBackend} calls this method to remove the callback after the JSONP request has
  11763. * completed or timed-out.
  11764. */
  11765. removeCallback: function(callbackPath) {
  11766. var callback = callbackMap[callbackPath];
  11767. delete callbacks[callback.id];
  11768. delete callbackMap[callbackPath];
  11769. }
  11770. };
  11771. }];
  11772. };
  11773. /**
  11774. * @ngdoc service
  11775. * @name $locale
  11776. *
  11777. * @description
  11778. * $locale service provides localization rules for various Angular components. As of right now the
  11779. * only public api is:
  11780. *
  11781. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  11782. */
  11783. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  11784. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  11785. var $locationMinErr = minErr('$location');
  11786. /**
  11787. * Encode path using encodeUriSegment, ignoring forward slashes
  11788. *
  11789. * @param {string} path Path to encode
  11790. * @returns {string}
  11791. */
  11792. function encodePath(path) {
  11793. var segments = path.split('/'),
  11794. i = segments.length;
  11795. while (i--) {
  11796. segments[i] = encodeUriSegment(segments[i]);
  11797. }
  11798. return segments.join('/');
  11799. }
  11800. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  11801. var parsedUrl = urlResolve(absoluteUrl);
  11802. locationObj.$$protocol = parsedUrl.protocol;
  11803. locationObj.$$host = parsedUrl.hostname;
  11804. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  11805. }
  11806. function parseAppUrl(relativeUrl, locationObj) {
  11807. var prefixed = (relativeUrl.charAt(0) !== '/');
  11808. if (prefixed) {
  11809. relativeUrl = '/' + relativeUrl;
  11810. }
  11811. var match = urlResolve(relativeUrl);
  11812. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  11813. match.pathname.substring(1) : match.pathname);
  11814. locationObj.$$search = parseKeyValue(match.search);
  11815. locationObj.$$hash = decodeURIComponent(match.hash);
  11816. // make sure path starts with '/';
  11817. if (locationObj.$$path && locationObj.$$path.charAt(0) !== '/') {
  11818. locationObj.$$path = '/' + locationObj.$$path;
  11819. }
  11820. }
  11821. function startsWith(haystack, needle) {
  11822. return haystack.lastIndexOf(needle, 0) === 0;
  11823. }
  11824. /**
  11825. *
  11826. * @param {string} base
  11827. * @param {string} url
  11828. * @returns {string} returns text from `url` after `base` or `undefined` if it does not begin with
  11829. * the expected string.
  11830. */
  11831. function stripBaseUrl(base, url) {
  11832. if (startsWith(url, base)) {
  11833. return url.substr(base.length);
  11834. }
  11835. }
  11836. function stripHash(url) {
  11837. var index = url.indexOf('#');
  11838. return index === -1 ? url : url.substr(0, index);
  11839. }
  11840. function trimEmptyHash(url) {
  11841. return url.replace(/(#.+)|#$/, '$1');
  11842. }
  11843. function stripFile(url) {
  11844. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  11845. }
  11846. /* return the server only (scheme://host:port) */
  11847. function serverBase(url) {
  11848. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  11849. }
  11850. /**
  11851. * LocationHtml5Url represents a URL
  11852. * This object is exposed as $location service when HTML5 mode is enabled and supported
  11853. *
  11854. * @constructor
  11855. * @param {string} appBase application base URL
  11856. * @param {string} appBaseNoFile application base URL stripped of any filename
  11857. * @param {string} basePrefix URL path prefix
  11858. */
  11859. function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
  11860. this.$$html5 = true;
  11861. basePrefix = basePrefix || '';
  11862. parseAbsoluteUrl(appBase, this);
  11863. /**
  11864. * Parse given HTML5 (regular) URL string into properties
  11865. * @param {string} url HTML5 URL
  11866. * @private
  11867. */
  11868. this.$$parse = function(url) {
  11869. var pathUrl = stripBaseUrl(appBaseNoFile, url);
  11870. if (!isString(pathUrl)) {
  11871. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  11872. appBaseNoFile);
  11873. }
  11874. parseAppUrl(pathUrl, this);
  11875. if (!this.$$path) {
  11876. this.$$path = '/';
  11877. }
  11878. this.$$compose();
  11879. };
  11880. /**
  11881. * Compose url and update `absUrl` property
  11882. * @private
  11883. */
  11884. this.$$compose = function() {
  11885. var search = toKeyValue(this.$$search),
  11886. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  11887. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  11888. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  11889. };
  11890. this.$$parseLinkUrl = function(url, relHref) {
  11891. if (relHref && relHref[0] === '#') {
  11892. // special case for links to hash fragments:
  11893. // keep the old url and only replace the hash fragment
  11894. this.hash(relHref.slice(1));
  11895. return true;
  11896. }
  11897. var appUrl, prevAppUrl;
  11898. var rewrittenUrl;
  11899. if (isDefined(appUrl = stripBaseUrl(appBase, url))) {
  11900. prevAppUrl = appUrl;
  11901. if (isDefined(appUrl = stripBaseUrl(basePrefix, appUrl))) {
  11902. rewrittenUrl = appBaseNoFile + (stripBaseUrl('/', appUrl) || appUrl);
  11903. } else {
  11904. rewrittenUrl = appBase + prevAppUrl;
  11905. }
  11906. } else if (isDefined(appUrl = stripBaseUrl(appBaseNoFile, url))) {
  11907. rewrittenUrl = appBaseNoFile + appUrl;
  11908. } else if (appBaseNoFile === url + '/') {
  11909. rewrittenUrl = appBaseNoFile;
  11910. }
  11911. if (rewrittenUrl) {
  11912. this.$$parse(rewrittenUrl);
  11913. }
  11914. return !!rewrittenUrl;
  11915. };
  11916. }
  11917. /**
  11918. * LocationHashbangUrl represents URL
  11919. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  11920. * It also serves as the base class for html5 mode fallback on legacy browsers.
  11921. *
  11922. * @constructor
  11923. * @param {string} appBase application base URL
  11924. * @param {string} appBaseNoFile application base URL stripped of any filename
  11925. * @param {string} hashPrefix hashbang prefix
  11926. */
  11927. function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
  11928. parseAbsoluteUrl(appBase, this);
  11929. /**
  11930. * Parse given hashbang URL into properties
  11931. * @param {string} url Hashbang URL
  11932. * @private
  11933. */
  11934. this.$$parse = function(url) {
  11935. var withoutBaseUrl = stripBaseUrl(appBase, url) || stripBaseUrl(appBaseNoFile, url);
  11936. var withoutHashUrl;
  11937. if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
  11938. // The rest of the URL starts with a hash so we have
  11939. // got either a hashbang path or a plain hash fragment
  11940. withoutHashUrl = stripBaseUrl(hashPrefix, withoutBaseUrl);
  11941. if (isUndefined(withoutHashUrl)) {
  11942. // There was no hashbang prefix so we just have a hash fragment
  11943. withoutHashUrl = withoutBaseUrl;
  11944. }
  11945. } else {
  11946. // There was no hashbang path nor hash fragment:
  11947. // If we are in HTML5 mode we use what is left as the path;
  11948. // Otherwise we ignore what is left
  11949. if (this.$$html5) {
  11950. withoutHashUrl = withoutBaseUrl;
  11951. } else {
  11952. withoutHashUrl = '';
  11953. if (isUndefined(withoutBaseUrl)) {
  11954. appBase = url;
  11955. this.replace();
  11956. }
  11957. }
  11958. }
  11959. parseAppUrl(withoutHashUrl, this);
  11960. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  11961. this.$$compose();
  11962. /*
  11963. * In Windows, on an anchor node on documents loaded from
  11964. * the filesystem, the browser will return a pathname
  11965. * prefixed with the drive name ('/C:/path') when a
  11966. * pathname without a drive is set:
  11967. * * a.setAttribute('href', '/foo')
  11968. * * a.pathname === '/C:/foo' //true
  11969. *
  11970. * Inside of Angular, we're always using pathnames that
  11971. * do not include drive names for routing.
  11972. */
  11973. function removeWindowsDriveName(path, url, base) {
  11974. /*
  11975. Matches paths for file protocol on windows,
  11976. such as /C:/foo/bar, and captures only /foo/bar.
  11977. */
  11978. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  11979. var firstPathSegmentMatch;
  11980. //Get the relative path from the input URL.
  11981. if (startsWith(url, base)) {
  11982. url = url.replace(base, '');
  11983. }
  11984. // The input URL intentionally contains a first path segment that ends with a colon.
  11985. if (windowsFilePathExp.exec(url)) {
  11986. return path;
  11987. }
  11988. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  11989. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  11990. }
  11991. };
  11992. /**
  11993. * Compose hashbang URL and update `absUrl` property
  11994. * @private
  11995. */
  11996. this.$$compose = function() {
  11997. var search = toKeyValue(this.$$search),
  11998. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  11999. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  12000. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  12001. };
  12002. this.$$parseLinkUrl = function(url, relHref) {
  12003. if (stripHash(appBase) === stripHash(url)) {
  12004. this.$$parse(url);
  12005. return true;
  12006. }
  12007. return false;
  12008. };
  12009. }
  12010. /**
  12011. * LocationHashbangUrl represents URL
  12012. * This object is exposed as $location service when html5 history api is enabled but the browser
  12013. * does not support it.
  12014. *
  12015. * @constructor
  12016. * @param {string} appBase application base URL
  12017. * @param {string} appBaseNoFile application base URL stripped of any filename
  12018. * @param {string} hashPrefix hashbang prefix
  12019. */
  12020. function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
  12021. this.$$html5 = true;
  12022. LocationHashbangUrl.apply(this, arguments);
  12023. this.$$parseLinkUrl = function(url, relHref) {
  12024. if (relHref && relHref[0] === '#') {
  12025. // special case for links to hash fragments:
  12026. // keep the old url and only replace the hash fragment
  12027. this.hash(relHref.slice(1));
  12028. return true;
  12029. }
  12030. var rewrittenUrl;
  12031. var appUrl;
  12032. if (appBase === stripHash(url)) {
  12033. rewrittenUrl = url;
  12034. } else if ((appUrl = stripBaseUrl(appBaseNoFile, url))) {
  12035. rewrittenUrl = appBase + hashPrefix + appUrl;
  12036. } else if (appBaseNoFile === url + '/') {
  12037. rewrittenUrl = appBaseNoFile;
  12038. }
  12039. if (rewrittenUrl) {
  12040. this.$$parse(rewrittenUrl);
  12041. }
  12042. return !!rewrittenUrl;
  12043. };
  12044. this.$$compose = function() {
  12045. var search = toKeyValue(this.$$search),
  12046. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  12047. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  12048. // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
  12049. this.$$absUrl = appBase + hashPrefix + this.$$url;
  12050. };
  12051. }
  12052. var locationPrototype = {
  12053. /**
  12054. * Ensure absolute URL is initialized.
  12055. * @private
  12056. */
  12057. $$absUrl:'',
  12058. /**
  12059. * Are we in html5 mode?
  12060. * @private
  12061. */
  12062. $$html5: false,
  12063. /**
  12064. * Has any change been replacing?
  12065. * @private
  12066. */
  12067. $$replace: false,
  12068. /**
  12069. * @ngdoc method
  12070. * @name $location#absUrl
  12071. *
  12072. * @description
  12073. * This method is getter only.
  12074. *
  12075. * Return full URL representation with all segments encoded according to rules specified in
  12076. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  12077. *
  12078. *
  12079. * ```js
  12080. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12081. * var absUrl = $location.absUrl();
  12082. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  12083. * ```
  12084. *
  12085. * @return {string} full URL
  12086. */
  12087. absUrl: locationGetter('$$absUrl'),
  12088. /**
  12089. * @ngdoc method
  12090. * @name $location#url
  12091. *
  12092. * @description
  12093. * This method is getter / setter.
  12094. *
  12095. * Return URL (e.g. `/path?a=b#hash`) when called without any parameter.
  12096. *
  12097. * Change path, search and hash, when called with parameter and return `$location`.
  12098. *
  12099. *
  12100. * ```js
  12101. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12102. * var url = $location.url();
  12103. * // => "/some/path?foo=bar&baz=xoxo"
  12104. * ```
  12105. *
  12106. * @param {string=} url New URL without base prefix (e.g. `/path?a=b#hash`)
  12107. * @return {string} url
  12108. */
  12109. url: function(url) {
  12110. if (isUndefined(url)) {
  12111. return this.$$url;
  12112. }
  12113. var match = PATH_MATCH.exec(url);
  12114. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  12115. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  12116. this.hash(match[5] || '');
  12117. return this;
  12118. },
  12119. /**
  12120. * @ngdoc method
  12121. * @name $location#protocol
  12122. *
  12123. * @description
  12124. * This method is getter only.
  12125. *
  12126. * Return protocol of current URL.
  12127. *
  12128. *
  12129. * ```js
  12130. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12131. * var protocol = $location.protocol();
  12132. * // => "http"
  12133. * ```
  12134. *
  12135. * @return {string} protocol of current URL
  12136. */
  12137. protocol: locationGetter('$$protocol'),
  12138. /**
  12139. * @ngdoc method
  12140. * @name $location#host
  12141. *
  12142. * @description
  12143. * This method is getter only.
  12144. *
  12145. * Return host of current URL.
  12146. *
  12147. * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  12148. *
  12149. *
  12150. * ```js
  12151. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12152. * var host = $location.host();
  12153. * // => "example.com"
  12154. *
  12155. * // given URL http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  12156. * host = $location.host();
  12157. * // => "example.com"
  12158. * host = location.host;
  12159. * // => "example.com:8080"
  12160. * ```
  12161. *
  12162. * @return {string} host of current URL.
  12163. */
  12164. host: locationGetter('$$host'),
  12165. /**
  12166. * @ngdoc method
  12167. * @name $location#port
  12168. *
  12169. * @description
  12170. * This method is getter only.
  12171. *
  12172. * Return port of current URL.
  12173. *
  12174. *
  12175. * ```js
  12176. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12177. * var port = $location.port();
  12178. * // => 80
  12179. * ```
  12180. *
  12181. * @return {Number} port
  12182. */
  12183. port: locationGetter('$$port'),
  12184. /**
  12185. * @ngdoc method
  12186. * @name $location#path
  12187. *
  12188. * @description
  12189. * This method is getter / setter.
  12190. *
  12191. * Return path of current URL when called without any parameter.
  12192. *
  12193. * Change path when called with parameter and return `$location`.
  12194. *
  12195. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  12196. * if it is missing.
  12197. *
  12198. *
  12199. * ```js
  12200. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12201. * var path = $location.path();
  12202. * // => "/some/path"
  12203. * ```
  12204. *
  12205. * @param {(string|number)=} path New path
  12206. * @return {(string|object)} path if called with no parameters, or `$location` if called with a parameter
  12207. */
  12208. path: locationGetterSetter('$$path', function(path) {
  12209. path = path !== null ? path.toString() : '';
  12210. return path.charAt(0) === '/' ? path : '/' + path;
  12211. }),
  12212. /**
  12213. * @ngdoc method
  12214. * @name $location#search
  12215. *
  12216. * @description
  12217. * This method is getter / setter.
  12218. *
  12219. * Return search part (as object) of current URL when called without any parameter.
  12220. *
  12221. * Change search part when called with parameter and return `$location`.
  12222. *
  12223. *
  12224. * ```js
  12225. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12226. * var searchObject = $location.search();
  12227. * // => {foo: 'bar', baz: 'xoxo'}
  12228. *
  12229. * // set foo to 'yipee'
  12230. * $location.search('foo', 'yipee');
  12231. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  12232. * ```
  12233. *
  12234. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  12235. * hash object.
  12236. *
  12237. * When called with a single argument the method acts as a setter, setting the `search` component
  12238. * of `$location` to the specified value.
  12239. *
  12240. * If the argument is a hash object containing an array of values, these values will be encoded
  12241. * as duplicate search parameters in the URL.
  12242. *
  12243. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  12244. * will override only a single search property.
  12245. *
  12246. * If `paramValue` is an array, it will override the property of the `search` component of
  12247. * `$location` specified via the first argument.
  12248. *
  12249. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  12250. *
  12251. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  12252. * value nor trailing equal sign.
  12253. *
  12254. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  12255. * one or more arguments returns `$location` object itself.
  12256. */
  12257. search: function(search, paramValue) {
  12258. switch (arguments.length) {
  12259. case 0:
  12260. return this.$$search;
  12261. case 1:
  12262. if (isString(search) || isNumber(search)) {
  12263. search = search.toString();
  12264. this.$$search = parseKeyValue(search);
  12265. } else if (isObject(search)) {
  12266. search = copy(search, {});
  12267. // remove object undefined or null properties
  12268. forEach(search, function(value, key) {
  12269. if (value == null) delete search[key];
  12270. });
  12271. this.$$search = search;
  12272. } else {
  12273. throw $locationMinErr('isrcharg',
  12274. 'The first argument of the `$location#search()` call must be a string or an object.');
  12275. }
  12276. break;
  12277. default:
  12278. if (isUndefined(paramValue) || paramValue === null) {
  12279. delete this.$$search[search];
  12280. } else {
  12281. this.$$search[search] = paramValue;
  12282. }
  12283. }
  12284. this.$$compose();
  12285. return this;
  12286. },
  12287. /**
  12288. * @ngdoc method
  12289. * @name $location#hash
  12290. *
  12291. * @description
  12292. * This method is getter / setter.
  12293. *
  12294. * Returns the hash fragment when called without any parameters.
  12295. *
  12296. * Changes the hash fragment when called with a parameter and returns `$location`.
  12297. *
  12298. *
  12299. * ```js
  12300. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  12301. * var hash = $location.hash();
  12302. * // => "hashValue"
  12303. * ```
  12304. *
  12305. * @param {(string|number)=} hash New hash fragment
  12306. * @return {string} hash
  12307. */
  12308. hash: locationGetterSetter('$$hash', function(hash) {
  12309. return hash !== null ? hash.toString() : '';
  12310. }),
  12311. /**
  12312. * @ngdoc method
  12313. * @name $location#replace
  12314. *
  12315. * @description
  12316. * If called, all changes to $location during the current `$digest` will replace the current history
  12317. * record, instead of adding a new one.
  12318. */
  12319. replace: function() {
  12320. this.$$replace = true;
  12321. return this;
  12322. }
  12323. };
  12324. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  12325. Location.prototype = Object.create(locationPrototype);
  12326. /**
  12327. * @ngdoc method
  12328. * @name $location#state
  12329. *
  12330. * @description
  12331. * This method is getter / setter.
  12332. *
  12333. * Return the history state object when called without any parameter.
  12334. *
  12335. * Change the history state object when called with one parameter and return `$location`.
  12336. * The state object is later passed to `pushState` or `replaceState`.
  12337. *
  12338. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  12339. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  12340. * older browsers (like IE9 or Android < 4.0), don't use this method.
  12341. *
  12342. * @param {object=} state State object for pushState or replaceState
  12343. * @return {object} state
  12344. */
  12345. Location.prototype.state = function(state) {
  12346. if (!arguments.length) {
  12347. return this.$$state;
  12348. }
  12349. if (Location !== LocationHtml5Url || !this.$$html5) {
  12350. throw $locationMinErr('nostate', 'History API state support is available only ' +
  12351. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  12352. }
  12353. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  12354. // but we're changing the $$state reference to $browser.state() during the $digest
  12355. // so the modification window is narrow.
  12356. this.$$state = isUndefined(state) ? null : state;
  12357. return this;
  12358. };
  12359. });
  12360. function locationGetter(property) {
  12361. return /** @this */ function() {
  12362. return this[property];
  12363. };
  12364. }
  12365. function locationGetterSetter(property, preprocess) {
  12366. return /** @this */ function(value) {
  12367. if (isUndefined(value)) {
  12368. return this[property];
  12369. }
  12370. this[property] = preprocess(value);
  12371. this.$$compose();
  12372. return this;
  12373. };
  12374. }
  12375. /**
  12376. * @ngdoc service
  12377. * @name $location
  12378. *
  12379. * @requires $rootElement
  12380. *
  12381. * @description
  12382. * The $location service parses the URL in the browser address bar (based on the
  12383. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  12384. * available to your application. Changes to the URL in the address bar are reflected into
  12385. * $location service and changes to $location are reflected into the browser address bar.
  12386. *
  12387. * **The $location service:**
  12388. *
  12389. * - Exposes the current URL in the browser address bar, so you can
  12390. * - Watch and observe the URL.
  12391. * - Change the URL.
  12392. * - Synchronizes the URL with the browser when the user
  12393. * - Changes the address bar.
  12394. * - Clicks the back or forward button (or clicks a History link).
  12395. * - Clicks on a link.
  12396. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  12397. *
  12398. * For more information see {@link guide/$location Developer Guide: Using $location}
  12399. */
  12400. /**
  12401. * @ngdoc provider
  12402. * @name $locationProvider
  12403. * @this
  12404. *
  12405. * @description
  12406. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  12407. */
  12408. function $LocationProvider() {
  12409. var hashPrefix = '!',
  12410. html5Mode = {
  12411. enabled: false,
  12412. requireBase: true,
  12413. rewriteLinks: true
  12414. };
  12415. /**
  12416. * @ngdoc method
  12417. * @name $locationProvider#hashPrefix
  12418. * @description
  12419. * The default value for the prefix is `'!'`.
  12420. * @param {string=} prefix Prefix for hash part (containing path and search)
  12421. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  12422. */
  12423. this.hashPrefix = function(prefix) {
  12424. if (isDefined(prefix)) {
  12425. hashPrefix = prefix;
  12426. return this;
  12427. } else {
  12428. return hashPrefix;
  12429. }
  12430. };
  12431. /**
  12432. * @ngdoc method
  12433. * @name $locationProvider#html5Mode
  12434. * @description
  12435. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  12436. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  12437. * properties:
  12438. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  12439. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  12440. * support `pushState`.
  12441. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  12442. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  12443. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  12444. * See the {@link guide/$location $location guide for more information}
  12445. * - **rewriteLinks** - `{boolean|string}` - (default: `true`) When html5Mode is enabled,
  12446. * enables/disables URL rewriting for relative links. If set to a string, URL rewriting will
  12447. * only happen on links with an attribute that matches the given string. For example, if set
  12448. * to `'internal-link'`, then the URL will only be rewritten for `<a internal-link>` links.
  12449. * Note that [attribute name normalization](guide/directive#normalization) does not apply
  12450. * here, so `'internalLink'` will **not** match `'internal-link'`.
  12451. *
  12452. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  12453. */
  12454. this.html5Mode = function(mode) {
  12455. if (isBoolean(mode)) {
  12456. html5Mode.enabled = mode;
  12457. return this;
  12458. } else if (isObject(mode)) {
  12459. if (isBoolean(mode.enabled)) {
  12460. html5Mode.enabled = mode.enabled;
  12461. }
  12462. if (isBoolean(mode.requireBase)) {
  12463. html5Mode.requireBase = mode.requireBase;
  12464. }
  12465. if (isBoolean(mode.rewriteLinks) || isString(mode.rewriteLinks)) {
  12466. html5Mode.rewriteLinks = mode.rewriteLinks;
  12467. }
  12468. return this;
  12469. } else {
  12470. return html5Mode;
  12471. }
  12472. };
  12473. /**
  12474. * @ngdoc event
  12475. * @name $location#$locationChangeStart
  12476. * @eventType broadcast on root scope
  12477. * @description
  12478. * Broadcasted before a URL will change.
  12479. *
  12480. * This change can be prevented by calling
  12481. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  12482. * details about event object. Upon successful change
  12483. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  12484. *
  12485. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  12486. * the browser supports the HTML5 History API.
  12487. *
  12488. * @param {Object} angularEvent Synthetic event object.
  12489. * @param {string} newUrl New URL
  12490. * @param {string=} oldUrl URL that was before it was changed.
  12491. * @param {string=} newState New history state object
  12492. * @param {string=} oldState History state object that was before it was changed.
  12493. */
  12494. /**
  12495. * @ngdoc event
  12496. * @name $location#$locationChangeSuccess
  12497. * @eventType broadcast on root scope
  12498. * @description
  12499. * Broadcasted after a URL was changed.
  12500. *
  12501. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  12502. * the browser supports the HTML5 History API.
  12503. *
  12504. * @param {Object} angularEvent Synthetic event object.
  12505. * @param {string} newUrl New URL
  12506. * @param {string=} oldUrl URL that was before it was changed.
  12507. * @param {string=} newState New history state object
  12508. * @param {string=} oldState History state object that was before it was changed.
  12509. */
  12510. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  12511. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  12512. var $location,
  12513. LocationMode,
  12514. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  12515. initialUrl = $browser.url(),
  12516. appBase;
  12517. if (html5Mode.enabled) {
  12518. if (!baseHref && html5Mode.requireBase) {
  12519. throw $locationMinErr('nobase',
  12520. '$location in HTML5 mode requires a <base> tag to be present!');
  12521. }
  12522. appBase = serverBase(initialUrl) + (baseHref || '/');
  12523. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  12524. } else {
  12525. appBase = stripHash(initialUrl);
  12526. LocationMode = LocationHashbangUrl;
  12527. }
  12528. var appBaseNoFile = stripFile(appBase);
  12529. $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
  12530. $location.$$parseLinkUrl(initialUrl, initialUrl);
  12531. $location.$$state = $browser.state();
  12532. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  12533. function setBrowserUrlWithFallback(url, replace, state) {
  12534. var oldUrl = $location.url();
  12535. var oldState = $location.$$state;
  12536. try {
  12537. $browser.url(url, replace, state);
  12538. // Make sure $location.state() returns referentially identical (not just deeply equal)
  12539. // state object; this makes possible quick checking if the state changed in the digest
  12540. // loop. Checking deep equality would be too expensive.
  12541. $location.$$state = $browser.state();
  12542. } catch (e) {
  12543. // Restore old values if pushState fails
  12544. $location.url(oldUrl);
  12545. $location.$$state = oldState;
  12546. throw e;
  12547. }
  12548. }
  12549. $rootElement.on('click', function(event) {
  12550. var rewriteLinks = html5Mode.rewriteLinks;
  12551. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  12552. // currently we open nice url link and redirect then
  12553. if (!rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which === 2 || event.button === 2) return;
  12554. var elm = jqLite(event.target);
  12555. // traverse the DOM up to find first A tag
  12556. while (nodeName_(elm[0]) !== 'a') {
  12557. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  12558. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  12559. }
  12560. if (isString(rewriteLinks) && isUndefined(elm.attr(rewriteLinks))) return;
  12561. var absHref = elm.prop('href');
  12562. // get the actual href attribute - see
  12563. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  12564. var relHref = elm.attr('href') || elm.attr('xlink:href');
  12565. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  12566. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  12567. // an animation.
  12568. absHref = urlResolve(absHref.animVal).href;
  12569. }
  12570. // Ignore when url is started with javascript: or mailto:
  12571. if (IGNORE_URI_REGEXP.test(absHref)) return;
  12572. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  12573. if ($location.$$parseLinkUrl(absHref, relHref)) {
  12574. // We do a preventDefault for all urls that are part of the angular application,
  12575. // in html5mode and also without, so that we are able to abort navigation without
  12576. // getting double entries in the location history.
  12577. event.preventDefault();
  12578. // update location manually
  12579. if ($location.absUrl() !== $browser.url()) {
  12580. $rootScope.$apply();
  12581. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  12582. $window.angular['ff-684208-preventDefault'] = true;
  12583. }
  12584. }
  12585. }
  12586. });
  12587. // rewrite hashbang url <> html5 url
  12588. if (trimEmptyHash($location.absUrl()) !== trimEmptyHash(initialUrl)) {
  12589. $browser.url($location.absUrl(), true);
  12590. }
  12591. var initializing = true;
  12592. // update $location when $browser url changes
  12593. $browser.onUrlChange(function(newUrl, newState) {
  12594. if (!startsWith(newUrl, appBaseNoFile)) {
  12595. // If we are navigating outside of the app then force a reload
  12596. $window.location.href = newUrl;
  12597. return;
  12598. }
  12599. $rootScope.$evalAsync(function() {
  12600. var oldUrl = $location.absUrl();
  12601. var oldState = $location.$$state;
  12602. var defaultPrevented;
  12603. newUrl = trimEmptyHash(newUrl);
  12604. $location.$$parse(newUrl);
  12605. $location.$$state = newState;
  12606. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  12607. newState, oldState).defaultPrevented;
  12608. // if the location was changed by a `$locationChangeStart` handler then stop
  12609. // processing this location change
  12610. if ($location.absUrl() !== newUrl) return;
  12611. if (defaultPrevented) {
  12612. $location.$$parse(oldUrl);
  12613. $location.$$state = oldState;
  12614. setBrowserUrlWithFallback(oldUrl, false, oldState);
  12615. } else {
  12616. initializing = false;
  12617. afterLocationChange(oldUrl, oldState);
  12618. }
  12619. });
  12620. if (!$rootScope.$$phase) $rootScope.$digest();
  12621. });
  12622. // update browser
  12623. $rootScope.$watch(function $locationWatch() {
  12624. var oldUrl = trimEmptyHash($browser.url());
  12625. var newUrl = trimEmptyHash($location.absUrl());
  12626. var oldState = $browser.state();
  12627. var currentReplace = $location.$$replace;
  12628. var urlOrStateChanged = oldUrl !== newUrl ||
  12629. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  12630. if (initializing || urlOrStateChanged) {
  12631. initializing = false;
  12632. $rootScope.$evalAsync(function() {
  12633. var newUrl = $location.absUrl();
  12634. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  12635. $location.$$state, oldState).defaultPrevented;
  12636. // if the location was changed by a `$locationChangeStart` handler then stop
  12637. // processing this location change
  12638. if ($location.absUrl() !== newUrl) return;
  12639. if (defaultPrevented) {
  12640. $location.$$parse(oldUrl);
  12641. $location.$$state = oldState;
  12642. } else {
  12643. if (urlOrStateChanged) {
  12644. setBrowserUrlWithFallback(newUrl, currentReplace,
  12645. oldState === $location.$$state ? null : $location.$$state);
  12646. }
  12647. afterLocationChange(oldUrl, oldState);
  12648. }
  12649. });
  12650. }
  12651. $location.$$replace = false;
  12652. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  12653. // there is a change
  12654. });
  12655. return $location;
  12656. function afterLocationChange(oldUrl, oldState) {
  12657. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  12658. $location.$$state, oldState);
  12659. }
  12660. }];
  12661. }
  12662. /**
  12663. * @ngdoc service
  12664. * @name $log
  12665. * @requires $window
  12666. *
  12667. * @description
  12668. * Simple service for logging. Default implementation safely writes the message
  12669. * into the browser's console (if present).
  12670. *
  12671. * The main purpose of this service is to simplify debugging and troubleshooting.
  12672. *
  12673. * The default is to log `debug` messages. You can use
  12674. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  12675. *
  12676. * @example
  12677. <example module="logExample" name="log-service">
  12678. <file name="script.js">
  12679. angular.module('logExample', [])
  12680. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  12681. $scope.$log = $log;
  12682. $scope.message = 'Hello World!';
  12683. }]);
  12684. </file>
  12685. <file name="index.html">
  12686. <div ng-controller="LogController">
  12687. <p>Reload this page with open console, enter text and hit the log button...</p>
  12688. <label>Message:
  12689. <input type="text" ng-model="message" /></label>
  12690. <button ng-click="$log.log(message)">log</button>
  12691. <button ng-click="$log.warn(message)">warn</button>
  12692. <button ng-click="$log.info(message)">info</button>
  12693. <button ng-click="$log.error(message)">error</button>
  12694. <button ng-click="$log.debug(message)">debug</button>
  12695. </div>
  12696. </file>
  12697. </example>
  12698. */
  12699. /**
  12700. * @ngdoc provider
  12701. * @name $logProvider
  12702. * @this
  12703. *
  12704. * @description
  12705. * Use the `$logProvider` to configure how the application logs messages
  12706. */
  12707. function $LogProvider() {
  12708. var debug = true,
  12709. self = this;
  12710. /**
  12711. * @ngdoc method
  12712. * @name $logProvider#debugEnabled
  12713. * @description
  12714. * @param {boolean=} flag enable or disable debug level messages
  12715. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  12716. */
  12717. this.debugEnabled = function(flag) {
  12718. if (isDefined(flag)) {
  12719. debug = flag;
  12720. return this;
  12721. } else {
  12722. return debug;
  12723. }
  12724. };
  12725. this.$get = ['$window', function($window) {
  12726. return {
  12727. /**
  12728. * @ngdoc method
  12729. * @name $log#log
  12730. *
  12731. * @description
  12732. * Write a log message
  12733. */
  12734. log: consoleLog('log'),
  12735. /**
  12736. * @ngdoc method
  12737. * @name $log#info
  12738. *
  12739. * @description
  12740. * Write an information message
  12741. */
  12742. info: consoleLog('info'),
  12743. /**
  12744. * @ngdoc method
  12745. * @name $log#warn
  12746. *
  12747. * @description
  12748. * Write a warning message
  12749. */
  12750. warn: consoleLog('warn'),
  12751. /**
  12752. * @ngdoc method
  12753. * @name $log#error
  12754. *
  12755. * @description
  12756. * Write an error message
  12757. */
  12758. error: consoleLog('error'),
  12759. /**
  12760. * @ngdoc method
  12761. * @name $log#debug
  12762. *
  12763. * @description
  12764. * Write a debug message
  12765. */
  12766. debug: (function() {
  12767. var fn = consoleLog('debug');
  12768. return function() {
  12769. if (debug) {
  12770. fn.apply(self, arguments);
  12771. }
  12772. };
  12773. })()
  12774. };
  12775. function formatError(arg) {
  12776. if (arg instanceof Error) {
  12777. if (arg.stack) {
  12778. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  12779. ? 'Error: ' + arg.message + '\n' + arg.stack
  12780. : arg.stack;
  12781. } else if (arg.sourceURL) {
  12782. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  12783. }
  12784. }
  12785. return arg;
  12786. }
  12787. function consoleLog(type) {
  12788. var console = $window.console || {},
  12789. logFn = console[type] || console.log || noop,
  12790. hasApply = false;
  12791. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  12792. // The reason behind this is that console.log has type "object" in IE8...
  12793. try {
  12794. hasApply = !!logFn.apply;
  12795. } catch (e) { /* empty */ }
  12796. if (hasApply) {
  12797. return function() {
  12798. var args = [];
  12799. forEach(arguments, function(arg) {
  12800. args.push(formatError(arg));
  12801. });
  12802. return logFn.apply(console, args);
  12803. };
  12804. }
  12805. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  12806. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  12807. return function(arg1, arg2) {
  12808. logFn(arg1, arg2 == null ? '' : arg2);
  12809. };
  12810. }
  12811. }];
  12812. }
  12813. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  12814. * Any commits to this file should be reviewed with security in mind. *
  12815. * Changes to this file can potentially create security vulnerabilities. *
  12816. * An approval from 2 Core members with history of modifying *
  12817. * this file is required. *
  12818. * *
  12819. * Does the change somehow allow for arbitrary javascript to be executed? *
  12820. * Or allows for someone to change the prototype of built-in objects? *
  12821. * Or gives undesired access to variables likes document or window? *
  12822. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  12823. var $parseMinErr = minErr('$parse');
  12824. var ARRAY_CTOR = [].constructor;
  12825. var BOOLEAN_CTOR = (false).constructor;
  12826. var FUNCTION_CTOR = Function.constructor;
  12827. var NUMBER_CTOR = (0).constructor;
  12828. var OBJECT_CTOR = {}.constructor;
  12829. var STRING_CTOR = ''.constructor;
  12830. var ARRAY_CTOR_PROTO = ARRAY_CTOR.prototype;
  12831. var BOOLEAN_CTOR_PROTO = BOOLEAN_CTOR.prototype;
  12832. var FUNCTION_CTOR_PROTO = FUNCTION_CTOR.prototype;
  12833. var NUMBER_CTOR_PROTO = NUMBER_CTOR.prototype;
  12834. var OBJECT_CTOR_PROTO = OBJECT_CTOR.prototype;
  12835. var STRING_CTOR_PROTO = STRING_CTOR.prototype;
  12836. var CALL = FUNCTION_CTOR_PROTO.call;
  12837. var APPLY = FUNCTION_CTOR_PROTO.apply;
  12838. var BIND = FUNCTION_CTOR_PROTO.bind;
  12839. var objectValueOf = OBJECT_CTOR_PROTO.valueOf;
  12840. // Sandboxing Angular Expressions
  12841. // ------------------------------
  12842. // Angular expressions are generally considered safe because these expressions only have direct
  12843. // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
  12844. // obtaining a reference to native JS functions such as the Function constructor.
  12845. //
  12846. // As an example, consider the following Angular expression:
  12847. //
  12848. // {}.toString.constructor('alert("evil JS code")')
  12849. //
  12850. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  12851. // against the expression language, but not to prevent exploits that were enabled by exposing
  12852. // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
  12853. // practice and therefore we are not even trying to protect against interaction with an object
  12854. // explicitly exposed in this way.
  12855. //
  12856. // In general, it is not possible to access a Window object from an angular expression unless a
  12857. // window or some DOM object that has a reference to window is published onto a Scope.
  12858. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  12859. // native objects.
  12860. //
  12861. // See https://docs.angularjs.org/guide/security
  12862. function ensureSafeMemberName(name, fullExpression) {
  12863. if (name === '__defineGetter__' || name === '__defineSetter__'
  12864. || name === '__lookupGetter__' || name === '__lookupSetter__'
  12865. || name === '__proto__') {
  12866. throw $parseMinErr('isecfld',
  12867. 'Attempting to access a disallowed field in Angular expressions! '
  12868. + 'Expression: {0}', fullExpression);
  12869. }
  12870. return name;
  12871. }
  12872. function getStringValue(name) {
  12873. // Property names must be strings. This means that non-string objects cannot be used
  12874. // as keys in an object. Any non-string object, including a number, is typecasted
  12875. // into a string via the toString method.
  12876. // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names
  12877. //
  12878. // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it
  12879. // to a string. It's not always possible. If `name` is an object and its `toString` method is
  12880. // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:
  12881. //
  12882. // TypeError: Cannot convert object to primitive value
  12883. //
  12884. // For performance reasons, we don't catch this error here and allow it to propagate up the call
  12885. // stack. Note that you'll get the same error in JavaScript if you try to access a property using
  12886. // such a 'broken' object as a key.
  12887. return name + '';
  12888. }
  12889. function ensureSafeObject(obj, fullExpression) {
  12890. // nifty check if obj is Function that is fast and works across iframes and other contexts
  12891. if (obj) {
  12892. if (obj.constructor === obj) {
  12893. throw $parseMinErr('isecfn',
  12894. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  12895. fullExpression);
  12896. } else if (// isWindow(obj)
  12897. obj.window === obj) {
  12898. throw $parseMinErr('isecwindow',
  12899. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  12900. fullExpression);
  12901. } else if (// isElement(obj)
  12902. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  12903. throw $parseMinErr('isecdom',
  12904. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  12905. fullExpression);
  12906. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  12907. obj === Object) {
  12908. throw $parseMinErr('isecobj',
  12909. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  12910. fullExpression);
  12911. }
  12912. }
  12913. return obj;
  12914. }
  12915. function ensureSafeFunction(obj, fullExpression) {
  12916. if (obj) {
  12917. if (obj.constructor === obj) {
  12918. throw $parseMinErr('isecfn',
  12919. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  12920. fullExpression);
  12921. } else if (obj === CALL || obj === APPLY || obj === BIND) {
  12922. throw $parseMinErr('isecff',
  12923. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  12924. fullExpression);
  12925. }
  12926. }
  12927. }
  12928. function ensureSafeAssignContext(obj, fullExpression) {
  12929. if (obj) {
  12930. if (obj === ARRAY_CTOR ||
  12931. obj === BOOLEAN_CTOR ||
  12932. obj === FUNCTION_CTOR ||
  12933. obj === NUMBER_CTOR ||
  12934. obj === OBJECT_CTOR ||
  12935. obj === STRING_CTOR ||
  12936. obj === ARRAY_CTOR_PROTO ||
  12937. obj === BOOLEAN_CTOR_PROTO ||
  12938. obj === FUNCTION_CTOR_PROTO ||
  12939. obj === NUMBER_CTOR_PROTO ||
  12940. obj === OBJECT_CTOR_PROTO ||
  12941. obj === STRING_CTOR_PROTO) {
  12942. throw $parseMinErr('isecaf',
  12943. 'Assigning to a constructor or its prototype is disallowed! Expression: {0}',
  12944. fullExpression);
  12945. }
  12946. }
  12947. }
  12948. var OPERATORS = createMap();
  12949. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  12950. var ESCAPE = {'n':'\n', 'f':'\f', 'r':'\r', 't':'\t', 'v':'\v', '\'':'\'', '"':'"'};
  12951. /////////////////////////////////////////
  12952. /**
  12953. * @constructor
  12954. */
  12955. var Lexer = function Lexer(options) {
  12956. this.options = options;
  12957. };
  12958. Lexer.prototype = {
  12959. constructor: Lexer,
  12960. lex: function(text) {
  12961. this.text = text;
  12962. this.index = 0;
  12963. this.tokens = [];
  12964. while (this.index < this.text.length) {
  12965. var ch = this.text.charAt(this.index);
  12966. if (ch === '"' || ch === '\'') {
  12967. this.readString(ch);
  12968. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  12969. this.readNumber();
  12970. } else if (this.isIdentifierStart(this.peekMultichar())) {
  12971. this.readIdent();
  12972. } else if (this.is(ch, '(){}[].,;:?')) {
  12973. this.tokens.push({index: this.index, text: ch});
  12974. this.index++;
  12975. } else if (this.isWhitespace(ch)) {
  12976. this.index++;
  12977. } else {
  12978. var ch2 = ch + this.peek();
  12979. var ch3 = ch2 + this.peek(2);
  12980. var op1 = OPERATORS[ch];
  12981. var op2 = OPERATORS[ch2];
  12982. var op3 = OPERATORS[ch3];
  12983. if (op1 || op2 || op3) {
  12984. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  12985. this.tokens.push({index: this.index, text: token, operator: true});
  12986. this.index += token.length;
  12987. } else {
  12988. this.throwError('Unexpected next character ', this.index, this.index + 1);
  12989. }
  12990. }
  12991. }
  12992. return this.tokens;
  12993. },
  12994. is: function(ch, chars) {
  12995. return chars.indexOf(ch) !== -1;
  12996. },
  12997. peek: function(i) {
  12998. var num = i || 1;
  12999. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  13000. },
  13001. isNumber: function(ch) {
  13002. return ('0' <= ch && ch <= '9') && typeof ch === 'string';
  13003. },
  13004. isWhitespace: function(ch) {
  13005. // IE treats non-breaking space as \u00A0
  13006. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  13007. ch === '\n' || ch === '\v' || ch === '\u00A0');
  13008. },
  13009. isIdentifierStart: function(ch) {
  13010. return this.options.isIdentifierStart ?
  13011. this.options.isIdentifierStart(ch, this.codePointAt(ch)) :
  13012. this.isValidIdentifierStart(ch);
  13013. },
  13014. isValidIdentifierStart: function(ch) {
  13015. return ('a' <= ch && ch <= 'z' ||
  13016. 'A' <= ch && ch <= 'Z' ||
  13017. '_' === ch || ch === '$');
  13018. },
  13019. isIdentifierContinue: function(ch) {
  13020. return this.options.isIdentifierContinue ?
  13021. this.options.isIdentifierContinue(ch, this.codePointAt(ch)) :
  13022. this.isValidIdentifierContinue(ch);
  13023. },
  13024. isValidIdentifierContinue: function(ch, cp) {
  13025. return this.isValidIdentifierStart(ch, cp) || this.isNumber(ch);
  13026. },
  13027. codePointAt: function(ch) {
  13028. if (ch.length === 1) return ch.charCodeAt(0);
  13029. // eslint-disable-next-line no-bitwise
  13030. return (ch.charCodeAt(0) << 10) + ch.charCodeAt(1) - 0x35FDC00;
  13031. },
  13032. peekMultichar: function() {
  13033. var ch = this.text.charAt(this.index);
  13034. var peek = this.peek();
  13035. if (!peek) {
  13036. return ch;
  13037. }
  13038. var cp1 = ch.charCodeAt(0);
  13039. var cp2 = peek.charCodeAt(0);
  13040. if (cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF) {
  13041. return ch + peek;
  13042. }
  13043. return ch;
  13044. },
  13045. isExpOperator: function(ch) {
  13046. return (ch === '-' || ch === '+' || this.isNumber(ch));
  13047. },
  13048. throwError: function(error, start, end) {
  13049. end = end || this.index;
  13050. var colStr = (isDefined(start)
  13051. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  13052. : ' ' + end);
  13053. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  13054. error, colStr, this.text);
  13055. },
  13056. readNumber: function() {
  13057. var number = '';
  13058. var start = this.index;
  13059. while (this.index < this.text.length) {
  13060. var ch = lowercase(this.text.charAt(this.index));
  13061. if (ch === '.' || this.isNumber(ch)) {
  13062. number += ch;
  13063. } else {
  13064. var peekCh = this.peek();
  13065. if (ch === 'e' && this.isExpOperator(peekCh)) {
  13066. number += ch;
  13067. } else if (this.isExpOperator(ch) &&
  13068. peekCh && this.isNumber(peekCh) &&
  13069. number.charAt(number.length - 1) === 'e') {
  13070. number += ch;
  13071. } else if (this.isExpOperator(ch) &&
  13072. (!peekCh || !this.isNumber(peekCh)) &&
  13073. number.charAt(number.length - 1) === 'e') {
  13074. this.throwError('Invalid exponent');
  13075. } else {
  13076. break;
  13077. }
  13078. }
  13079. this.index++;
  13080. }
  13081. this.tokens.push({
  13082. index: start,
  13083. text: number,
  13084. constant: true,
  13085. value: Number(number)
  13086. });
  13087. },
  13088. readIdent: function() {
  13089. var start = this.index;
  13090. this.index += this.peekMultichar().length;
  13091. while (this.index < this.text.length) {
  13092. var ch = this.peekMultichar();
  13093. if (!this.isIdentifierContinue(ch)) {
  13094. break;
  13095. }
  13096. this.index += ch.length;
  13097. }
  13098. this.tokens.push({
  13099. index: start,
  13100. text: this.text.slice(start, this.index),
  13101. identifier: true
  13102. });
  13103. },
  13104. readString: function(quote) {
  13105. var start = this.index;
  13106. this.index++;
  13107. var string = '';
  13108. var rawString = quote;
  13109. var escape = false;
  13110. while (this.index < this.text.length) {
  13111. var ch = this.text.charAt(this.index);
  13112. rawString += ch;
  13113. if (escape) {
  13114. if (ch === 'u') {
  13115. var hex = this.text.substring(this.index + 1, this.index + 5);
  13116. if (!hex.match(/[\da-f]{4}/i)) {
  13117. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  13118. }
  13119. this.index += 4;
  13120. string += String.fromCharCode(parseInt(hex, 16));
  13121. } else {
  13122. var rep = ESCAPE[ch];
  13123. string = string + (rep || ch);
  13124. }
  13125. escape = false;
  13126. } else if (ch === '\\') {
  13127. escape = true;
  13128. } else if (ch === quote) {
  13129. this.index++;
  13130. this.tokens.push({
  13131. index: start,
  13132. text: rawString,
  13133. constant: true,
  13134. value: string
  13135. });
  13136. return;
  13137. } else {
  13138. string += ch;
  13139. }
  13140. this.index++;
  13141. }
  13142. this.throwError('Unterminated quote', start);
  13143. }
  13144. };
  13145. var AST = function AST(lexer, options) {
  13146. this.lexer = lexer;
  13147. this.options = options;
  13148. };
  13149. AST.Program = 'Program';
  13150. AST.ExpressionStatement = 'ExpressionStatement';
  13151. AST.AssignmentExpression = 'AssignmentExpression';
  13152. AST.ConditionalExpression = 'ConditionalExpression';
  13153. AST.LogicalExpression = 'LogicalExpression';
  13154. AST.BinaryExpression = 'BinaryExpression';
  13155. AST.UnaryExpression = 'UnaryExpression';
  13156. AST.CallExpression = 'CallExpression';
  13157. AST.MemberExpression = 'MemberExpression';
  13158. AST.Identifier = 'Identifier';
  13159. AST.Literal = 'Literal';
  13160. AST.ArrayExpression = 'ArrayExpression';
  13161. AST.Property = 'Property';
  13162. AST.ObjectExpression = 'ObjectExpression';
  13163. AST.ThisExpression = 'ThisExpression';
  13164. AST.LocalsExpression = 'LocalsExpression';
  13165. // Internal use only
  13166. AST.NGValueParameter = 'NGValueParameter';
  13167. AST.prototype = {
  13168. ast: function(text) {
  13169. this.text = text;
  13170. this.tokens = this.lexer.lex(text);
  13171. var value = this.program();
  13172. if (this.tokens.length !== 0) {
  13173. this.throwError('is an unexpected token', this.tokens[0]);
  13174. }
  13175. return value;
  13176. },
  13177. program: function() {
  13178. var body = [];
  13179. while (true) {
  13180. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  13181. body.push(this.expressionStatement());
  13182. if (!this.expect(';')) {
  13183. return { type: AST.Program, body: body};
  13184. }
  13185. }
  13186. },
  13187. expressionStatement: function() {
  13188. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  13189. },
  13190. filterChain: function() {
  13191. var left = this.expression();
  13192. while (this.expect('|')) {
  13193. left = this.filter(left);
  13194. }
  13195. return left;
  13196. },
  13197. expression: function() {
  13198. return this.assignment();
  13199. },
  13200. assignment: function() {
  13201. var result = this.ternary();
  13202. if (this.expect('=')) {
  13203. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  13204. }
  13205. return result;
  13206. },
  13207. ternary: function() {
  13208. var test = this.logicalOR();
  13209. var alternate;
  13210. var consequent;
  13211. if (this.expect('?')) {
  13212. alternate = this.expression();
  13213. if (this.consume(':')) {
  13214. consequent = this.expression();
  13215. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  13216. }
  13217. }
  13218. return test;
  13219. },
  13220. logicalOR: function() {
  13221. var left = this.logicalAND();
  13222. while (this.expect('||')) {
  13223. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  13224. }
  13225. return left;
  13226. },
  13227. logicalAND: function() {
  13228. var left = this.equality();
  13229. while (this.expect('&&')) {
  13230. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  13231. }
  13232. return left;
  13233. },
  13234. equality: function() {
  13235. var left = this.relational();
  13236. var token;
  13237. while ((token = this.expect('==','!=','===','!=='))) {
  13238. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  13239. }
  13240. return left;
  13241. },
  13242. relational: function() {
  13243. var left = this.additive();
  13244. var token;
  13245. while ((token = this.expect('<', '>', '<=', '>='))) {
  13246. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  13247. }
  13248. return left;
  13249. },
  13250. additive: function() {
  13251. var left = this.multiplicative();
  13252. var token;
  13253. while ((token = this.expect('+','-'))) {
  13254. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  13255. }
  13256. return left;
  13257. },
  13258. multiplicative: function() {
  13259. var left = this.unary();
  13260. var token;
  13261. while ((token = this.expect('*','/','%'))) {
  13262. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  13263. }
  13264. return left;
  13265. },
  13266. unary: function() {
  13267. var token;
  13268. if ((token = this.expect('+', '-', '!'))) {
  13269. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  13270. } else {
  13271. return this.primary();
  13272. }
  13273. },
  13274. primary: function() {
  13275. var primary;
  13276. if (this.expect('(')) {
  13277. primary = this.filterChain();
  13278. this.consume(')');
  13279. } else if (this.expect('[')) {
  13280. primary = this.arrayDeclaration();
  13281. } else if (this.expect('{')) {
  13282. primary = this.object();
  13283. } else if (this.selfReferential.hasOwnProperty(this.peek().text)) {
  13284. primary = copy(this.selfReferential[this.consume().text]);
  13285. } else if (this.options.literals.hasOwnProperty(this.peek().text)) {
  13286. primary = { type: AST.Literal, value: this.options.literals[this.consume().text]};
  13287. } else if (this.peek().identifier) {
  13288. primary = this.identifier();
  13289. } else if (this.peek().constant) {
  13290. primary = this.constant();
  13291. } else {
  13292. this.throwError('not a primary expression', this.peek());
  13293. }
  13294. var next;
  13295. while ((next = this.expect('(', '[', '.'))) {
  13296. if (next.text === '(') {
  13297. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  13298. this.consume(')');
  13299. } else if (next.text === '[') {
  13300. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  13301. this.consume(']');
  13302. } else if (next.text === '.') {
  13303. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  13304. } else {
  13305. this.throwError('IMPOSSIBLE');
  13306. }
  13307. }
  13308. return primary;
  13309. },
  13310. filter: function(baseExpression) {
  13311. var args = [baseExpression];
  13312. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  13313. while (this.expect(':')) {
  13314. args.push(this.expression());
  13315. }
  13316. return result;
  13317. },
  13318. parseArguments: function() {
  13319. var args = [];
  13320. if (this.peekToken().text !== ')') {
  13321. do {
  13322. args.push(this.filterChain());
  13323. } while (this.expect(','));
  13324. }
  13325. return args;
  13326. },
  13327. identifier: function() {
  13328. var token = this.consume();
  13329. if (!token.identifier) {
  13330. this.throwError('is not a valid identifier', token);
  13331. }
  13332. return { type: AST.Identifier, name: token.text };
  13333. },
  13334. constant: function() {
  13335. // TODO check that it is a constant
  13336. return { type: AST.Literal, value: this.consume().value };
  13337. },
  13338. arrayDeclaration: function() {
  13339. var elements = [];
  13340. if (this.peekToken().text !== ']') {
  13341. do {
  13342. if (this.peek(']')) {
  13343. // Support trailing commas per ES5.1.
  13344. break;
  13345. }
  13346. elements.push(this.expression());
  13347. } while (this.expect(','));
  13348. }
  13349. this.consume(']');
  13350. return { type: AST.ArrayExpression, elements: elements };
  13351. },
  13352. object: function() {
  13353. var properties = [], property;
  13354. if (this.peekToken().text !== '}') {
  13355. do {
  13356. if (this.peek('}')) {
  13357. // Support trailing commas per ES5.1.
  13358. break;
  13359. }
  13360. property = {type: AST.Property, kind: 'init'};
  13361. if (this.peek().constant) {
  13362. property.key = this.constant();
  13363. property.computed = false;
  13364. this.consume(':');
  13365. property.value = this.expression();
  13366. } else if (this.peek().identifier) {
  13367. property.key = this.identifier();
  13368. property.computed = false;
  13369. if (this.peek(':')) {
  13370. this.consume(':');
  13371. property.value = this.expression();
  13372. } else {
  13373. property.value = property.key;
  13374. }
  13375. } else if (this.peek('[')) {
  13376. this.consume('[');
  13377. property.key = this.expression();
  13378. this.consume(']');
  13379. property.computed = true;
  13380. this.consume(':');
  13381. property.value = this.expression();
  13382. } else {
  13383. this.throwError('invalid key', this.peek());
  13384. }
  13385. properties.push(property);
  13386. } while (this.expect(','));
  13387. }
  13388. this.consume('}');
  13389. return {type: AST.ObjectExpression, properties: properties };
  13390. },
  13391. throwError: function(msg, token) {
  13392. throw $parseMinErr('syntax',
  13393. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  13394. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  13395. },
  13396. consume: function(e1) {
  13397. if (this.tokens.length === 0) {
  13398. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  13399. }
  13400. var token = this.expect(e1);
  13401. if (!token) {
  13402. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  13403. }
  13404. return token;
  13405. },
  13406. peekToken: function() {
  13407. if (this.tokens.length === 0) {
  13408. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  13409. }
  13410. return this.tokens[0];
  13411. },
  13412. peek: function(e1, e2, e3, e4) {
  13413. return this.peekAhead(0, e1, e2, e3, e4);
  13414. },
  13415. peekAhead: function(i, e1, e2, e3, e4) {
  13416. if (this.tokens.length > i) {
  13417. var token = this.tokens[i];
  13418. var t = token.text;
  13419. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  13420. (!e1 && !e2 && !e3 && !e4)) {
  13421. return token;
  13422. }
  13423. }
  13424. return false;
  13425. },
  13426. expect: function(e1, e2, e3, e4) {
  13427. var token = this.peek(e1, e2, e3, e4);
  13428. if (token) {
  13429. this.tokens.shift();
  13430. return token;
  13431. }
  13432. return false;
  13433. },
  13434. selfReferential: {
  13435. 'this': {type: AST.ThisExpression },
  13436. '$locals': {type: AST.LocalsExpression }
  13437. }
  13438. };
  13439. function ifDefined(v, d) {
  13440. return typeof v !== 'undefined' ? v : d;
  13441. }
  13442. function plusFn(l, r) {
  13443. if (typeof l === 'undefined') return r;
  13444. if (typeof r === 'undefined') return l;
  13445. return l + r;
  13446. }
  13447. function isStateless($filter, filterName) {
  13448. var fn = $filter(filterName);
  13449. return !fn.$stateful;
  13450. }
  13451. function findConstantAndWatchExpressions(ast, $filter) {
  13452. var allConstants;
  13453. var argsToWatch;
  13454. var isStatelessFilter;
  13455. switch (ast.type) {
  13456. case AST.Program:
  13457. allConstants = true;
  13458. forEach(ast.body, function(expr) {
  13459. findConstantAndWatchExpressions(expr.expression, $filter);
  13460. allConstants = allConstants && expr.expression.constant;
  13461. });
  13462. ast.constant = allConstants;
  13463. break;
  13464. case AST.Literal:
  13465. ast.constant = true;
  13466. ast.toWatch = [];
  13467. break;
  13468. case AST.UnaryExpression:
  13469. findConstantAndWatchExpressions(ast.argument, $filter);
  13470. ast.constant = ast.argument.constant;
  13471. ast.toWatch = ast.argument.toWatch;
  13472. break;
  13473. case AST.BinaryExpression:
  13474. findConstantAndWatchExpressions(ast.left, $filter);
  13475. findConstantAndWatchExpressions(ast.right, $filter);
  13476. ast.constant = ast.left.constant && ast.right.constant;
  13477. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  13478. break;
  13479. case AST.LogicalExpression:
  13480. findConstantAndWatchExpressions(ast.left, $filter);
  13481. findConstantAndWatchExpressions(ast.right, $filter);
  13482. ast.constant = ast.left.constant && ast.right.constant;
  13483. ast.toWatch = ast.constant ? [] : [ast];
  13484. break;
  13485. case AST.ConditionalExpression:
  13486. findConstantAndWatchExpressions(ast.test, $filter);
  13487. findConstantAndWatchExpressions(ast.alternate, $filter);
  13488. findConstantAndWatchExpressions(ast.consequent, $filter);
  13489. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  13490. ast.toWatch = ast.constant ? [] : [ast];
  13491. break;
  13492. case AST.Identifier:
  13493. ast.constant = false;
  13494. ast.toWatch = [ast];
  13495. break;
  13496. case AST.MemberExpression:
  13497. findConstantAndWatchExpressions(ast.object, $filter);
  13498. if (ast.computed) {
  13499. findConstantAndWatchExpressions(ast.property, $filter);
  13500. }
  13501. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  13502. ast.toWatch = [ast];
  13503. break;
  13504. case AST.CallExpression:
  13505. isStatelessFilter = ast.filter ? isStateless($filter, ast.callee.name) : false;
  13506. allConstants = isStatelessFilter;
  13507. argsToWatch = [];
  13508. forEach(ast.arguments, function(expr) {
  13509. findConstantAndWatchExpressions(expr, $filter);
  13510. allConstants = allConstants && expr.constant;
  13511. if (!expr.constant) {
  13512. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  13513. }
  13514. });
  13515. ast.constant = allConstants;
  13516. ast.toWatch = isStatelessFilter ? argsToWatch : [ast];
  13517. break;
  13518. case AST.AssignmentExpression:
  13519. findConstantAndWatchExpressions(ast.left, $filter);
  13520. findConstantAndWatchExpressions(ast.right, $filter);
  13521. ast.constant = ast.left.constant && ast.right.constant;
  13522. ast.toWatch = [ast];
  13523. break;
  13524. case AST.ArrayExpression:
  13525. allConstants = true;
  13526. argsToWatch = [];
  13527. forEach(ast.elements, function(expr) {
  13528. findConstantAndWatchExpressions(expr, $filter);
  13529. allConstants = allConstants && expr.constant;
  13530. if (!expr.constant) {
  13531. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  13532. }
  13533. });
  13534. ast.constant = allConstants;
  13535. ast.toWatch = argsToWatch;
  13536. break;
  13537. case AST.ObjectExpression:
  13538. allConstants = true;
  13539. argsToWatch = [];
  13540. forEach(ast.properties, function(property) {
  13541. findConstantAndWatchExpressions(property.value, $filter);
  13542. allConstants = allConstants && property.value.constant && !property.computed;
  13543. if (!property.value.constant) {
  13544. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  13545. }
  13546. });
  13547. ast.constant = allConstants;
  13548. ast.toWatch = argsToWatch;
  13549. break;
  13550. case AST.ThisExpression:
  13551. ast.constant = false;
  13552. ast.toWatch = [];
  13553. break;
  13554. case AST.LocalsExpression:
  13555. ast.constant = false;
  13556. ast.toWatch = [];
  13557. break;
  13558. }
  13559. }
  13560. function getInputs(body) {
  13561. if (body.length !== 1) return;
  13562. var lastExpression = body[0].expression;
  13563. var candidate = lastExpression.toWatch;
  13564. if (candidate.length !== 1) return candidate;
  13565. return candidate[0] !== lastExpression ? candidate : undefined;
  13566. }
  13567. function isAssignable(ast) {
  13568. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  13569. }
  13570. function assignableAST(ast) {
  13571. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  13572. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  13573. }
  13574. }
  13575. function isLiteral(ast) {
  13576. return ast.body.length === 0 ||
  13577. ast.body.length === 1 && (
  13578. ast.body[0].expression.type === AST.Literal ||
  13579. ast.body[0].expression.type === AST.ArrayExpression ||
  13580. ast.body[0].expression.type === AST.ObjectExpression);
  13581. }
  13582. function isConstant(ast) {
  13583. return ast.constant;
  13584. }
  13585. function ASTCompiler(astBuilder, $filter) {
  13586. this.astBuilder = astBuilder;
  13587. this.$filter = $filter;
  13588. }
  13589. ASTCompiler.prototype = {
  13590. compile: function(expression, expensiveChecks) {
  13591. var self = this;
  13592. var ast = this.astBuilder.ast(expression);
  13593. this.state = {
  13594. nextId: 0,
  13595. filters: {},
  13596. expensiveChecks: expensiveChecks,
  13597. fn: {vars: [], body: [], own: {}},
  13598. assign: {vars: [], body: [], own: {}},
  13599. inputs: []
  13600. };
  13601. findConstantAndWatchExpressions(ast, self.$filter);
  13602. var extra = '';
  13603. var assignable;
  13604. this.stage = 'assign';
  13605. if ((assignable = assignableAST(ast))) {
  13606. this.state.computing = 'assign';
  13607. var result = this.nextId();
  13608. this.recurse(assignable, result);
  13609. this.return_(result);
  13610. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  13611. }
  13612. var toWatch = getInputs(ast.body);
  13613. self.stage = 'inputs';
  13614. forEach(toWatch, function(watch, key) {
  13615. var fnKey = 'fn' + key;
  13616. self.state[fnKey] = {vars: [], body: [], own: {}};
  13617. self.state.computing = fnKey;
  13618. var intoId = self.nextId();
  13619. self.recurse(watch, intoId);
  13620. self.return_(intoId);
  13621. self.state.inputs.push(fnKey);
  13622. watch.watchId = key;
  13623. });
  13624. this.state.computing = 'fn';
  13625. this.stage = 'main';
  13626. this.recurse(ast);
  13627. var fnString =
  13628. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  13629. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  13630. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  13631. this.filterPrefix() +
  13632. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  13633. extra +
  13634. this.watchFns() +
  13635. 'return fn;';
  13636. // eslint-disable-next-line no-new-func
  13637. var fn = (new Function('$filter',
  13638. 'ensureSafeMemberName',
  13639. 'ensureSafeObject',
  13640. 'ensureSafeFunction',
  13641. 'getStringValue',
  13642. 'ensureSafeAssignContext',
  13643. 'ifDefined',
  13644. 'plus',
  13645. 'text',
  13646. fnString))(
  13647. this.$filter,
  13648. ensureSafeMemberName,
  13649. ensureSafeObject,
  13650. ensureSafeFunction,
  13651. getStringValue,
  13652. ensureSafeAssignContext,
  13653. ifDefined,
  13654. plusFn,
  13655. expression);
  13656. this.state = this.stage = undefined;
  13657. fn.literal = isLiteral(ast);
  13658. fn.constant = isConstant(ast);
  13659. return fn;
  13660. },
  13661. USE: 'use',
  13662. STRICT: 'strict',
  13663. watchFns: function() {
  13664. var result = [];
  13665. var fns = this.state.inputs;
  13666. var self = this;
  13667. forEach(fns, function(name) {
  13668. result.push('var ' + name + '=' + self.generateFunction(name, 's'));
  13669. });
  13670. if (fns.length) {
  13671. result.push('fn.inputs=[' + fns.join(',') + '];');
  13672. }
  13673. return result.join('');
  13674. },
  13675. generateFunction: function(name, params) {
  13676. return 'function(' + params + '){' +
  13677. this.varsPrefix(name) +
  13678. this.body(name) +
  13679. '};';
  13680. },
  13681. filterPrefix: function() {
  13682. var parts = [];
  13683. var self = this;
  13684. forEach(this.state.filters, function(id, filter) {
  13685. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  13686. });
  13687. if (parts.length) return 'var ' + parts.join(',') + ';';
  13688. return '';
  13689. },
  13690. varsPrefix: function(section) {
  13691. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  13692. },
  13693. body: function(section) {
  13694. return this.state[section].body.join('');
  13695. },
  13696. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  13697. var left, right, self = this, args, expression, computed;
  13698. recursionFn = recursionFn || noop;
  13699. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  13700. intoId = intoId || this.nextId();
  13701. this.if_('i',
  13702. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  13703. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  13704. );
  13705. return;
  13706. }
  13707. switch (ast.type) {
  13708. case AST.Program:
  13709. forEach(ast.body, function(expression, pos) {
  13710. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  13711. if (pos !== ast.body.length - 1) {
  13712. self.current().body.push(right, ';');
  13713. } else {
  13714. self.return_(right);
  13715. }
  13716. });
  13717. break;
  13718. case AST.Literal:
  13719. expression = this.escape(ast.value);
  13720. this.assign(intoId, expression);
  13721. recursionFn(intoId || expression);
  13722. break;
  13723. case AST.UnaryExpression:
  13724. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  13725. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  13726. this.assign(intoId, expression);
  13727. recursionFn(expression);
  13728. break;
  13729. case AST.BinaryExpression:
  13730. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  13731. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  13732. if (ast.operator === '+') {
  13733. expression = this.plus(left, right);
  13734. } else if (ast.operator === '-') {
  13735. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  13736. } else {
  13737. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  13738. }
  13739. this.assign(intoId, expression);
  13740. recursionFn(expression);
  13741. break;
  13742. case AST.LogicalExpression:
  13743. intoId = intoId || this.nextId();
  13744. self.recurse(ast.left, intoId);
  13745. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  13746. recursionFn(intoId);
  13747. break;
  13748. case AST.ConditionalExpression:
  13749. intoId = intoId || this.nextId();
  13750. self.recurse(ast.test, intoId);
  13751. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  13752. recursionFn(intoId);
  13753. break;
  13754. case AST.Identifier:
  13755. intoId = intoId || this.nextId();
  13756. if (nameId) {
  13757. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  13758. nameId.computed = false;
  13759. nameId.name = ast.name;
  13760. }
  13761. ensureSafeMemberName(ast.name);
  13762. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  13763. function() {
  13764. self.if_(self.stage === 'inputs' || 's', function() {
  13765. if (create && create !== 1) {
  13766. self.if_(
  13767. self.not(self.nonComputedMember('s', ast.name)),
  13768. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  13769. }
  13770. self.assign(intoId, self.nonComputedMember('s', ast.name));
  13771. });
  13772. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  13773. );
  13774. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
  13775. self.addEnsureSafeObject(intoId);
  13776. }
  13777. recursionFn(intoId);
  13778. break;
  13779. case AST.MemberExpression:
  13780. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  13781. intoId = intoId || this.nextId();
  13782. self.recurse(ast.object, left, undefined, function() {
  13783. self.if_(self.notNull(left), function() {
  13784. if (create && create !== 1) {
  13785. self.addEnsureSafeAssignContext(left);
  13786. }
  13787. if (ast.computed) {
  13788. right = self.nextId();
  13789. self.recurse(ast.property, right);
  13790. self.getStringValue(right);
  13791. self.addEnsureSafeMemberName(right);
  13792. if (create && create !== 1) {
  13793. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  13794. }
  13795. expression = self.ensureSafeObject(self.computedMember(left, right));
  13796. self.assign(intoId, expression);
  13797. if (nameId) {
  13798. nameId.computed = true;
  13799. nameId.name = right;
  13800. }
  13801. } else {
  13802. ensureSafeMemberName(ast.property.name);
  13803. if (create && create !== 1) {
  13804. self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  13805. }
  13806. expression = self.nonComputedMember(left, ast.property.name);
  13807. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
  13808. expression = self.ensureSafeObject(expression);
  13809. }
  13810. self.assign(intoId, expression);
  13811. if (nameId) {
  13812. nameId.computed = false;
  13813. nameId.name = ast.property.name;
  13814. }
  13815. }
  13816. }, function() {
  13817. self.assign(intoId, 'undefined');
  13818. });
  13819. recursionFn(intoId);
  13820. }, !!create);
  13821. break;
  13822. case AST.CallExpression:
  13823. intoId = intoId || this.nextId();
  13824. if (ast.filter) {
  13825. right = self.filter(ast.callee.name);
  13826. args = [];
  13827. forEach(ast.arguments, function(expr) {
  13828. var argument = self.nextId();
  13829. self.recurse(expr, argument);
  13830. args.push(argument);
  13831. });
  13832. expression = right + '(' + args.join(',') + ')';
  13833. self.assign(intoId, expression);
  13834. recursionFn(intoId);
  13835. } else {
  13836. right = self.nextId();
  13837. left = {};
  13838. args = [];
  13839. self.recurse(ast.callee, right, left, function() {
  13840. self.if_(self.notNull(right), function() {
  13841. self.addEnsureSafeFunction(right);
  13842. forEach(ast.arguments, function(expr) {
  13843. self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
  13844. args.push(self.ensureSafeObject(argument));
  13845. });
  13846. });
  13847. if (left.name) {
  13848. if (!self.state.expensiveChecks) {
  13849. self.addEnsureSafeObject(left.context);
  13850. }
  13851. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  13852. } else {
  13853. expression = right + '(' + args.join(',') + ')';
  13854. }
  13855. expression = self.ensureSafeObject(expression);
  13856. self.assign(intoId, expression);
  13857. }, function() {
  13858. self.assign(intoId, 'undefined');
  13859. });
  13860. recursionFn(intoId);
  13861. });
  13862. }
  13863. break;
  13864. case AST.AssignmentExpression:
  13865. right = this.nextId();
  13866. left = {};
  13867. if (!isAssignable(ast.left)) {
  13868. throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
  13869. }
  13870. this.recurse(ast.left, undefined, left, function() {
  13871. self.if_(self.notNull(left.context), function() {
  13872. self.recurse(ast.right, right);
  13873. self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
  13874. self.addEnsureSafeAssignContext(left.context);
  13875. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  13876. self.assign(intoId, expression);
  13877. recursionFn(intoId || expression);
  13878. });
  13879. }, 1);
  13880. break;
  13881. case AST.ArrayExpression:
  13882. args = [];
  13883. forEach(ast.elements, function(expr) {
  13884. self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
  13885. args.push(argument);
  13886. });
  13887. });
  13888. expression = '[' + args.join(',') + ']';
  13889. this.assign(intoId, expression);
  13890. recursionFn(intoId || expression);
  13891. break;
  13892. case AST.ObjectExpression:
  13893. args = [];
  13894. computed = false;
  13895. forEach(ast.properties, function(property) {
  13896. if (property.computed) {
  13897. computed = true;
  13898. }
  13899. });
  13900. if (computed) {
  13901. intoId = intoId || this.nextId();
  13902. this.assign(intoId, '{}');
  13903. forEach(ast.properties, function(property) {
  13904. if (property.computed) {
  13905. left = self.nextId();
  13906. self.recurse(property.key, left);
  13907. } else {
  13908. left = property.key.type === AST.Identifier ?
  13909. property.key.name :
  13910. ('' + property.key.value);
  13911. }
  13912. right = self.nextId();
  13913. self.recurse(property.value, right);
  13914. self.assign(self.member(intoId, left, property.computed), right);
  13915. });
  13916. } else {
  13917. forEach(ast.properties, function(property) {
  13918. self.recurse(property.value, ast.constant ? undefined : self.nextId(), undefined, function(expr) {
  13919. args.push(self.escape(
  13920. property.key.type === AST.Identifier ? property.key.name :
  13921. ('' + property.key.value)) +
  13922. ':' + expr);
  13923. });
  13924. });
  13925. expression = '{' + args.join(',') + '}';
  13926. this.assign(intoId, expression);
  13927. }
  13928. recursionFn(intoId || expression);
  13929. break;
  13930. case AST.ThisExpression:
  13931. this.assign(intoId, 's');
  13932. recursionFn(intoId || 's');
  13933. break;
  13934. case AST.LocalsExpression:
  13935. this.assign(intoId, 'l');
  13936. recursionFn(intoId || 'l');
  13937. break;
  13938. case AST.NGValueParameter:
  13939. this.assign(intoId, 'v');
  13940. recursionFn(intoId || 'v');
  13941. break;
  13942. }
  13943. },
  13944. getHasOwnProperty: function(element, property) {
  13945. var key = element + '.' + property;
  13946. var own = this.current().own;
  13947. if (!own.hasOwnProperty(key)) {
  13948. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  13949. }
  13950. return own[key];
  13951. },
  13952. assign: function(id, value) {
  13953. if (!id) return;
  13954. this.current().body.push(id, '=', value, ';');
  13955. return id;
  13956. },
  13957. filter: function(filterName) {
  13958. if (!this.state.filters.hasOwnProperty(filterName)) {
  13959. this.state.filters[filterName] = this.nextId(true);
  13960. }
  13961. return this.state.filters[filterName];
  13962. },
  13963. ifDefined: function(id, defaultValue) {
  13964. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  13965. },
  13966. plus: function(left, right) {
  13967. return 'plus(' + left + ',' + right + ')';
  13968. },
  13969. return_: function(id) {
  13970. this.current().body.push('return ', id, ';');
  13971. },
  13972. if_: function(test, alternate, consequent) {
  13973. if (test === true) {
  13974. alternate();
  13975. } else {
  13976. var body = this.current().body;
  13977. body.push('if(', test, '){');
  13978. alternate();
  13979. body.push('}');
  13980. if (consequent) {
  13981. body.push('else{');
  13982. consequent();
  13983. body.push('}');
  13984. }
  13985. }
  13986. },
  13987. not: function(expression) {
  13988. return '!(' + expression + ')';
  13989. },
  13990. notNull: function(expression) {
  13991. return expression + '!=null';
  13992. },
  13993. nonComputedMember: function(left, right) {
  13994. var SAFE_IDENTIFIER = /^[$_a-zA-Z][$_a-zA-Z0-9]*$/;
  13995. var UNSAFE_CHARACTERS = /[^$_a-zA-Z0-9]/g;
  13996. if (SAFE_IDENTIFIER.test(right)) {
  13997. return left + '.' + right;
  13998. } else {
  13999. return left + '["' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '"]';
  14000. }
  14001. },
  14002. computedMember: function(left, right) {
  14003. return left + '[' + right + ']';
  14004. },
  14005. member: function(left, right, computed) {
  14006. if (computed) return this.computedMember(left, right);
  14007. return this.nonComputedMember(left, right);
  14008. },
  14009. addEnsureSafeObject: function(item) {
  14010. this.current().body.push(this.ensureSafeObject(item), ';');
  14011. },
  14012. addEnsureSafeMemberName: function(item) {
  14013. this.current().body.push(this.ensureSafeMemberName(item), ';');
  14014. },
  14015. addEnsureSafeFunction: function(item) {
  14016. this.current().body.push(this.ensureSafeFunction(item), ';');
  14017. },
  14018. addEnsureSafeAssignContext: function(item) {
  14019. this.current().body.push(this.ensureSafeAssignContext(item), ';');
  14020. },
  14021. ensureSafeObject: function(item) {
  14022. return 'ensureSafeObject(' + item + ',text)';
  14023. },
  14024. ensureSafeMemberName: function(item) {
  14025. return 'ensureSafeMemberName(' + item + ',text)';
  14026. },
  14027. ensureSafeFunction: function(item) {
  14028. return 'ensureSafeFunction(' + item + ',text)';
  14029. },
  14030. getStringValue: function(item) {
  14031. this.assign(item, 'getStringValue(' + item + ')');
  14032. },
  14033. ensureSafeAssignContext: function(item) {
  14034. return 'ensureSafeAssignContext(' + item + ',text)';
  14035. },
  14036. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  14037. var self = this;
  14038. return function() {
  14039. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  14040. };
  14041. },
  14042. lazyAssign: function(id, value) {
  14043. var self = this;
  14044. return function() {
  14045. self.assign(id, value);
  14046. };
  14047. },
  14048. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  14049. stringEscapeFn: function(c) {
  14050. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  14051. },
  14052. escape: function(value) {
  14053. if (isString(value)) return '\'' + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + '\'';
  14054. if (isNumber(value)) return value.toString();
  14055. if (value === true) return 'true';
  14056. if (value === false) return 'false';
  14057. if (value === null) return 'null';
  14058. if (typeof value === 'undefined') return 'undefined';
  14059. throw $parseMinErr('esc', 'IMPOSSIBLE');
  14060. },
  14061. nextId: function(skip, init) {
  14062. var id = 'v' + (this.state.nextId++);
  14063. if (!skip) {
  14064. this.current().vars.push(id + (init ? '=' + init : ''));
  14065. }
  14066. return id;
  14067. },
  14068. current: function() {
  14069. return this.state[this.state.computing];
  14070. }
  14071. };
  14072. function ASTInterpreter(astBuilder, $filter) {
  14073. this.astBuilder = astBuilder;
  14074. this.$filter = $filter;
  14075. }
  14076. ASTInterpreter.prototype = {
  14077. compile: function(expression, expensiveChecks) {
  14078. var self = this;
  14079. var ast = this.astBuilder.ast(expression);
  14080. this.expression = expression;
  14081. this.expensiveChecks = expensiveChecks;
  14082. findConstantAndWatchExpressions(ast, self.$filter);
  14083. var assignable;
  14084. var assign;
  14085. if ((assignable = assignableAST(ast))) {
  14086. assign = this.recurse(assignable);
  14087. }
  14088. var toWatch = getInputs(ast.body);
  14089. var inputs;
  14090. if (toWatch) {
  14091. inputs = [];
  14092. forEach(toWatch, function(watch, key) {
  14093. var input = self.recurse(watch);
  14094. watch.input = input;
  14095. inputs.push(input);
  14096. watch.watchId = key;
  14097. });
  14098. }
  14099. var expressions = [];
  14100. forEach(ast.body, function(expression) {
  14101. expressions.push(self.recurse(expression.expression));
  14102. });
  14103. var fn = ast.body.length === 0 ? noop :
  14104. ast.body.length === 1 ? expressions[0] :
  14105. function(scope, locals) {
  14106. var lastValue;
  14107. forEach(expressions, function(exp) {
  14108. lastValue = exp(scope, locals);
  14109. });
  14110. return lastValue;
  14111. };
  14112. if (assign) {
  14113. fn.assign = function(scope, value, locals) {
  14114. return assign(scope, locals, value);
  14115. };
  14116. }
  14117. if (inputs) {
  14118. fn.inputs = inputs;
  14119. }
  14120. fn.literal = isLiteral(ast);
  14121. fn.constant = isConstant(ast);
  14122. return fn;
  14123. },
  14124. recurse: function(ast, context, create) {
  14125. var left, right, self = this, args;
  14126. if (ast.input) {
  14127. return this.inputs(ast.input, ast.watchId);
  14128. }
  14129. switch (ast.type) {
  14130. case AST.Literal:
  14131. return this.value(ast.value, context);
  14132. case AST.UnaryExpression:
  14133. right = this.recurse(ast.argument);
  14134. return this['unary' + ast.operator](right, context);
  14135. case AST.BinaryExpression:
  14136. left = this.recurse(ast.left);
  14137. right = this.recurse(ast.right);
  14138. return this['binary' + ast.operator](left, right, context);
  14139. case AST.LogicalExpression:
  14140. left = this.recurse(ast.left);
  14141. right = this.recurse(ast.right);
  14142. return this['binary' + ast.operator](left, right, context);
  14143. case AST.ConditionalExpression:
  14144. return this['ternary?:'](
  14145. this.recurse(ast.test),
  14146. this.recurse(ast.alternate),
  14147. this.recurse(ast.consequent),
  14148. context
  14149. );
  14150. case AST.Identifier:
  14151. ensureSafeMemberName(ast.name, self.expression);
  14152. return self.identifier(ast.name,
  14153. self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
  14154. context, create, self.expression);
  14155. case AST.MemberExpression:
  14156. left = this.recurse(ast.object, false, !!create);
  14157. if (!ast.computed) {
  14158. ensureSafeMemberName(ast.property.name, self.expression);
  14159. right = ast.property.name;
  14160. }
  14161. if (ast.computed) right = this.recurse(ast.property);
  14162. return ast.computed ?
  14163. this.computedMember(left, right, context, create, self.expression) :
  14164. this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
  14165. case AST.CallExpression:
  14166. args = [];
  14167. forEach(ast.arguments, function(expr) {
  14168. args.push(self.recurse(expr));
  14169. });
  14170. if (ast.filter) right = this.$filter(ast.callee.name);
  14171. if (!ast.filter) right = this.recurse(ast.callee, true);
  14172. return ast.filter ?
  14173. function(scope, locals, assign, inputs) {
  14174. var values = [];
  14175. for (var i = 0; i < args.length; ++i) {
  14176. values.push(args[i](scope, locals, assign, inputs));
  14177. }
  14178. var value = right.apply(undefined, values, inputs);
  14179. return context ? {context: undefined, name: undefined, value: value} : value;
  14180. } :
  14181. function(scope, locals, assign, inputs) {
  14182. var rhs = right(scope, locals, assign, inputs);
  14183. var value;
  14184. if (rhs.value != null) {
  14185. ensureSafeObject(rhs.context, self.expression);
  14186. ensureSafeFunction(rhs.value, self.expression);
  14187. var values = [];
  14188. for (var i = 0; i < args.length; ++i) {
  14189. values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
  14190. }
  14191. value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
  14192. }
  14193. return context ? {value: value} : value;
  14194. };
  14195. case AST.AssignmentExpression:
  14196. left = this.recurse(ast.left, true, 1);
  14197. right = this.recurse(ast.right);
  14198. return function(scope, locals, assign, inputs) {
  14199. var lhs = left(scope, locals, assign, inputs);
  14200. var rhs = right(scope, locals, assign, inputs);
  14201. ensureSafeObject(lhs.value, self.expression);
  14202. ensureSafeAssignContext(lhs.context);
  14203. lhs.context[lhs.name] = rhs;
  14204. return context ? {value: rhs} : rhs;
  14205. };
  14206. case AST.ArrayExpression:
  14207. args = [];
  14208. forEach(ast.elements, function(expr) {
  14209. args.push(self.recurse(expr));
  14210. });
  14211. return function(scope, locals, assign, inputs) {
  14212. var value = [];
  14213. for (var i = 0; i < args.length; ++i) {
  14214. value.push(args[i](scope, locals, assign, inputs));
  14215. }
  14216. return context ? {value: value} : value;
  14217. };
  14218. case AST.ObjectExpression:
  14219. args = [];
  14220. forEach(ast.properties, function(property) {
  14221. if (property.computed) {
  14222. args.push({key: self.recurse(property.key),
  14223. computed: true,
  14224. value: self.recurse(property.value)
  14225. });
  14226. } else {
  14227. args.push({key: property.key.type === AST.Identifier ?
  14228. property.key.name :
  14229. ('' + property.key.value),
  14230. computed: false,
  14231. value: self.recurse(property.value)
  14232. });
  14233. }
  14234. });
  14235. return function(scope, locals, assign, inputs) {
  14236. var value = {};
  14237. for (var i = 0; i < args.length; ++i) {
  14238. if (args[i].computed) {
  14239. value[args[i].key(scope, locals, assign, inputs)] = args[i].value(scope, locals, assign, inputs);
  14240. } else {
  14241. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  14242. }
  14243. }
  14244. return context ? {value: value} : value;
  14245. };
  14246. case AST.ThisExpression:
  14247. return function(scope) {
  14248. return context ? {value: scope} : scope;
  14249. };
  14250. case AST.LocalsExpression:
  14251. return function(scope, locals) {
  14252. return context ? {value: locals} : locals;
  14253. };
  14254. case AST.NGValueParameter:
  14255. return function(scope, locals, assign) {
  14256. return context ? {value: assign} : assign;
  14257. };
  14258. }
  14259. },
  14260. 'unary+': function(argument, context) {
  14261. return function(scope, locals, assign, inputs) {
  14262. var arg = argument(scope, locals, assign, inputs);
  14263. if (isDefined(arg)) {
  14264. arg = +arg;
  14265. } else {
  14266. arg = 0;
  14267. }
  14268. return context ? {value: arg} : arg;
  14269. };
  14270. },
  14271. 'unary-': function(argument, context) {
  14272. return function(scope, locals, assign, inputs) {
  14273. var arg = argument(scope, locals, assign, inputs);
  14274. if (isDefined(arg)) {
  14275. arg = -arg;
  14276. } else {
  14277. arg = -0;
  14278. }
  14279. return context ? {value: arg} : arg;
  14280. };
  14281. },
  14282. 'unary!': function(argument, context) {
  14283. return function(scope, locals, assign, inputs) {
  14284. var arg = !argument(scope, locals, assign, inputs);
  14285. return context ? {value: arg} : arg;
  14286. };
  14287. },
  14288. 'binary+': function(left, right, context) {
  14289. return function(scope, locals, assign, inputs) {
  14290. var lhs = left(scope, locals, assign, inputs);
  14291. var rhs = right(scope, locals, assign, inputs);
  14292. var arg = plusFn(lhs, rhs);
  14293. return context ? {value: arg} : arg;
  14294. };
  14295. },
  14296. 'binary-': function(left, right, context) {
  14297. return function(scope, locals, assign, inputs) {
  14298. var lhs = left(scope, locals, assign, inputs);
  14299. var rhs = right(scope, locals, assign, inputs);
  14300. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  14301. return context ? {value: arg} : arg;
  14302. };
  14303. },
  14304. 'binary*': function(left, right, context) {
  14305. return function(scope, locals, assign, inputs) {
  14306. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  14307. return context ? {value: arg} : arg;
  14308. };
  14309. },
  14310. 'binary/': function(left, right, context) {
  14311. return function(scope, locals, assign, inputs) {
  14312. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  14313. return context ? {value: arg} : arg;
  14314. };
  14315. },
  14316. 'binary%': function(left, right, context) {
  14317. return function(scope, locals, assign, inputs) {
  14318. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  14319. return context ? {value: arg} : arg;
  14320. };
  14321. },
  14322. 'binary===': function(left, right, context) {
  14323. return function(scope, locals, assign, inputs) {
  14324. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  14325. return context ? {value: arg} : arg;
  14326. };
  14327. },
  14328. 'binary!==': function(left, right, context) {
  14329. return function(scope, locals, assign, inputs) {
  14330. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  14331. return context ? {value: arg} : arg;
  14332. };
  14333. },
  14334. 'binary==': function(left, right, context) {
  14335. return function(scope, locals, assign, inputs) {
  14336. // eslint-disable-next-line eqeqeq
  14337. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  14338. return context ? {value: arg} : arg;
  14339. };
  14340. },
  14341. 'binary!=': function(left, right, context) {
  14342. return function(scope, locals, assign, inputs) {
  14343. // eslint-disable-next-line eqeqeq
  14344. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  14345. return context ? {value: arg} : arg;
  14346. };
  14347. },
  14348. 'binary<': function(left, right, context) {
  14349. return function(scope, locals, assign, inputs) {
  14350. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  14351. return context ? {value: arg} : arg;
  14352. };
  14353. },
  14354. 'binary>': function(left, right, context) {
  14355. return function(scope, locals, assign, inputs) {
  14356. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  14357. return context ? {value: arg} : arg;
  14358. };
  14359. },
  14360. 'binary<=': function(left, right, context) {
  14361. return function(scope, locals, assign, inputs) {
  14362. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  14363. return context ? {value: arg} : arg;
  14364. };
  14365. },
  14366. 'binary>=': function(left, right, context) {
  14367. return function(scope, locals, assign, inputs) {
  14368. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  14369. return context ? {value: arg} : arg;
  14370. };
  14371. },
  14372. 'binary&&': function(left, right, context) {
  14373. return function(scope, locals, assign, inputs) {
  14374. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  14375. return context ? {value: arg} : arg;
  14376. };
  14377. },
  14378. 'binary||': function(left, right, context) {
  14379. return function(scope, locals, assign, inputs) {
  14380. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  14381. return context ? {value: arg} : arg;
  14382. };
  14383. },
  14384. 'ternary?:': function(test, alternate, consequent, context) {
  14385. return function(scope, locals, assign, inputs) {
  14386. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  14387. return context ? {value: arg} : arg;
  14388. };
  14389. },
  14390. value: function(value, context) {
  14391. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  14392. },
  14393. identifier: function(name, expensiveChecks, context, create, expression) {
  14394. return function(scope, locals, assign, inputs) {
  14395. var base = locals && (name in locals) ? locals : scope;
  14396. if (create && create !== 1 && base && !(base[name])) {
  14397. base[name] = {};
  14398. }
  14399. var value = base ? base[name] : undefined;
  14400. if (expensiveChecks) {
  14401. ensureSafeObject(value, expression);
  14402. }
  14403. if (context) {
  14404. return {context: base, name: name, value: value};
  14405. } else {
  14406. return value;
  14407. }
  14408. };
  14409. },
  14410. computedMember: function(left, right, context, create, expression) {
  14411. return function(scope, locals, assign, inputs) {
  14412. var lhs = left(scope, locals, assign, inputs);
  14413. var rhs;
  14414. var value;
  14415. if (lhs != null) {
  14416. rhs = right(scope, locals, assign, inputs);
  14417. rhs = getStringValue(rhs);
  14418. ensureSafeMemberName(rhs, expression);
  14419. if (create && create !== 1) {
  14420. ensureSafeAssignContext(lhs);
  14421. if (lhs && !(lhs[rhs])) {
  14422. lhs[rhs] = {};
  14423. }
  14424. }
  14425. value = lhs[rhs];
  14426. ensureSafeObject(value, expression);
  14427. }
  14428. if (context) {
  14429. return {context: lhs, name: rhs, value: value};
  14430. } else {
  14431. return value;
  14432. }
  14433. };
  14434. },
  14435. nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
  14436. return function(scope, locals, assign, inputs) {
  14437. var lhs = left(scope, locals, assign, inputs);
  14438. if (create && create !== 1) {
  14439. ensureSafeAssignContext(lhs);
  14440. if (lhs && !(lhs[right])) {
  14441. lhs[right] = {};
  14442. }
  14443. }
  14444. var value = lhs != null ? lhs[right] : undefined;
  14445. if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
  14446. ensureSafeObject(value, expression);
  14447. }
  14448. if (context) {
  14449. return {context: lhs, name: right, value: value};
  14450. } else {
  14451. return value;
  14452. }
  14453. };
  14454. },
  14455. inputs: function(input, watchId) {
  14456. return function(scope, value, locals, inputs) {
  14457. if (inputs) return inputs[watchId];
  14458. return input(scope, value, locals);
  14459. };
  14460. }
  14461. };
  14462. /**
  14463. * @constructor
  14464. */
  14465. var Parser = function Parser(lexer, $filter, options) {
  14466. this.lexer = lexer;
  14467. this.$filter = $filter;
  14468. this.options = options;
  14469. this.ast = new AST(lexer, options);
  14470. this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
  14471. new ASTCompiler(this.ast, $filter);
  14472. };
  14473. Parser.prototype = {
  14474. constructor: Parser,
  14475. parse: function(text) {
  14476. return this.astCompiler.compile(text, this.options.expensiveChecks);
  14477. }
  14478. };
  14479. function isPossiblyDangerousMemberName(name) {
  14480. return name === 'constructor';
  14481. }
  14482. function getValueOf(value) {
  14483. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  14484. }
  14485. ///////////////////////////////////
  14486. /**
  14487. * @ngdoc service
  14488. * @name $parse
  14489. * @kind function
  14490. *
  14491. * @description
  14492. *
  14493. * Converts Angular {@link guide/expression expression} into a function.
  14494. *
  14495. * ```js
  14496. * var getter = $parse('user.name');
  14497. * var setter = getter.assign;
  14498. * var context = {user:{name:'angular'}};
  14499. * var locals = {user:{name:'local'}};
  14500. *
  14501. * expect(getter(context)).toEqual('angular');
  14502. * setter(context, 'newValue');
  14503. * expect(context.user.name).toEqual('newValue');
  14504. * expect(getter(context, locals)).toEqual('local');
  14505. * ```
  14506. *
  14507. *
  14508. * @param {string} expression String expression to compile.
  14509. * @returns {function(context, locals)} a function which represents the compiled expression:
  14510. *
  14511. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14512. * are evaluated against (typically a scope object).
  14513. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14514. * `context`.
  14515. *
  14516. * The returned function also has the following properties:
  14517. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  14518. * literal.
  14519. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  14520. * constant literals.
  14521. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  14522. * set to a function to change its value on the given context.
  14523. *
  14524. */
  14525. /**
  14526. * @ngdoc provider
  14527. * @name $parseProvider
  14528. * @this
  14529. *
  14530. * @description
  14531. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  14532. * service.
  14533. */
  14534. function $ParseProvider() {
  14535. var cacheDefault = createMap();
  14536. var cacheExpensive = createMap();
  14537. var literals = {
  14538. 'true': true,
  14539. 'false': false,
  14540. 'null': null,
  14541. 'undefined': undefined
  14542. };
  14543. var identStart, identContinue;
  14544. /**
  14545. * @ngdoc method
  14546. * @name $parseProvider#addLiteral
  14547. * @description
  14548. *
  14549. * Configure $parse service to add literal values that will be present as literal at expressions.
  14550. *
  14551. * @param {string} literalName Token for the literal value. The literal name value must be a valid literal name.
  14552. * @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`.
  14553. *
  14554. **/
  14555. this.addLiteral = function(literalName, literalValue) {
  14556. literals[literalName] = literalValue;
  14557. };
  14558. /**
  14559. * @ngdoc method
  14560. * @name $parseProvider#setIdentifierFns
  14561. *
  14562. * @description
  14563. *
  14564. * Allows defining the set of characters that are allowed in Angular expressions. The function
  14565. * `identifierStart` will get called to know if a given character is a valid character to be the
  14566. * first character for an identifier. The function `identifierContinue` will get called to know if
  14567. * a given character is a valid character to be a follow-up identifier character. The functions
  14568. * `identifierStart` and `identifierContinue` will receive as arguments the single character to be
  14569. * identifier and the character code point. These arguments will be `string` and `numeric`. Keep in
  14570. * mind that the `string` parameter can be two characters long depending on the character
  14571. * representation. It is expected for the function to return `true` or `false`, whether that
  14572. * character is allowed or not.
  14573. *
  14574. * Since this function will be called extensivelly, keep the implementation of these functions fast,
  14575. * as the performance of these functions have a direct impact on the expressions parsing speed.
  14576. *
  14577. * @param {function=} identifierStart The function that will decide whether the given character is
  14578. * a valid identifier start character.
  14579. * @param {function=} identifierContinue The function that will decide whether the given character is
  14580. * a valid identifier continue character.
  14581. */
  14582. this.setIdentifierFns = function(identifierStart, identifierContinue) {
  14583. identStart = identifierStart;
  14584. identContinue = identifierContinue;
  14585. return this;
  14586. };
  14587. this.$get = ['$filter', function($filter) {
  14588. var noUnsafeEval = csp().noUnsafeEval;
  14589. var $parseOptions = {
  14590. csp: noUnsafeEval,
  14591. expensiveChecks: false,
  14592. literals: copy(literals),
  14593. isIdentifierStart: isFunction(identStart) && identStart,
  14594. isIdentifierContinue: isFunction(identContinue) && identContinue
  14595. },
  14596. $parseOptionsExpensive = {
  14597. csp: noUnsafeEval,
  14598. expensiveChecks: true,
  14599. literals: copy(literals),
  14600. isIdentifierStart: isFunction(identStart) && identStart,
  14601. isIdentifierContinue: isFunction(identContinue) && identContinue
  14602. };
  14603. var runningChecksEnabled = false;
  14604. $parse.$$runningExpensiveChecks = function() {
  14605. return runningChecksEnabled;
  14606. };
  14607. return $parse;
  14608. function $parse(exp, interceptorFn, expensiveChecks) {
  14609. var parsedExpression, oneTime, cacheKey;
  14610. expensiveChecks = expensiveChecks || runningChecksEnabled;
  14611. switch (typeof exp) {
  14612. case 'string':
  14613. exp = exp.trim();
  14614. cacheKey = exp;
  14615. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  14616. parsedExpression = cache[cacheKey];
  14617. if (!parsedExpression) {
  14618. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  14619. oneTime = true;
  14620. exp = exp.substring(2);
  14621. }
  14622. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  14623. var lexer = new Lexer(parseOptions);
  14624. var parser = new Parser(lexer, $filter, parseOptions);
  14625. parsedExpression = parser.parse(exp);
  14626. if (parsedExpression.constant) {
  14627. parsedExpression.$$watchDelegate = constantWatchDelegate;
  14628. } else if (oneTime) {
  14629. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  14630. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  14631. } else if (parsedExpression.inputs) {
  14632. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  14633. }
  14634. if (expensiveChecks) {
  14635. parsedExpression = expensiveChecksInterceptor(parsedExpression);
  14636. }
  14637. cache[cacheKey] = parsedExpression;
  14638. }
  14639. return addInterceptor(parsedExpression, interceptorFn);
  14640. case 'function':
  14641. return addInterceptor(exp, interceptorFn);
  14642. default:
  14643. return addInterceptor(noop, interceptorFn);
  14644. }
  14645. }
  14646. function expensiveChecksInterceptor(fn) {
  14647. if (!fn) return fn;
  14648. expensiveCheckFn.$$watchDelegate = fn.$$watchDelegate;
  14649. expensiveCheckFn.assign = expensiveChecksInterceptor(fn.assign);
  14650. expensiveCheckFn.constant = fn.constant;
  14651. expensiveCheckFn.literal = fn.literal;
  14652. for (var i = 0; fn.inputs && i < fn.inputs.length; ++i) {
  14653. fn.inputs[i] = expensiveChecksInterceptor(fn.inputs[i]);
  14654. }
  14655. expensiveCheckFn.inputs = fn.inputs;
  14656. return expensiveCheckFn;
  14657. function expensiveCheckFn(scope, locals, assign, inputs) {
  14658. var expensiveCheckOldValue = runningChecksEnabled;
  14659. runningChecksEnabled = true;
  14660. try {
  14661. return fn(scope, locals, assign, inputs);
  14662. } finally {
  14663. runningChecksEnabled = expensiveCheckOldValue;
  14664. }
  14665. }
  14666. }
  14667. function expressionInputDirtyCheck(newValue, oldValueOfValue) {
  14668. if (newValue == null || oldValueOfValue == null) { // null/undefined
  14669. return newValue === oldValueOfValue;
  14670. }
  14671. if (typeof newValue === 'object') {
  14672. // attempt to convert the value to a primitive type
  14673. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  14674. // be cheaply dirty-checked
  14675. newValue = getValueOf(newValue);
  14676. if (typeof newValue === 'object') {
  14677. // objects/arrays are not supported - deep-watching them would be too expensive
  14678. return false;
  14679. }
  14680. // fall-through to the primitive equality check
  14681. }
  14682. //Primitive or NaN
  14683. // eslint-disable-next-line no-self-compare
  14684. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  14685. }
  14686. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  14687. var inputExpressions = parsedExpression.inputs;
  14688. var lastResult;
  14689. if (inputExpressions.length === 1) {
  14690. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  14691. inputExpressions = inputExpressions[0];
  14692. return scope.$watch(function expressionInputWatch(scope) {
  14693. var newInputValue = inputExpressions(scope);
  14694. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
  14695. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  14696. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  14697. }
  14698. return lastResult;
  14699. }, listener, objectEquality, prettyPrintExpression);
  14700. }
  14701. var oldInputValueOfValues = [];
  14702. var oldInputValues = [];
  14703. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  14704. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  14705. oldInputValues[i] = null;
  14706. }
  14707. return scope.$watch(function expressionInputsWatch(scope) {
  14708. var changed = false;
  14709. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  14710. var newInputValue = inputExpressions[i](scope);
  14711. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
  14712. oldInputValues[i] = newInputValue;
  14713. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  14714. }
  14715. }
  14716. if (changed) {
  14717. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  14718. }
  14719. return lastResult;
  14720. }, listener, objectEquality, prettyPrintExpression);
  14721. }
  14722. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  14723. var unwatch, lastValue;
  14724. if (parsedExpression.inputs) {
  14725. unwatch = inputsWatchDelegate(scope, oneTimeListener, objectEquality, parsedExpression, prettyPrintExpression);
  14726. } else {
  14727. unwatch = scope.$watch(oneTimeWatch, oneTimeListener, objectEquality);
  14728. }
  14729. return unwatch;
  14730. function oneTimeWatch(scope) {
  14731. return parsedExpression(scope);
  14732. }
  14733. function oneTimeListener(value, old, scope) {
  14734. lastValue = value;
  14735. if (isFunction(listener)) {
  14736. listener(value, old, scope);
  14737. }
  14738. if (isDefined(value)) {
  14739. scope.$$postDigest(function() {
  14740. if (isDefined(lastValue)) {
  14741. unwatch();
  14742. }
  14743. });
  14744. }
  14745. }
  14746. }
  14747. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  14748. var unwatch, lastValue;
  14749. unwatch = scope.$watch(function oneTimeWatch(scope) {
  14750. return parsedExpression(scope);
  14751. }, function oneTimeListener(value, old, scope) {
  14752. lastValue = value;
  14753. if (isFunction(listener)) {
  14754. listener(value, old, scope);
  14755. }
  14756. if (isAllDefined(value)) {
  14757. scope.$$postDigest(function() {
  14758. if (isAllDefined(lastValue)) unwatch();
  14759. });
  14760. }
  14761. }, objectEquality);
  14762. return unwatch;
  14763. function isAllDefined(value) {
  14764. var allDefined = true;
  14765. forEach(value, function(val) {
  14766. if (!isDefined(val)) allDefined = false;
  14767. });
  14768. return allDefined;
  14769. }
  14770. }
  14771. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  14772. var unwatch = scope.$watch(function constantWatch(scope) {
  14773. unwatch();
  14774. return parsedExpression(scope);
  14775. }, listener, objectEquality);
  14776. return unwatch;
  14777. }
  14778. function addInterceptor(parsedExpression, interceptorFn) {
  14779. if (!interceptorFn) return parsedExpression;
  14780. var watchDelegate = parsedExpression.$$watchDelegate;
  14781. var useInputs = false;
  14782. var regularWatch =
  14783. watchDelegate !== oneTimeLiteralWatchDelegate &&
  14784. watchDelegate !== oneTimeWatchDelegate;
  14785. var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
  14786. var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
  14787. return interceptorFn(value, scope, locals);
  14788. } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
  14789. var value = parsedExpression(scope, locals, assign, inputs);
  14790. var result = interceptorFn(value, scope, locals);
  14791. // we only return the interceptor's result if the
  14792. // initial value is defined (for bind-once)
  14793. return isDefined(value) ? result : value;
  14794. };
  14795. // Propagate $$watchDelegates other then inputsWatchDelegate
  14796. useInputs = !parsedExpression.inputs;
  14797. if (parsedExpression.$$watchDelegate &&
  14798. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  14799. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  14800. fn.inputs = parsedExpression.inputs;
  14801. } else if (!interceptorFn.$stateful) {
  14802. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  14803. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  14804. fn.$$watchDelegate = inputsWatchDelegate;
  14805. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  14806. }
  14807. return fn;
  14808. }
  14809. }];
  14810. }
  14811. /**
  14812. * @ngdoc service
  14813. * @name $q
  14814. * @requires $rootScope
  14815. *
  14816. * @description
  14817. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  14818. * when they are done processing.
  14819. *
  14820. * This is an implementation of promises/deferred objects inspired by
  14821. * [Kris Kowal's Q](https://github.com/kriskowal/q).
  14822. *
  14823. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  14824. * implementations, and the other which resembles ES6 (ES2015) promises to some degree.
  14825. *
  14826. * # $q constructor
  14827. *
  14828. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  14829. * function as the first argument. This is similar to the native Promise implementation from ES6,
  14830. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  14831. *
  14832. * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are
  14833. * available yet.
  14834. *
  14835. * It can be used like so:
  14836. *
  14837. * ```js
  14838. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  14839. * // are available in the current lexical scope (they could have been injected or passed in).
  14840. *
  14841. * function asyncGreet(name) {
  14842. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  14843. * return $q(function(resolve, reject) {
  14844. * setTimeout(function() {
  14845. * if (okToGreet(name)) {
  14846. * resolve('Hello, ' + name + '!');
  14847. * } else {
  14848. * reject('Greeting ' + name + ' is not allowed.');
  14849. * }
  14850. * }, 1000);
  14851. * });
  14852. * }
  14853. *
  14854. * var promise = asyncGreet('Robin Hood');
  14855. * promise.then(function(greeting) {
  14856. * alert('Success: ' + greeting);
  14857. * }, function(reason) {
  14858. * alert('Failed: ' + reason);
  14859. * });
  14860. * ```
  14861. *
  14862. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  14863. *
  14864. * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.
  14865. *
  14866. * However, the more traditional CommonJS-style usage is still available, and documented below.
  14867. *
  14868. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  14869. * interface for interacting with an object that represents the result of an action that is
  14870. * performed asynchronously, and may or may not be finished at any given point in time.
  14871. *
  14872. * From the perspective of dealing with error handling, deferred and promise APIs are to
  14873. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  14874. *
  14875. * ```js
  14876. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  14877. * // are available in the current lexical scope (they could have been injected or passed in).
  14878. *
  14879. * function asyncGreet(name) {
  14880. * var deferred = $q.defer();
  14881. *
  14882. * setTimeout(function() {
  14883. * deferred.notify('About to greet ' + name + '.');
  14884. *
  14885. * if (okToGreet(name)) {
  14886. * deferred.resolve('Hello, ' + name + '!');
  14887. * } else {
  14888. * deferred.reject('Greeting ' + name + ' is not allowed.');
  14889. * }
  14890. * }, 1000);
  14891. *
  14892. * return deferred.promise;
  14893. * }
  14894. *
  14895. * var promise = asyncGreet('Robin Hood');
  14896. * promise.then(function(greeting) {
  14897. * alert('Success: ' + greeting);
  14898. * }, function(reason) {
  14899. * alert('Failed: ' + reason);
  14900. * }, function(update) {
  14901. * alert('Got notification: ' + update);
  14902. * });
  14903. * ```
  14904. *
  14905. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  14906. * comes in the way of guarantees that promise and deferred APIs make, see
  14907. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  14908. *
  14909. * Additionally the promise api allows for composition that is very hard to do with the
  14910. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  14911. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  14912. * section on serial or parallel joining of promises.
  14913. *
  14914. * # The Deferred API
  14915. *
  14916. * A new instance of deferred is constructed by calling `$q.defer()`.
  14917. *
  14918. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  14919. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  14920. * of the task.
  14921. *
  14922. * **Methods**
  14923. *
  14924. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  14925. * constructed via `$q.reject`, the promise will be rejected instead.
  14926. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  14927. * resolving it with a rejection constructed via `$q.reject`.
  14928. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  14929. * multiple times before the promise is either resolved or rejected.
  14930. *
  14931. * **Properties**
  14932. *
  14933. * - promise – `{Promise}` – promise object associated with this deferred.
  14934. *
  14935. *
  14936. * # The Promise API
  14937. *
  14938. * A new promise instance is created when a deferred instance is created and can be retrieved by
  14939. * calling `deferred.promise`.
  14940. *
  14941. * The purpose of the promise object is to allow for interested parties to get access to the result
  14942. * of the deferred task when it completes.
  14943. *
  14944. * **Methods**
  14945. *
  14946. * - `then(successCallback, [errorCallback], [notifyCallback])` – regardless of when the promise was or
  14947. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  14948. * as soon as the result is available. The callbacks are called with a single argument: the result
  14949. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  14950. * provide a progress indication, before the promise is resolved or rejected.
  14951. *
  14952. * This method *returns a new promise* which is resolved or rejected via the return value of the
  14953. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  14954. * with the value which is resolved in that promise using
  14955. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  14956. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  14957. * resolved or rejected from the notifyCallback method. The errorCallback and notifyCallback
  14958. * arguments are optional.
  14959. *
  14960. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  14961. *
  14962. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  14963. * but to do so without modifying the final value. This is useful to release resources or do some
  14964. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  14965. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  14966. * more information.
  14967. *
  14968. * # Chaining promises
  14969. *
  14970. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  14971. * possible to create a chain of promises:
  14972. *
  14973. * ```js
  14974. * promiseB = promiseA.then(function(result) {
  14975. * return result + 1;
  14976. * });
  14977. *
  14978. * // promiseB will be resolved immediately after promiseA is resolved and its value
  14979. * // will be the result of promiseA incremented by 1
  14980. * ```
  14981. *
  14982. * It is possible to create chains of any length and since a promise can be resolved with another
  14983. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  14984. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  14985. * $http's response interceptors.
  14986. *
  14987. *
  14988. * # Differences between Kris Kowal's Q and $q
  14989. *
  14990. * There are two main differences:
  14991. *
  14992. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  14993. * mechanism in angular, which means faster propagation of resolution or rejection into your
  14994. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  14995. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  14996. * all the important functionality needed for common async tasks.
  14997. *
  14998. * # Testing
  14999. *
  15000. * ```js
  15001. * it('should simulate promise', inject(function($q, $rootScope) {
  15002. * var deferred = $q.defer();
  15003. * var promise = deferred.promise;
  15004. * var resolvedValue;
  15005. *
  15006. * promise.then(function(value) { resolvedValue = value; });
  15007. * expect(resolvedValue).toBeUndefined();
  15008. *
  15009. * // Simulate resolving of promise
  15010. * deferred.resolve(123);
  15011. * // Note that the 'then' function does not get called synchronously.
  15012. * // This is because we want the promise API to always be async, whether or not
  15013. * // it got called synchronously or asynchronously.
  15014. * expect(resolvedValue).toBeUndefined();
  15015. *
  15016. * // Propagate promise resolution to 'then' functions using $apply().
  15017. * $rootScope.$apply();
  15018. * expect(resolvedValue).toEqual(123);
  15019. * }));
  15020. * ```
  15021. *
  15022. * @param {function(function, function)} resolver Function which is responsible for resolving or
  15023. * rejecting the newly created promise. The first parameter is a function which resolves the
  15024. * promise, the second parameter is a function which rejects the promise.
  15025. *
  15026. * @returns {Promise} The newly created promise.
  15027. */
  15028. /**
  15029. * @ngdoc provider
  15030. * @name $qProvider
  15031. * @this
  15032. *
  15033. * @description
  15034. */
  15035. function $QProvider() {
  15036. var errorOnUnhandledRejections = true;
  15037. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  15038. return qFactory(function(callback) {
  15039. $rootScope.$evalAsync(callback);
  15040. }, $exceptionHandler, errorOnUnhandledRejections);
  15041. }];
  15042. /**
  15043. * @ngdoc method
  15044. * @name $qProvider#errorOnUnhandledRejections
  15045. * @kind function
  15046. *
  15047. * @description
  15048. * Retrieves or overrides whether to generate an error when a rejected promise is not handled.
  15049. *
  15050. * @param {boolean=} value Whether to generate an error when a rejected promise is not handled.
  15051. * @returns {boolean|ng.$qProvider} Current value when called without a new value or self for
  15052. * chaining otherwise.
  15053. */
  15054. this.errorOnUnhandledRejections = function(value) {
  15055. if (isDefined(value)) {
  15056. errorOnUnhandledRejections = value;
  15057. return this;
  15058. } else {
  15059. return errorOnUnhandledRejections;
  15060. }
  15061. };
  15062. }
  15063. /** @this */
  15064. function $$QProvider() {
  15065. var errorOnUnhandledRejections = true;
  15066. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  15067. return qFactory(function(callback) {
  15068. $browser.defer(callback);
  15069. }, $exceptionHandler, errorOnUnhandledRejections);
  15070. }];
  15071. this.errorOnUnhandledRejections = function(value) {
  15072. if (isDefined(value)) {
  15073. errorOnUnhandledRejections = value;
  15074. return this;
  15075. } else {
  15076. return errorOnUnhandledRejections;
  15077. }
  15078. };
  15079. }
  15080. /**
  15081. * Constructs a promise manager.
  15082. *
  15083. * @param {function(function)} nextTick Function for executing functions in the next turn.
  15084. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  15085. * debugging purposes.
  15086. @ param {=boolean} errorOnUnhandledRejections Whether an error should be generated on unhandled
  15087. * promises rejections.
  15088. * @returns {object} Promise manager.
  15089. */
  15090. function qFactory(nextTick, exceptionHandler, errorOnUnhandledRejections) {
  15091. var $qMinErr = minErr('$q', TypeError);
  15092. var queueSize = 0;
  15093. var checkQueue = [];
  15094. /**
  15095. * @ngdoc method
  15096. * @name ng.$q#defer
  15097. * @kind function
  15098. *
  15099. * @description
  15100. * Creates a `Deferred` object which represents a task which will finish in the future.
  15101. *
  15102. * @returns {Deferred} Returns a new instance of deferred.
  15103. */
  15104. function defer() {
  15105. var d = new Deferred();
  15106. //Necessary to support unbound execution :/
  15107. d.resolve = simpleBind(d, d.resolve);
  15108. d.reject = simpleBind(d, d.reject);
  15109. d.notify = simpleBind(d, d.notify);
  15110. return d;
  15111. }
  15112. function Promise() {
  15113. this.$$state = { status: 0 };
  15114. }
  15115. extend(Promise.prototype, {
  15116. then: function(onFulfilled, onRejected, progressBack) {
  15117. if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
  15118. return this;
  15119. }
  15120. var result = new Deferred();
  15121. this.$$state.pending = this.$$state.pending || [];
  15122. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  15123. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  15124. return result.promise;
  15125. },
  15126. 'catch': function(callback) {
  15127. return this.then(null, callback);
  15128. },
  15129. 'finally': function(callback, progressBack) {
  15130. return this.then(function(value) {
  15131. return handleCallback(value, resolve, callback);
  15132. }, function(error) {
  15133. return handleCallback(error, reject, callback);
  15134. }, progressBack);
  15135. }
  15136. });
  15137. //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
  15138. function simpleBind(context, fn) {
  15139. return function(value) {
  15140. fn.call(context, value);
  15141. };
  15142. }
  15143. function processQueue(state) {
  15144. var fn, deferred, pending;
  15145. pending = state.pending;
  15146. state.processScheduled = false;
  15147. state.pending = undefined;
  15148. try {
  15149. for (var i = 0, ii = pending.length; i < ii; ++i) {
  15150. state.pur = true;
  15151. deferred = pending[i][0];
  15152. fn = pending[i][state.status];
  15153. try {
  15154. if (isFunction(fn)) {
  15155. deferred.resolve(fn(state.value));
  15156. } else if (state.status === 1) {
  15157. deferred.resolve(state.value);
  15158. } else {
  15159. deferred.reject(state.value);
  15160. }
  15161. } catch (e) {
  15162. deferred.reject(e);
  15163. exceptionHandler(e);
  15164. }
  15165. }
  15166. } finally {
  15167. --queueSize;
  15168. if (errorOnUnhandledRejections && queueSize === 0) {
  15169. nextTick(processChecks);
  15170. }
  15171. }
  15172. }
  15173. function processChecks() {
  15174. // eslint-disable-next-line no-unmodified-loop-condition
  15175. while (!queueSize && checkQueue.length) {
  15176. var toCheck = checkQueue.shift();
  15177. if (!toCheck.pur) {
  15178. toCheck.pur = true;
  15179. var errorMessage = 'Possibly unhandled rejection: ' + toDebugString(toCheck.value);
  15180. exceptionHandler(errorMessage);
  15181. }
  15182. }
  15183. }
  15184. function scheduleProcessQueue(state) {
  15185. if (errorOnUnhandledRejections && !state.pending && state.status === 2 && !state.pur) {
  15186. if (queueSize === 0 && checkQueue.length === 0) {
  15187. nextTick(processChecks);
  15188. }
  15189. checkQueue.push(state);
  15190. }
  15191. if (state.processScheduled || !state.pending) return;
  15192. state.processScheduled = true;
  15193. ++queueSize;
  15194. nextTick(function() { processQueue(state); });
  15195. }
  15196. function Deferred() {
  15197. this.promise = new Promise();
  15198. }
  15199. extend(Deferred.prototype, {
  15200. resolve: function(val) {
  15201. if (this.promise.$$state.status) return;
  15202. if (val === this.promise) {
  15203. this.$$reject($qMinErr(
  15204. 'qcycle',
  15205. 'Expected promise to be resolved with value other than itself \'{0}\'',
  15206. val));
  15207. } else {
  15208. this.$$resolve(val);
  15209. }
  15210. },
  15211. $$resolve: function(val) {
  15212. var then;
  15213. var that = this;
  15214. var done = false;
  15215. try {
  15216. if ((isObject(val) || isFunction(val))) then = val && val.then;
  15217. if (isFunction(then)) {
  15218. this.promise.$$state.status = -1;
  15219. then.call(val, resolvePromise, rejectPromise, simpleBind(this, this.notify));
  15220. } else {
  15221. this.promise.$$state.value = val;
  15222. this.promise.$$state.status = 1;
  15223. scheduleProcessQueue(this.promise.$$state);
  15224. }
  15225. } catch (e) {
  15226. rejectPromise(e);
  15227. exceptionHandler(e);
  15228. }
  15229. function resolvePromise(val) {
  15230. if (done) return;
  15231. done = true;
  15232. that.$$resolve(val);
  15233. }
  15234. function rejectPromise(val) {
  15235. if (done) return;
  15236. done = true;
  15237. that.$$reject(val);
  15238. }
  15239. },
  15240. reject: function(reason) {
  15241. if (this.promise.$$state.status) return;
  15242. this.$$reject(reason);
  15243. },
  15244. $$reject: function(reason) {
  15245. this.promise.$$state.value = reason;
  15246. this.promise.$$state.status = 2;
  15247. scheduleProcessQueue(this.promise.$$state);
  15248. },
  15249. notify: function(progress) {
  15250. var callbacks = this.promise.$$state.pending;
  15251. if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
  15252. nextTick(function() {
  15253. var callback, result;
  15254. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  15255. result = callbacks[i][0];
  15256. callback = callbacks[i][3];
  15257. try {
  15258. result.notify(isFunction(callback) ? callback(progress) : progress);
  15259. } catch (e) {
  15260. exceptionHandler(e);
  15261. }
  15262. }
  15263. });
  15264. }
  15265. }
  15266. });
  15267. /**
  15268. * @ngdoc method
  15269. * @name $q#reject
  15270. * @kind function
  15271. *
  15272. * @description
  15273. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  15274. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  15275. * a promise chain, you don't need to worry about it.
  15276. *
  15277. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  15278. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  15279. * a promise error callback and you want to forward the error to the promise derived from the
  15280. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  15281. * `reject`.
  15282. *
  15283. * ```js
  15284. * promiseB = promiseA.then(function(result) {
  15285. * // success: do something and resolve promiseB
  15286. * // with the old or a new result
  15287. * return result;
  15288. * }, function(reason) {
  15289. * // error: handle the error if possible and
  15290. * // resolve promiseB with newPromiseOrValue,
  15291. * // otherwise forward the rejection to promiseB
  15292. * if (canHandle(reason)) {
  15293. * // handle the error and recover
  15294. * return newPromiseOrValue;
  15295. * }
  15296. * return $q.reject(reason);
  15297. * });
  15298. * ```
  15299. *
  15300. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  15301. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  15302. */
  15303. function reject(reason) {
  15304. var result = new Deferred();
  15305. result.reject(reason);
  15306. return result.promise;
  15307. }
  15308. function handleCallback(value, resolver, callback) {
  15309. var callbackOutput = null;
  15310. try {
  15311. if (isFunction(callback)) callbackOutput = callback();
  15312. } catch (e) {
  15313. return reject(e);
  15314. }
  15315. if (isPromiseLike(callbackOutput)) {
  15316. return callbackOutput.then(function() {
  15317. return resolver(value);
  15318. }, reject);
  15319. } else {
  15320. return resolver(value);
  15321. }
  15322. }
  15323. /**
  15324. * @ngdoc method
  15325. * @name $q#when
  15326. * @kind function
  15327. *
  15328. * @description
  15329. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  15330. * This is useful when you are dealing with an object that might or might not be a promise, or if
  15331. * the promise comes from a source that can't be trusted.
  15332. *
  15333. * @param {*} value Value or a promise
  15334. * @param {Function=} successCallback
  15335. * @param {Function=} errorCallback
  15336. * @param {Function=} progressCallback
  15337. * @returns {Promise} Returns a promise of the passed value or promise
  15338. */
  15339. function when(value, callback, errback, progressBack) {
  15340. var result = new Deferred();
  15341. result.resolve(value);
  15342. return result.promise.then(callback, errback, progressBack);
  15343. }
  15344. /**
  15345. * @ngdoc method
  15346. * @name $q#resolve
  15347. * @kind function
  15348. *
  15349. * @description
  15350. * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
  15351. *
  15352. * @param {*} value Value or a promise
  15353. * @param {Function=} successCallback
  15354. * @param {Function=} errorCallback
  15355. * @param {Function=} progressCallback
  15356. * @returns {Promise} Returns a promise of the passed value or promise
  15357. */
  15358. var resolve = when;
  15359. /**
  15360. * @ngdoc method
  15361. * @name $q#all
  15362. * @kind function
  15363. *
  15364. * @description
  15365. * Combines multiple promises into a single promise that is resolved when all of the input
  15366. * promises are resolved.
  15367. *
  15368. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  15369. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  15370. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  15371. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  15372. * with the same rejection value.
  15373. */
  15374. function all(promises) {
  15375. var deferred = new Deferred(),
  15376. counter = 0,
  15377. results = isArray(promises) ? [] : {};
  15378. forEach(promises, function(promise, key) {
  15379. counter++;
  15380. when(promise).then(function(value) {
  15381. results[key] = value;
  15382. if (!(--counter)) deferred.resolve(results);
  15383. }, function(reason) {
  15384. deferred.reject(reason);
  15385. });
  15386. });
  15387. if (counter === 0) {
  15388. deferred.resolve(results);
  15389. }
  15390. return deferred.promise;
  15391. }
  15392. /**
  15393. * @ngdoc method
  15394. * @name $q#race
  15395. * @kind function
  15396. *
  15397. * @description
  15398. * Returns a promise that resolves or rejects as soon as one of those promises
  15399. * resolves or rejects, with the value or reason from that promise.
  15400. *
  15401. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  15402. * @returns {Promise} a promise that resolves or rejects as soon as one of the `promises`
  15403. * resolves or rejects, with the value or reason from that promise.
  15404. */
  15405. function race(promises) {
  15406. var deferred = defer();
  15407. forEach(promises, function(promise) {
  15408. when(promise).then(deferred.resolve, deferred.reject);
  15409. });
  15410. return deferred.promise;
  15411. }
  15412. function $Q(resolver) {
  15413. if (!isFunction(resolver)) {
  15414. throw $qMinErr('norslvr', 'Expected resolverFn, got \'{0}\'', resolver);
  15415. }
  15416. var deferred = new Deferred();
  15417. function resolveFn(value) {
  15418. deferred.resolve(value);
  15419. }
  15420. function rejectFn(reason) {
  15421. deferred.reject(reason);
  15422. }
  15423. resolver(resolveFn, rejectFn);
  15424. return deferred.promise;
  15425. }
  15426. // Let's make the instanceof operator work for promises, so that
  15427. // `new $q(fn) instanceof $q` would evaluate to true.
  15428. $Q.prototype = Promise.prototype;
  15429. $Q.defer = defer;
  15430. $Q.reject = reject;
  15431. $Q.when = when;
  15432. $Q.resolve = resolve;
  15433. $Q.all = all;
  15434. $Q.race = race;
  15435. return $Q;
  15436. }
  15437. /** @this */
  15438. function $$RAFProvider() { //rAF
  15439. this.$get = ['$window', '$timeout', function($window, $timeout) {
  15440. var requestAnimationFrame = $window.requestAnimationFrame ||
  15441. $window.webkitRequestAnimationFrame;
  15442. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  15443. $window.webkitCancelAnimationFrame ||
  15444. $window.webkitCancelRequestAnimationFrame;
  15445. var rafSupported = !!requestAnimationFrame;
  15446. var raf = rafSupported
  15447. ? function(fn) {
  15448. var id = requestAnimationFrame(fn);
  15449. return function() {
  15450. cancelAnimationFrame(id);
  15451. };
  15452. }
  15453. : function(fn) {
  15454. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  15455. return function() {
  15456. $timeout.cancel(timer);
  15457. };
  15458. };
  15459. raf.supported = rafSupported;
  15460. return raf;
  15461. }];
  15462. }
  15463. /**
  15464. * DESIGN NOTES
  15465. *
  15466. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  15467. *
  15468. * The typical use of scope is to watch the expressions, which most of the time return the same
  15469. * value as last time so we optimize the operation.
  15470. *
  15471. * Closures construction is expensive in terms of speed as well as memory:
  15472. * - No closures, instead use prototypical inheritance for API
  15473. * - Internal state needs to be stored on scope directly, which means that private state is
  15474. * exposed as $$____ properties
  15475. *
  15476. * Loop operations are optimized by using while(count--) { ... }
  15477. * - This means that in order to keep the same order of execution as addition we have to add
  15478. * items to the array at the beginning (unshift) instead of at the end (push)
  15479. *
  15480. * Child scopes are created and removed often
  15481. * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
  15482. *
  15483. * There are fewer watches than observers. This is why you don't want the observer to be implemented
  15484. * in the same way as watch. Watch requires return of the initialization function which is expensive
  15485. * to construct.
  15486. */
  15487. /**
  15488. * @ngdoc provider
  15489. * @name $rootScopeProvider
  15490. * @description
  15491. *
  15492. * Provider for the $rootScope service.
  15493. */
  15494. /**
  15495. * @ngdoc method
  15496. * @name $rootScopeProvider#digestTtl
  15497. * @description
  15498. *
  15499. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  15500. * assuming that the model is unstable.
  15501. *
  15502. * The current default is 10 iterations.
  15503. *
  15504. * In complex applications it's possible that the dependencies between `$watch`s will result in
  15505. * several digest iterations. However if an application needs more than the default 10 digest
  15506. * iterations for its model to stabilize then you should investigate what is causing the model to
  15507. * continuously change during the digest.
  15508. *
  15509. * Increasing the TTL could have performance implications, so you should not change it without
  15510. * proper justification.
  15511. *
  15512. * @param {number} limit The number of digest iterations.
  15513. */
  15514. /**
  15515. * @ngdoc service
  15516. * @name $rootScope
  15517. * @this
  15518. *
  15519. * @description
  15520. *
  15521. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  15522. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  15523. * between the model and the view, via a mechanism for watching the model for changes.
  15524. * They also provide event emission/broadcast and subscription facility. See the
  15525. * {@link guide/scope developer guide on scopes}.
  15526. */
  15527. function $RootScopeProvider() {
  15528. var TTL = 10;
  15529. var $rootScopeMinErr = minErr('$rootScope');
  15530. var lastDirtyWatch = null;
  15531. var applyAsyncId = null;
  15532. this.digestTtl = function(value) {
  15533. if (arguments.length) {
  15534. TTL = value;
  15535. }
  15536. return TTL;
  15537. };
  15538. function createChildScopeClass(parent) {
  15539. function ChildScope() {
  15540. this.$$watchers = this.$$nextSibling =
  15541. this.$$childHead = this.$$childTail = null;
  15542. this.$$listeners = {};
  15543. this.$$listenerCount = {};
  15544. this.$$watchersCount = 0;
  15545. this.$id = nextUid();
  15546. this.$$ChildScope = null;
  15547. }
  15548. ChildScope.prototype = parent;
  15549. return ChildScope;
  15550. }
  15551. this.$get = ['$exceptionHandler', '$parse', '$browser',
  15552. function($exceptionHandler, $parse, $browser) {
  15553. function destroyChildScope($event) {
  15554. $event.currentScope.$$destroyed = true;
  15555. }
  15556. function cleanUpScope($scope) {
  15557. if (msie === 9) {
  15558. // There is a memory leak in IE9 if all child scopes are not disconnected
  15559. // completely when a scope is destroyed. So this code will recurse up through
  15560. // all this scopes children
  15561. //
  15562. // See issue https://github.com/angular/angular.js/issues/10706
  15563. if ($scope.$$childHead) {
  15564. cleanUpScope($scope.$$childHead);
  15565. }
  15566. if ($scope.$$nextSibling) {
  15567. cleanUpScope($scope.$$nextSibling);
  15568. }
  15569. }
  15570. // The code below works around IE9 and V8's memory leaks
  15571. //
  15572. // See:
  15573. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  15574. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  15575. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  15576. $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
  15577. $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
  15578. }
  15579. /**
  15580. * @ngdoc type
  15581. * @name $rootScope.Scope
  15582. *
  15583. * @description
  15584. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  15585. * {@link auto.$injector $injector}. Child scopes are created using the
  15586. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  15587. * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
  15588. * an in-depth introduction and usage examples.
  15589. *
  15590. *
  15591. * # Inheritance
  15592. * A scope can inherit from a parent scope, as in this example:
  15593. * ```js
  15594. var parent = $rootScope;
  15595. var child = parent.$new();
  15596. parent.salutation = "Hello";
  15597. expect(child.salutation).toEqual('Hello');
  15598. child.salutation = "Welcome";
  15599. expect(child.salutation).toEqual('Welcome');
  15600. expect(parent.salutation).toEqual('Hello');
  15601. * ```
  15602. *
  15603. * When interacting with `Scope` in tests, additional helper methods are available on the
  15604. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  15605. * details.
  15606. *
  15607. *
  15608. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  15609. * provided for the current scope. Defaults to {@link ng}.
  15610. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  15611. * append/override services provided by `providers`. This is handy
  15612. * when unit-testing and having the need to override a default
  15613. * service.
  15614. * @returns {Object} Newly created scope.
  15615. *
  15616. */
  15617. function Scope() {
  15618. this.$id = nextUid();
  15619. this.$$phase = this.$parent = this.$$watchers =
  15620. this.$$nextSibling = this.$$prevSibling =
  15621. this.$$childHead = this.$$childTail = null;
  15622. this.$root = this;
  15623. this.$$destroyed = false;
  15624. this.$$listeners = {};
  15625. this.$$listenerCount = {};
  15626. this.$$watchersCount = 0;
  15627. this.$$isolateBindings = null;
  15628. }
  15629. /**
  15630. * @ngdoc property
  15631. * @name $rootScope.Scope#$id
  15632. *
  15633. * @description
  15634. * Unique scope ID (monotonically increasing) useful for debugging.
  15635. */
  15636. /**
  15637. * @ngdoc property
  15638. * @name $rootScope.Scope#$parent
  15639. *
  15640. * @description
  15641. * Reference to the parent scope.
  15642. */
  15643. /**
  15644. * @ngdoc property
  15645. * @name $rootScope.Scope#$root
  15646. *
  15647. * @description
  15648. * Reference to the root scope.
  15649. */
  15650. Scope.prototype = {
  15651. constructor: Scope,
  15652. /**
  15653. * @ngdoc method
  15654. * @name $rootScope.Scope#$new
  15655. * @kind function
  15656. *
  15657. * @description
  15658. * Creates a new child {@link ng.$rootScope.Scope scope}.
  15659. *
  15660. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  15661. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  15662. *
  15663. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  15664. * desired for the scope and its child scopes to be permanently detached from the parent and
  15665. * thus stop participating in model change detection and listener notification by invoking.
  15666. *
  15667. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  15668. * parent scope. The scope is isolated, as it can not see parent scope properties.
  15669. * When creating widgets, it is useful for the widget to not accidentally read parent
  15670. * state.
  15671. *
  15672. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  15673. * of the newly created scope. Defaults to `this` scope if not provided.
  15674. * This is used when creating a transclude scope to correctly place it
  15675. * in the scope hierarchy while maintaining the correct prototypical
  15676. * inheritance.
  15677. *
  15678. * @returns {Object} The newly created child scope.
  15679. *
  15680. */
  15681. $new: function(isolate, parent) {
  15682. var child;
  15683. parent = parent || this;
  15684. if (isolate) {
  15685. child = new Scope();
  15686. child.$root = this.$root;
  15687. } else {
  15688. // Only create a child scope class if somebody asks for one,
  15689. // but cache it to allow the VM to optimize lookups.
  15690. if (!this.$$ChildScope) {
  15691. this.$$ChildScope = createChildScopeClass(this);
  15692. }
  15693. child = new this.$$ChildScope();
  15694. }
  15695. child.$parent = parent;
  15696. child.$$prevSibling = parent.$$childTail;
  15697. if (parent.$$childHead) {
  15698. parent.$$childTail.$$nextSibling = child;
  15699. parent.$$childTail = child;
  15700. } else {
  15701. parent.$$childHead = parent.$$childTail = child;
  15702. }
  15703. // When the new scope is not isolated or we inherit from `this`, and
  15704. // the parent scope is destroyed, the property `$$destroyed` is inherited
  15705. // prototypically. In all other cases, this property needs to be set
  15706. // when the parent scope is destroyed.
  15707. // The listener needs to be added after the parent is set
  15708. if (isolate || parent !== this) child.$on('$destroy', destroyChildScope);
  15709. return child;
  15710. },
  15711. /**
  15712. * @ngdoc method
  15713. * @name $rootScope.Scope#$watch
  15714. * @kind function
  15715. *
  15716. * @description
  15717. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  15718. *
  15719. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  15720. * $digest()} and should return the value that will be watched. (`watchExpression` should not change
  15721. * its value when executed multiple times with the same input because it may be executed multiple
  15722. * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
  15723. * [idempotent](http://en.wikipedia.org/wiki/Idempotence).
  15724. * - The `listener` is called only when the value from the current `watchExpression` and the
  15725. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  15726. * see below). Inequality is determined according to reference inequality,
  15727. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  15728. * via the `!==` Javascript operator, unless `objectEquality == true`
  15729. * (see next point)
  15730. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  15731. * according to the {@link angular.equals} function. To save the value of the object for
  15732. * later comparison, the {@link angular.copy} function is used. This therefore means that
  15733. * watching complex objects will have adverse memory and performance implications.
  15734. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  15735. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  15736. * iteration limit is 10 to prevent an infinite loop deadlock.
  15737. *
  15738. *
  15739. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  15740. * you can register a `watchExpression` function with no `listener`. (Be prepared for
  15741. * multiple calls to your `watchExpression` because it will execute multiple times in a
  15742. * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
  15743. *
  15744. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  15745. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  15746. * watcher. In rare cases, this is undesirable because the listener is called when the result
  15747. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  15748. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  15749. * listener was called due to initialization.
  15750. *
  15751. *
  15752. *
  15753. * # Example
  15754. * ```js
  15755. // let's assume that scope was dependency injected as the $rootScope
  15756. var scope = $rootScope;
  15757. scope.name = 'misko';
  15758. scope.counter = 0;
  15759. expect(scope.counter).toEqual(0);
  15760. scope.$watch('name', function(newValue, oldValue) {
  15761. scope.counter = scope.counter + 1;
  15762. });
  15763. expect(scope.counter).toEqual(0);
  15764. scope.$digest();
  15765. // the listener is always called during the first $digest loop after it was registered
  15766. expect(scope.counter).toEqual(1);
  15767. scope.$digest();
  15768. // but now it will not be called unless the value changes
  15769. expect(scope.counter).toEqual(1);
  15770. scope.name = 'adam';
  15771. scope.$digest();
  15772. expect(scope.counter).toEqual(2);
  15773. // Using a function as a watchExpression
  15774. var food;
  15775. scope.foodCounter = 0;
  15776. expect(scope.foodCounter).toEqual(0);
  15777. scope.$watch(
  15778. // This function returns the value being watched. It is called for each turn of the $digest loop
  15779. function() { return food; },
  15780. // This is the change listener, called when the value returned from the above function changes
  15781. function(newValue, oldValue) {
  15782. if ( newValue !== oldValue ) {
  15783. // Only increment the counter if the value changed
  15784. scope.foodCounter = scope.foodCounter + 1;
  15785. }
  15786. }
  15787. );
  15788. // No digest has been run so the counter will be zero
  15789. expect(scope.foodCounter).toEqual(0);
  15790. // Run the digest but since food has not changed count will still be zero
  15791. scope.$digest();
  15792. expect(scope.foodCounter).toEqual(0);
  15793. // Update food and run digest. Now the counter will increment
  15794. food = 'cheeseburger';
  15795. scope.$digest();
  15796. expect(scope.foodCounter).toEqual(1);
  15797. * ```
  15798. *
  15799. *
  15800. *
  15801. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  15802. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  15803. * a call to the `listener`.
  15804. *
  15805. * - `string`: Evaluated as {@link guide/expression expression}
  15806. * - `function(scope)`: called with current `scope` as a parameter.
  15807. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  15808. * of `watchExpression` changes.
  15809. *
  15810. * - `newVal` contains the current value of the `watchExpression`
  15811. * - `oldVal` contains the previous value of the `watchExpression`
  15812. * - `scope` refers to the current scope
  15813. * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of
  15814. * comparing for reference equality.
  15815. * @returns {function()} Returns a deregistration function for this listener.
  15816. */
  15817. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  15818. var get = $parse(watchExp);
  15819. if (get.$$watchDelegate) {
  15820. return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
  15821. }
  15822. var scope = this,
  15823. array = scope.$$watchers,
  15824. watcher = {
  15825. fn: listener,
  15826. last: initWatchVal,
  15827. get: get,
  15828. exp: prettyPrintExpression || watchExp,
  15829. eq: !!objectEquality
  15830. };
  15831. lastDirtyWatch = null;
  15832. if (!isFunction(listener)) {
  15833. watcher.fn = noop;
  15834. }
  15835. if (!array) {
  15836. array = scope.$$watchers = [];
  15837. }
  15838. // we use unshift since we use a while loop in $digest for speed.
  15839. // the while loop reads in reverse order.
  15840. array.unshift(watcher);
  15841. incrementWatchersCount(this, 1);
  15842. return function deregisterWatch() {
  15843. if (arrayRemove(array, watcher) >= 0) {
  15844. incrementWatchersCount(scope, -1);
  15845. }
  15846. lastDirtyWatch = null;
  15847. };
  15848. },
  15849. /**
  15850. * @ngdoc method
  15851. * @name $rootScope.Scope#$watchGroup
  15852. * @kind function
  15853. *
  15854. * @description
  15855. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  15856. * If any one expression in the collection changes the `listener` is executed.
  15857. *
  15858. * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
  15859. * call to $digest() to see if any items changes.
  15860. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  15861. *
  15862. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  15863. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  15864. *
  15865. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  15866. * expression in `watchExpressions` changes
  15867. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  15868. * those of `watchExpression`
  15869. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  15870. * those of `watchExpression`
  15871. * The `scope` refers to the current scope.
  15872. * @returns {function()} Returns a de-registration function for all listeners.
  15873. */
  15874. $watchGroup: function(watchExpressions, listener) {
  15875. var oldValues = new Array(watchExpressions.length);
  15876. var newValues = new Array(watchExpressions.length);
  15877. var deregisterFns = [];
  15878. var self = this;
  15879. var changeReactionScheduled = false;
  15880. var firstRun = true;
  15881. if (!watchExpressions.length) {
  15882. // No expressions means we call the listener ASAP
  15883. var shouldCall = true;
  15884. self.$evalAsync(function() {
  15885. if (shouldCall) listener(newValues, newValues, self);
  15886. });
  15887. return function deregisterWatchGroup() {
  15888. shouldCall = false;
  15889. };
  15890. }
  15891. if (watchExpressions.length === 1) {
  15892. // Special case size of one
  15893. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  15894. newValues[0] = value;
  15895. oldValues[0] = oldValue;
  15896. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  15897. });
  15898. }
  15899. forEach(watchExpressions, function(expr, i) {
  15900. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  15901. newValues[i] = value;
  15902. oldValues[i] = oldValue;
  15903. if (!changeReactionScheduled) {
  15904. changeReactionScheduled = true;
  15905. self.$evalAsync(watchGroupAction);
  15906. }
  15907. });
  15908. deregisterFns.push(unwatchFn);
  15909. });
  15910. function watchGroupAction() {
  15911. changeReactionScheduled = false;
  15912. if (firstRun) {
  15913. firstRun = false;
  15914. listener(newValues, newValues, self);
  15915. } else {
  15916. listener(newValues, oldValues, self);
  15917. }
  15918. }
  15919. return function deregisterWatchGroup() {
  15920. while (deregisterFns.length) {
  15921. deregisterFns.shift()();
  15922. }
  15923. };
  15924. },
  15925. /**
  15926. * @ngdoc method
  15927. * @name $rootScope.Scope#$watchCollection
  15928. * @kind function
  15929. *
  15930. * @description
  15931. * Shallow watches the properties of an object and fires whenever any of the properties change
  15932. * (for arrays, this implies watching the array items; for object maps, this implies watching
  15933. * the properties). If a change is detected, the `listener` callback is fired.
  15934. *
  15935. * - The `obj` collection is observed via standard $watch operation and is examined on every
  15936. * call to $digest() to see if any items have been added, removed, or moved.
  15937. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  15938. * adding, removing, and moving items belonging to an object or array.
  15939. *
  15940. *
  15941. * # Example
  15942. * ```js
  15943. $scope.names = ['igor', 'matias', 'misko', 'james'];
  15944. $scope.dataCount = 4;
  15945. $scope.$watchCollection('names', function(newNames, oldNames) {
  15946. $scope.dataCount = newNames.length;
  15947. });
  15948. expect($scope.dataCount).toEqual(4);
  15949. $scope.$digest();
  15950. //still at 4 ... no changes
  15951. expect($scope.dataCount).toEqual(4);
  15952. $scope.names.pop();
  15953. $scope.$digest();
  15954. //now there's been a change
  15955. expect($scope.dataCount).toEqual(3);
  15956. * ```
  15957. *
  15958. *
  15959. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  15960. * expression value should evaluate to an object or an array which is observed on each
  15961. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  15962. * collection will trigger a call to the `listener`.
  15963. *
  15964. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  15965. * when a change is detected.
  15966. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  15967. * - The `oldCollection` object is a copy of the former collection data.
  15968. * Due to performance considerations, the`oldCollection` value is computed only if the
  15969. * `listener` function declares two or more arguments.
  15970. * - The `scope` argument refers to the current scope.
  15971. *
  15972. * @returns {function()} Returns a de-registration function for this listener. When the
  15973. * de-registration function is executed, the internal watch operation is terminated.
  15974. */
  15975. $watchCollection: function(obj, listener) {
  15976. $watchCollectionInterceptor.$stateful = true;
  15977. var self = this;
  15978. // the current value, updated on each dirty-check run
  15979. var newValue;
  15980. // a shallow copy of the newValue from the last dirty-check run,
  15981. // updated to match newValue during dirty-check run
  15982. var oldValue;
  15983. // a shallow copy of the newValue from when the last change happened
  15984. var veryOldValue;
  15985. // only track veryOldValue if the listener is asking for it
  15986. var trackVeryOldValue = (listener.length > 1);
  15987. var changeDetected = 0;
  15988. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  15989. var internalArray = [];
  15990. var internalObject = {};
  15991. var initRun = true;
  15992. var oldLength = 0;
  15993. function $watchCollectionInterceptor(_value) {
  15994. newValue = _value;
  15995. var newLength, key, bothNaN, newItem, oldItem;
  15996. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  15997. if (isUndefined(newValue)) return;
  15998. if (!isObject(newValue)) { // if primitive
  15999. if (oldValue !== newValue) {
  16000. oldValue = newValue;
  16001. changeDetected++;
  16002. }
  16003. } else if (isArrayLike(newValue)) {
  16004. if (oldValue !== internalArray) {
  16005. // we are transitioning from something which was not an array into array.
  16006. oldValue = internalArray;
  16007. oldLength = oldValue.length = 0;
  16008. changeDetected++;
  16009. }
  16010. newLength = newValue.length;
  16011. if (oldLength !== newLength) {
  16012. // if lengths do not match we need to trigger change notification
  16013. changeDetected++;
  16014. oldValue.length = oldLength = newLength;
  16015. }
  16016. // copy the items to oldValue and look for changes.
  16017. for (var i = 0; i < newLength; i++) {
  16018. oldItem = oldValue[i];
  16019. newItem = newValue[i];
  16020. // eslint-disable-next-line no-self-compare
  16021. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  16022. if (!bothNaN && (oldItem !== newItem)) {
  16023. changeDetected++;
  16024. oldValue[i] = newItem;
  16025. }
  16026. }
  16027. } else {
  16028. if (oldValue !== internalObject) {
  16029. // we are transitioning from something which was not an object into object.
  16030. oldValue = internalObject = {};
  16031. oldLength = 0;
  16032. changeDetected++;
  16033. }
  16034. // copy the items to oldValue and look for changes.
  16035. newLength = 0;
  16036. for (key in newValue) {
  16037. if (hasOwnProperty.call(newValue, key)) {
  16038. newLength++;
  16039. newItem = newValue[key];
  16040. oldItem = oldValue[key];
  16041. if (key in oldValue) {
  16042. // eslint-disable-next-line no-self-compare
  16043. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  16044. if (!bothNaN && (oldItem !== newItem)) {
  16045. changeDetected++;
  16046. oldValue[key] = newItem;
  16047. }
  16048. } else {
  16049. oldLength++;
  16050. oldValue[key] = newItem;
  16051. changeDetected++;
  16052. }
  16053. }
  16054. }
  16055. if (oldLength > newLength) {
  16056. // we used to have more keys, need to find them and destroy them.
  16057. changeDetected++;
  16058. for (key in oldValue) {
  16059. if (!hasOwnProperty.call(newValue, key)) {
  16060. oldLength--;
  16061. delete oldValue[key];
  16062. }
  16063. }
  16064. }
  16065. }
  16066. return changeDetected;
  16067. }
  16068. function $watchCollectionAction() {
  16069. if (initRun) {
  16070. initRun = false;
  16071. listener(newValue, newValue, self);
  16072. } else {
  16073. listener(newValue, veryOldValue, self);
  16074. }
  16075. // make a copy for the next time a collection is changed
  16076. if (trackVeryOldValue) {
  16077. if (!isObject(newValue)) {
  16078. //primitive
  16079. veryOldValue = newValue;
  16080. } else if (isArrayLike(newValue)) {
  16081. veryOldValue = new Array(newValue.length);
  16082. for (var i = 0; i < newValue.length; i++) {
  16083. veryOldValue[i] = newValue[i];
  16084. }
  16085. } else { // if object
  16086. veryOldValue = {};
  16087. for (var key in newValue) {
  16088. if (hasOwnProperty.call(newValue, key)) {
  16089. veryOldValue[key] = newValue[key];
  16090. }
  16091. }
  16092. }
  16093. }
  16094. }
  16095. return this.$watch(changeDetector, $watchCollectionAction);
  16096. },
  16097. /**
  16098. * @ngdoc method
  16099. * @name $rootScope.Scope#$digest
  16100. * @kind function
  16101. *
  16102. * @description
  16103. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  16104. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  16105. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  16106. * until no more listeners are firing. This means that it is possible to get into an infinite
  16107. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  16108. * iterations exceeds 10.
  16109. *
  16110. * Usually, you don't call `$digest()` directly in
  16111. * {@link ng.directive:ngController controllers} or in
  16112. * {@link ng.$compileProvider#directive directives}.
  16113. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  16114. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  16115. *
  16116. * If you want to be notified whenever `$digest()` is called,
  16117. * you can register a `watchExpression` function with
  16118. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  16119. *
  16120. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  16121. *
  16122. * # Example
  16123. * ```js
  16124. var scope = ...;
  16125. scope.name = 'misko';
  16126. scope.counter = 0;
  16127. expect(scope.counter).toEqual(0);
  16128. scope.$watch('name', function(newValue, oldValue) {
  16129. scope.counter = scope.counter + 1;
  16130. });
  16131. expect(scope.counter).toEqual(0);
  16132. scope.$digest();
  16133. // the listener is always called during the first $digest loop after it was registered
  16134. expect(scope.counter).toEqual(1);
  16135. scope.$digest();
  16136. // but now it will not be called unless the value changes
  16137. expect(scope.counter).toEqual(1);
  16138. scope.name = 'adam';
  16139. scope.$digest();
  16140. expect(scope.counter).toEqual(2);
  16141. * ```
  16142. *
  16143. */
  16144. $digest: function() {
  16145. var watch, value, last, fn, get,
  16146. watchers,
  16147. length,
  16148. dirty, ttl = TTL,
  16149. next, current, target = this,
  16150. watchLog = [],
  16151. logIdx, asyncTask;
  16152. beginPhase('$digest');
  16153. // Check for changes to browser url that happened in sync before the call to $digest
  16154. $browser.$$checkUrlChange();
  16155. if (this === $rootScope && applyAsyncId !== null) {
  16156. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  16157. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  16158. $browser.defer.cancel(applyAsyncId);
  16159. flushApplyAsync();
  16160. }
  16161. lastDirtyWatch = null;
  16162. do { // "while dirty" loop
  16163. dirty = false;
  16164. current = target;
  16165. // It's safe for asyncQueuePosition to be a local variable here because this loop can't
  16166. // be reentered recursively. Calling $digest from a function passed to $applyAsync would
  16167. // lead to a '$digest already in progress' error.
  16168. for (var asyncQueuePosition = 0; asyncQueuePosition < asyncQueue.length; asyncQueuePosition++) {
  16169. try {
  16170. asyncTask = asyncQueue[asyncQueuePosition];
  16171. asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
  16172. } catch (e) {
  16173. $exceptionHandler(e);
  16174. }
  16175. lastDirtyWatch = null;
  16176. }
  16177. asyncQueue.length = 0;
  16178. traverseScopesLoop:
  16179. do { // "traverse the scopes" loop
  16180. if ((watchers = current.$$watchers)) {
  16181. // process our watches
  16182. length = watchers.length;
  16183. while (length--) {
  16184. try {
  16185. watch = watchers[length];
  16186. // Most common watches are on primitives, in which case we can short
  16187. // circuit it with === operator, only when === fails do we use .equals
  16188. if (watch) {
  16189. get = watch.get;
  16190. if ((value = get(current)) !== (last = watch.last) &&
  16191. !(watch.eq
  16192. ? equals(value, last)
  16193. : (isNumberNaN(value) && isNumberNaN(last)))) {
  16194. dirty = true;
  16195. lastDirtyWatch = watch;
  16196. watch.last = watch.eq ? copy(value, null) : value;
  16197. fn = watch.fn;
  16198. fn(value, ((last === initWatchVal) ? value : last), current);
  16199. if (ttl < 5) {
  16200. logIdx = 4 - ttl;
  16201. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  16202. watchLog[logIdx].push({
  16203. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  16204. newVal: value,
  16205. oldVal: last
  16206. });
  16207. }
  16208. } else if (watch === lastDirtyWatch) {
  16209. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  16210. // have already been tested.
  16211. dirty = false;
  16212. break traverseScopesLoop;
  16213. }
  16214. }
  16215. } catch (e) {
  16216. $exceptionHandler(e);
  16217. }
  16218. }
  16219. }
  16220. // Insanity Warning: scope depth-first traversal
  16221. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  16222. // this piece should be kept in sync with the traversal in $broadcast
  16223. if (!(next = ((current.$$watchersCount && current.$$childHead) ||
  16224. (current !== target && current.$$nextSibling)))) {
  16225. while (current !== target && !(next = current.$$nextSibling)) {
  16226. current = current.$parent;
  16227. }
  16228. }
  16229. } while ((current = next));
  16230. // `break traverseScopesLoop;` takes us to here
  16231. if ((dirty || asyncQueue.length) && !(ttl--)) {
  16232. clearPhase();
  16233. throw $rootScopeMinErr('infdig',
  16234. '{0} $digest() iterations reached. Aborting!\n' +
  16235. 'Watchers fired in the last 5 iterations: {1}',
  16236. TTL, watchLog);
  16237. }
  16238. } while (dirty || asyncQueue.length);
  16239. clearPhase();
  16240. // postDigestQueuePosition isn't local here because this loop can be reentered recursively.
  16241. while (postDigestQueuePosition < postDigestQueue.length) {
  16242. try {
  16243. postDigestQueue[postDigestQueuePosition++]();
  16244. } catch (e) {
  16245. $exceptionHandler(e);
  16246. }
  16247. }
  16248. postDigestQueue.length = postDigestQueuePosition = 0;
  16249. },
  16250. /**
  16251. * @ngdoc event
  16252. * @name $rootScope.Scope#$destroy
  16253. * @eventType broadcast on scope being destroyed
  16254. *
  16255. * @description
  16256. * Broadcasted when a scope and its children are being destroyed.
  16257. *
  16258. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  16259. * clean up DOM bindings before an element is removed from the DOM.
  16260. */
  16261. /**
  16262. * @ngdoc method
  16263. * @name $rootScope.Scope#$destroy
  16264. * @kind function
  16265. *
  16266. * @description
  16267. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  16268. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  16269. * propagate to the current scope and its children. Removal also implies that the current
  16270. * scope is eligible for garbage collection.
  16271. *
  16272. * The `$destroy()` is usually used by directives such as
  16273. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  16274. * unrolling of the loop.
  16275. *
  16276. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  16277. * Application code can register a `$destroy` event handler that will give it a chance to
  16278. * perform any necessary cleanup.
  16279. *
  16280. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  16281. * clean up DOM bindings before an element is removed from the DOM.
  16282. */
  16283. $destroy: function() {
  16284. // We can't destroy a scope that has been already destroyed.
  16285. if (this.$$destroyed) return;
  16286. var parent = this.$parent;
  16287. this.$broadcast('$destroy');
  16288. this.$$destroyed = true;
  16289. if (this === $rootScope) {
  16290. //Remove handlers attached to window when $rootScope is removed
  16291. $browser.$$applicationDestroyed();
  16292. }
  16293. incrementWatchersCount(this, -this.$$watchersCount);
  16294. for (var eventName in this.$$listenerCount) {
  16295. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  16296. }
  16297. // sever all the references to parent scopes (after this cleanup, the current scope should
  16298. // not be retained by any of our references and should be eligible for garbage collection)
  16299. if (parent && parent.$$childHead === this) parent.$$childHead = this.$$nextSibling;
  16300. if (parent && parent.$$childTail === this) parent.$$childTail = this.$$prevSibling;
  16301. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  16302. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  16303. // Disable listeners, watchers and apply/digest methods
  16304. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  16305. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  16306. this.$$listeners = {};
  16307. // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
  16308. this.$$nextSibling = null;
  16309. cleanUpScope(this);
  16310. },
  16311. /**
  16312. * @ngdoc method
  16313. * @name $rootScope.Scope#$eval
  16314. * @kind function
  16315. *
  16316. * @description
  16317. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  16318. * the expression are propagated (uncaught). This is useful when evaluating Angular
  16319. * expressions.
  16320. *
  16321. * # Example
  16322. * ```js
  16323. var scope = ng.$rootScope.Scope();
  16324. scope.a = 1;
  16325. scope.b = 2;
  16326. expect(scope.$eval('a+b')).toEqual(3);
  16327. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  16328. * ```
  16329. *
  16330. * @param {(string|function())=} expression An angular expression to be executed.
  16331. *
  16332. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16333. * - `function(scope)`: execute the function with the current `scope` parameter.
  16334. *
  16335. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  16336. * @returns {*} The result of evaluating the expression.
  16337. */
  16338. $eval: function(expr, locals) {
  16339. return $parse(expr)(this, locals);
  16340. },
  16341. /**
  16342. * @ngdoc method
  16343. * @name $rootScope.Scope#$evalAsync
  16344. * @kind function
  16345. *
  16346. * @description
  16347. * Executes the expression on the current scope at a later point in time.
  16348. *
  16349. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  16350. * that:
  16351. *
  16352. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  16353. * rendering).
  16354. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  16355. * `expression` execution.
  16356. *
  16357. * Any exceptions from the execution of the expression are forwarded to the
  16358. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16359. *
  16360. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  16361. * will be scheduled. However, it is encouraged to always call code that changes the model
  16362. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  16363. *
  16364. * @param {(string|function())=} expression An angular expression to be executed.
  16365. *
  16366. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16367. * - `function(scope)`: execute the function with the current `scope` parameter.
  16368. *
  16369. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  16370. */
  16371. $evalAsync: function(expr, locals) {
  16372. // if we are outside of an $digest loop and this is the first time we are scheduling async
  16373. // task also schedule async auto-flush
  16374. if (!$rootScope.$$phase && !asyncQueue.length) {
  16375. $browser.defer(function() {
  16376. if (asyncQueue.length) {
  16377. $rootScope.$digest();
  16378. }
  16379. });
  16380. }
  16381. asyncQueue.push({scope: this, expression: $parse(expr), locals: locals});
  16382. },
  16383. $$postDigest: function(fn) {
  16384. postDigestQueue.push(fn);
  16385. },
  16386. /**
  16387. * @ngdoc method
  16388. * @name $rootScope.Scope#$apply
  16389. * @kind function
  16390. *
  16391. * @description
  16392. * `$apply()` is used to execute an expression in angular from outside of the angular
  16393. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  16394. * Because we are calling into the angular framework we need to perform proper scope life
  16395. * cycle of {@link ng.$exceptionHandler exception handling},
  16396. * {@link ng.$rootScope.Scope#$digest executing watches}.
  16397. *
  16398. * ## Life cycle
  16399. *
  16400. * # Pseudo-Code of `$apply()`
  16401. * ```js
  16402. function $apply(expr) {
  16403. try {
  16404. return $eval(expr);
  16405. } catch (e) {
  16406. $exceptionHandler(e);
  16407. } finally {
  16408. $root.$digest();
  16409. }
  16410. }
  16411. * ```
  16412. *
  16413. *
  16414. * Scope's `$apply()` method transitions through the following stages:
  16415. *
  16416. * 1. The {@link guide/expression expression} is executed using the
  16417. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  16418. * 2. Any exceptions from the execution of the expression are forwarded to the
  16419. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16420. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  16421. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  16422. *
  16423. *
  16424. * @param {(string|function())=} exp An angular expression to be executed.
  16425. *
  16426. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16427. * - `function(scope)`: execute the function with current `scope` parameter.
  16428. *
  16429. * @returns {*} The result of evaluating the expression.
  16430. */
  16431. $apply: function(expr) {
  16432. try {
  16433. beginPhase('$apply');
  16434. try {
  16435. return this.$eval(expr);
  16436. } finally {
  16437. clearPhase();
  16438. }
  16439. } catch (e) {
  16440. $exceptionHandler(e);
  16441. } finally {
  16442. try {
  16443. $rootScope.$digest();
  16444. } catch (e) {
  16445. $exceptionHandler(e);
  16446. // eslint-disable-next-line no-unsafe-finally
  16447. throw e;
  16448. }
  16449. }
  16450. },
  16451. /**
  16452. * @ngdoc method
  16453. * @name $rootScope.Scope#$applyAsync
  16454. * @kind function
  16455. *
  16456. * @description
  16457. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  16458. * varies across browsers, but is typically around ~10 milliseconds.
  16459. *
  16460. * This can be used to queue up multiple expressions which need to be evaluated in the same
  16461. * digest.
  16462. *
  16463. * @param {(string|function())=} exp An angular expression to be executed.
  16464. *
  16465. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16466. * - `function(scope)`: execute the function with current `scope` parameter.
  16467. */
  16468. $applyAsync: function(expr) {
  16469. var scope = this;
  16470. if (expr) {
  16471. applyAsyncQueue.push($applyAsyncExpression);
  16472. }
  16473. expr = $parse(expr);
  16474. scheduleApplyAsync();
  16475. function $applyAsyncExpression() {
  16476. scope.$eval(expr);
  16477. }
  16478. },
  16479. /**
  16480. * @ngdoc method
  16481. * @name $rootScope.Scope#$on
  16482. * @kind function
  16483. *
  16484. * @description
  16485. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  16486. * discussion of event life cycle.
  16487. *
  16488. * The event listener function format is: `function(event, args...)`. The `event` object
  16489. * passed into the listener has the following attributes:
  16490. *
  16491. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  16492. * `$broadcast`-ed.
  16493. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  16494. * event propagates through the scope hierarchy, this property is set to null.
  16495. * - `name` - `{string}`: name of the event.
  16496. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  16497. * further event propagation (available only for events that were `$emit`-ed).
  16498. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  16499. * to true.
  16500. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  16501. *
  16502. * @param {string} name Event name to listen on.
  16503. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  16504. * @returns {function()} Returns a deregistration function for this listener.
  16505. */
  16506. $on: function(name, listener) {
  16507. var namedListeners = this.$$listeners[name];
  16508. if (!namedListeners) {
  16509. this.$$listeners[name] = namedListeners = [];
  16510. }
  16511. namedListeners.push(listener);
  16512. var current = this;
  16513. do {
  16514. if (!current.$$listenerCount[name]) {
  16515. current.$$listenerCount[name] = 0;
  16516. }
  16517. current.$$listenerCount[name]++;
  16518. } while ((current = current.$parent));
  16519. var self = this;
  16520. return function() {
  16521. var indexOfListener = namedListeners.indexOf(listener);
  16522. if (indexOfListener !== -1) {
  16523. namedListeners[indexOfListener] = null;
  16524. decrementListenerCount(self, 1, name);
  16525. }
  16526. };
  16527. },
  16528. /**
  16529. * @ngdoc method
  16530. * @name $rootScope.Scope#$emit
  16531. * @kind function
  16532. *
  16533. * @description
  16534. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  16535. * registered {@link ng.$rootScope.Scope#$on} listeners.
  16536. *
  16537. * The event life cycle starts at the scope on which `$emit` was called. All
  16538. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  16539. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  16540. * registered listeners along the way. The event will stop propagating if one of the listeners
  16541. * cancels it.
  16542. *
  16543. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  16544. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  16545. *
  16546. * @param {string} name Event name to emit.
  16547. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  16548. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  16549. */
  16550. $emit: function(name, args) {
  16551. var empty = [],
  16552. namedListeners,
  16553. scope = this,
  16554. stopPropagation = false,
  16555. event = {
  16556. name: name,
  16557. targetScope: scope,
  16558. stopPropagation: function() {stopPropagation = true;},
  16559. preventDefault: function() {
  16560. event.defaultPrevented = true;
  16561. },
  16562. defaultPrevented: false
  16563. },
  16564. listenerArgs = concat([event], arguments, 1),
  16565. i, length;
  16566. do {
  16567. namedListeners = scope.$$listeners[name] || empty;
  16568. event.currentScope = scope;
  16569. for (i = 0, length = namedListeners.length; i < length; i++) {
  16570. // if listeners were deregistered, defragment the array
  16571. if (!namedListeners[i]) {
  16572. namedListeners.splice(i, 1);
  16573. i--;
  16574. length--;
  16575. continue;
  16576. }
  16577. try {
  16578. //allow all listeners attached to the current scope to run
  16579. namedListeners[i].apply(null, listenerArgs);
  16580. } catch (e) {
  16581. $exceptionHandler(e);
  16582. }
  16583. }
  16584. //if any listener on the current scope stops propagation, prevent bubbling
  16585. if (stopPropagation) {
  16586. event.currentScope = null;
  16587. return event;
  16588. }
  16589. //traverse upwards
  16590. scope = scope.$parent;
  16591. } while (scope);
  16592. event.currentScope = null;
  16593. return event;
  16594. },
  16595. /**
  16596. * @ngdoc method
  16597. * @name $rootScope.Scope#$broadcast
  16598. * @kind function
  16599. *
  16600. * @description
  16601. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  16602. * registered {@link ng.$rootScope.Scope#$on} listeners.
  16603. *
  16604. * The event life cycle starts at the scope on which `$broadcast` was called. All
  16605. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  16606. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  16607. * scope and calls all registered listeners along the way. The event cannot be canceled.
  16608. *
  16609. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  16610. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  16611. *
  16612. * @param {string} name Event name to broadcast.
  16613. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  16614. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  16615. */
  16616. $broadcast: function(name, args) {
  16617. var target = this,
  16618. current = target,
  16619. next = target,
  16620. event = {
  16621. name: name,
  16622. targetScope: target,
  16623. preventDefault: function() {
  16624. event.defaultPrevented = true;
  16625. },
  16626. defaultPrevented: false
  16627. };
  16628. if (!target.$$listenerCount[name]) return event;
  16629. var listenerArgs = concat([event], arguments, 1),
  16630. listeners, i, length;
  16631. //down while you can, then up and next sibling or up and next sibling until back at root
  16632. while ((current = next)) {
  16633. event.currentScope = current;
  16634. listeners = current.$$listeners[name] || [];
  16635. for (i = 0, length = listeners.length; i < length; i++) {
  16636. // if listeners were deregistered, defragment the array
  16637. if (!listeners[i]) {
  16638. listeners.splice(i, 1);
  16639. i--;
  16640. length--;
  16641. continue;
  16642. }
  16643. try {
  16644. listeners[i].apply(null, listenerArgs);
  16645. } catch (e) {
  16646. $exceptionHandler(e);
  16647. }
  16648. }
  16649. // Insanity Warning: scope depth-first traversal
  16650. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  16651. // this piece should be kept in sync with the traversal in $digest
  16652. // (though it differs due to having the extra check for $$listenerCount)
  16653. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  16654. (current !== target && current.$$nextSibling)))) {
  16655. while (current !== target && !(next = current.$$nextSibling)) {
  16656. current = current.$parent;
  16657. }
  16658. }
  16659. }
  16660. event.currentScope = null;
  16661. return event;
  16662. }
  16663. };
  16664. var $rootScope = new Scope();
  16665. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  16666. var asyncQueue = $rootScope.$$asyncQueue = [];
  16667. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  16668. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  16669. var postDigestQueuePosition = 0;
  16670. return $rootScope;
  16671. function beginPhase(phase) {
  16672. if ($rootScope.$$phase) {
  16673. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  16674. }
  16675. $rootScope.$$phase = phase;
  16676. }
  16677. function clearPhase() {
  16678. $rootScope.$$phase = null;
  16679. }
  16680. function incrementWatchersCount(current, count) {
  16681. do {
  16682. current.$$watchersCount += count;
  16683. } while ((current = current.$parent));
  16684. }
  16685. function decrementListenerCount(current, count, name) {
  16686. do {
  16687. current.$$listenerCount[name] -= count;
  16688. if (current.$$listenerCount[name] === 0) {
  16689. delete current.$$listenerCount[name];
  16690. }
  16691. } while ((current = current.$parent));
  16692. }
  16693. /**
  16694. * function used as an initial value for watchers.
  16695. * because it's unique we can easily tell it apart from other values
  16696. */
  16697. function initWatchVal() {}
  16698. function flushApplyAsync() {
  16699. while (applyAsyncQueue.length) {
  16700. try {
  16701. applyAsyncQueue.shift()();
  16702. } catch (e) {
  16703. $exceptionHandler(e);
  16704. }
  16705. }
  16706. applyAsyncId = null;
  16707. }
  16708. function scheduleApplyAsync() {
  16709. if (applyAsyncId === null) {
  16710. applyAsyncId = $browser.defer(function() {
  16711. $rootScope.$apply(flushApplyAsync);
  16712. });
  16713. }
  16714. }
  16715. }];
  16716. }
  16717. /**
  16718. * @ngdoc service
  16719. * @name $rootElement
  16720. *
  16721. * @description
  16722. * The root element of Angular application. This is either the element where {@link
  16723. * ng.directive:ngApp ngApp} was declared or the element passed into
  16724. * {@link angular.bootstrap}. The element represents the root element of application. It is also the
  16725. * location where the application's {@link auto.$injector $injector} service gets
  16726. * published, and can be retrieved using `$rootElement.injector()`.
  16727. */
  16728. // the implementation is in angular.bootstrap
  16729. /**
  16730. * @this
  16731. * @description
  16732. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  16733. */
  16734. function $$SanitizeUriProvider() {
  16735. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  16736. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  16737. /**
  16738. * @description
  16739. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  16740. * urls during a[href] sanitization.
  16741. *
  16742. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  16743. *
  16744. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  16745. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  16746. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  16747. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  16748. *
  16749. * @param {RegExp=} regexp New regexp to whitelist urls with.
  16750. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  16751. * chaining otherwise.
  16752. */
  16753. this.aHrefSanitizationWhitelist = function(regexp) {
  16754. if (isDefined(regexp)) {
  16755. aHrefSanitizationWhitelist = regexp;
  16756. return this;
  16757. }
  16758. return aHrefSanitizationWhitelist;
  16759. };
  16760. /**
  16761. * @description
  16762. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  16763. * urls during img[src] sanitization.
  16764. *
  16765. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  16766. *
  16767. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  16768. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  16769. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  16770. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  16771. *
  16772. * @param {RegExp=} regexp New regexp to whitelist urls with.
  16773. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  16774. * chaining otherwise.
  16775. */
  16776. this.imgSrcSanitizationWhitelist = function(regexp) {
  16777. if (isDefined(regexp)) {
  16778. imgSrcSanitizationWhitelist = regexp;
  16779. return this;
  16780. }
  16781. return imgSrcSanitizationWhitelist;
  16782. };
  16783. this.$get = function() {
  16784. return function sanitizeUri(uri, isImage) {
  16785. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  16786. var normalizedVal;
  16787. normalizedVal = urlResolve(uri).href;
  16788. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  16789. return 'unsafe:' + normalizedVal;
  16790. }
  16791. return uri;
  16792. };
  16793. };
  16794. }
  16795. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  16796. * Any commits to this file should be reviewed with security in mind. *
  16797. * Changes to this file can potentially create security vulnerabilities. *
  16798. * An approval from 2 Core members with history of modifying *
  16799. * this file is required. *
  16800. * *
  16801. * Does the change somehow allow for arbitrary javascript to be executed? *
  16802. * Or allows for someone to change the prototype of built-in objects? *
  16803. * Or gives undesired access to variables likes document or window? *
  16804. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  16805. /* exported $SceProvider, $SceDelegateProvider */
  16806. var $sceMinErr = minErr('$sce');
  16807. var SCE_CONTEXTS = {
  16808. HTML: 'html',
  16809. CSS: 'css',
  16810. URL: 'url',
  16811. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  16812. // url. (e.g. ng-include, script src, templateUrl)
  16813. RESOURCE_URL: 'resourceUrl',
  16814. JS: 'js'
  16815. };
  16816. // Helper functions follow.
  16817. function adjustMatcher(matcher) {
  16818. if (matcher === 'self') {
  16819. return matcher;
  16820. } else if (isString(matcher)) {
  16821. // Strings match exactly except for 2 wildcards - '*' and '**'.
  16822. // '*' matches any character except those from the set ':/.?&'.
  16823. // '**' matches any character (like .* in a RegExp).
  16824. // More than 2 *'s raises an error as it's ill defined.
  16825. if (matcher.indexOf('***') > -1) {
  16826. throw $sceMinErr('iwcard',
  16827. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  16828. }
  16829. matcher = escapeForRegexp(matcher).
  16830. replace('\\*\\*', '.*').
  16831. replace('\\*', '[^:/.?&;]*');
  16832. return new RegExp('^' + matcher + '$');
  16833. } else if (isRegExp(matcher)) {
  16834. // The only other type of matcher allowed is a Regexp.
  16835. // Match entire URL / disallow partial matches.
  16836. // Flags are reset (i.e. no global, ignoreCase or multiline)
  16837. return new RegExp('^' + matcher.source + '$');
  16838. } else {
  16839. throw $sceMinErr('imatcher',
  16840. 'Matchers may only be "self", string patterns or RegExp objects');
  16841. }
  16842. }
  16843. function adjustMatchers(matchers) {
  16844. var adjustedMatchers = [];
  16845. if (isDefined(matchers)) {
  16846. forEach(matchers, function(matcher) {
  16847. adjustedMatchers.push(adjustMatcher(matcher));
  16848. });
  16849. }
  16850. return adjustedMatchers;
  16851. }
  16852. /**
  16853. * @ngdoc service
  16854. * @name $sceDelegate
  16855. * @kind function
  16856. *
  16857. * @description
  16858. *
  16859. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  16860. * Contextual Escaping (SCE)} services to AngularJS.
  16861. *
  16862. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  16863. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  16864. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  16865. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  16866. * work because `$sce` delegates to `$sceDelegate` for these operations.
  16867. *
  16868. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  16869. *
  16870. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  16871. * can override it completely to change the behavior of `$sce`, the common case would
  16872. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  16873. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  16874. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  16875. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  16876. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  16877. */
  16878. /**
  16879. * @ngdoc provider
  16880. * @name $sceDelegateProvider
  16881. * @this
  16882. *
  16883. * @description
  16884. *
  16885. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  16886. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  16887. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  16888. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  16889. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  16890. *
  16891. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  16892. * Strict Contextual Escaping (SCE)}.
  16893. *
  16894. * **Example**: Consider the following case. <a name="example"></a>
  16895. *
  16896. * - your app is hosted at url `http://myapp.example.com/`
  16897. * - but some of your templates are hosted on other domains you control such as
  16898. * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
  16899. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  16900. *
  16901. * Here is what a secure configuration for this scenario might look like:
  16902. *
  16903. * ```
  16904. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  16905. * $sceDelegateProvider.resourceUrlWhitelist([
  16906. * // Allow same origin resource loads.
  16907. * 'self',
  16908. * // Allow loading from our assets domain. Notice the difference between * and **.
  16909. * 'http://srv*.assets.example.com/**'
  16910. * ]);
  16911. *
  16912. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  16913. * $sceDelegateProvider.resourceUrlBlacklist([
  16914. * 'http://myapp.example.com/clickThru**'
  16915. * ]);
  16916. * });
  16917. * ```
  16918. */
  16919. function $SceDelegateProvider() {
  16920. this.SCE_CONTEXTS = SCE_CONTEXTS;
  16921. // Resource URLs can also be trusted by policy.
  16922. var resourceUrlWhitelist = ['self'],
  16923. resourceUrlBlacklist = [];
  16924. /**
  16925. * @ngdoc method
  16926. * @name $sceDelegateProvider#resourceUrlWhitelist
  16927. * @kind function
  16928. *
  16929. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  16930. * provided. This must be an array or null. A snapshot of this array is used so further
  16931. * changes to the array are ignored.
  16932. *
  16933. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  16934. * allowed in this array.
  16935. *
  16936. * <div class="alert alert-warning">
  16937. * **Note:** an empty whitelist array will block all URLs!
  16938. * </div>
  16939. *
  16940. * @return {Array} the currently set whitelist array.
  16941. *
  16942. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  16943. * same origin resource requests.
  16944. *
  16945. * @description
  16946. * Sets/Gets the whitelist of trusted resource URLs.
  16947. */
  16948. this.resourceUrlWhitelist = function(value) {
  16949. if (arguments.length) {
  16950. resourceUrlWhitelist = adjustMatchers(value);
  16951. }
  16952. return resourceUrlWhitelist;
  16953. };
  16954. /**
  16955. * @ngdoc method
  16956. * @name $sceDelegateProvider#resourceUrlBlacklist
  16957. * @kind function
  16958. *
  16959. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  16960. * provided. This must be an array or null. A snapshot of this array is used so further
  16961. * changes to the array are ignored.
  16962. *
  16963. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  16964. * allowed in this array.
  16965. *
  16966. * The typical usage for the blacklist is to **block
  16967. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  16968. * these would otherwise be trusted but actually return content from the redirected domain.
  16969. *
  16970. * Finally, **the blacklist overrides the whitelist** and has the final say.
  16971. *
  16972. * @return {Array} the currently set blacklist array.
  16973. *
  16974. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  16975. * is no blacklist.)
  16976. *
  16977. * @description
  16978. * Sets/Gets the blacklist of trusted resource URLs.
  16979. */
  16980. this.resourceUrlBlacklist = function(value) {
  16981. if (arguments.length) {
  16982. resourceUrlBlacklist = adjustMatchers(value);
  16983. }
  16984. return resourceUrlBlacklist;
  16985. };
  16986. this.$get = ['$injector', function($injector) {
  16987. var htmlSanitizer = function htmlSanitizer(html) {
  16988. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  16989. };
  16990. if ($injector.has('$sanitize')) {
  16991. htmlSanitizer = $injector.get('$sanitize');
  16992. }
  16993. function matchUrl(matcher, parsedUrl) {
  16994. if (matcher === 'self') {
  16995. return urlIsSameOrigin(parsedUrl);
  16996. } else {
  16997. // definitely a regex. See adjustMatchers()
  16998. return !!matcher.exec(parsedUrl.href);
  16999. }
  17000. }
  17001. function isResourceUrlAllowedByPolicy(url) {
  17002. var parsedUrl = urlResolve(url.toString());
  17003. var i, n, allowed = false;
  17004. // Ensure that at least one item from the whitelist allows this url.
  17005. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  17006. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  17007. allowed = true;
  17008. break;
  17009. }
  17010. }
  17011. if (allowed) {
  17012. // Ensure that no item from the blacklist blocked this url.
  17013. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  17014. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  17015. allowed = false;
  17016. break;
  17017. }
  17018. }
  17019. }
  17020. return allowed;
  17021. }
  17022. function generateHolderType(Base) {
  17023. var holderType = function TrustedValueHolderType(trustedValue) {
  17024. this.$$unwrapTrustedValue = function() {
  17025. return trustedValue;
  17026. };
  17027. };
  17028. if (Base) {
  17029. holderType.prototype = new Base();
  17030. }
  17031. holderType.prototype.valueOf = function sceValueOf() {
  17032. return this.$$unwrapTrustedValue();
  17033. };
  17034. holderType.prototype.toString = function sceToString() {
  17035. return this.$$unwrapTrustedValue().toString();
  17036. };
  17037. return holderType;
  17038. }
  17039. var trustedValueHolderBase = generateHolderType(),
  17040. byType = {};
  17041. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  17042. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  17043. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  17044. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  17045. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  17046. /**
  17047. * @ngdoc method
  17048. * @name $sceDelegate#trustAs
  17049. *
  17050. * @description
  17051. * Returns an object that is trusted by angular for use in specified strict
  17052. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  17053. * attribute interpolation, any dom event binding attribute interpolation
  17054. * such as for onclick, etc.) that uses the provided value.
  17055. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  17056. *
  17057. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  17058. * resourceUrl, html, js and css.
  17059. * @param {*} value The value that that should be considered trusted/safe.
  17060. * @returns {*} A value that can be used to stand in for the provided `value` in places
  17061. * where Angular expects a $sce.trustAs() return value.
  17062. */
  17063. function trustAs(type, trustedValue) {
  17064. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  17065. if (!Constructor) {
  17066. throw $sceMinErr('icontext',
  17067. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  17068. type, trustedValue);
  17069. }
  17070. if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
  17071. return trustedValue;
  17072. }
  17073. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  17074. // mutable objects, we ensure here that the value passed in is actually a string.
  17075. if (typeof trustedValue !== 'string') {
  17076. throw $sceMinErr('itype',
  17077. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  17078. type);
  17079. }
  17080. return new Constructor(trustedValue);
  17081. }
  17082. /**
  17083. * @ngdoc method
  17084. * @name $sceDelegate#valueOf
  17085. *
  17086. * @description
  17087. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  17088. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  17089. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  17090. *
  17091. * If the passed parameter is not a value that had been returned by {@link
  17092. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  17093. *
  17094. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  17095. * call or anything else.
  17096. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  17097. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  17098. * `value` unchanged.
  17099. */
  17100. function valueOf(maybeTrusted) {
  17101. if (maybeTrusted instanceof trustedValueHolderBase) {
  17102. return maybeTrusted.$$unwrapTrustedValue();
  17103. } else {
  17104. return maybeTrusted;
  17105. }
  17106. }
  17107. /**
  17108. * @ngdoc method
  17109. * @name $sceDelegate#getTrusted
  17110. *
  17111. * @description
  17112. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  17113. * returns the originally supplied value if the queried context type is a supertype of the
  17114. * created type. If this condition isn't satisfied, throws an exception.
  17115. *
  17116. * <div class="alert alert-danger">
  17117. * Disabling auto-escaping is extremely dangerous, it usually creates a Cross Site Scripting
  17118. * (XSS) vulnerability in your application.
  17119. * </div>
  17120. *
  17121. * @param {string} type The kind of context in which this value is to be used.
  17122. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  17123. * `$sceDelegate.trustAs`} call.
  17124. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  17125. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  17126. */
  17127. function getTrusted(type, maybeTrusted) {
  17128. if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
  17129. return maybeTrusted;
  17130. }
  17131. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  17132. if (constructor && maybeTrusted instanceof constructor) {
  17133. return maybeTrusted.$$unwrapTrustedValue();
  17134. }
  17135. // If we get here, then we may only take one of two actions.
  17136. // 1. sanitize the value for the requested type, or
  17137. // 2. throw an exception.
  17138. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  17139. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  17140. return maybeTrusted;
  17141. } else {
  17142. throw $sceMinErr('insecurl',
  17143. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  17144. maybeTrusted.toString());
  17145. }
  17146. } else if (type === SCE_CONTEXTS.HTML) {
  17147. return htmlSanitizer(maybeTrusted);
  17148. }
  17149. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  17150. }
  17151. return { trustAs: trustAs,
  17152. getTrusted: getTrusted,
  17153. valueOf: valueOf };
  17154. }];
  17155. }
  17156. /**
  17157. * @ngdoc provider
  17158. * @name $sceProvider
  17159. * @this
  17160. *
  17161. * @description
  17162. *
  17163. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  17164. * - enable/disable Strict Contextual Escaping (SCE) in a module
  17165. * - override the default implementation with a custom delegate
  17166. *
  17167. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  17168. */
  17169. /**
  17170. * @ngdoc service
  17171. * @name $sce
  17172. * @kind function
  17173. *
  17174. * @description
  17175. *
  17176. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  17177. *
  17178. * # Strict Contextual Escaping
  17179. *
  17180. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  17181. * contexts to result in a value that is marked as safe to use for that context. One example of
  17182. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  17183. * to these contexts as privileged or SCE contexts.
  17184. *
  17185. * As of version 1.2, Angular ships with SCE enabled by default.
  17186. *
  17187. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  17188. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  17189. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  17190. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  17191. * to the top of your HTML document.
  17192. *
  17193. * SCE assists in writing code in a way that (a) is secure by default and (b) makes auditing for
  17194. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  17195. *
  17196. * Here's an example of a binding in a privileged context:
  17197. *
  17198. * ```
  17199. * <input ng-model="userHtml" aria-label="User input">
  17200. * <div ng-bind-html="userHtml"></div>
  17201. * ```
  17202. *
  17203. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  17204. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  17205. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  17206. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  17207. * security vulnerabilities.)
  17208. *
  17209. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  17210. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  17211. *
  17212. * How would you ensure that every place that used these types of bindings was bound to a value that
  17213. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  17214. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  17215. * properties/fields and forgot to update the binding to the sanitized value?
  17216. *
  17217. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  17218. * determine that something explicitly says it's safe to use a value for binding in that
  17219. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  17220. * for those values that you can easily tell are safe - because they were received from your server,
  17221. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  17222. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  17223. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  17224. *
  17225. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  17226. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  17227. * obtain values that will be accepted by SCE / privileged contexts.
  17228. *
  17229. *
  17230. * ## How does it work?
  17231. *
  17232. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  17233. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  17234. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  17235. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  17236. *
  17237. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  17238. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  17239. * simplified):
  17240. *
  17241. * ```
  17242. * var ngBindHtmlDirective = ['$sce', function($sce) {
  17243. * return function(scope, element, attr) {
  17244. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  17245. * element.html(value || '');
  17246. * });
  17247. * };
  17248. * }];
  17249. * ```
  17250. *
  17251. * ## Impact on loading templates
  17252. *
  17253. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  17254. * `templateUrl`'s specified by {@link guide/directive directives}.
  17255. *
  17256. * By default, Angular only loads templates from the same domain and protocol as the application
  17257. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  17258. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  17259. * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  17260. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  17261. *
  17262. * *Please note*:
  17263. * The browser's
  17264. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  17265. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  17266. * policy apply in addition to this and may further restrict whether the template is successfully
  17267. * loaded. This means that without the right CORS policy, loading templates from a different domain
  17268. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  17269. * browsers.
  17270. *
  17271. * ## This feels like too much overhead
  17272. *
  17273. * It's important to remember that SCE only applies to interpolation expressions.
  17274. *
  17275. * If your expressions are constant literals, they're automatically trusted and you don't need to
  17276. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  17277. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  17278. *
  17279. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  17280. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  17281. *
  17282. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  17283. * templates in `ng-include` from your application's domain without having to even know about SCE.
  17284. * It blocks loading templates from other domains or loading templates over http from an https
  17285. * served document. You can change these by setting your own custom {@link
  17286. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  17287. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  17288. *
  17289. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  17290. * application that's secure and can be audited to verify that with much more ease than bolting
  17291. * security onto an application later.
  17292. *
  17293. * <a name="contexts"></a>
  17294. * ## What trusted context types are supported?
  17295. *
  17296. * | Context | Notes |
  17297. * |---------------------|----------------|
  17298. * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. |
  17299. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  17300. * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=` and `<img src=` sanitize their urls and don't constitute an SCE context. |
  17301. * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG`, `VIDEO`, `AUDIO`, `SOURCE`, and `TRACK` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
  17302. * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. |
  17303. *
  17304. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  17305. *
  17306. * Each element in these arrays must be one of the following:
  17307. *
  17308. * - **'self'**
  17309. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  17310. * domain** as the application document using the **same protocol**.
  17311. * - **String** (except the special value `'self'`)
  17312. * - The string is matched against the full *normalized / absolute URL* of the resource
  17313. * being tested (substring matches are not good enough.)
  17314. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  17315. * match themselves.
  17316. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  17317. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
  17318. * in a whitelist.
  17319. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  17320. * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
  17321. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  17322. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  17323. * http://foo.example.com/templates/**).
  17324. * - **RegExp** (*see caveat below*)
  17325. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  17326. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  17327. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  17328. * have good test coverage). For instance, the use of `.` in the regex is correct only in a
  17329. * small number of cases. A `.` character in the regex used when matching the scheme or a
  17330. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  17331. * is highly recommended to use the string patterns and only fall back to regular expressions
  17332. * as a last resort.
  17333. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  17334. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  17335. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  17336. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  17337. * - If you are generating your JavaScript from some other templating engine (not
  17338. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  17339. * remember to escape your regular expression (and be aware that you might need more than
  17340. * one level of escaping depending on your templating engine and the way you interpolated
  17341. * the value.) Do make use of your platform's escaping mechanism as it might be good
  17342. * enough before coding your own. E.g. Ruby has
  17343. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  17344. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  17345. * Javascript lacks a similar built in function for escaping. Take a look at Google
  17346. * Closure library's [goog.string.regExpEscape(s)](
  17347. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  17348. *
  17349. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  17350. *
  17351. * ## Show me an example using SCE.
  17352. *
  17353. * <example module="mySceApp" deps="angular-sanitize.js" name="sce-service">
  17354. * <file name="index.html">
  17355. * <div ng-controller="AppController as myCtrl">
  17356. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  17357. * <b>User comments</b><br>
  17358. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  17359. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  17360. * exploit.
  17361. * <div class="well">
  17362. * <div ng-repeat="userComment in myCtrl.userComments">
  17363. * <b>{{userComment.name}}</b>:
  17364. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  17365. * <br>
  17366. * </div>
  17367. * </div>
  17368. * </div>
  17369. * </file>
  17370. *
  17371. * <file name="script.js">
  17372. * angular.module('mySceApp', ['ngSanitize'])
  17373. * .controller('AppController', ['$http', '$templateCache', '$sce',
  17374. * function AppController($http, $templateCache, $sce) {
  17375. * var self = this;
  17376. * $http.get('test_data.json', {cache: $templateCache}).success(function(userComments) {
  17377. * self.userComments = userComments;
  17378. * });
  17379. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  17380. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  17381. * 'sanitization.&quot;">Hover over this text.</span>');
  17382. * }]);
  17383. * </file>
  17384. *
  17385. * <file name="test_data.json">
  17386. * [
  17387. * { "name": "Alice",
  17388. * "htmlComment":
  17389. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  17390. * },
  17391. * { "name": "Bob",
  17392. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  17393. * }
  17394. * ]
  17395. * </file>
  17396. *
  17397. * <file name="protractor.js" type="protractor">
  17398. * describe('SCE doc demo', function() {
  17399. * it('should sanitize untrusted values', function() {
  17400. * expect(element.all(by.css('.htmlComment')).first().getAttribute('innerHTML'))
  17401. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  17402. * });
  17403. *
  17404. * it('should NOT sanitize explicitly trusted values', function() {
  17405. * expect(element(by.id('explicitlyTrustedHtml')).getAttribute('innerHTML')).toBe(
  17406. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  17407. * 'sanitization.&quot;">Hover over this text.</span>');
  17408. * });
  17409. * });
  17410. * </file>
  17411. * </example>
  17412. *
  17413. *
  17414. *
  17415. * ## Can I disable SCE completely?
  17416. *
  17417. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  17418. * for little coding overhead. It will be much harder to take an SCE disabled application and
  17419. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  17420. * for cases where you have a lot of existing code that was written before SCE was introduced and
  17421. * you're migrating them a module at a time.
  17422. *
  17423. * That said, here's how you can completely disable SCE:
  17424. *
  17425. * ```
  17426. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  17427. * // Completely disable SCE. For demonstration purposes only!
  17428. * // Do not use in new projects.
  17429. * $sceProvider.enabled(false);
  17430. * });
  17431. * ```
  17432. *
  17433. */
  17434. function $SceProvider() {
  17435. var enabled = true;
  17436. /**
  17437. * @ngdoc method
  17438. * @name $sceProvider#enabled
  17439. * @kind function
  17440. *
  17441. * @param {boolean=} value If provided, then enables/disables SCE.
  17442. * @return {boolean} true if SCE is enabled, false otherwise.
  17443. *
  17444. * @description
  17445. * Enables/disables SCE and returns the current value.
  17446. */
  17447. this.enabled = function(value) {
  17448. if (arguments.length) {
  17449. enabled = !!value;
  17450. }
  17451. return enabled;
  17452. };
  17453. /* Design notes on the default implementation for SCE.
  17454. *
  17455. * The API contract for the SCE delegate
  17456. * -------------------------------------
  17457. * The SCE delegate object must provide the following 3 methods:
  17458. *
  17459. * - trustAs(contextEnum, value)
  17460. * This method is used to tell the SCE service that the provided value is OK to use in the
  17461. * contexts specified by contextEnum. It must return an object that will be accepted by
  17462. * getTrusted() for a compatible contextEnum and return this value.
  17463. *
  17464. * - valueOf(value)
  17465. * For values that were not produced by trustAs(), return them as is. For values that were
  17466. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  17467. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  17468. * such a value.
  17469. *
  17470. * - getTrusted(contextEnum, value)
  17471. * This function should return the a value that is safe to use in the context specified by
  17472. * contextEnum or throw and exception otherwise.
  17473. *
  17474. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  17475. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  17476. * instance, an implementation could maintain a registry of all trusted objects by context. In
  17477. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  17478. * return the same object passed in if it was found in the registry under a compatible context or
  17479. * throw an exception otherwise. An implementation might only wrap values some of the time based
  17480. * on some criteria. getTrusted() might return a value and not throw an exception for special
  17481. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  17482. *
  17483. *
  17484. * A note on the inheritance model for SCE contexts
  17485. * ------------------------------------------------
  17486. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  17487. * is purely an implementation details.
  17488. *
  17489. * The contract is simply this:
  17490. *
  17491. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  17492. * will also succeed.
  17493. *
  17494. * Inheritance happens to capture this in a natural way. In some future, we
  17495. * may not use inheritance anymore. That is OK because no code outside of
  17496. * sce.js and sceSpecs.js would need to be aware of this detail.
  17497. */
  17498. this.$get = ['$parse', '$sceDelegate', function(
  17499. $parse, $sceDelegate) {
  17500. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  17501. // the "expression(javascript expression)" syntax which is insecure.
  17502. if (enabled && msie < 8) {
  17503. throw $sceMinErr('iequirks',
  17504. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  17505. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  17506. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  17507. }
  17508. var sce = shallowCopy(SCE_CONTEXTS);
  17509. /**
  17510. * @ngdoc method
  17511. * @name $sce#isEnabled
  17512. * @kind function
  17513. *
  17514. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  17515. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  17516. *
  17517. * @description
  17518. * Returns a boolean indicating if SCE is enabled.
  17519. */
  17520. sce.isEnabled = function() {
  17521. return enabled;
  17522. };
  17523. sce.trustAs = $sceDelegate.trustAs;
  17524. sce.getTrusted = $sceDelegate.getTrusted;
  17525. sce.valueOf = $sceDelegate.valueOf;
  17526. if (!enabled) {
  17527. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  17528. sce.valueOf = identity;
  17529. }
  17530. /**
  17531. * @ngdoc method
  17532. * @name $sce#parseAs
  17533. *
  17534. * @description
  17535. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  17536. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  17537. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  17538. * *result*)}
  17539. *
  17540. * @param {string} type The kind of SCE context in which this result will be used.
  17541. * @param {string} expression String expression to compile.
  17542. * @returns {function(context, locals)} a function which represents the compiled expression:
  17543. *
  17544. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17545. * are evaluated against (typically a scope object).
  17546. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17547. * `context`.
  17548. */
  17549. sce.parseAs = function sceParseAs(type, expr) {
  17550. var parsed = $parse(expr);
  17551. if (parsed.literal && parsed.constant) {
  17552. return parsed;
  17553. } else {
  17554. return $parse(expr, function(value) {
  17555. return sce.getTrusted(type, value);
  17556. });
  17557. }
  17558. };
  17559. /**
  17560. * @ngdoc method
  17561. * @name $sce#trustAs
  17562. *
  17563. * @description
  17564. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  17565. * returns an object that is trusted by angular for use in specified strict contextual
  17566. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  17567. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  17568. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  17569. * escaping.
  17570. *
  17571. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  17572. * resourceUrl, html, js and css.
  17573. * @param {*} value The value that that should be considered trusted/safe.
  17574. * @returns {*} A value that can be used to stand in for the provided `value` in places
  17575. * where Angular expects a $sce.trustAs() return value.
  17576. */
  17577. /**
  17578. * @ngdoc method
  17579. * @name $sce#trustAsHtml
  17580. *
  17581. * @description
  17582. * Shorthand method. `$sce.trustAsHtml(value)` →
  17583. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  17584. *
  17585. * @param {*} value The value to trustAs.
  17586. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  17587. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  17588. * only accept expressions that are either literal constants or are the
  17589. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17590. */
  17591. /**
  17592. * @ngdoc method
  17593. * @name $sce#trustAsUrl
  17594. *
  17595. * @description
  17596. * Shorthand method. `$sce.trustAsUrl(value)` →
  17597. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  17598. *
  17599. * @param {*} value The value to trustAs.
  17600. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  17601. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  17602. * only accept expressions that are either literal constants or are the
  17603. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17604. */
  17605. /**
  17606. * @ngdoc method
  17607. * @name $sce#trustAsResourceUrl
  17608. *
  17609. * @description
  17610. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  17611. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  17612. *
  17613. * @param {*} value The value to trustAs.
  17614. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  17615. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  17616. * only accept expressions that are either literal constants or are the return
  17617. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17618. */
  17619. /**
  17620. * @ngdoc method
  17621. * @name $sce#trustAsJs
  17622. *
  17623. * @description
  17624. * Shorthand method. `$sce.trustAsJs(value)` →
  17625. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  17626. *
  17627. * @param {*} value The value to trustAs.
  17628. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  17629. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  17630. * only accept expressions that are either literal constants or are the
  17631. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17632. */
  17633. /**
  17634. * @ngdoc method
  17635. * @name $sce#getTrusted
  17636. *
  17637. * @description
  17638. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  17639. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  17640. * originally supplied value if the queried context type is a supertype of the created type.
  17641. * If this condition isn't satisfied, throws an exception.
  17642. *
  17643. * @param {string} type The kind of context in which this value is to be used.
  17644. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  17645. * call.
  17646. * @returns {*} The value the was originally provided to
  17647. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  17648. * Otherwise, throws an exception.
  17649. */
  17650. /**
  17651. * @ngdoc method
  17652. * @name $sce#getTrustedHtml
  17653. *
  17654. * @description
  17655. * Shorthand method. `$sce.getTrustedHtml(value)` →
  17656. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  17657. *
  17658. * @param {*} value The value to pass to `$sce.getTrusted`.
  17659. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  17660. */
  17661. /**
  17662. * @ngdoc method
  17663. * @name $sce#getTrustedCss
  17664. *
  17665. * @description
  17666. * Shorthand method. `$sce.getTrustedCss(value)` →
  17667. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  17668. *
  17669. * @param {*} value The value to pass to `$sce.getTrusted`.
  17670. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  17671. */
  17672. /**
  17673. * @ngdoc method
  17674. * @name $sce#getTrustedUrl
  17675. *
  17676. * @description
  17677. * Shorthand method. `$sce.getTrustedUrl(value)` →
  17678. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  17679. *
  17680. * @param {*} value The value to pass to `$sce.getTrusted`.
  17681. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  17682. */
  17683. /**
  17684. * @ngdoc method
  17685. * @name $sce#getTrustedResourceUrl
  17686. *
  17687. * @description
  17688. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  17689. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  17690. *
  17691. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  17692. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  17693. */
  17694. /**
  17695. * @ngdoc method
  17696. * @name $sce#getTrustedJs
  17697. *
  17698. * @description
  17699. * Shorthand method. `$sce.getTrustedJs(value)` →
  17700. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  17701. *
  17702. * @param {*} value The value to pass to `$sce.getTrusted`.
  17703. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  17704. */
  17705. /**
  17706. * @ngdoc method
  17707. * @name $sce#parseAsHtml
  17708. *
  17709. * @description
  17710. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  17711. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  17712. *
  17713. * @param {string} expression String expression to compile.
  17714. * @returns {function(context, locals)} a function which represents the compiled expression:
  17715. *
  17716. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17717. * are evaluated against (typically a scope object).
  17718. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17719. * `context`.
  17720. */
  17721. /**
  17722. * @ngdoc method
  17723. * @name $sce#parseAsCss
  17724. *
  17725. * @description
  17726. * Shorthand method. `$sce.parseAsCss(value)` →
  17727. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  17728. *
  17729. * @param {string} expression String expression to compile.
  17730. * @returns {function(context, locals)} a function which represents the compiled expression:
  17731. *
  17732. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17733. * are evaluated against (typically a scope object).
  17734. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17735. * `context`.
  17736. */
  17737. /**
  17738. * @ngdoc method
  17739. * @name $sce#parseAsUrl
  17740. *
  17741. * @description
  17742. * Shorthand method. `$sce.parseAsUrl(value)` →
  17743. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  17744. *
  17745. * @param {string} expression String expression to compile.
  17746. * @returns {function(context, locals)} a function which represents the compiled expression:
  17747. *
  17748. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17749. * are evaluated against (typically a scope object).
  17750. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17751. * `context`.
  17752. */
  17753. /**
  17754. * @ngdoc method
  17755. * @name $sce#parseAsResourceUrl
  17756. *
  17757. * @description
  17758. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  17759. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  17760. *
  17761. * @param {string} expression String expression to compile.
  17762. * @returns {function(context, locals)} a function which represents the compiled expression:
  17763. *
  17764. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17765. * are evaluated against (typically a scope object).
  17766. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17767. * `context`.
  17768. */
  17769. /**
  17770. * @ngdoc method
  17771. * @name $sce#parseAsJs
  17772. *
  17773. * @description
  17774. * Shorthand method. `$sce.parseAsJs(value)` →
  17775. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  17776. *
  17777. * @param {string} expression String expression to compile.
  17778. * @returns {function(context, locals)} a function which represents the compiled expression:
  17779. *
  17780. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17781. * are evaluated against (typically a scope object).
  17782. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17783. * `context`.
  17784. */
  17785. // Shorthand delegations.
  17786. var parse = sce.parseAs,
  17787. getTrusted = sce.getTrusted,
  17788. trustAs = sce.trustAs;
  17789. forEach(SCE_CONTEXTS, function(enumValue, name) {
  17790. var lName = lowercase(name);
  17791. sce[camelCase('parse_as_' + lName)] = function(expr) {
  17792. return parse(enumValue, expr);
  17793. };
  17794. sce[camelCase('get_trusted_' + lName)] = function(value) {
  17795. return getTrusted(enumValue, value);
  17796. };
  17797. sce[camelCase('trust_as_' + lName)] = function(value) {
  17798. return trustAs(enumValue, value);
  17799. };
  17800. });
  17801. return sce;
  17802. }];
  17803. }
  17804. /* exported $SnifferProvider */
  17805. /**
  17806. * !!! This is an undocumented "private" service !!!
  17807. *
  17808. * @name $sniffer
  17809. * @requires $window
  17810. * @requires $document
  17811. * @this
  17812. *
  17813. * @property {boolean} history Does the browser support html5 history api ?
  17814. * @property {boolean} transitions Does the browser support CSS transition events ?
  17815. * @property {boolean} animations Does the browser support CSS animation events ?
  17816. *
  17817. * @description
  17818. * This is very simple implementation of testing browser's features.
  17819. */
  17820. function $SnifferProvider() {
  17821. this.$get = ['$window', '$document', function($window, $document) {
  17822. var eventSupport = {},
  17823. // Chrome Packaged Apps are not allowed to access `history.pushState`.
  17824. // If not sandboxed, they can be detected by the presence of `chrome.app.runtime`
  17825. // (see https://developer.chrome.com/apps/api_index). If sandboxed, they can be detected by
  17826. // the presence of an extension runtime ID and the absence of other Chrome runtime APIs
  17827. // (see https://developer.chrome.com/apps/manifest/sandbox).
  17828. isChromePackagedApp =
  17829. $window.chrome &&
  17830. ($window.chrome.app && $window.chrome.app.runtime ||
  17831. !$window.chrome.app && $window.chrome.runtime && $window.chrome.runtime.id),
  17832. hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState,
  17833. android =
  17834. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  17835. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  17836. document = $document[0] || {},
  17837. vendorPrefix,
  17838. vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
  17839. bodyStyle = document.body && document.body.style,
  17840. transitions = false,
  17841. animations = false,
  17842. match;
  17843. if (bodyStyle) {
  17844. for (var prop in bodyStyle) {
  17845. if ((match = vendorRegex.exec(prop))) {
  17846. vendorPrefix = match[0];
  17847. vendorPrefix = vendorPrefix[0].toUpperCase() + vendorPrefix.substr(1);
  17848. break;
  17849. }
  17850. }
  17851. if (!vendorPrefix) {
  17852. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  17853. }
  17854. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  17855. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  17856. if (android && (!transitions || !animations)) {
  17857. transitions = isString(bodyStyle.webkitTransition);
  17858. animations = isString(bodyStyle.webkitAnimation);
  17859. }
  17860. }
  17861. return {
  17862. // Android has history.pushState, but it does not update location correctly
  17863. // so let's not use the history API at all.
  17864. // http://code.google.com/p/android/issues/detail?id=17471
  17865. // https://github.com/angular/angular.js/issues/904
  17866. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  17867. // so let's not use the history API also
  17868. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  17869. history: !!(hasHistoryPushState && !(android < 4) && !boxee),
  17870. hasEvent: function(event) {
  17871. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  17872. // it. In particular the event is not fired when backspace or delete key are pressed or
  17873. // when cut operation is performed.
  17874. // IE10+ implements 'input' event but it erroneously fires under various situations,
  17875. // e.g. when placeholder changes, or a form is focused.
  17876. if (event === 'input' && msie <= 11) return false;
  17877. if (isUndefined(eventSupport[event])) {
  17878. var divElm = document.createElement('div');
  17879. eventSupport[event] = 'on' + event in divElm;
  17880. }
  17881. return eventSupport[event];
  17882. },
  17883. csp: csp(),
  17884. vendorPrefix: vendorPrefix,
  17885. transitions: transitions,
  17886. animations: animations,
  17887. android: android
  17888. };
  17889. }];
  17890. }
  17891. var $templateRequestMinErr = minErr('$compile');
  17892. /**
  17893. * @ngdoc provider
  17894. * @name $templateRequestProvider
  17895. * @this
  17896. *
  17897. * @description
  17898. * Used to configure the options passed to the {@link $http} service when making a template request.
  17899. *
  17900. * For example, it can be used for specifying the "Accept" header that is sent to the server, when
  17901. * requesting a template.
  17902. */
  17903. function $TemplateRequestProvider() {
  17904. var httpOptions;
  17905. /**
  17906. * @ngdoc method
  17907. * @name $templateRequestProvider#httpOptions
  17908. * @description
  17909. * The options to be passed to the {@link $http} service when making the request.
  17910. * You can use this to override options such as the "Accept" header for template requests.
  17911. *
  17912. * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
  17913. * options if not overridden here.
  17914. *
  17915. * @param {string=} value new value for the {@link $http} options.
  17916. * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.
  17917. */
  17918. this.httpOptions = function(val) {
  17919. if (val) {
  17920. httpOptions = val;
  17921. return this;
  17922. }
  17923. return httpOptions;
  17924. };
  17925. /**
  17926. * @ngdoc service
  17927. * @name $templateRequest
  17928. *
  17929. * @description
  17930. * The `$templateRequest` service runs security checks then downloads the provided template using
  17931. * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
  17932. * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
  17933. * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
  17934. * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
  17935. * when `tpl` is of type string and `$templateCache` has the matching entry.
  17936. *
  17937. * If you want to pass custom options to the `$http` service, such as setting the Accept header you
  17938. * can configure this via {@link $templateRequestProvider#httpOptions}.
  17939. *
  17940. * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
  17941. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  17942. *
  17943. * @return {Promise} a promise for the HTTP response data of the given URL.
  17944. *
  17945. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  17946. */
  17947. this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
  17948. function handleRequestFn(tpl, ignoreRequestError) {
  17949. handleRequestFn.totalPendingRequests++;
  17950. // We consider the template cache holds only trusted templates, so
  17951. // there's no need to go through whitelisting again for keys that already
  17952. // are included in there. This also makes Angular accept any script
  17953. // directive, no matter its name. However, we still need to unwrap trusted
  17954. // types.
  17955. if (!isString(tpl) || isUndefined($templateCache.get(tpl))) {
  17956. tpl = $sce.getTrustedResourceUrl(tpl);
  17957. }
  17958. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  17959. if (isArray(transformResponse)) {
  17960. transformResponse = transformResponse.filter(function(transformer) {
  17961. return transformer !== defaultHttpResponseTransform;
  17962. });
  17963. } else if (transformResponse === defaultHttpResponseTransform) {
  17964. transformResponse = null;
  17965. }
  17966. return $http.get(tpl, extend({
  17967. cache: $templateCache,
  17968. transformResponse: transformResponse
  17969. }, httpOptions))
  17970. .finally(function() {
  17971. handleRequestFn.totalPendingRequests--;
  17972. })
  17973. .then(function(response) {
  17974. $templateCache.put(tpl, response.data);
  17975. return response.data;
  17976. }, handleError);
  17977. function handleError(resp) {
  17978. if (!ignoreRequestError) {
  17979. throw $templateRequestMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
  17980. tpl, resp.status, resp.statusText);
  17981. }
  17982. return $q.reject(resp);
  17983. }
  17984. }
  17985. handleRequestFn.totalPendingRequests = 0;
  17986. return handleRequestFn;
  17987. }];
  17988. }
  17989. /** @this */
  17990. function $$TestabilityProvider() {
  17991. this.$get = ['$rootScope', '$browser', '$location',
  17992. function($rootScope, $browser, $location) {
  17993. /**
  17994. * @name $testability
  17995. *
  17996. * @description
  17997. * The private $$testability service provides a collection of methods for use when debugging
  17998. * or by automated test and debugging tools.
  17999. */
  18000. var testability = {};
  18001. /**
  18002. * @name $$testability#findBindings
  18003. *
  18004. * @description
  18005. * Returns an array of elements that are bound (via ng-bind or {{}})
  18006. * to expressions matching the input.
  18007. *
  18008. * @param {Element} element The element root to search from.
  18009. * @param {string} expression The binding expression to match.
  18010. * @param {boolean} opt_exactMatch If true, only returns exact matches
  18011. * for the expression. Filters and whitespace are ignored.
  18012. */
  18013. testability.findBindings = function(element, expression, opt_exactMatch) {
  18014. var bindings = element.getElementsByClassName('ng-binding');
  18015. var matches = [];
  18016. forEach(bindings, function(binding) {
  18017. var dataBinding = angular.element(binding).data('$binding');
  18018. if (dataBinding) {
  18019. forEach(dataBinding, function(bindingName) {
  18020. if (opt_exactMatch) {
  18021. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  18022. if (matcher.test(bindingName)) {
  18023. matches.push(binding);
  18024. }
  18025. } else {
  18026. if (bindingName.indexOf(expression) !== -1) {
  18027. matches.push(binding);
  18028. }
  18029. }
  18030. });
  18031. }
  18032. });
  18033. return matches;
  18034. };
  18035. /**
  18036. * @name $$testability#findModels
  18037. *
  18038. * @description
  18039. * Returns an array of elements that are two-way found via ng-model to
  18040. * expressions matching the input.
  18041. *
  18042. * @param {Element} element The element root to search from.
  18043. * @param {string} expression The model expression to match.
  18044. * @param {boolean} opt_exactMatch If true, only returns exact matches
  18045. * for the expression.
  18046. */
  18047. testability.findModels = function(element, expression, opt_exactMatch) {
  18048. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  18049. for (var p = 0; p < prefixes.length; ++p) {
  18050. var attributeEquals = opt_exactMatch ? '=' : '*=';
  18051. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  18052. var elements = element.querySelectorAll(selector);
  18053. if (elements.length) {
  18054. return elements;
  18055. }
  18056. }
  18057. };
  18058. /**
  18059. * @name $$testability#getLocation
  18060. *
  18061. * @description
  18062. * Shortcut for getting the location in a browser agnostic way. Returns
  18063. * the path, search, and hash. (e.g. /path?a=b#hash)
  18064. */
  18065. testability.getLocation = function() {
  18066. return $location.url();
  18067. };
  18068. /**
  18069. * @name $$testability#setLocation
  18070. *
  18071. * @description
  18072. * Shortcut for navigating to a location without doing a full page reload.
  18073. *
  18074. * @param {string} url The location url (path, search and hash,
  18075. * e.g. /path?a=b#hash) to go to.
  18076. */
  18077. testability.setLocation = function(url) {
  18078. if (url !== $location.url()) {
  18079. $location.url(url);
  18080. $rootScope.$digest();
  18081. }
  18082. };
  18083. /**
  18084. * @name $$testability#whenStable
  18085. *
  18086. * @description
  18087. * Calls the callback when $timeout and $http requests are completed.
  18088. *
  18089. * @param {function} callback
  18090. */
  18091. testability.whenStable = function(callback) {
  18092. $browser.notifyWhenNoOutstandingRequests(callback);
  18093. };
  18094. return testability;
  18095. }];
  18096. }
  18097. /** @this */
  18098. function $TimeoutProvider() {
  18099. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  18100. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  18101. var deferreds = {};
  18102. /**
  18103. * @ngdoc service
  18104. * @name $timeout
  18105. *
  18106. * @description
  18107. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  18108. * block and delegates any exceptions to
  18109. * {@link ng.$exceptionHandler $exceptionHandler} service.
  18110. *
  18111. * The return value of calling `$timeout` is a promise, which will be resolved when
  18112. * the delay has passed and the timeout function, if provided, is executed.
  18113. *
  18114. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  18115. *
  18116. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  18117. * synchronously flush the queue of deferred functions.
  18118. *
  18119. * If you only want a promise that will be resolved after some specified delay
  18120. * then you can call `$timeout` without the `fn` function.
  18121. *
  18122. * @param {function()=} fn A function, whose execution should be delayed.
  18123. * @param {number=} [delay=0] Delay in milliseconds.
  18124. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  18125. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  18126. * @param {...*=} Pass additional parameters to the executed function.
  18127. * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise
  18128. * will be resolved with the return value of the `fn` function.
  18129. *
  18130. */
  18131. function timeout(fn, delay, invokeApply) {
  18132. if (!isFunction(fn)) {
  18133. invokeApply = delay;
  18134. delay = fn;
  18135. fn = noop;
  18136. }
  18137. var args = sliceArgs(arguments, 3),
  18138. skipApply = (isDefined(invokeApply) && !invokeApply),
  18139. deferred = (skipApply ? $$q : $q).defer(),
  18140. promise = deferred.promise,
  18141. timeoutId;
  18142. timeoutId = $browser.defer(function() {
  18143. try {
  18144. deferred.resolve(fn.apply(null, args));
  18145. } catch (e) {
  18146. deferred.reject(e);
  18147. $exceptionHandler(e);
  18148. } finally {
  18149. delete deferreds[promise.$$timeoutId];
  18150. }
  18151. if (!skipApply) $rootScope.$apply();
  18152. }, delay);
  18153. promise.$$timeoutId = timeoutId;
  18154. deferreds[timeoutId] = deferred;
  18155. return promise;
  18156. }
  18157. /**
  18158. * @ngdoc method
  18159. * @name $timeout#cancel
  18160. *
  18161. * @description
  18162. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  18163. * resolved with a rejection.
  18164. *
  18165. * @param {Promise=} promise Promise returned by the `$timeout` function.
  18166. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  18167. * canceled.
  18168. */
  18169. timeout.cancel = function(promise) {
  18170. if (promise && promise.$$timeoutId in deferreds) {
  18171. // Timeout cancels should not report an unhandled promise.
  18172. deferreds[promise.$$timeoutId].promise.catch(noop);
  18173. deferreds[promise.$$timeoutId].reject('canceled');
  18174. delete deferreds[promise.$$timeoutId];
  18175. return $browser.defer.cancel(promise.$$timeoutId);
  18176. }
  18177. return false;
  18178. };
  18179. return timeout;
  18180. }];
  18181. }
  18182. // NOTE: The usage of window and document instead of $window and $document here is
  18183. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  18184. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  18185. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  18186. // doesn't know about mocked locations and resolves URLs to the real document - which is
  18187. // exactly the behavior needed here. There is little value is mocking these out for this
  18188. // service.
  18189. var urlParsingNode = window.document.createElement('a');
  18190. var originUrl = urlResolve(window.location.href);
  18191. /**
  18192. *
  18193. * Implementation Notes for non-IE browsers
  18194. * ----------------------------------------
  18195. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  18196. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  18197. * URL will be resolved into an absolute URL in the context of the application document.
  18198. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  18199. * properties are all populated to reflect the normalized URL. This approach has wide
  18200. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  18201. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  18202. *
  18203. * Implementation Notes for IE
  18204. * ---------------------------
  18205. * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
  18206. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  18207. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  18208. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  18209. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  18210. * properties such as protocol, hostname, port, etc.
  18211. *
  18212. * References:
  18213. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  18214. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  18215. * http://url.spec.whatwg.org/#urlutils
  18216. * https://github.com/angular/angular.js/pull/2902
  18217. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  18218. *
  18219. * @kind function
  18220. * @param {string} url The URL to be parsed.
  18221. * @description Normalizes and parses a URL.
  18222. * @returns {object} Returns the normalized URL as a dictionary.
  18223. *
  18224. * | member name | Description |
  18225. * |---------------|----------------|
  18226. * | href | A normalized version of the provided URL if it was not an absolute URL |
  18227. * | protocol | The protocol including the trailing colon |
  18228. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  18229. * | search | The search params, minus the question mark |
  18230. * | hash | The hash string, minus the hash symbol
  18231. * | hostname | The hostname
  18232. * | port | The port, without ":"
  18233. * | pathname | The pathname, beginning with "/"
  18234. *
  18235. */
  18236. function urlResolve(url) {
  18237. var href = url;
  18238. if (msie) {
  18239. // Normalize before parse. Refer Implementation Notes on why this is
  18240. // done in two steps on IE.
  18241. urlParsingNode.setAttribute('href', href);
  18242. href = urlParsingNode.href;
  18243. }
  18244. urlParsingNode.setAttribute('href', href);
  18245. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  18246. return {
  18247. href: urlParsingNode.href,
  18248. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  18249. host: urlParsingNode.host,
  18250. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  18251. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  18252. hostname: urlParsingNode.hostname,
  18253. port: urlParsingNode.port,
  18254. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  18255. ? urlParsingNode.pathname
  18256. : '/' + urlParsingNode.pathname
  18257. };
  18258. }
  18259. /**
  18260. * Parse a request URL and determine whether this is a same-origin request as the application document.
  18261. *
  18262. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  18263. * or a parsed URL object.
  18264. * @returns {boolean} Whether the request is for the same origin as the application document.
  18265. */
  18266. function urlIsSameOrigin(requestUrl) {
  18267. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  18268. return (parsed.protocol === originUrl.protocol &&
  18269. parsed.host === originUrl.host);
  18270. }
  18271. /**
  18272. * @ngdoc service
  18273. * @name $window
  18274. * @this
  18275. *
  18276. * @description
  18277. * A reference to the browser's `window` object. While `window`
  18278. * is globally available in JavaScript, it causes testability problems, because
  18279. * it is a global variable. In angular we always refer to it through the
  18280. * `$window` service, so it may be overridden, removed or mocked for testing.
  18281. *
  18282. * Expressions, like the one defined for the `ngClick` directive in the example
  18283. * below, are evaluated with respect to the current scope. Therefore, there is
  18284. * no risk of inadvertently coding in a dependency on a global value in such an
  18285. * expression.
  18286. *
  18287. * @example
  18288. <example module="windowExample" name="window-service">
  18289. <file name="index.html">
  18290. <script>
  18291. angular.module('windowExample', [])
  18292. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  18293. $scope.greeting = 'Hello, World!';
  18294. $scope.doGreeting = function(greeting) {
  18295. $window.alert(greeting);
  18296. };
  18297. }]);
  18298. </script>
  18299. <div ng-controller="ExampleController">
  18300. <input type="text" ng-model="greeting" aria-label="greeting" />
  18301. <button ng-click="doGreeting(greeting)">ALERT</button>
  18302. </div>
  18303. </file>
  18304. <file name="protractor.js" type="protractor">
  18305. it('should display the greeting in the input box', function() {
  18306. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  18307. // If we click the button it will block the test runner
  18308. // element(':button').click();
  18309. });
  18310. </file>
  18311. </example>
  18312. */
  18313. function $WindowProvider() {
  18314. this.$get = valueFn(window);
  18315. }
  18316. /**
  18317. * @name $$cookieReader
  18318. * @requires $document
  18319. *
  18320. * @description
  18321. * This is a private service for reading cookies used by $http and ngCookies
  18322. *
  18323. * @return {Object} a key/value map of the current cookies
  18324. */
  18325. function $$CookieReader($document) {
  18326. var rawDocument = $document[0] || {};
  18327. var lastCookies = {};
  18328. var lastCookieString = '';
  18329. function safeDecodeURIComponent(str) {
  18330. try {
  18331. return decodeURIComponent(str);
  18332. } catch (e) {
  18333. return str;
  18334. }
  18335. }
  18336. return function() {
  18337. var cookieArray, cookie, i, index, name;
  18338. var currentCookieString = rawDocument.cookie || '';
  18339. if (currentCookieString !== lastCookieString) {
  18340. lastCookieString = currentCookieString;
  18341. cookieArray = lastCookieString.split('; ');
  18342. lastCookies = {};
  18343. for (i = 0; i < cookieArray.length; i++) {
  18344. cookie = cookieArray[i];
  18345. index = cookie.indexOf('=');
  18346. if (index > 0) { //ignore nameless cookies
  18347. name = safeDecodeURIComponent(cookie.substring(0, index));
  18348. // the first value that is seen for a cookie is the most
  18349. // specific one. values for the same cookie name that
  18350. // follow are for less specific paths.
  18351. if (isUndefined(lastCookies[name])) {
  18352. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  18353. }
  18354. }
  18355. }
  18356. }
  18357. return lastCookies;
  18358. };
  18359. }
  18360. $$CookieReader.$inject = ['$document'];
  18361. /** @this */
  18362. function $$CookieReaderProvider() {
  18363. this.$get = $$CookieReader;
  18364. }
  18365. /* global currencyFilter: true,
  18366. dateFilter: true,
  18367. filterFilter: true,
  18368. jsonFilter: true,
  18369. limitToFilter: true,
  18370. lowercaseFilter: true,
  18371. numberFilter: true,
  18372. orderByFilter: true,
  18373. uppercaseFilter: true,
  18374. */
  18375. /**
  18376. * @ngdoc provider
  18377. * @name $filterProvider
  18378. * @description
  18379. *
  18380. * Filters are just functions which transform input to an output. However filters need to be
  18381. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  18382. * annotated with dependencies and is responsible for creating a filter function.
  18383. *
  18384. * <div class="alert alert-warning">
  18385. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  18386. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  18387. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  18388. * (`myapp_subsection_filterx`).
  18389. * </div>
  18390. *
  18391. * ```js
  18392. * // Filter registration
  18393. * function MyModule($provide, $filterProvider) {
  18394. * // create a service to demonstrate injection (not always needed)
  18395. * $provide.value('greet', function(name){
  18396. * return 'Hello ' + name + '!';
  18397. * });
  18398. *
  18399. * // register a filter factory which uses the
  18400. * // greet service to demonstrate DI.
  18401. * $filterProvider.register('greet', function(greet){
  18402. * // return the filter function which uses the greet service
  18403. * // to generate salutation
  18404. * return function(text) {
  18405. * // filters need to be forgiving so check input validity
  18406. * return text && greet(text) || text;
  18407. * };
  18408. * });
  18409. * }
  18410. * ```
  18411. *
  18412. * The filter function is registered with the `$injector` under the filter name suffix with
  18413. * `Filter`.
  18414. *
  18415. * ```js
  18416. * it('should be the same instance', inject(
  18417. * function($filterProvider) {
  18418. * $filterProvider.register('reverse', function(){
  18419. * return ...;
  18420. * });
  18421. * },
  18422. * function($filter, reverseFilter) {
  18423. * expect($filter('reverse')).toBe(reverseFilter);
  18424. * });
  18425. * ```
  18426. *
  18427. *
  18428. * For more information about how angular filters work, and how to create your own filters, see
  18429. * {@link guide/filter Filters} in the Angular Developer Guide.
  18430. */
  18431. /**
  18432. * @ngdoc service
  18433. * @name $filter
  18434. * @kind function
  18435. * @description
  18436. * Filters are used for formatting data displayed to the user.
  18437. *
  18438. * They can be used in view templates, controllers or services.Angular comes
  18439. * with a collection of [built-in filters](api/ng/filter), but it is easy to
  18440. * define your own as well.
  18441. *
  18442. * The general syntax in templates is as follows:
  18443. *
  18444. * ```html
  18445. * {{ expression [| filter_name[:parameter_value] ... ] }}
  18446. * ```
  18447. *
  18448. * @param {String} name Name of the filter function to retrieve
  18449. * @return {Function} the filter function
  18450. * @example
  18451. <example name="$filter" module="filterExample">
  18452. <file name="index.html">
  18453. <div ng-controller="MainCtrl">
  18454. <h3>{{ originalText }}</h3>
  18455. <h3>{{ filteredText }}</h3>
  18456. </div>
  18457. </file>
  18458. <file name="script.js">
  18459. angular.module('filterExample', [])
  18460. .controller('MainCtrl', function($scope, $filter) {
  18461. $scope.originalText = 'hello';
  18462. $scope.filteredText = $filter('uppercase')($scope.originalText);
  18463. });
  18464. </file>
  18465. </example>
  18466. */
  18467. $FilterProvider.$inject = ['$provide'];
  18468. /** @this */
  18469. function $FilterProvider($provide) {
  18470. var suffix = 'Filter';
  18471. /**
  18472. * @ngdoc method
  18473. * @name $filterProvider#register
  18474. * @param {string|Object} name Name of the filter function, or an object map of filters where
  18475. * the keys are the filter names and the values are the filter factories.
  18476. *
  18477. * <div class="alert alert-warning">
  18478. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  18479. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  18480. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  18481. * (`myapp_subsection_filterx`).
  18482. * </div>
  18483. * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
  18484. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  18485. * of the registered filter instances.
  18486. */
  18487. function register(name, factory) {
  18488. if (isObject(name)) {
  18489. var filters = {};
  18490. forEach(name, function(filter, key) {
  18491. filters[key] = register(key, filter);
  18492. });
  18493. return filters;
  18494. } else {
  18495. return $provide.factory(name + suffix, factory);
  18496. }
  18497. }
  18498. this.register = register;
  18499. this.$get = ['$injector', function($injector) {
  18500. return function(name) {
  18501. return $injector.get(name + suffix);
  18502. };
  18503. }];
  18504. ////////////////////////////////////////
  18505. /* global
  18506. currencyFilter: false,
  18507. dateFilter: false,
  18508. filterFilter: false,
  18509. jsonFilter: false,
  18510. limitToFilter: false,
  18511. lowercaseFilter: false,
  18512. numberFilter: false,
  18513. orderByFilter: false,
  18514. uppercaseFilter: false
  18515. */
  18516. register('currency', currencyFilter);
  18517. register('date', dateFilter);
  18518. register('filter', filterFilter);
  18519. register('json', jsonFilter);
  18520. register('limitTo', limitToFilter);
  18521. register('lowercase', lowercaseFilter);
  18522. register('number', numberFilter);
  18523. register('orderBy', orderByFilter);
  18524. register('uppercase', uppercaseFilter);
  18525. }
  18526. /**
  18527. * @ngdoc filter
  18528. * @name filter
  18529. * @kind function
  18530. *
  18531. * @description
  18532. * Selects a subset of items from `array` and returns it as a new array.
  18533. *
  18534. * @param {Array} array The source array.
  18535. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  18536. * `array`.
  18537. *
  18538. * Can be one of:
  18539. *
  18540. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  18541. * objects with string properties in `array` that match this string will be returned. This also
  18542. * applies to nested object properties.
  18543. * The predicate can be negated by prefixing the string with `!`.
  18544. *
  18545. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  18546. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  18547. * which have property `name` containing "M" and property `phone` containing "1". A special
  18548. * property name (`$` by default) can be used (e.g. as in `{$: "text"}`) to accept a match
  18549. * against any property of the object or its nested object properties. That's equivalent to the
  18550. * simple substring match with a `string` as described above. The special property name can be
  18551. * overwritten, using the `anyPropertyKey` parameter.
  18552. * The predicate can be negated by prefixing the string with `!`.
  18553. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  18554. * not containing "M".
  18555. *
  18556. * Note that a named property will match properties on the same level only, while the special
  18557. * `$` property will match properties on the same level or deeper. E.g. an array item like
  18558. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  18559. * **will** be matched by `{$: 'John'}`.
  18560. *
  18561. * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
  18562. * The function is called for each element of the array, with the element, its index, and
  18563. * the entire array itself as arguments.
  18564. *
  18565. * The final result is an array of those elements that the predicate returned true for.
  18566. *
  18567. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  18568. * determining if the expected value (from the filter expression) and actual value (from
  18569. * the object in the array) should be considered a match.
  18570. *
  18571. * Can be one of:
  18572. *
  18573. * - `function(actual, expected)`:
  18574. * The function will be given the object value and the predicate value to compare and
  18575. * should return true if both values should be considered equal.
  18576. *
  18577. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  18578. * This is essentially strict comparison of expected and actual.
  18579. *
  18580. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  18581. * insensitive way.
  18582. *
  18583. * Primitive values are converted to strings. Objects are not compared against primitives,
  18584. * unless they have a custom `toString` method (e.g. `Date` objects).
  18585. *
  18586. * @param {string=} anyPropertyKey The special property name that matches against any property.
  18587. * By default `$`.
  18588. *
  18589. * @example
  18590. <example name="filter-filter">
  18591. <file name="index.html">
  18592. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  18593. {name:'Mary', phone:'800-BIG-MARY'},
  18594. {name:'Mike', phone:'555-4321'},
  18595. {name:'Adam', phone:'555-5678'},
  18596. {name:'Julie', phone:'555-8765'},
  18597. {name:'Juliette', phone:'555-5678'}]"></div>
  18598. <label>Search: <input ng-model="searchText"></label>
  18599. <table id="searchTextResults">
  18600. <tr><th>Name</th><th>Phone</th></tr>
  18601. <tr ng-repeat="friend in friends | filter:searchText">
  18602. <td>{{friend.name}}</td>
  18603. <td>{{friend.phone}}</td>
  18604. </tr>
  18605. </table>
  18606. <hr>
  18607. <label>Any: <input ng-model="search.$"></label> <br>
  18608. <label>Name only <input ng-model="search.name"></label><br>
  18609. <label>Phone only <input ng-model="search.phone"></label><br>
  18610. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  18611. <table id="searchObjResults">
  18612. <tr><th>Name</th><th>Phone</th></tr>
  18613. <tr ng-repeat="friendObj in friends | filter:search:strict">
  18614. <td>{{friendObj.name}}</td>
  18615. <td>{{friendObj.phone}}</td>
  18616. </tr>
  18617. </table>
  18618. </file>
  18619. <file name="protractor.js" type="protractor">
  18620. var expectFriendNames = function(expectedNames, key) {
  18621. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  18622. arr.forEach(function(wd, i) {
  18623. expect(wd.getText()).toMatch(expectedNames[i]);
  18624. });
  18625. });
  18626. };
  18627. it('should search across all fields when filtering with a string', function() {
  18628. var searchText = element(by.model('searchText'));
  18629. searchText.clear();
  18630. searchText.sendKeys('m');
  18631. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  18632. searchText.clear();
  18633. searchText.sendKeys('76');
  18634. expectFriendNames(['John', 'Julie'], 'friend');
  18635. });
  18636. it('should search in specific fields when filtering with a predicate object', function() {
  18637. var searchAny = element(by.model('search.$'));
  18638. searchAny.clear();
  18639. searchAny.sendKeys('i');
  18640. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  18641. });
  18642. it('should use a equal comparison when comparator is true', function() {
  18643. var searchName = element(by.model('search.name'));
  18644. var strict = element(by.model('strict'));
  18645. searchName.clear();
  18646. searchName.sendKeys('Julie');
  18647. strict.click();
  18648. expectFriendNames(['Julie'], 'friendObj');
  18649. });
  18650. </file>
  18651. </example>
  18652. */
  18653. function filterFilter() {
  18654. return function(array, expression, comparator, anyPropertyKey) {
  18655. if (!isArrayLike(array)) {
  18656. if (array == null) {
  18657. return array;
  18658. } else {
  18659. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  18660. }
  18661. }
  18662. anyPropertyKey = anyPropertyKey || '$';
  18663. var expressionType = getTypeForFilter(expression);
  18664. var predicateFn;
  18665. var matchAgainstAnyProp;
  18666. switch (expressionType) {
  18667. case 'function':
  18668. predicateFn = expression;
  18669. break;
  18670. case 'boolean':
  18671. case 'null':
  18672. case 'number':
  18673. case 'string':
  18674. matchAgainstAnyProp = true;
  18675. // falls through
  18676. case 'object':
  18677. predicateFn = createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp);
  18678. break;
  18679. default:
  18680. return array;
  18681. }
  18682. return Array.prototype.filter.call(array, predicateFn);
  18683. };
  18684. }
  18685. // Helper functions for `filterFilter`
  18686. function createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp) {
  18687. var shouldMatchPrimitives = isObject(expression) && (anyPropertyKey in expression);
  18688. var predicateFn;
  18689. if (comparator === true) {
  18690. comparator = equals;
  18691. } else if (!isFunction(comparator)) {
  18692. comparator = function(actual, expected) {
  18693. if (isUndefined(actual)) {
  18694. // No substring matching against `undefined`
  18695. return false;
  18696. }
  18697. if ((actual === null) || (expected === null)) {
  18698. // No substring matching against `null`; only match against `null`
  18699. return actual === expected;
  18700. }
  18701. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  18702. // Should not compare primitives against objects, unless they have custom `toString` method
  18703. return false;
  18704. }
  18705. actual = lowercase('' + actual);
  18706. expected = lowercase('' + expected);
  18707. return actual.indexOf(expected) !== -1;
  18708. };
  18709. }
  18710. predicateFn = function(item) {
  18711. if (shouldMatchPrimitives && !isObject(item)) {
  18712. return deepCompare(item, expression[anyPropertyKey], comparator, anyPropertyKey, false);
  18713. }
  18714. return deepCompare(item, expression, comparator, anyPropertyKey, matchAgainstAnyProp);
  18715. };
  18716. return predicateFn;
  18717. }
  18718. function deepCompare(actual, expected, comparator, anyPropertyKey, matchAgainstAnyProp, dontMatchWholeObject) {
  18719. var actualType = getTypeForFilter(actual);
  18720. var expectedType = getTypeForFilter(expected);
  18721. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  18722. return !deepCompare(actual, expected.substring(1), comparator, anyPropertyKey, matchAgainstAnyProp);
  18723. } else if (isArray(actual)) {
  18724. // In case `actual` is an array, consider it a match
  18725. // if ANY of it's items matches `expected`
  18726. return actual.some(function(item) {
  18727. return deepCompare(item, expected, comparator, anyPropertyKey, matchAgainstAnyProp);
  18728. });
  18729. }
  18730. switch (actualType) {
  18731. case 'object':
  18732. var key;
  18733. if (matchAgainstAnyProp) {
  18734. for (key in actual) {
  18735. if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, anyPropertyKey, true)) {
  18736. return true;
  18737. }
  18738. }
  18739. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, anyPropertyKey, false);
  18740. } else if (expectedType === 'object') {
  18741. for (key in expected) {
  18742. var expectedVal = expected[key];
  18743. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  18744. continue;
  18745. }
  18746. var matchAnyProperty = key === anyPropertyKey;
  18747. var actualVal = matchAnyProperty ? actual : actual[key];
  18748. if (!deepCompare(actualVal, expectedVal, comparator, anyPropertyKey, matchAnyProperty, matchAnyProperty)) {
  18749. return false;
  18750. }
  18751. }
  18752. return true;
  18753. } else {
  18754. return comparator(actual, expected);
  18755. }
  18756. case 'function':
  18757. return false;
  18758. default:
  18759. return comparator(actual, expected);
  18760. }
  18761. }
  18762. // Used for easily differentiating between `null` and actual `object`
  18763. function getTypeForFilter(val) {
  18764. return (val === null) ? 'null' : typeof val;
  18765. }
  18766. var MAX_DIGITS = 22;
  18767. var DECIMAL_SEP = '.';
  18768. var ZERO_CHAR = '0';
  18769. /**
  18770. * @ngdoc filter
  18771. * @name currency
  18772. * @kind function
  18773. *
  18774. * @description
  18775. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  18776. * symbol for current locale is used.
  18777. *
  18778. * @param {number} amount Input to filter.
  18779. * @param {string=} symbol Currency symbol or identifier to be displayed.
  18780. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  18781. * @returns {string} Formatted number.
  18782. *
  18783. *
  18784. * @example
  18785. <example module="currencyExample" name="currency-filter">
  18786. <file name="index.html">
  18787. <script>
  18788. angular.module('currencyExample', [])
  18789. .controller('ExampleController', ['$scope', function($scope) {
  18790. $scope.amount = 1234.56;
  18791. }]);
  18792. </script>
  18793. <div ng-controller="ExampleController">
  18794. <input type="number" ng-model="amount" aria-label="amount"> <br>
  18795. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  18796. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span><br>
  18797. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  18798. </div>
  18799. </file>
  18800. <file name="protractor.js" type="protractor">
  18801. it('should init with 1234.56', function() {
  18802. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  18803. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  18804. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  18805. });
  18806. it('should update', function() {
  18807. if (browser.params.browser === 'safari') {
  18808. // Safari does not understand the minus key. See
  18809. // https://github.com/angular/protractor/issues/481
  18810. return;
  18811. }
  18812. element(by.model('amount')).clear();
  18813. element(by.model('amount')).sendKeys('-1234');
  18814. expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
  18815. expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
  18816. expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
  18817. });
  18818. </file>
  18819. </example>
  18820. */
  18821. currencyFilter.$inject = ['$locale'];
  18822. function currencyFilter($locale) {
  18823. var formats = $locale.NUMBER_FORMATS;
  18824. return function(amount, currencySymbol, fractionSize) {
  18825. if (isUndefined(currencySymbol)) {
  18826. currencySymbol = formats.CURRENCY_SYM;
  18827. }
  18828. if (isUndefined(fractionSize)) {
  18829. fractionSize = formats.PATTERNS[1].maxFrac;
  18830. }
  18831. // if null or undefined pass it through
  18832. return (amount == null)
  18833. ? amount
  18834. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  18835. replace(/\u00A4/g, currencySymbol);
  18836. };
  18837. }
  18838. /**
  18839. * @ngdoc filter
  18840. * @name number
  18841. * @kind function
  18842. *
  18843. * @description
  18844. * Formats a number as text.
  18845. *
  18846. * If the input is null or undefined, it will just be returned.
  18847. * If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively.
  18848. * If the input is not a number an empty string is returned.
  18849. *
  18850. *
  18851. * @param {number|string} number Number to format.
  18852. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  18853. * If this is not provided then the fraction size is computed from the current locale's number
  18854. * formatting pattern. In the case of the default locale, it will be 3.
  18855. * @returns {string} Number rounded to `fractionSize` appropriately formatted based on the current
  18856. * locale (e.g., in the en_US locale it will have "." as the decimal separator and
  18857. * include "," group separators after each third digit).
  18858. *
  18859. * @example
  18860. <example module="numberFilterExample" name="number-filter">
  18861. <file name="index.html">
  18862. <script>
  18863. angular.module('numberFilterExample', [])
  18864. .controller('ExampleController', ['$scope', function($scope) {
  18865. $scope.val = 1234.56789;
  18866. }]);
  18867. </script>
  18868. <div ng-controller="ExampleController">
  18869. <label>Enter number: <input ng-model='val'></label><br>
  18870. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  18871. No fractions: <span>{{val | number:0}}</span><br>
  18872. Negative number: <span>{{-val | number:4}}</span>
  18873. </div>
  18874. </file>
  18875. <file name="protractor.js" type="protractor">
  18876. it('should format numbers', function() {
  18877. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  18878. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  18879. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  18880. });
  18881. it('should update', function() {
  18882. element(by.model('val')).clear();
  18883. element(by.model('val')).sendKeys('3374.333');
  18884. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  18885. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  18886. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  18887. });
  18888. </file>
  18889. </example>
  18890. */
  18891. numberFilter.$inject = ['$locale'];
  18892. function numberFilter($locale) {
  18893. var formats = $locale.NUMBER_FORMATS;
  18894. return function(number, fractionSize) {
  18895. // if null or undefined pass it through
  18896. return (number == null)
  18897. ? number
  18898. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  18899. fractionSize);
  18900. };
  18901. }
  18902. /**
  18903. * Parse a number (as a string) into three components that can be used
  18904. * for formatting the number.
  18905. *
  18906. * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)
  18907. *
  18908. * @param {string} numStr The number to parse
  18909. * @return {object} An object describing this number, containing the following keys:
  18910. * - d : an array of digits containing leading zeros as necessary
  18911. * - i : the number of the digits in `d` that are to the left of the decimal point
  18912. * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`
  18913. *
  18914. */
  18915. function parse(numStr) {
  18916. var exponent = 0, digits, numberOfIntegerDigits;
  18917. var i, j, zeros;
  18918. // Decimal point?
  18919. if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {
  18920. numStr = numStr.replace(DECIMAL_SEP, '');
  18921. }
  18922. // Exponential form?
  18923. if ((i = numStr.search(/e/i)) > 0) {
  18924. // Work out the exponent.
  18925. if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i;
  18926. numberOfIntegerDigits += +numStr.slice(i + 1);
  18927. numStr = numStr.substring(0, i);
  18928. } else if (numberOfIntegerDigits < 0) {
  18929. // There was no decimal point or exponent so it is an integer.
  18930. numberOfIntegerDigits = numStr.length;
  18931. }
  18932. // Count the number of leading zeros.
  18933. for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */ }
  18934. if (i === (zeros = numStr.length)) {
  18935. // The digits are all zero.
  18936. digits = [0];
  18937. numberOfIntegerDigits = 1;
  18938. } else {
  18939. // Count the number of trailing zeros
  18940. zeros--;
  18941. while (numStr.charAt(zeros) === ZERO_CHAR) zeros--;
  18942. // Trailing zeros are insignificant so ignore them
  18943. numberOfIntegerDigits -= i;
  18944. digits = [];
  18945. // Convert string to array of digits without leading/trailing zeros.
  18946. for (j = 0; i <= zeros; i++, j++) {
  18947. digits[j] = +numStr.charAt(i);
  18948. }
  18949. }
  18950. // If the number overflows the maximum allowed digits then use an exponent.
  18951. if (numberOfIntegerDigits > MAX_DIGITS) {
  18952. digits = digits.splice(0, MAX_DIGITS - 1);
  18953. exponent = numberOfIntegerDigits - 1;
  18954. numberOfIntegerDigits = 1;
  18955. }
  18956. return { d: digits, e: exponent, i: numberOfIntegerDigits };
  18957. }
  18958. /**
  18959. * Round the parsed number to the specified number of decimal places
  18960. * This function changed the parsedNumber in-place
  18961. */
  18962. function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
  18963. var digits = parsedNumber.d;
  18964. var fractionLen = digits.length - parsedNumber.i;
  18965. // determine fractionSize if it is not specified; `+fractionSize` converts it to a number
  18966. fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
  18967. // The index of the digit to where rounding is to occur
  18968. var roundAt = fractionSize + parsedNumber.i;
  18969. var digit = digits[roundAt];
  18970. if (roundAt > 0) {
  18971. // Drop fractional digits beyond `roundAt`
  18972. digits.splice(Math.max(parsedNumber.i, roundAt));
  18973. // Set non-fractional digits beyond `roundAt` to 0
  18974. for (var j = roundAt; j < digits.length; j++) {
  18975. digits[j] = 0;
  18976. }
  18977. } else {
  18978. // We rounded to zero so reset the parsedNumber
  18979. fractionLen = Math.max(0, fractionLen);
  18980. parsedNumber.i = 1;
  18981. digits.length = Math.max(1, roundAt = fractionSize + 1);
  18982. digits[0] = 0;
  18983. for (var i = 1; i < roundAt; i++) digits[i] = 0;
  18984. }
  18985. if (digit >= 5) {
  18986. if (roundAt - 1 < 0) {
  18987. for (var k = 0; k > roundAt; k--) {
  18988. digits.unshift(0);
  18989. parsedNumber.i++;
  18990. }
  18991. digits.unshift(1);
  18992. parsedNumber.i++;
  18993. } else {
  18994. digits[roundAt - 1]++;
  18995. }
  18996. }
  18997. // Pad out with zeros to get the required fraction length
  18998. for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);
  18999. // Do any carrying, e.g. a digit was rounded up to 10
  19000. var carry = digits.reduceRight(function(carry, d, i, digits) {
  19001. d = d + carry;
  19002. digits[i] = d % 10;
  19003. return Math.floor(d / 10);
  19004. }, 0);
  19005. if (carry) {
  19006. digits.unshift(carry);
  19007. parsedNumber.i++;
  19008. }
  19009. }
  19010. /**
  19011. * Format a number into a string
  19012. * @param {number} number The number to format
  19013. * @param {{
  19014. * minFrac, // the minimum number of digits required in the fraction part of the number
  19015. * maxFrac, // the maximum number of digits required in the fraction part of the number
  19016. * gSize, // number of digits in each group of separated digits
  19017. * lgSize, // number of digits in the last group of digits before the decimal separator
  19018. * negPre, // the string to go in front of a negative number (e.g. `-` or `(`))
  19019. * posPre, // the string to go in front of a positive number
  19020. * negSuf, // the string to go after a negative number (e.g. `)`)
  19021. * posSuf // the string to go after a positive number
  19022. * }} pattern
  19023. * @param {string} groupSep The string to separate groups of number (e.g. `,`)
  19024. * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`)
  19025. * @param {[type]} fractionSize The size of the fractional part of the number
  19026. * @return {string} The number formatted as a string
  19027. */
  19028. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  19029. if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';
  19030. var isInfinity = !isFinite(number);
  19031. var isZero = false;
  19032. var numStr = Math.abs(number) + '',
  19033. formattedText = '',
  19034. parsedNumber;
  19035. if (isInfinity) {
  19036. formattedText = '\u221e';
  19037. } else {
  19038. parsedNumber = parse(numStr);
  19039. roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);
  19040. var digits = parsedNumber.d;
  19041. var integerLen = parsedNumber.i;
  19042. var exponent = parsedNumber.e;
  19043. var decimals = [];
  19044. isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);
  19045. // pad zeros for small numbers
  19046. while (integerLen < 0) {
  19047. digits.unshift(0);
  19048. integerLen++;
  19049. }
  19050. // extract decimals digits
  19051. if (integerLen > 0) {
  19052. decimals = digits.splice(integerLen, digits.length);
  19053. } else {
  19054. decimals = digits;
  19055. digits = [0];
  19056. }
  19057. // format the integer digits with grouping separators
  19058. var groups = [];
  19059. if (digits.length >= pattern.lgSize) {
  19060. groups.unshift(digits.splice(-pattern.lgSize, digits.length).join(''));
  19061. }
  19062. while (digits.length > pattern.gSize) {
  19063. groups.unshift(digits.splice(-pattern.gSize, digits.length).join(''));
  19064. }
  19065. if (digits.length) {
  19066. groups.unshift(digits.join(''));
  19067. }
  19068. formattedText = groups.join(groupSep);
  19069. // append the decimal digits
  19070. if (decimals.length) {
  19071. formattedText += decimalSep + decimals.join('');
  19072. }
  19073. if (exponent) {
  19074. formattedText += 'e+' + exponent;
  19075. }
  19076. }
  19077. if (number < 0 && !isZero) {
  19078. return pattern.negPre + formattedText + pattern.negSuf;
  19079. } else {
  19080. return pattern.posPre + formattedText + pattern.posSuf;
  19081. }
  19082. }
  19083. function padNumber(num, digits, trim, negWrap) {
  19084. var neg = '';
  19085. if (num < 0 || (negWrap && num <= 0)) {
  19086. if (negWrap) {
  19087. num = -num + 1;
  19088. } else {
  19089. num = -num;
  19090. neg = '-';
  19091. }
  19092. }
  19093. num = '' + num;
  19094. while (num.length < digits) num = ZERO_CHAR + num;
  19095. if (trim) {
  19096. num = num.substr(num.length - digits);
  19097. }
  19098. return neg + num;
  19099. }
  19100. function dateGetter(name, size, offset, trim, negWrap) {
  19101. offset = offset || 0;
  19102. return function(date) {
  19103. var value = date['get' + name]();
  19104. if (offset > 0 || value > -offset) {
  19105. value += offset;
  19106. }
  19107. if (value === 0 && offset === -12) value = 12;
  19108. return padNumber(value, size, trim, negWrap);
  19109. };
  19110. }
  19111. function dateStrGetter(name, shortForm, standAlone) {
  19112. return function(date, formats) {
  19113. var value = date['get' + name]();
  19114. var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : '');
  19115. var get = uppercase(propPrefix + name);
  19116. return formats[get][value];
  19117. };
  19118. }
  19119. function timeZoneGetter(date, formats, offset) {
  19120. var zone = -1 * offset;
  19121. var paddedZone = (zone >= 0) ? '+' : '';
  19122. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  19123. padNumber(Math.abs(zone % 60), 2);
  19124. return paddedZone;
  19125. }
  19126. function getFirstThursdayOfYear(year) {
  19127. // 0 = index of January
  19128. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  19129. // 4 = index of Thursday (+1 to account for 1st = 5)
  19130. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  19131. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  19132. }
  19133. function getThursdayThisWeek(datetime) {
  19134. return new Date(datetime.getFullYear(), datetime.getMonth(),
  19135. // 4 = index of Thursday
  19136. datetime.getDate() + (4 - datetime.getDay()));
  19137. }
  19138. function weekGetter(size) {
  19139. return function(date) {
  19140. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  19141. thisThurs = getThursdayThisWeek(date);
  19142. var diff = +thisThurs - +firstThurs,
  19143. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  19144. return padNumber(result, size);
  19145. };
  19146. }
  19147. function ampmGetter(date, formats) {
  19148. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  19149. }
  19150. function eraGetter(date, formats) {
  19151. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  19152. }
  19153. function longEraGetter(date, formats) {
  19154. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  19155. }
  19156. var DATE_FORMATS = {
  19157. yyyy: dateGetter('FullYear', 4, 0, false, true),
  19158. yy: dateGetter('FullYear', 2, 0, true, true),
  19159. y: dateGetter('FullYear', 1, 0, false, true),
  19160. MMMM: dateStrGetter('Month'),
  19161. MMM: dateStrGetter('Month', true),
  19162. MM: dateGetter('Month', 2, 1),
  19163. M: dateGetter('Month', 1, 1),
  19164. LLLL: dateStrGetter('Month', false, true),
  19165. dd: dateGetter('Date', 2),
  19166. d: dateGetter('Date', 1),
  19167. HH: dateGetter('Hours', 2),
  19168. H: dateGetter('Hours', 1),
  19169. hh: dateGetter('Hours', 2, -12),
  19170. h: dateGetter('Hours', 1, -12),
  19171. mm: dateGetter('Minutes', 2),
  19172. m: dateGetter('Minutes', 1),
  19173. ss: dateGetter('Seconds', 2),
  19174. s: dateGetter('Seconds', 1),
  19175. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  19176. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  19177. sss: dateGetter('Milliseconds', 3),
  19178. EEEE: dateStrGetter('Day'),
  19179. EEE: dateStrGetter('Day', true),
  19180. a: ampmGetter,
  19181. Z: timeZoneGetter,
  19182. ww: weekGetter(2),
  19183. w: weekGetter(1),
  19184. G: eraGetter,
  19185. GG: eraGetter,
  19186. GGG: eraGetter,
  19187. GGGG: longEraGetter
  19188. };
  19189. var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
  19190. NUMBER_STRING = /^\-?\d+$/;
  19191. /**
  19192. * @ngdoc filter
  19193. * @name date
  19194. * @kind function
  19195. *
  19196. * @description
  19197. * Formats `date` to a string based on the requested `format`.
  19198. *
  19199. * `format` string can be composed of the following elements:
  19200. *
  19201. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  19202. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  19203. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  19204. * * `'MMMM'`: Month in year (January-December)
  19205. * * `'MMM'`: Month in year (Jan-Dec)
  19206. * * `'MM'`: Month in year, padded (01-12)
  19207. * * `'M'`: Month in year (1-12)
  19208. * * `'LLLL'`: Stand-alone month in year (January-December)
  19209. * * `'dd'`: Day in month, padded (01-31)
  19210. * * `'d'`: Day in month (1-31)
  19211. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  19212. * * `'EEE'`: Day in Week, (Sun-Sat)
  19213. * * `'HH'`: Hour in day, padded (00-23)
  19214. * * `'H'`: Hour in day (0-23)
  19215. * * `'hh'`: Hour in AM/PM, padded (01-12)
  19216. * * `'h'`: Hour in AM/PM, (1-12)
  19217. * * `'mm'`: Minute in hour, padded (00-59)
  19218. * * `'m'`: Minute in hour (0-59)
  19219. * * `'ss'`: Second in minute, padded (00-59)
  19220. * * `'s'`: Second in minute (0-59)
  19221. * * `'sss'`: Millisecond in second, padded (000-999)
  19222. * * `'a'`: AM/PM marker
  19223. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  19224. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  19225. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  19226. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  19227. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  19228. *
  19229. * `format` string can also be one of the following predefined
  19230. * {@link guide/i18n localizable formats}:
  19231. *
  19232. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  19233. * (e.g. Sep 3, 2010 12:05:08 PM)
  19234. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  19235. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  19236. * (e.g. Friday, September 3, 2010)
  19237. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  19238. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  19239. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  19240. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  19241. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  19242. *
  19243. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  19244. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  19245. * (e.g. `"h 'o''clock'"`).
  19246. *
  19247. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  19248. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  19249. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  19250. * specified in the string input, the time is considered to be in the local timezone.
  19251. * @param {string=} format Formatting rules (see Description). If not specified,
  19252. * `mediumDate` is used.
  19253. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  19254. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  19255. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  19256. * If not specified, the timezone of the browser will be used.
  19257. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  19258. *
  19259. * @example
  19260. <example name="filter-date">
  19261. <file name="index.html">
  19262. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  19263. <span>{{1288323623006 | date:'medium'}}</span><br>
  19264. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  19265. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  19266. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  19267. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  19268. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  19269. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  19270. </file>
  19271. <file name="protractor.js" type="protractor">
  19272. it('should format date', function() {
  19273. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  19274. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  19275. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  19276. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  19277. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  19278. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  19279. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  19280. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  19281. });
  19282. </file>
  19283. </example>
  19284. */
  19285. dateFilter.$inject = ['$locale'];
  19286. function dateFilter($locale) {
  19287. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  19288. // 1 2 3 4 5 6 7 8 9 10 11
  19289. function jsonStringToDate(string) {
  19290. var match;
  19291. if ((match = string.match(R_ISO8601_STR))) {
  19292. var date = new Date(0),
  19293. tzHour = 0,
  19294. tzMin = 0,
  19295. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  19296. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  19297. if (match[9]) {
  19298. tzHour = toInt(match[9] + match[10]);
  19299. tzMin = toInt(match[9] + match[11]);
  19300. }
  19301. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  19302. var h = toInt(match[4] || 0) - tzHour;
  19303. var m = toInt(match[5] || 0) - tzMin;
  19304. var s = toInt(match[6] || 0);
  19305. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  19306. timeSetter.call(date, h, m, s, ms);
  19307. return date;
  19308. }
  19309. return string;
  19310. }
  19311. return function(date, format, timezone) {
  19312. var text = '',
  19313. parts = [],
  19314. fn, match;
  19315. format = format || 'mediumDate';
  19316. format = $locale.DATETIME_FORMATS[format] || format;
  19317. if (isString(date)) {
  19318. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  19319. }
  19320. if (isNumber(date)) {
  19321. date = new Date(date);
  19322. }
  19323. if (!isDate(date) || !isFinite(date.getTime())) {
  19324. return date;
  19325. }
  19326. while (format) {
  19327. match = DATE_FORMATS_SPLIT.exec(format);
  19328. if (match) {
  19329. parts = concat(parts, match, 1);
  19330. format = parts.pop();
  19331. } else {
  19332. parts.push(format);
  19333. format = null;
  19334. }
  19335. }
  19336. var dateTimezoneOffset = date.getTimezoneOffset();
  19337. if (timezone) {
  19338. dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  19339. date = convertTimezoneToLocal(date, timezone, true);
  19340. }
  19341. forEach(parts, function(value) {
  19342. fn = DATE_FORMATS[value];
  19343. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  19344. : value === '\'\'' ? '\'' : value.replace(/(^'|'$)/g, '').replace(/''/g, '\'');
  19345. });
  19346. return text;
  19347. };
  19348. }
  19349. /**
  19350. * @ngdoc filter
  19351. * @name json
  19352. * @kind function
  19353. *
  19354. * @description
  19355. * Allows you to convert a JavaScript object into JSON string.
  19356. *
  19357. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  19358. * the binding is automatically converted to JSON.
  19359. *
  19360. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  19361. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  19362. * @returns {string} JSON string.
  19363. *
  19364. *
  19365. * @example
  19366. <example name="filter-json">
  19367. <file name="index.html">
  19368. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  19369. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  19370. </file>
  19371. <file name="protractor.js" type="protractor">
  19372. it('should jsonify filtered objects', function() {
  19373. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n {2}"name": ?"value"\n}/);
  19374. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n {4}"name": ?"value"\n}/);
  19375. });
  19376. </file>
  19377. </example>
  19378. *
  19379. */
  19380. function jsonFilter() {
  19381. return function(object, spacing) {
  19382. if (isUndefined(spacing)) {
  19383. spacing = 2;
  19384. }
  19385. return toJson(object, spacing);
  19386. };
  19387. }
  19388. /**
  19389. * @ngdoc filter
  19390. * @name lowercase
  19391. * @kind function
  19392. * @description
  19393. * Converts string to lowercase.
  19394. * @see angular.lowercase
  19395. */
  19396. var lowercaseFilter = valueFn(lowercase);
  19397. /**
  19398. * @ngdoc filter
  19399. * @name uppercase
  19400. * @kind function
  19401. * @description
  19402. * Converts string to uppercase.
  19403. * @see angular.uppercase
  19404. */
  19405. var uppercaseFilter = valueFn(uppercase);
  19406. /**
  19407. * @ngdoc filter
  19408. * @name limitTo
  19409. * @kind function
  19410. *
  19411. * @description
  19412. * Creates a new array or string containing only a specified number of elements. The elements are
  19413. * taken from either the beginning or the end of the source array, string or number, as specified by
  19414. * the value and sign (positive or negative) of `limit`. Other array-like objects are also supported
  19415. * (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input,
  19416. * it is converted to a string.
  19417. *
  19418. * @param {Array|ArrayLike|string|number} input - Array/array-like, string or number to be limited.
  19419. * @param {string|number} limit - The length of the returned array or string. If the `limit` number
  19420. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  19421. * If the number is negative, `limit` number of items from the end of the source array/string
  19422. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  19423. * the input will be returned unchanged.
  19424. * @param {(string|number)=} begin - Index at which to begin limitation. As a negative index,
  19425. * `begin` indicates an offset from the end of `input`. Defaults to `0`.
  19426. * @returns {Array|string} A new sub-array or substring of length `limit` or less if the input had
  19427. * less than `limit` elements.
  19428. *
  19429. * @example
  19430. <example module="limitToExample" name="limit-to-filter">
  19431. <file name="index.html">
  19432. <script>
  19433. angular.module('limitToExample', [])
  19434. .controller('ExampleController', ['$scope', function($scope) {
  19435. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  19436. $scope.letters = "abcdefghi";
  19437. $scope.longNumber = 2345432342;
  19438. $scope.numLimit = 3;
  19439. $scope.letterLimit = 3;
  19440. $scope.longNumberLimit = 3;
  19441. }]);
  19442. </script>
  19443. <div ng-controller="ExampleController">
  19444. <label>
  19445. Limit {{numbers}} to:
  19446. <input type="number" step="1" ng-model="numLimit">
  19447. </label>
  19448. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  19449. <label>
  19450. Limit {{letters}} to:
  19451. <input type="number" step="1" ng-model="letterLimit">
  19452. </label>
  19453. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  19454. <label>
  19455. Limit {{longNumber}} to:
  19456. <input type="number" step="1" ng-model="longNumberLimit">
  19457. </label>
  19458. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  19459. </div>
  19460. </file>
  19461. <file name="protractor.js" type="protractor">
  19462. var numLimitInput = element(by.model('numLimit'));
  19463. var letterLimitInput = element(by.model('letterLimit'));
  19464. var longNumberLimitInput = element(by.model('longNumberLimit'));
  19465. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  19466. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  19467. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  19468. it('should limit the number array to first three items', function() {
  19469. expect(numLimitInput.getAttribute('value')).toBe('3');
  19470. expect(letterLimitInput.getAttribute('value')).toBe('3');
  19471. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  19472. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  19473. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  19474. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  19475. });
  19476. // There is a bug in safari and protractor that doesn't like the minus key
  19477. // it('should update the output when -3 is entered', function() {
  19478. // numLimitInput.clear();
  19479. // numLimitInput.sendKeys('-3');
  19480. // letterLimitInput.clear();
  19481. // letterLimitInput.sendKeys('-3');
  19482. // longNumberLimitInput.clear();
  19483. // longNumberLimitInput.sendKeys('-3');
  19484. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  19485. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  19486. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  19487. // });
  19488. it('should not exceed the maximum size of input array', function() {
  19489. numLimitInput.clear();
  19490. numLimitInput.sendKeys('100');
  19491. letterLimitInput.clear();
  19492. letterLimitInput.sendKeys('100');
  19493. longNumberLimitInput.clear();
  19494. longNumberLimitInput.sendKeys('100');
  19495. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  19496. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  19497. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  19498. });
  19499. </file>
  19500. </example>
  19501. */
  19502. function limitToFilter() {
  19503. return function(input, limit, begin) {
  19504. if (Math.abs(Number(limit)) === Infinity) {
  19505. limit = Number(limit);
  19506. } else {
  19507. limit = toInt(limit);
  19508. }
  19509. if (isNumberNaN(limit)) return input;
  19510. if (isNumber(input)) input = input.toString();
  19511. if (!isArrayLike(input)) return input;
  19512. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  19513. begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
  19514. if (limit >= 0) {
  19515. return sliceFn(input, begin, begin + limit);
  19516. } else {
  19517. if (begin === 0) {
  19518. return sliceFn(input, limit, input.length);
  19519. } else {
  19520. return sliceFn(input, Math.max(0, begin + limit), begin);
  19521. }
  19522. }
  19523. };
  19524. }
  19525. function sliceFn(input, begin, end) {
  19526. if (isString(input)) return input.slice(begin, end);
  19527. return slice.call(input, begin, end);
  19528. }
  19529. /**
  19530. * @ngdoc filter
  19531. * @name orderBy
  19532. * @kind function
  19533. *
  19534. * @description
  19535. * Returns an array containing the items from the specified `collection`, ordered by a `comparator`
  19536. * function based on the values computed using the `expression` predicate.
  19537. *
  19538. * For example, `[{id: 'foo'}, {id: 'bar'}] | orderBy:'id'` would result in
  19539. * `[{id: 'bar'}, {id: 'foo'}]`.
  19540. *
  19541. * The `collection` can be an Array or array-like object (e.g. NodeList, jQuery object, TypedArray,
  19542. * String, etc).
  19543. *
  19544. * The `expression` can be a single predicate, or a list of predicates each serving as a tie-breaker
  19545. * for the preceeding one. The `expression` is evaluated against each item and the output is used
  19546. * for comparing with other items.
  19547. *
  19548. * You can change the sorting order by setting `reverse` to `true`. By default, items are sorted in
  19549. * ascending order.
  19550. *
  19551. * The comparison is done using the `comparator` function. If none is specified, a default, built-in
  19552. * comparator is used (see below for details - in a nutshell, it compares numbers numerically and
  19553. * strings alphabetically).
  19554. *
  19555. * ### Under the hood
  19556. *
  19557. * Ordering the specified `collection` happens in two phases:
  19558. *
  19559. * 1. All items are passed through the predicate (or predicates), and the returned values are saved
  19560. * along with their type (`string`, `number` etc). For example, an item `{label: 'foo'}`, passed
  19561. * through a predicate that extracts the value of the `label` property, would be transformed to:
  19562. * ```
  19563. * {
  19564. * value: 'foo',
  19565. * type: 'string',
  19566. * index: ...
  19567. * }
  19568. * ```
  19569. * 2. The comparator function is used to sort the items, based on the derived values, types and
  19570. * indices.
  19571. *
  19572. * If you use a custom comparator, it will be called with pairs of objects of the form
  19573. * `{value: ..., type: '...', index: ...}` and is expected to return `0` if the objects are equal
  19574. * (as far as the comparator is concerned), `-1` if the 1st one should be ranked higher than the
  19575. * second, or `1` otherwise.
  19576. *
  19577. * In order to ensure that the sorting will be deterministic across platforms, if none of the
  19578. * specified predicates can distinguish between two items, `orderBy` will automatically introduce a
  19579. * dummy predicate that returns the item's index as `value`.
  19580. * (If you are using a custom comparator, make sure it can handle this predicate as well.)
  19581. *
  19582. * Finally, in an attempt to simplify things, if a predicate returns an object as the extracted
  19583. * value for an item, `orderBy` will try to convert that object to a primitive value, before passing
  19584. * it to the comparator. The following rules govern the conversion:
  19585. *
  19586. * 1. If the object has a `valueOf()` method that returns a primitive, its return value will be
  19587. * used instead.<br />
  19588. * (If the object has a `valueOf()` method that returns another object, then the returned object
  19589. * will be used in subsequent steps.)
  19590. * 2. If the object has a custom `toString()` method (i.e. not the one inherited from `Object`) that
  19591. * returns a primitive, its return value will be used instead.<br />
  19592. * (If the object has a `toString()` method that returns another object, then the returned object
  19593. * will be used in subsequent steps.)
  19594. * 3. No conversion; the object itself is used.
  19595. *
  19596. * ### The default comparator
  19597. *
  19598. * The default, built-in comparator should be sufficient for most usecases. In short, it compares
  19599. * numbers numerically, strings alphabetically (and case-insensitively), for objects falls back to
  19600. * using their index in the original collection, and sorts values of different types by type.
  19601. *
  19602. * More specifically, it follows these steps to determine the relative order of items:
  19603. *
  19604. * 1. If the compared values are of different types, compare the types themselves alphabetically.
  19605. * 2. If both values are of type `string`, compare them alphabetically in a case- and
  19606. * locale-insensitive way.
  19607. * 3. If both values are objects, compare their indices instead.
  19608. * 4. Otherwise, return:
  19609. * - `0`, if the values are equal (by strict equality comparison, i.e. using `===`).
  19610. * - `-1`, if the 1st value is "less than" the 2nd value (compared using the `<` operator).
  19611. * - `1`, otherwise.
  19612. *
  19613. * **Note:** If you notice numbers not being sorted as expected, make sure they are actually being
  19614. * saved as numbers and not strings.
  19615. *
  19616. * @param {Array|ArrayLike} collection - The collection (array or array-like object) to sort.
  19617. * @param {(Function|string|Array.<Function|string>)=} expression - A predicate (or list of
  19618. * predicates) to be used by the comparator to determine the order of elements.
  19619. *
  19620. * Can be one of:
  19621. *
  19622. * - `Function`: A getter function. This function will be called with each item as argument and
  19623. * the return value will be used for sorting.
  19624. * - `string`: An Angular expression. This expression will be evaluated against each item and the
  19625. * result will be used for sorting. For example, use `'label'` to sort by a property called
  19626. * `label` or `'label.substring(0, 3)'` to sort by the first 3 characters of the `label`
  19627. * property.<br />
  19628. * (The result of a constant expression is interpreted as a property name to be used for
  19629. * comparison. For example, use `'"special name"'` (note the extra pair of quotes) to sort by a
  19630. * property called `special name`.)<br />
  19631. * An expression can be optionally prefixed with `+` or `-` to control the sorting direction,
  19632. * ascending or descending. For example, `'+label'` or `'-label'`. If no property is provided,
  19633. * (e.g. `'+'` or `'-'`), the collection element itself is used in comparisons.
  19634. * - `Array`: An array of function and/or string predicates. If a predicate cannot determine the
  19635. * relative order of two items, the next predicate is used as a tie-breaker.
  19636. *
  19637. * **Note:** If the predicate is missing or empty then it defaults to `'+'`.
  19638. *
  19639. * @param {boolean=} reverse - If `true`, reverse the sorting order.
  19640. * @param {(Function)=} comparator - The comparator function used to determine the relative order of
  19641. * value pairs. If omitted, the built-in comparator will be used.
  19642. *
  19643. * @returns {Array} - The sorted array.
  19644. *
  19645. *
  19646. * @example
  19647. * ### Ordering a table with `ngRepeat`
  19648. *
  19649. * The example below demonstrates a simple {@link ngRepeat ngRepeat}, where the data is sorted by
  19650. * age in descending order (expression is set to `'-age'`). The `comparator` is not set, which means
  19651. * it defaults to the built-in comparator.
  19652. *
  19653. <example name="orderBy-static" module="orderByExample1">
  19654. <file name="index.html">
  19655. <div ng-controller="ExampleController">
  19656. <table class="friends">
  19657. <tr>
  19658. <th>Name</th>
  19659. <th>Phone Number</th>
  19660. <th>Age</th>
  19661. </tr>
  19662. <tr ng-repeat="friend in friends | orderBy:'-age'">
  19663. <td>{{friend.name}}</td>
  19664. <td>{{friend.phone}}</td>
  19665. <td>{{friend.age}}</td>
  19666. </tr>
  19667. </table>
  19668. </div>
  19669. </file>
  19670. <file name="script.js">
  19671. angular.module('orderByExample1', [])
  19672. .controller('ExampleController', ['$scope', function($scope) {
  19673. $scope.friends = [
  19674. {name: 'John', phone: '555-1212', age: 10},
  19675. {name: 'Mary', phone: '555-9876', age: 19},
  19676. {name: 'Mike', phone: '555-4321', age: 21},
  19677. {name: 'Adam', phone: '555-5678', age: 35},
  19678. {name: 'Julie', phone: '555-8765', age: 29}
  19679. ];
  19680. }]);
  19681. </file>
  19682. <file name="style.css">
  19683. .friends {
  19684. border-collapse: collapse;
  19685. }
  19686. .friends th {
  19687. border-bottom: 1px solid;
  19688. }
  19689. .friends td, .friends th {
  19690. border-left: 1px solid;
  19691. padding: 5px 10px;
  19692. }
  19693. .friends td:first-child, .friends th:first-child {
  19694. border-left: none;
  19695. }
  19696. </file>
  19697. <file name="protractor.js" type="protractor">
  19698. // Element locators
  19699. var names = element.all(by.repeater('friends').column('friend.name'));
  19700. it('should sort friends by age in reverse order', function() {
  19701. expect(names.get(0).getText()).toBe('Adam');
  19702. expect(names.get(1).getText()).toBe('Julie');
  19703. expect(names.get(2).getText()).toBe('Mike');
  19704. expect(names.get(3).getText()).toBe('Mary');
  19705. expect(names.get(4).getText()).toBe('John');
  19706. });
  19707. </file>
  19708. </example>
  19709. * <hr />
  19710. *
  19711. * @example
  19712. * ### Changing parameters dynamically
  19713. *
  19714. * All parameters can be changed dynamically. The next example shows how you can make the columns of
  19715. * a table sortable, by binding the `expression` and `reverse` parameters to scope properties.
  19716. *
  19717. <example name="orderBy-dynamic" module="orderByExample2">
  19718. <file name="index.html">
  19719. <div ng-controller="ExampleController">
  19720. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  19721. <hr/>
  19722. <button ng-click="propertyName = null; reverse = false">Set to unsorted</button>
  19723. <hr/>
  19724. <table class="friends">
  19725. <tr>
  19726. <th>
  19727. <button ng-click="sortBy('name')">Name</button>
  19728. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  19729. </th>
  19730. <th>
  19731. <button ng-click="sortBy('phone')">Phone Number</button>
  19732. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  19733. </th>
  19734. <th>
  19735. <button ng-click="sortBy('age')">Age</button>
  19736. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  19737. </th>
  19738. </tr>
  19739. <tr ng-repeat="friend in friends | orderBy:propertyName:reverse">
  19740. <td>{{friend.name}}</td>
  19741. <td>{{friend.phone}}</td>
  19742. <td>{{friend.age}}</td>
  19743. </tr>
  19744. </table>
  19745. </div>
  19746. </file>
  19747. <file name="script.js">
  19748. angular.module('orderByExample2', [])
  19749. .controller('ExampleController', ['$scope', function($scope) {
  19750. var friends = [
  19751. {name: 'John', phone: '555-1212', age: 10},
  19752. {name: 'Mary', phone: '555-9876', age: 19},
  19753. {name: 'Mike', phone: '555-4321', age: 21},
  19754. {name: 'Adam', phone: '555-5678', age: 35},
  19755. {name: 'Julie', phone: '555-8765', age: 29}
  19756. ];
  19757. $scope.propertyName = 'age';
  19758. $scope.reverse = true;
  19759. $scope.friends = friends;
  19760. $scope.sortBy = function(propertyName) {
  19761. $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
  19762. $scope.propertyName = propertyName;
  19763. };
  19764. }]);
  19765. </file>
  19766. <file name="style.css">
  19767. .friends {
  19768. border-collapse: collapse;
  19769. }
  19770. .friends th {
  19771. border-bottom: 1px solid;
  19772. }
  19773. .friends td, .friends th {
  19774. border-left: 1px solid;
  19775. padding: 5px 10px;
  19776. }
  19777. .friends td:first-child, .friends th:first-child {
  19778. border-left: none;
  19779. }
  19780. .sortorder:after {
  19781. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  19782. }
  19783. .sortorder.reverse:after {
  19784. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  19785. }
  19786. </file>
  19787. <file name="protractor.js" type="protractor">
  19788. // Element locators
  19789. var unsortButton = element(by.partialButtonText('unsorted'));
  19790. var nameHeader = element(by.partialButtonText('Name'));
  19791. var phoneHeader = element(by.partialButtonText('Phone'));
  19792. var ageHeader = element(by.partialButtonText('Age'));
  19793. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  19794. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  19795. it('should sort friends by some property, when clicking on the column header', function() {
  19796. expect(firstName.getText()).toBe('Adam');
  19797. expect(lastName.getText()).toBe('John');
  19798. phoneHeader.click();
  19799. expect(firstName.getText()).toBe('John');
  19800. expect(lastName.getText()).toBe('Mary');
  19801. nameHeader.click();
  19802. expect(firstName.getText()).toBe('Adam');
  19803. expect(lastName.getText()).toBe('Mike');
  19804. ageHeader.click();
  19805. expect(firstName.getText()).toBe('John');
  19806. expect(lastName.getText()).toBe('Adam');
  19807. });
  19808. it('should sort friends in reverse order, when clicking on the same column', function() {
  19809. expect(firstName.getText()).toBe('Adam');
  19810. expect(lastName.getText()).toBe('John');
  19811. ageHeader.click();
  19812. expect(firstName.getText()).toBe('John');
  19813. expect(lastName.getText()).toBe('Adam');
  19814. ageHeader.click();
  19815. expect(firstName.getText()).toBe('Adam');
  19816. expect(lastName.getText()).toBe('John');
  19817. });
  19818. it('should restore the original order, when clicking "Set to unsorted"', function() {
  19819. expect(firstName.getText()).toBe('Adam');
  19820. expect(lastName.getText()).toBe('John');
  19821. unsortButton.click();
  19822. expect(firstName.getText()).toBe('John');
  19823. expect(lastName.getText()).toBe('Julie');
  19824. });
  19825. </file>
  19826. </example>
  19827. * <hr />
  19828. *
  19829. * @example
  19830. * ### Using `orderBy` inside a controller
  19831. *
  19832. * It is also possible to call the `orderBy` filter manually, by injecting `orderByFilter`, and
  19833. * calling it with the desired parameters. (Alternatively, you could inject the `$filter` factory
  19834. * and retrieve the `orderBy` filter with `$filter('orderBy')`.)
  19835. *
  19836. <example name="orderBy-call-manually" module="orderByExample3">
  19837. <file name="index.html">
  19838. <div ng-controller="ExampleController">
  19839. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  19840. <hr/>
  19841. <button ng-click="sortBy(null)">Set to unsorted</button>
  19842. <hr/>
  19843. <table class="friends">
  19844. <tr>
  19845. <th>
  19846. <button ng-click="sortBy('name')">Name</button>
  19847. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  19848. </th>
  19849. <th>
  19850. <button ng-click="sortBy('phone')">Phone Number</button>
  19851. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  19852. </th>
  19853. <th>
  19854. <button ng-click="sortBy('age')">Age</button>
  19855. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  19856. </th>
  19857. </tr>
  19858. <tr ng-repeat="friend in friends">
  19859. <td>{{friend.name}}</td>
  19860. <td>{{friend.phone}}</td>
  19861. <td>{{friend.age}}</td>
  19862. </tr>
  19863. </table>
  19864. </div>
  19865. </file>
  19866. <file name="script.js">
  19867. angular.module('orderByExample3', [])
  19868. .controller('ExampleController', ['$scope', 'orderByFilter', function($scope, orderBy) {
  19869. var friends = [
  19870. {name: 'John', phone: '555-1212', age: 10},
  19871. {name: 'Mary', phone: '555-9876', age: 19},
  19872. {name: 'Mike', phone: '555-4321', age: 21},
  19873. {name: 'Adam', phone: '555-5678', age: 35},
  19874. {name: 'Julie', phone: '555-8765', age: 29}
  19875. ];
  19876. $scope.propertyName = 'age';
  19877. $scope.reverse = true;
  19878. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  19879. $scope.sortBy = function(propertyName) {
  19880. $scope.reverse = (propertyName !== null && $scope.propertyName === propertyName)
  19881. ? !$scope.reverse : false;
  19882. $scope.propertyName = propertyName;
  19883. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  19884. };
  19885. }]);
  19886. </file>
  19887. <file name="style.css">
  19888. .friends {
  19889. border-collapse: collapse;
  19890. }
  19891. .friends th {
  19892. border-bottom: 1px solid;
  19893. }
  19894. .friends td, .friends th {
  19895. border-left: 1px solid;
  19896. padding: 5px 10px;
  19897. }
  19898. .friends td:first-child, .friends th:first-child {
  19899. border-left: none;
  19900. }
  19901. .sortorder:after {
  19902. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  19903. }
  19904. .sortorder.reverse:after {
  19905. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  19906. }
  19907. </file>
  19908. <file name="protractor.js" type="protractor">
  19909. // Element locators
  19910. var unsortButton = element(by.partialButtonText('unsorted'));
  19911. var nameHeader = element(by.partialButtonText('Name'));
  19912. var phoneHeader = element(by.partialButtonText('Phone'));
  19913. var ageHeader = element(by.partialButtonText('Age'));
  19914. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  19915. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  19916. it('should sort friends by some property, when clicking on the column header', function() {
  19917. expect(firstName.getText()).toBe('Adam');
  19918. expect(lastName.getText()).toBe('John');
  19919. phoneHeader.click();
  19920. expect(firstName.getText()).toBe('John');
  19921. expect(lastName.getText()).toBe('Mary');
  19922. nameHeader.click();
  19923. expect(firstName.getText()).toBe('Adam');
  19924. expect(lastName.getText()).toBe('Mike');
  19925. ageHeader.click();
  19926. expect(firstName.getText()).toBe('John');
  19927. expect(lastName.getText()).toBe('Adam');
  19928. });
  19929. it('should sort friends in reverse order, when clicking on the same column', function() {
  19930. expect(firstName.getText()).toBe('Adam');
  19931. expect(lastName.getText()).toBe('John');
  19932. ageHeader.click();
  19933. expect(firstName.getText()).toBe('John');
  19934. expect(lastName.getText()).toBe('Adam');
  19935. ageHeader.click();
  19936. expect(firstName.getText()).toBe('Adam');
  19937. expect(lastName.getText()).toBe('John');
  19938. });
  19939. it('should restore the original order, when clicking "Set to unsorted"', function() {
  19940. expect(firstName.getText()).toBe('Adam');
  19941. expect(lastName.getText()).toBe('John');
  19942. unsortButton.click();
  19943. expect(firstName.getText()).toBe('John');
  19944. expect(lastName.getText()).toBe('Julie');
  19945. });
  19946. </file>
  19947. </example>
  19948. * <hr />
  19949. *
  19950. * @example
  19951. * ### Using a custom comparator
  19952. *
  19953. * If you have very specific requirements about the way items are sorted, you can pass your own
  19954. * comparator function. For example, you might need to compare some strings in a locale-sensitive
  19955. * way. (When specifying a custom comparator, you also need to pass a value for the `reverse`
  19956. * argument - passing `false` retains the default sorting order, i.e. ascending.)
  19957. *
  19958. <example name="orderBy-custom-comparator" module="orderByExample4">
  19959. <file name="index.html">
  19960. <div ng-controller="ExampleController">
  19961. <div class="friends-container custom-comparator">
  19962. <h3>Locale-sensitive Comparator</h3>
  19963. <table class="friends">
  19964. <tr>
  19965. <th>Name</th>
  19966. <th>Favorite Letter</th>
  19967. </tr>
  19968. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter':false:localeSensitiveComparator">
  19969. <td>{{friend.name}}</td>
  19970. <td>{{friend.favoriteLetter}}</td>
  19971. </tr>
  19972. </table>
  19973. </div>
  19974. <div class="friends-container default-comparator">
  19975. <h3>Default Comparator</h3>
  19976. <table class="friends">
  19977. <tr>
  19978. <th>Name</th>
  19979. <th>Favorite Letter</th>
  19980. </tr>
  19981. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter'">
  19982. <td>{{friend.name}}</td>
  19983. <td>{{friend.favoriteLetter}}</td>
  19984. </tr>
  19985. </table>
  19986. </div>
  19987. </div>
  19988. </file>
  19989. <file name="script.js">
  19990. angular.module('orderByExample4', [])
  19991. .controller('ExampleController', ['$scope', function($scope) {
  19992. $scope.friends = [
  19993. {name: 'John', favoriteLetter: 'Ä'},
  19994. {name: 'Mary', favoriteLetter: 'Ü'},
  19995. {name: 'Mike', favoriteLetter: 'Ö'},
  19996. {name: 'Adam', favoriteLetter: 'H'},
  19997. {name: 'Julie', favoriteLetter: 'Z'}
  19998. ];
  19999. $scope.localeSensitiveComparator = function(v1, v2) {
  20000. // If we don't get strings, just compare by index
  20001. if (v1.type !== 'string' || v2.type !== 'string') {
  20002. return (v1.index < v2.index) ? -1 : 1;
  20003. }
  20004. // Compare strings alphabetically, taking locale into account
  20005. return v1.value.localeCompare(v2.value);
  20006. };
  20007. }]);
  20008. </file>
  20009. <file name="style.css">
  20010. .friends-container {
  20011. display: inline-block;
  20012. margin: 0 30px;
  20013. }
  20014. .friends {
  20015. border-collapse: collapse;
  20016. }
  20017. .friends th {
  20018. border-bottom: 1px solid;
  20019. }
  20020. .friends td, .friends th {
  20021. border-left: 1px solid;
  20022. padding: 5px 10px;
  20023. }
  20024. .friends td:first-child, .friends th:first-child {
  20025. border-left: none;
  20026. }
  20027. </file>
  20028. <file name="protractor.js" type="protractor">
  20029. // Element locators
  20030. var container = element(by.css('.custom-comparator'));
  20031. var names = container.all(by.repeater('friends').column('friend.name'));
  20032. it('should sort friends by favorite letter (in correct alphabetical order)', function() {
  20033. expect(names.get(0).getText()).toBe('John');
  20034. expect(names.get(1).getText()).toBe('Adam');
  20035. expect(names.get(2).getText()).toBe('Mike');
  20036. expect(names.get(3).getText()).toBe('Mary');
  20037. expect(names.get(4).getText()).toBe('Julie');
  20038. });
  20039. </file>
  20040. </example>
  20041. *
  20042. */
  20043. orderByFilter.$inject = ['$parse'];
  20044. function orderByFilter($parse) {
  20045. return function(array, sortPredicate, reverseOrder, compareFn) {
  20046. if (array == null) return array;
  20047. if (!isArrayLike(array)) {
  20048. throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
  20049. }
  20050. if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
  20051. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  20052. var predicates = processPredicates(sortPredicate);
  20053. var descending = reverseOrder ? -1 : 1;
  20054. // Define the `compare()` function. Use a default comparator if none is specified.
  20055. var compare = isFunction(compareFn) ? compareFn : defaultCompare;
  20056. // The next three lines are a version of a Swartzian Transform idiom from Perl
  20057. // (sometimes called the Decorate-Sort-Undecorate idiom)
  20058. // See https://en.wikipedia.org/wiki/Schwartzian_transform
  20059. var compareValues = Array.prototype.map.call(array, getComparisonObject);
  20060. compareValues.sort(doComparison);
  20061. array = compareValues.map(function(item) { return item.value; });
  20062. return array;
  20063. function getComparisonObject(value, index) {
  20064. // NOTE: We are adding an extra `tieBreaker` value based on the element's index.
  20065. // This will be used to keep the sort stable when none of the input predicates can
  20066. // distinguish between two elements.
  20067. return {
  20068. value: value,
  20069. tieBreaker: {value: index, type: 'number', index: index},
  20070. predicateValues: predicates.map(function(predicate) {
  20071. return getPredicateValue(predicate.get(value), index);
  20072. })
  20073. };
  20074. }
  20075. function doComparison(v1, v2) {
  20076. for (var i = 0, ii = predicates.length; i < ii; i++) {
  20077. var result = compare(v1.predicateValues[i], v2.predicateValues[i]);
  20078. if (result) {
  20079. return result * predicates[i].descending * descending;
  20080. }
  20081. }
  20082. return compare(v1.tieBreaker, v2.tieBreaker) * descending;
  20083. }
  20084. };
  20085. function processPredicates(sortPredicates) {
  20086. return sortPredicates.map(function(predicate) {
  20087. var descending = 1, get = identity;
  20088. if (isFunction(predicate)) {
  20089. get = predicate;
  20090. } else if (isString(predicate)) {
  20091. if ((predicate.charAt(0) === '+' || predicate.charAt(0) === '-')) {
  20092. descending = predicate.charAt(0) === '-' ? -1 : 1;
  20093. predicate = predicate.substring(1);
  20094. }
  20095. if (predicate !== '') {
  20096. get = $parse(predicate);
  20097. if (get.constant) {
  20098. var key = get();
  20099. get = function(value) { return value[key]; };
  20100. }
  20101. }
  20102. }
  20103. return {get: get, descending: descending};
  20104. });
  20105. }
  20106. function isPrimitive(value) {
  20107. switch (typeof value) {
  20108. case 'number': /* falls through */
  20109. case 'boolean': /* falls through */
  20110. case 'string':
  20111. return true;
  20112. default:
  20113. return false;
  20114. }
  20115. }
  20116. function objectValue(value) {
  20117. // If `valueOf` is a valid function use that
  20118. if (isFunction(value.valueOf)) {
  20119. value = value.valueOf();
  20120. if (isPrimitive(value)) return value;
  20121. }
  20122. // If `toString` is a valid function and not the one from `Object.prototype` use that
  20123. if (hasCustomToString(value)) {
  20124. value = value.toString();
  20125. if (isPrimitive(value)) return value;
  20126. }
  20127. return value;
  20128. }
  20129. function getPredicateValue(value, index) {
  20130. var type = typeof value;
  20131. if (value === null) {
  20132. type = 'string';
  20133. value = 'null';
  20134. } else if (type === 'object') {
  20135. value = objectValue(value);
  20136. }
  20137. return {value: value, type: type, index: index};
  20138. }
  20139. function defaultCompare(v1, v2) {
  20140. var result = 0;
  20141. var type1 = v1.type;
  20142. var type2 = v2.type;
  20143. if (type1 === type2) {
  20144. var value1 = v1.value;
  20145. var value2 = v2.value;
  20146. if (type1 === 'string') {
  20147. // Compare strings case-insensitively
  20148. value1 = value1.toLowerCase();
  20149. value2 = value2.toLowerCase();
  20150. } else if (type1 === 'object') {
  20151. // For basic objects, use the position of the object
  20152. // in the collection instead of the value
  20153. if (isObject(value1)) value1 = v1.index;
  20154. if (isObject(value2)) value2 = v2.index;
  20155. }
  20156. if (value1 !== value2) {
  20157. result = value1 < value2 ? -1 : 1;
  20158. }
  20159. } else {
  20160. result = type1 < type2 ? -1 : 1;
  20161. }
  20162. return result;
  20163. }
  20164. }
  20165. function ngDirective(directive) {
  20166. if (isFunction(directive)) {
  20167. directive = {
  20168. link: directive
  20169. };
  20170. }
  20171. directive.restrict = directive.restrict || 'AC';
  20172. return valueFn(directive);
  20173. }
  20174. /**
  20175. * @ngdoc directive
  20176. * @name a
  20177. * @restrict E
  20178. *
  20179. * @description
  20180. * Modifies the default behavior of the html A tag so that the default action is prevented when
  20181. * the href attribute is empty.
  20182. *
  20183. * This change permits the easy creation of action links with the `ngClick` directive
  20184. * without changing the location or causing page reloads, e.g.:
  20185. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  20186. */
  20187. var htmlAnchorDirective = valueFn({
  20188. restrict: 'E',
  20189. compile: function(element, attr) {
  20190. if (!attr.href && !attr.xlinkHref) {
  20191. return function(scope, element) {
  20192. // If the linked element is not an anchor tag anymore, do nothing
  20193. if (element[0].nodeName.toLowerCase() !== 'a') return;
  20194. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  20195. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  20196. 'xlink:href' : 'href';
  20197. element.on('click', function(event) {
  20198. // if we have no href url, then don't navigate anywhere.
  20199. if (!element.attr(href)) {
  20200. event.preventDefault();
  20201. }
  20202. });
  20203. };
  20204. }
  20205. }
  20206. });
  20207. /**
  20208. * @ngdoc directive
  20209. * @name ngHref
  20210. * @restrict A
  20211. * @priority 99
  20212. *
  20213. * @description
  20214. * Using Angular markup like `{{hash}}` in an href attribute will
  20215. * make the link go to the wrong URL if the user clicks it before
  20216. * Angular has a chance to replace the `{{hash}}` markup with its
  20217. * value. Until Angular replaces the markup the link will be broken
  20218. * and will most likely return a 404 error. The `ngHref` directive
  20219. * solves this problem.
  20220. *
  20221. * The wrong way to write it:
  20222. * ```html
  20223. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  20224. * ```
  20225. *
  20226. * The correct way to write it:
  20227. * ```html
  20228. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  20229. * ```
  20230. *
  20231. * @element A
  20232. * @param {template} ngHref any string which can contain `{{}}` markup.
  20233. *
  20234. * @example
  20235. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  20236. * in links and their different behaviors:
  20237. <example name="ng-href">
  20238. <file name="index.html">
  20239. <input ng-model="value" /><br />
  20240. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  20241. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  20242. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  20243. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  20244. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  20245. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  20246. </file>
  20247. <file name="protractor.js" type="protractor">
  20248. it('should execute ng-click but not reload when href without value', function() {
  20249. element(by.id('link-1')).click();
  20250. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  20251. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  20252. });
  20253. it('should execute ng-click but not reload when href empty string', function() {
  20254. element(by.id('link-2')).click();
  20255. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  20256. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  20257. });
  20258. it('should execute ng-click and change url when ng-href specified', function() {
  20259. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  20260. element(by.id('link-3')).click();
  20261. // At this point, we navigate away from an Angular page, so we need
  20262. // to use browser.driver to get the base webdriver.
  20263. browser.wait(function() {
  20264. return browser.driver.getCurrentUrl().then(function(url) {
  20265. return url.match(/\/123$/);
  20266. });
  20267. }, 5000, 'page should navigate to /123');
  20268. });
  20269. it('should execute ng-click but not reload when href empty string and name specified', function() {
  20270. element(by.id('link-4')).click();
  20271. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  20272. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  20273. });
  20274. it('should execute ng-click but not reload when no href but name specified', function() {
  20275. element(by.id('link-5')).click();
  20276. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  20277. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  20278. });
  20279. it('should only change url when only ng-href', function() {
  20280. element(by.model('value')).clear();
  20281. element(by.model('value')).sendKeys('6');
  20282. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  20283. element(by.id('link-6')).click();
  20284. // At this point, we navigate away from an Angular page, so we need
  20285. // to use browser.driver to get the base webdriver.
  20286. browser.wait(function() {
  20287. return browser.driver.getCurrentUrl().then(function(url) {
  20288. return url.match(/\/6$/);
  20289. });
  20290. }, 5000, 'page should navigate to /6');
  20291. });
  20292. </file>
  20293. </example>
  20294. */
  20295. /**
  20296. * @ngdoc directive
  20297. * @name ngSrc
  20298. * @restrict A
  20299. * @priority 99
  20300. *
  20301. * @description
  20302. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  20303. * work right: The browser will fetch from the URL with the literal
  20304. * text `{{hash}}` until Angular replaces the expression inside
  20305. * `{{hash}}`. The `ngSrc` directive solves this problem.
  20306. *
  20307. * The buggy way to write it:
  20308. * ```html
  20309. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  20310. * ```
  20311. *
  20312. * The correct way to write it:
  20313. * ```html
  20314. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  20315. * ```
  20316. *
  20317. * @element IMG
  20318. * @param {template} ngSrc any string which can contain `{{}}` markup.
  20319. */
  20320. /**
  20321. * @ngdoc directive
  20322. * @name ngSrcset
  20323. * @restrict A
  20324. * @priority 99
  20325. *
  20326. * @description
  20327. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  20328. * work right: The browser will fetch from the URL with the literal
  20329. * text `{{hash}}` until Angular replaces the expression inside
  20330. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  20331. *
  20332. * The buggy way to write it:
  20333. * ```html
  20334. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  20335. * ```
  20336. *
  20337. * The correct way to write it:
  20338. * ```html
  20339. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  20340. * ```
  20341. *
  20342. * @element IMG
  20343. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  20344. */
  20345. /**
  20346. * @ngdoc directive
  20347. * @name ngDisabled
  20348. * @restrict A
  20349. * @priority 100
  20350. *
  20351. * @description
  20352. *
  20353. * This directive sets the `disabled` attribute on the element if the
  20354. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  20355. *
  20356. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  20357. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20358. *
  20359. * @example
  20360. <example name="ng-disabled">
  20361. <file name="index.html">
  20362. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  20363. <button ng-model="button" ng-disabled="checked">Button</button>
  20364. </file>
  20365. <file name="protractor.js" type="protractor">
  20366. it('should toggle button', function() {
  20367. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  20368. element(by.model('checked')).click();
  20369. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  20370. });
  20371. </file>
  20372. </example>
  20373. *
  20374. * @element INPUT
  20375. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  20376. * then the `disabled` attribute will be set on the element
  20377. */
  20378. /**
  20379. * @ngdoc directive
  20380. * @name ngChecked
  20381. * @restrict A
  20382. * @priority 100
  20383. *
  20384. * @description
  20385. * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
  20386. *
  20387. * Note that this directive should not be used together with {@link ngModel `ngModel`},
  20388. * as this can lead to unexpected behavior.
  20389. *
  20390. * A special directive is necessary because we cannot use interpolation inside the `checked`
  20391. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20392. *
  20393. * @example
  20394. <example name="ng-checked">
  20395. <file name="index.html">
  20396. <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
  20397. <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
  20398. </file>
  20399. <file name="protractor.js" type="protractor">
  20400. it('should check both checkBoxes', function() {
  20401. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  20402. element(by.model('master')).click();
  20403. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  20404. });
  20405. </file>
  20406. </example>
  20407. *
  20408. * @element INPUT
  20409. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  20410. * then the `checked` attribute will be set on the element
  20411. */
  20412. /**
  20413. * @ngdoc directive
  20414. * @name ngReadonly
  20415. * @restrict A
  20416. * @priority 100
  20417. *
  20418. * @description
  20419. *
  20420. * Sets the `readonly` attribute on the element, if the expression inside `ngReadonly` is truthy.
  20421. * Note that `readonly` applies only to `input` elements with specific types. [See the input docs on
  20422. * MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-readonly) for more information.
  20423. *
  20424. * A special directive is necessary because we cannot use interpolation inside the `readonly`
  20425. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20426. *
  20427. * @example
  20428. <example name="ng-readonly">
  20429. <file name="index.html">
  20430. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  20431. <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
  20432. </file>
  20433. <file name="protractor.js" type="protractor">
  20434. it('should toggle readonly attr', function() {
  20435. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  20436. element(by.model('checked')).click();
  20437. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  20438. });
  20439. </file>
  20440. </example>
  20441. *
  20442. * @element INPUT
  20443. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  20444. * then special attribute "readonly" will be set on the element
  20445. */
  20446. /**
  20447. * @ngdoc directive
  20448. * @name ngSelected
  20449. * @restrict A
  20450. * @priority 100
  20451. *
  20452. * @description
  20453. *
  20454. * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy.
  20455. *
  20456. * A special directive is necessary because we cannot use interpolation inside the `selected`
  20457. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20458. *
  20459. * <div class="alert alert-warning">
  20460. * **Note:** `ngSelected` does not interact with the `select` and `ngModel` directives, it only
  20461. * sets the `selected` attribute on the element. If you are using `ngModel` on the select, you
  20462. * should not use `ngSelected` on the options, as `ngModel` will set the select value and
  20463. * selected options.
  20464. * </div>
  20465. *
  20466. * @example
  20467. <example name="ng-selected">
  20468. <file name="index.html">
  20469. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  20470. <select aria-label="ngSelected demo">
  20471. <option>Hello!</option>
  20472. <option id="greet" ng-selected="selected">Greetings!</option>
  20473. </select>
  20474. </file>
  20475. <file name="protractor.js" type="protractor">
  20476. it('should select Greetings!', function() {
  20477. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  20478. element(by.model('selected')).click();
  20479. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  20480. });
  20481. </file>
  20482. </example>
  20483. *
  20484. * @element OPTION
  20485. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  20486. * then special attribute "selected" will be set on the element
  20487. */
  20488. /**
  20489. * @ngdoc directive
  20490. * @name ngOpen
  20491. * @restrict A
  20492. * @priority 100
  20493. *
  20494. * @description
  20495. *
  20496. * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy.
  20497. *
  20498. * A special directive is necessary because we cannot use interpolation inside the `open`
  20499. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20500. *
  20501. * ## A note about browser compatibility
  20502. *
  20503. * Edge, Firefox, and Internet Explorer do not support the `details` element, it is
  20504. * recommended to use {@link ng.ngShow} and {@link ng.ngHide} instead.
  20505. *
  20506. * @example
  20507. <example name="ng-open">
  20508. <file name="index.html">
  20509. <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
  20510. <details id="details" ng-open="open">
  20511. <summary>Show/Hide me</summary>
  20512. </details>
  20513. </file>
  20514. <file name="protractor.js" type="protractor">
  20515. it('should toggle open', function() {
  20516. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  20517. element(by.model('open')).click();
  20518. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  20519. });
  20520. </file>
  20521. </example>
  20522. *
  20523. * @element DETAILS
  20524. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  20525. * then special attribute "open" will be set on the element
  20526. */
  20527. var ngAttributeAliasDirectives = {};
  20528. // boolean attrs are evaluated
  20529. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  20530. // binding to multiple is not supported
  20531. if (propName === 'multiple') return;
  20532. function defaultLinkFn(scope, element, attr) {
  20533. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  20534. attr.$set(attrName, !!value);
  20535. });
  20536. }
  20537. var normalized = directiveNormalize('ng-' + attrName);
  20538. var linkFn = defaultLinkFn;
  20539. if (propName === 'checked') {
  20540. linkFn = function(scope, element, attr) {
  20541. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  20542. if (attr.ngModel !== attr[normalized]) {
  20543. defaultLinkFn(scope, element, attr);
  20544. }
  20545. };
  20546. }
  20547. ngAttributeAliasDirectives[normalized] = function() {
  20548. return {
  20549. restrict: 'A',
  20550. priority: 100,
  20551. link: linkFn
  20552. };
  20553. };
  20554. });
  20555. // aliased input attrs are evaluated
  20556. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  20557. ngAttributeAliasDirectives[ngAttr] = function() {
  20558. return {
  20559. priority: 100,
  20560. link: function(scope, element, attr) {
  20561. //special case ngPattern when a literal regular expression value
  20562. //is used as the expression (this way we don't have to watch anything).
  20563. if (ngAttr === 'ngPattern' && attr.ngPattern.charAt(0) === '/') {
  20564. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  20565. if (match) {
  20566. attr.$set('ngPattern', new RegExp(match[1], match[2]));
  20567. return;
  20568. }
  20569. }
  20570. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  20571. attr.$set(ngAttr, value);
  20572. });
  20573. }
  20574. };
  20575. };
  20576. });
  20577. // ng-src, ng-srcset, ng-href are interpolated
  20578. forEach(['src', 'srcset', 'href'], function(attrName) {
  20579. var normalized = directiveNormalize('ng-' + attrName);
  20580. ngAttributeAliasDirectives[normalized] = function() {
  20581. return {
  20582. priority: 99, // it needs to run after the attributes are interpolated
  20583. link: function(scope, element, attr) {
  20584. var propName = attrName,
  20585. name = attrName;
  20586. if (attrName === 'href' &&
  20587. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  20588. name = 'xlinkHref';
  20589. attr.$attr[name] = 'xlink:href';
  20590. propName = null;
  20591. }
  20592. attr.$observe(normalized, function(value) {
  20593. if (!value) {
  20594. if (attrName === 'href') {
  20595. attr.$set(name, null);
  20596. }
  20597. return;
  20598. }
  20599. attr.$set(name, value);
  20600. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  20601. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  20602. // to set the property as well to achieve the desired effect.
  20603. // we use attr[attrName] value since $set can sanitize the url.
  20604. if (msie && propName) element.prop(propName, attr[name]);
  20605. });
  20606. }
  20607. };
  20608. };
  20609. });
  20610. /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
  20611. */
  20612. var nullFormCtrl = {
  20613. $addControl: noop,
  20614. $$renameControl: nullFormRenameControl,
  20615. $removeControl: noop,
  20616. $setValidity: noop,
  20617. $setDirty: noop,
  20618. $setPristine: noop,
  20619. $setSubmitted: noop
  20620. },
  20621. SUBMITTED_CLASS = 'ng-submitted';
  20622. function nullFormRenameControl(control, name) {
  20623. control.$name = name;
  20624. }
  20625. /**
  20626. * @ngdoc type
  20627. * @name form.FormController
  20628. *
  20629. * @property {boolean} $pristine True if user has not interacted with the form yet.
  20630. * @property {boolean} $dirty True if user has already interacted with the form.
  20631. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  20632. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  20633. * @property {boolean} $pending True if at least one containing control or form is pending.
  20634. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  20635. *
  20636. * @property {Object} $error Is an object hash, containing references to controls or
  20637. * forms with failing validators, where:
  20638. *
  20639. * - keys are validation tokens (error names),
  20640. * - values are arrays of controls or forms that have a failing validator for given error name.
  20641. *
  20642. * Built-in validation tokens:
  20643. *
  20644. * - `email`
  20645. * - `max`
  20646. * - `maxlength`
  20647. * - `min`
  20648. * - `minlength`
  20649. * - `number`
  20650. * - `pattern`
  20651. * - `required`
  20652. * - `url`
  20653. * - `date`
  20654. * - `datetimelocal`
  20655. * - `time`
  20656. * - `week`
  20657. * - `month`
  20658. *
  20659. * @description
  20660. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  20661. * such as being valid/invalid or dirty/pristine.
  20662. *
  20663. * Each {@link ng.directive:form form} directive creates an instance
  20664. * of `FormController`.
  20665. *
  20666. */
  20667. //asks for $scope to fool the BC controller module
  20668. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  20669. function FormController(element, attrs, $scope, $animate, $interpolate) {
  20670. var form = this,
  20671. controls = [];
  20672. // init state
  20673. form.$error = {};
  20674. form.$$success = {};
  20675. form.$pending = undefined;
  20676. form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
  20677. form.$dirty = false;
  20678. form.$pristine = true;
  20679. form.$valid = true;
  20680. form.$invalid = false;
  20681. form.$submitted = false;
  20682. form.$$parentForm = nullFormCtrl;
  20683. /**
  20684. * @ngdoc method
  20685. * @name form.FormController#$rollbackViewValue
  20686. *
  20687. * @description
  20688. * Rollback all form controls pending updates to the `$modelValue`.
  20689. *
  20690. * Updates may be pending by a debounced event or because the input is waiting for a some future
  20691. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  20692. * a form that uses `ng-model-options` to pend updates.
  20693. */
  20694. form.$rollbackViewValue = function() {
  20695. forEach(controls, function(control) {
  20696. control.$rollbackViewValue();
  20697. });
  20698. };
  20699. /**
  20700. * @ngdoc method
  20701. * @name form.FormController#$commitViewValue
  20702. *
  20703. * @description
  20704. * Commit all form controls pending updates to the `$modelValue`.
  20705. *
  20706. * Updates may be pending by a debounced event or because the input is waiting for a some future
  20707. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  20708. * usually handles calling this in response to input events.
  20709. */
  20710. form.$commitViewValue = function() {
  20711. forEach(controls, function(control) {
  20712. control.$commitViewValue();
  20713. });
  20714. };
  20715. /**
  20716. * @ngdoc method
  20717. * @name form.FormController#$addControl
  20718. * @param {object} control control object, either a {@link form.FormController} or an
  20719. * {@link ngModel.NgModelController}
  20720. *
  20721. * @description
  20722. * Register a control with the form. Input elements using ngModelController do this automatically
  20723. * when they are linked.
  20724. *
  20725. * Note that the current state of the control will not be reflected on the new parent form. This
  20726. * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
  20727. * state.
  20728. *
  20729. * However, if the method is used programmatically, for example by adding dynamically created controls,
  20730. * or controls that have been previously removed without destroying their corresponding DOM element,
  20731. * it's the developers responsibility to make sure the current state propagates to the parent form.
  20732. *
  20733. * For example, if an input control is added that is already `$dirty` and has `$error` properties,
  20734. * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
  20735. */
  20736. form.$addControl = function(control) {
  20737. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  20738. // and not added to the scope. Now we throw an error.
  20739. assertNotHasOwnProperty(control.$name, 'input');
  20740. controls.push(control);
  20741. if (control.$name) {
  20742. form[control.$name] = control;
  20743. }
  20744. control.$$parentForm = form;
  20745. };
  20746. // Private API: rename a form control
  20747. form.$$renameControl = function(control, newName) {
  20748. var oldName = control.$name;
  20749. if (form[oldName] === control) {
  20750. delete form[oldName];
  20751. }
  20752. form[newName] = control;
  20753. control.$name = newName;
  20754. };
  20755. /**
  20756. * @ngdoc method
  20757. * @name form.FormController#$removeControl
  20758. * @param {object} control control object, either a {@link form.FormController} or an
  20759. * {@link ngModel.NgModelController}
  20760. *
  20761. * @description
  20762. * Deregister a control from the form.
  20763. *
  20764. * Input elements using ngModelController do this automatically when they are destroyed.
  20765. *
  20766. * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
  20767. * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
  20768. * different from case to case. For example, removing the only `$dirty` control from a form may or
  20769. * may not mean that the form is still `$dirty`.
  20770. */
  20771. form.$removeControl = function(control) {
  20772. if (control.$name && form[control.$name] === control) {
  20773. delete form[control.$name];
  20774. }
  20775. forEach(form.$pending, function(value, name) {
  20776. form.$setValidity(name, null, control);
  20777. });
  20778. forEach(form.$error, function(value, name) {
  20779. form.$setValidity(name, null, control);
  20780. });
  20781. forEach(form.$$success, function(value, name) {
  20782. form.$setValidity(name, null, control);
  20783. });
  20784. arrayRemove(controls, control);
  20785. control.$$parentForm = nullFormCtrl;
  20786. };
  20787. /**
  20788. * @ngdoc method
  20789. * @name form.FormController#$setValidity
  20790. *
  20791. * @description
  20792. * Sets the validity of a form control.
  20793. *
  20794. * This method will also propagate to parent forms.
  20795. */
  20796. addSetValidityMethod({
  20797. ctrl: this,
  20798. $element: element,
  20799. set: function(object, property, controller) {
  20800. var list = object[property];
  20801. if (!list) {
  20802. object[property] = [controller];
  20803. } else {
  20804. var index = list.indexOf(controller);
  20805. if (index === -1) {
  20806. list.push(controller);
  20807. }
  20808. }
  20809. },
  20810. unset: function(object, property, controller) {
  20811. var list = object[property];
  20812. if (!list) {
  20813. return;
  20814. }
  20815. arrayRemove(list, controller);
  20816. if (list.length === 0) {
  20817. delete object[property];
  20818. }
  20819. },
  20820. $animate: $animate
  20821. });
  20822. /**
  20823. * @ngdoc method
  20824. * @name form.FormController#$setDirty
  20825. *
  20826. * @description
  20827. * Sets the form to a dirty state.
  20828. *
  20829. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  20830. * state (ng-dirty class). This method will also propagate to parent forms.
  20831. */
  20832. form.$setDirty = function() {
  20833. $animate.removeClass(element, PRISTINE_CLASS);
  20834. $animate.addClass(element, DIRTY_CLASS);
  20835. form.$dirty = true;
  20836. form.$pristine = false;
  20837. form.$$parentForm.$setDirty();
  20838. };
  20839. /**
  20840. * @ngdoc method
  20841. * @name form.FormController#$setPristine
  20842. *
  20843. * @description
  20844. * Sets the form to its pristine state.
  20845. *
  20846. * This method sets the form's `$pristine` state to true, the `$dirty` state to false, removes
  20847. * the `ng-dirty` class and adds the `ng-pristine` class. Additionally, it sets the `$submitted`
  20848. * state to false.
  20849. *
  20850. * This method will also propagate to all the controls contained in this form.
  20851. *
  20852. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  20853. * saving or resetting it.
  20854. */
  20855. form.$setPristine = function() {
  20856. $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  20857. form.$dirty = false;
  20858. form.$pristine = true;
  20859. form.$submitted = false;
  20860. forEach(controls, function(control) {
  20861. control.$setPristine();
  20862. });
  20863. };
  20864. /**
  20865. * @ngdoc method
  20866. * @name form.FormController#$setUntouched
  20867. *
  20868. * @description
  20869. * Sets the form to its untouched state.
  20870. *
  20871. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  20872. * untouched state (ng-untouched class).
  20873. *
  20874. * Setting a form controls back to their untouched state is often useful when setting the form
  20875. * back to its pristine state.
  20876. */
  20877. form.$setUntouched = function() {
  20878. forEach(controls, function(control) {
  20879. control.$setUntouched();
  20880. });
  20881. };
  20882. /**
  20883. * @ngdoc method
  20884. * @name form.FormController#$setSubmitted
  20885. *
  20886. * @description
  20887. * Sets the form to its submitted state.
  20888. */
  20889. form.$setSubmitted = function() {
  20890. $animate.addClass(element, SUBMITTED_CLASS);
  20891. form.$submitted = true;
  20892. form.$$parentForm.$setSubmitted();
  20893. };
  20894. }
  20895. /**
  20896. * @ngdoc directive
  20897. * @name ngForm
  20898. * @restrict EAC
  20899. *
  20900. * @description
  20901. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  20902. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  20903. * sub-group of controls needs to be determined.
  20904. *
  20905. * Note: the purpose of `ngForm` is to group controls,
  20906. * but not to be a replacement for the `<form>` tag with all of its capabilities
  20907. * (e.g. posting to the server, ...).
  20908. *
  20909. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  20910. * related scope, under this name.
  20911. *
  20912. */
  20913. /**
  20914. * @ngdoc directive
  20915. * @name form
  20916. * @restrict E
  20917. *
  20918. * @description
  20919. * Directive that instantiates
  20920. * {@link form.FormController FormController}.
  20921. *
  20922. * If the `name` attribute is specified, the form controller is published onto the current scope under
  20923. * this name.
  20924. *
  20925. * # Alias: {@link ng.directive:ngForm `ngForm`}
  20926. *
  20927. * In Angular, forms can be nested. This means that the outer form is valid when all of the child
  20928. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  20929. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to
  20930. * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group
  20931. * of controls needs to be determined.
  20932. *
  20933. * # CSS classes
  20934. * - `ng-valid` is set if the form is valid.
  20935. * - `ng-invalid` is set if the form is invalid.
  20936. * - `ng-pending` is set if the form is pending.
  20937. * - `ng-pristine` is set if the form is pristine.
  20938. * - `ng-dirty` is set if the form is dirty.
  20939. * - `ng-submitted` is set if the form was submitted.
  20940. *
  20941. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  20942. *
  20943. *
  20944. * # Submitting a form and preventing the default action
  20945. *
  20946. * Since the role of forms in client-side Angular applications is different than in classical
  20947. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  20948. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  20949. * to handle the form submission in an application-specific way.
  20950. *
  20951. * For this reason, Angular prevents the default action (form submission to the server) unless the
  20952. * `<form>` element has an `action` attribute specified.
  20953. *
  20954. * You can use one of the following two ways to specify what javascript method should be called when
  20955. * a form is submitted:
  20956. *
  20957. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  20958. * - {@link ng.directive:ngClick ngClick} directive on the first
  20959. * button or input field of type submit (input[type=submit])
  20960. *
  20961. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  20962. * or {@link ng.directive:ngClick ngClick} directives.
  20963. * This is because of the following form submission rules in the HTML specification:
  20964. *
  20965. * - If a form has only one input field then hitting enter in this field triggers form submit
  20966. * (`ngSubmit`)
  20967. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  20968. * doesn't trigger submit
  20969. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  20970. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  20971. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  20972. *
  20973. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  20974. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  20975. * to have access to the updated model.
  20976. *
  20977. * ## Animation Hooks
  20978. *
  20979. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  20980. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  20981. * other validations that are performed within the form. Animations in ngForm are similar to how
  20982. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  20983. * as JS animations.
  20984. *
  20985. * The following example shows a simple way to utilize CSS transitions to style a form element
  20986. * that has been rendered as invalid after it has been validated:
  20987. *
  20988. * <pre>
  20989. * //be sure to include ngAnimate as a module to hook into more
  20990. * //advanced animations
  20991. * .my-form {
  20992. * transition:0.5s linear all;
  20993. * background: white;
  20994. * }
  20995. * .my-form.ng-invalid {
  20996. * background: red;
  20997. * color:white;
  20998. * }
  20999. * </pre>
  21000. *
  21001. * @example
  21002. <example name="ng-form" deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  21003. <file name="index.html">
  21004. <script>
  21005. angular.module('formExample', [])
  21006. .controller('FormController', ['$scope', function($scope) {
  21007. $scope.userType = 'guest';
  21008. }]);
  21009. </script>
  21010. <style>
  21011. .my-form {
  21012. transition:all linear 0.5s;
  21013. background: transparent;
  21014. }
  21015. .my-form.ng-invalid {
  21016. background: red;
  21017. }
  21018. </style>
  21019. <form name="myForm" ng-controller="FormController" class="my-form">
  21020. userType: <input name="input" ng-model="userType" required>
  21021. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  21022. <code>userType = {{userType}}</code><br>
  21023. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  21024. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  21025. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  21026. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  21027. </form>
  21028. </file>
  21029. <file name="protractor.js" type="protractor">
  21030. it('should initialize to model', function() {
  21031. var userType = element(by.binding('userType'));
  21032. var valid = element(by.binding('myForm.input.$valid'));
  21033. expect(userType.getText()).toContain('guest');
  21034. expect(valid.getText()).toContain('true');
  21035. });
  21036. it('should be invalid if empty', function() {
  21037. var userType = element(by.binding('userType'));
  21038. var valid = element(by.binding('myForm.input.$valid'));
  21039. var userInput = element(by.model('userType'));
  21040. userInput.clear();
  21041. userInput.sendKeys('');
  21042. expect(userType.getText()).toEqual('userType =');
  21043. expect(valid.getText()).toContain('false');
  21044. });
  21045. </file>
  21046. </example>
  21047. *
  21048. * @param {string=} name Name of the form. If specified, the form controller will be published into
  21049. * related scope, under this name.
  21050. */
  21051. var formDirectiveFactory = function(isNgForm) {
  21052. return ['$timeout', '$parse', function($timeout, $parse) {
  21053. var formDirective = {
  21054. name: 'form',
  21055. restrict: isNgForm ? 'EAC' : 'E',
  21056. require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
  21057. controller: FormController,
  21058. compile: function ngFormCompile(formElement, attr) {
  21059. // Setup initial state of the control
  21060. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  21061. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  21062. return {
  21063. pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
  21064. var controller = ctrls[0];
  21065. // if `action` attr is not present on the form, prevent the default action (submission)
  21066. if (!('action' in attr)) {
  21067. // we can't use jq events because if a form is destroyed during submission the default
  21068. // action is not prevented. see #1238
  21069. //
  21070. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  21071. // page reload if the form was destroyed by submission of the form via a click handler
  21072. // on a button in the form. Looks like an IE9 specific bug.
  21073. var handleFormSubmission = function(event) {
  21074. scope.$apply(function() {
  21075. controller.$commitViewValue();
  21076. controller.$setSubmitted();
  21077. });
  21078. event.preventDefault();
  21079. };
  21080. formElement[0].addEventListener('submit', handleFormSubmission);
  21081. // unregister the preventDefault listener so that we don't not leak memory but in a
  21082. // way that will achieve the prevention of the default action.
  21083. formElement.on('$destroy', function() {
  21084. $timeout(function() {
  21085. formElement[0].removeEventListener('submit', handleFormSubmission);
  21086. }, 0, false);
  21087. });
  21088. }
  21089. var parentFormCtrl = ctrls[1] || controller.$$parentForm;
  21090. parentFormCtrl.$addControl(controller);
  21091. var setter = nameAttr ? getSetter(controller.$name) : noop;
  21092. if (nameAttr) {
  21093. setter(scope, controller);
  21094. attr.$observe(nameAttr, function(newValue) {
  21095. if (controller.$name === newValue) return;
  21096. setter(scope, undefined);
  21097. controller.$$parentForm.$$renameControl(controller, newValue);
  21098. setter = getSetter(controller.$name);
  21099. setter(scope, controller);
  21100. });
  21101. }
  21102. formElement.on('$destroy', function() {
  21103. controller.$$parentForm.$removeControl(controller);
  21104. setter(scope, undefined);
  21105. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  21106. });
  21107. }
  21108. };
  21109. }
  21110. };
  21111. return formDirective;
  21112. function getSetter(expression) {
  21113. if (expression === '') {
  21114. //create an assignable expression, so forms with an empty name can be renamed later
  21115. return $parse('this[""]').assign;
  21116. }
  21117. return $parse(expression).assign || noop;
  21118. }
  21119. }];
  21120. };
  21121. var formDirective = formDirectiveFactory();
  21122. var ngFormDirective = formDirectiveFactory(true);
  21123. /* global
  21124. VALID_CLASS: false,
  21125. INVALID_CLASS: false,
  21126. PRISTINE_CLASS: false,
  21127. DIRTY_CLASS: false,
  21128. ngModelMinErr: false
  21129. */
  21130. // Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  21131. 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)$/;
  21132. // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
  21133. // Note: We are being more lenient, because browsers are too.
  21134. // 1. Scheme
  21135. // 2. Slashes
  21136. // 3. Username
  21137. // 4. Password
  21138. // 5. Hostname
  21139. // 6. Port
  21140. // 7. Path
  21141. // 8. Query
  21142. // 9. Fragment
  21143. // 1111111111111111 222 333333 44444 555555555555555555555555 666 77777777 8888888 999
  21144. var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+\])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
  21145. // eslint-disable-next-line max-len
  21146. 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])?)*$/;
  21147. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
  21148. var DATE_REGEXP = /^(\d{4,})-(\d{2})-(\d{2})$/;
  21149. var DATETIMELOCAL_REGEXP = /^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  21150. var WEEK_REGEXP = /^(\d{4,})-W(\d\d)$/;
  21151. var MONTH_REGEXP = /^(\d{4,})-(\d\d)$/;
  21152. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  21153. var PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown';
  21154. var PARTIAL_VALIDATION_TYPES = createMap();
  21155. forEach('date,datetime-local,month,time,week'.split(','), function(type) {
  21156. PARTIAL_VALIDATION_TYPES[type] = true;
  21157. });
  21158. var inputType = {
  21159. /**
  21160. * @ngdoc input
  21161. * @name input[text]
  21162. *
  21163. * @description
  21164. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  21165. *
  21166. *
  21167. * @param {string} ngModel Assignable angular expression to data-bind to.
  21168. * @param {string=} name Property name of the form under which the control is published.
  21169. * @param {string=} required Adds `required` validation error key if the value is not entered.
  21170. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21171. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21172. * `required` when you want to data-bind to the `required` attribute.
  21173. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21174. * minlength.
  21175. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21176. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  21177. * any length.
  21178. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  21179. * that contains the regular expression body that will be converted to a regular expression
  21180. * as in the ngPattern directive.
  21181. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21182. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21183. * If the expression evaluates to a RegExp object, then this is used directly.
  21184. * If the expression evaluates to a string, then it will be converted to a RegExp
  21185. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21186. * `new RegExp('^abc$')`.<br />
  21187. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21188. * start at the index of the last search's match, thus not taking the whole input value into
  21189. * account.
  21190. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21191. * interaction with the input element.
  21192. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  21193. * This parameter is ignored for input[type=password] controls, which will never trim the
  21194. * input.
  21195. *
  21196. * @example
  21197. <example name="text-input-directive" module="textInputExample">
  21198. <file name="index.html">
  21199. <script>
  21200. angular.module('textInputExample', [])
  21201. .controller('ExampleController', ['$scope', function($scope) {
  21202. $scope.example = {
  21203. text: 'guest',
  21204. word: /^\s*\w*\s*$/
  21205. };
  21206. }]);
  21207. </script>
  21208. <form name="myForm" ng-controller="ExampleController">
  21209. <label>Single word:
  21210. <input type="text" name="input" ng-model="example.text"
  21211. ng-pattern="example.word" required ng-trim="false">
  21212. </label>
  21213. <div role="alert">
  21214. <span class="error" ng-show="myForm.input.$error.required">
  21215. Required!</span>
  21216. <span class="error" ng-show="myForm.input.$error.pattern">
  21217. Single word only!</span>
  21218. </div>
  21219. <code>text = {{example.text}}</code><br/>
  21220. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br/>
  21221. <code>myForm.input.$error = {{myForm.input.$error}}</code><br/>
  21222. <code>myForm.$valid = {{myForm.$valid}}</code><br/>
  21223. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br/>
  21224. </form>
  21225. </file>
  21226. <file name="protractor.js" type="protractor">
  21227. var text = element(by.binding('example.text'));
  21228. var valid = element(by.binding('myForm.input.$valid'));
  21229. var input = element(by.model('example.text'));
  21230. it('should initialize to model', function() {
  21231. expect(text.getText()).toContain('guest');
  21232. expect(valid.getText()).toContain('true');
  21233. });
  21234. it('should be invalid if empty', function() {
  21235. input.clear();
  21236. input.sendKeys('');
  21237. expect(text.getText()).toEqual('text =');
  21238. expect(valid.getText()).toContain('false');
  21239. });
  21240. it('should be invalid if multi word', function() {
  21241. input.clear();
  21242. input.sendKeys('hello world');
  21243. expect(valid.getText()).toContain('false');
  21244. });
  21245. </file>
  21246. </example>
  21247. */
  21248. 'text': textInputType,
  21249. /**
  21250. * @ngdoc input
  21251. * @name input[date]
  21252. *
  21253. * @description
  21254. * Input with date validation and transformation. In browsers that do not yet support
  21255. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  21256. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  21257. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  21258. * expected input format via a placeholder or label.
  21259. *
  21260. * The model must always be a Date object, otherwise Angular will throw an error.
  21261. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21262. *
  21263. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21264. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21265. *
  21266. * @param {string} ngModel Assignable angular expression to data-bind to.
  21267. * @param {string=} name Property name of the form under which the control is published.
  21268. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  21269. * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  21270. * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
  21271. * constraint validation.
  21272. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  21273. * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  21274. * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
  21275. * constraint validation.
  21276. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
  21277. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21278. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
  21279. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21280. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21281. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21282. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21283. * `required` when you want to data-bind to the `required` attribute.
  21284. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21285. * interaction with the input element.
  21286. *
  21287. * @example
  21288. <example name="date-input-directive" module="dateInputExample">
  21289. <file name="index.html">
  21290. <script>
  21291. angular.module('dateInputExample', [])
  21292. .controller('DateController', ['$scope', function($scope) {
  21293. $scope.example = {
  21294. value: new Date(2013, 9, 22)
  21295. };
  21296. }]);
  21297. </script>
  21298. <form name="myForm" ng-controller="DateController as dateCtrl">
  21299. <label for="exampleInput">Pick a date in 2013:</label>
  21300. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  21301. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  21302. <div role="alert">
  21303. <span class="error" ng-show="myForm.input.$error.required">
  21304. Required!</span>
  21305. <span class="error" ng-show="myForm.input.$error.date">
  21306. Not a valid date!</span>
  21307. </div>
  21308. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  21309. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21310. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21311. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21312. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21313. </form>
  21314. </file>
  21315. <file name="protractor.js" type="protractor">
  21316. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  21317. var valid = element(by.binding('myForm.input.$valid'));
  21318. // currently protractor/webdriver does not support
  21319. // sending keys to all known HTML5 input controls
  21320. // for various browsers (see https://github.com/angular/protractor/issues/562).
  21321. function setInput(val) {
  21322. // set the value of the element and force validation.
  21323. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21324. "ipt.value = '" + val + "';" +
  21325. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21326. browser.executeScript(scr);
  21327. }
  21328. it('should initialize to model', function() {
  21329. expect(value.getText()).toContain('2013-10-22');
  21330. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21331. });
  21332. it('should be invalid if empty', function() {
  21333. setInput('');
  21334. expect(value.getText()).toEqual('value =');
  21335. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21336. });
  21337. it('should be invalid if over max', function() {
  21338. setInput('2015-01-01');
  21339. expect(value.getText()).toContain('');
  21340. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21341. });
  21342. </file>
  21343. </example>
  21344. */
  21345. 'date': createDateInputType('date', DATE_REGEXP,
  21346. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  21347. 'yyyy-MM-dd'),
  21348. /**
  21349. * @ngdoc input
  21350. * @name input[datetime-local]
  21351. *
  21352. * @description
  21353. * Input with datetime validation and transformation. In browsers that do not yet support
  21354. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21355. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  21356. *
  21357. * The model must always be a Date object, otherwise Angular will throw an error.
  21358. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21359. *
  21360. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21361. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21362. *
  21363. * @param {string} ngModel Assignable angular expression to data-bind to.
  21364. * @param {string=} name Property name of the form under which the control is published.
  21365. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21366. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  21367. * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  21368. * Note that `min` will also add native HTML5 constraint validation.
  21369. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21370. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  21371. * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  21372. * Note that `max` will also add native HTML5 constraint validation.
  21373. * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
  21374. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21375. * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
  21376. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21377. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21378. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21379. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21380. * `required` when you want to data-bind to the `required` attribute.
  21381. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21382. * interaction with the input element.
  21383. *
  21384. * @example
  21385. <example name="datetimelocal-input-directive" module="dateExample">
  21386. <file name="index.html">
  21387. <script>
  21388. angular.module('dateExample', [])
  21389. .controller('DateController', ['$scope', function($scope) {
  21390. $scope.example = {
  21391. value: new Date(2010, 11, 28, 14, 57)
  21392. };
  21393. }]);
  21394. </script>
  21395. <form name="myForm" ng-controller="DateController as dateCtrl">
  21396. <label for="exampleInput">Pick a date between in 2013:</label>
  21397. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  21398. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  21399. <div role="alert">
  21400. <span class="error" ng-show="myForm.input.$error.required">
  21401. Required!</span>
  21402. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  21403. Not a valid date!</span>
  21404. </div>
  21405. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  21406. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21407. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21408. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21409. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21410. </form>
  21411. </file>
  21412. <file name="protractor.js" type="protractor">
  21413. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  21414. var valid = element(by.binding('myForm.input.$valid'));
  21415. // currently protractor/webdriver does not support
  21416. // sending keys to all known HTML5 input controls
  21417. // for various browsers (https://github.com/angular/protractor/issues/562).
  21418. function setInput(val) {
  21419. // set the value of the element and force validation.
  21420. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21421. "ipt.value = '" + val + "';" +
  21422. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21423. browser.executeScript(scr);
  21424. }
  21425. it('should initialize to model', function() {
  21426. expect(value.getText()).toContain('2010-12-28T14:57:00');
  21427. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21428. });
  21429. it('should be invalid if empty', function() {
  21430. setInput('');
  21431. expect(value.getText()).toEqual('value =');
  21432. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21433. });
  21434. it('should be invalid if over max', function() {
  21435. setInput('2015-01-01T23:59:00');
  21436. expect(value.getText()).toContain('');
  21437. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21438. });
  21439. </file>
  21440. </example>
  21441. */
  21442. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  21443. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  21444. 'yyyy-MM-ddTHH:mm:ss.sss'),
  21445. /**
  21446. * @ngdoc input
  21447. * @name input[time]
  21448. *
  21449. * @description
  21450. * Input with time validation and transformation. In browsers that do not yet support
  21451. * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21452. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  21453. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  21454. *
  21455. * The model must always be a Date object, otherwise Angular will throw an error.
  21456. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21457. *
  21458. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21459. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21460. *
  21461. * @param {string} ngModel Assignable angular expression to data-bind to.
  21462. * @param {string=} name Property name of the form under which the control is published.
  21463. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21464. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  21465. * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
  21466. * native HTML5 constraint validation.
  21467. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21468. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  21469. * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
  21470. * native HTML5 constraint validation.
  21471. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
  21472. * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21473. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
  21474. * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21475. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21476. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21477. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21478. * `required` when you want to data-bind to the `required` attribute.
  21479. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21480. * interaction with the input element.
  21481. *
  21482. * @example
  21483. <example name="time-input-directive" module="timeExample">
  21484. <file name="index.html">
  21485. <script>
  21486. angular.module('timeExample', [])
  21487. .controller('DateController', ['$scope', function($scope) {
  21488. $scope.example = {
  21489. value: new Date(1970, 0, 1, 14, 57, 0)
  21490. };
  21491. }]);
  21492. </script>
  21493. <form name="myForm" ng-controller="DateController as dateCtrl">
  21494. <label for="exampleInput">Pick a time between 8am and 5pm:</label>
  21495. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  21496. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  21497. <div role="alert">
  21498. <span class="error" ng-show="myForm.input.$error.required">
  21499. Required!</span>
  21500. <span class="error" ng-show="myForm.input.$error.time">
  21501. Not a valid date!</span>
  21502. </div>
  21503. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  21504. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21505. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21506. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21507. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21508. </form>
  21509. </file>
  21510. <file name="protractor.js" type="protractor">
  21511. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  21512. var valid = element(by.binding('myForm.input.$valid'));
  21513. // currently protractor/webdriver does not support
  21514. // sending keys to all known HTML5 input controls
  21515. // for various browsers (https://github.com/angular/protractor/issues/562).
  21516. function setInput(val) {
  21517. // set the value of the element and force validation.
  21518. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21519. "ipt.value = '" + val + "';" +
  21520. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21521. browser.executeScript(scr);
  21522. }
  21523. it('should initialize to model', function() {
  21524. expect(value.getText()).toContain('14:57:00');
  21525. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21526. });
  21527. it('should be invalid if empty', function() {
  21528. setInput('');
  21529. expect(value.getText()).toEqual('value =');
  21530. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21531. });
  21532. it('should be invalid if over max', function() {
  21533. setInput('23:59:00');
  21534. expect(value.getText()).toContain('');
  21535. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21536. });
  21537. </file>
  21538. </example>
  21539. */
  21540. 'time': createDateInputType('time', TIME_REGEXP,
  21541. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  21542. 'HH:mm:ss.sss'),
  21543. /**
  21544. * @ngdoc input
  21545. * @name input[week]
  21546. *
  21547. * @description
  21548. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  21549. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21550. * week format (yyyy-W##), for example: `2013-W02`.
  21551. *
  21552. * The model must always be a Date object, otherwise Angular will throw an error.
  21553. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21554. *
  21555. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21556. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21557. *
  21558. * @param {string} ngModel Assignable angular expression to data-bind to.
  21559. * @param {string=} name Property name of the form under which the control is published.
  21560. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21561. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  21562. * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
  21563. * native HTML5 constraint validation.
  21564. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21565. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  21566. * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
  21567. * native HTML5 constraint validation.
  21568. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  21569. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21570. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  21571. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21572. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21573. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21574. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21575. * `required` when you want to data-bind to the `required` attribute.
  21576. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21577. * interaction with the input element.
  21578. *
  21579. * @example
  21580. <example name="week-input-directive" module="weekExample">
  21581. <file name="index.html">
  21582. <script>
  21583. angular.module('weekExample', [])
  21584. .controller('DateController', ['$scope', function($scope) {
  21585. $scope.example = {
  21586. value: new Date(2013, 0, 3)
  21587. };
  21588. }]);
  21589. </script>
  21590. <form name="myForm" ng-controller="DateController as dateCtrl">
  21591. <label>Pick a date between in 2013:
  21592. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  21593. placeholder="YYYY-W##" min="2012-W32"
  21594. max="2013-W52" required />
  21595. </label>
  21596. <div role="alert">
  21597. <span class="error" ng-show="myForm.input.$error.required">
  21598. Required!</span>
  21599. <span class="error" ng-show="myForm.input.$error.week">
  21600. Not a valid date!</span>
  21601. </div>
  21602. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  21603. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21604. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21605. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21606. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21607. </form>
  21608. </file>
  21609. <file name="protractor.js" type="protractor">
  21610. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  21611. var valid = element(by.binding('myForm.input.$valid'));
  21612. // currently protractor/webdriver does not support
  21613. // sending keys to all known HTML5 input controls
  21614. // for various browsers (https://github.com/angular/protractor/issues/562).
  21615. function setInput(val) {
  21616. // set the value of the element and force validation.
  21617. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21618. "ipt.value = '" + val + "';" +
  21619. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21620. browser.executeScript(scr);
  21621. }
  21622. it('should initialize to model', function() {
  21623. expect(value.getText()).toContain('2013-W01');
  21624. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21625. });
  21626. it('should be invalid if empty', function() {
  21627. setInput('');
  21628. expect(value.getText()).toEqual('value =');
  21629. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21630. });
  21631. it('should be invalid if over max', function() {
  21632. setInput('2015-W01');
  21633. expect(value.getText()).toContain('');
  21634. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21635. });
  21636. </file>
  21637. </example>
  21638. */
  21639. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  21640. /**
  21641. * @ngdoc input
  21642. * @name input[month]
  21643. *
  21644. * @description
  21645. * Input with month validation and transformation. In browsers that do not yet support
  21646. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21647. * month format (yyyy-MM), for example: `2009-01`.
  21648. *
  21649. * The model must always be a Date object, otherwise Angular will throw an error.
  21650. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21651. * If the model is not set to the first of the month, the next view to model update will set it
  21652. * to the first of the month.
  21653. *
  21654. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21655. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21656. *
  21657. * @param {string} ngModel Assignable angular expression to data-bind to.
  21658. * @param {string=} name Property name of the form under which the control is published.
  21659. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21660. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  21661. * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
  21662. * native HTML5 constraint validation.
  21663. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21664. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  21665. * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
  21666. * native HTML5 constraint validation.
  21667. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  21668. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21669. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  21670. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21671. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21672. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21673. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21674. * `required` when you want to data-bind to the `required` attribute.
  21675. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21676. * interaction with the input element.
  21677. *
  21678. * @example
  21679. <example name="month-input-directive" module="monthExample">
  21680. <file name="index.html">
  21681. <script>
  21682. angular.module('monthExample', [])
  21683. .controller('DateController', ['$scope', function($scope) {
  21684. $scope.example = {
  21685. value: new Date(2013, 9, 1)
  21686. };
  21687. }]);
  21688. </script>
  21689. <form name="myForm" ng-controller="DateController as dateCtrl">
  21690. <label for="exampleInput">Pick a month in 2013:</label>
  21691. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  21692. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  21693. <div role="alert">
  21694. <span class="error" ng-show="myForm.input.$error.required">
  21695. Required!</span>
  21696. <span class="error" ng-show="myForm.input.$error.month">
  21697. Not a valid month!</span>
  21698. </div>
  21699. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  21700. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21701. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21702. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21703. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21704. </form>
  21705. </file>
  21706. <file name="protractor.js" type="protractor">
  21707. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  21708. var valid = element(by.binding('myForm.input.$valid'));
  21709. // currently protractor/webdriver does not support
  21710. // sending keys to all known HTML5 input controls
  21711. // for various browsers (https://github.com/angular/protractor/issues/562).
  21712. function setInput(val) {
  21713. // set the value of the element and force validation.
  21714. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21715. "ipt.value = '" + val + "';" +
  21716. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21717. browser.executeScript(scr);
  21718. }
  21719. it('should initialize to model', function() {
  21720. expect(value.getText()).toContain('2013-10');
  21721. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21722. });
  21723. it('should be invalid if empty', function() {
  21724. setInput('');
  21725. expect(value.getText()).toEqual('value =');
  21726. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21727. });
  21728. it('should be invalid if over max', function() {
  21729. setInput('2015-01');
  21730. expect(value.getText()).toContain('');
  21731. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21732. });
  21733. </file>
  21734. </example>
  21735. */
  21736. 'month': createDateInputType('month', MONTH_REGEXP,
  21737. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  21738. 'yyyy-MM'),
  21739. /**
  21740. * @ngdoc input
  21741. * @name input[number]
  21742. *
  21743. * @description
  21744. * Text input with number validation and transformation. Sets the `number` validation
  21745. * error if not a valid number.
  21746. *
  21747. * <div class="alert alert-warning">
  21748. * The model must always be of type `number` otherwise Angular will throw an error.
  21749. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  21750. * error docs for more information and an example of how to convert your model if necessary.
  21751. * </div>
  21752. *
  21753. * ## Issues with HTML5 constraint validation
  21754. *
  21755. * In browsers that follow the
  21756. * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
  21757. * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
  21758. * If a non-number is entered in the input, the browser will report the value as an empty string,
  21759. * which means the view / model values in `ngModel` and subsequently the scope value
  21760. * will also be an empty string.
  21761. *
  21762. *
  21763. * @param {string} ngModel Assignable angular expression to data-bind to.
  21764. * @param {string=} name Property name of the form under which the control is published.
  21765. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21766. * Can be interpolated.
  21767. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21768. * Can be interpolated.
  21769. * @param {string=} ngMin Like `min`, sets the `min` validation error key if the value entered is less than `ngMin`,
  21770. * but does not trigger HTML5 native validation. Takes an expression.
  21771. * @param {string=} ngMax Like `max`, sets the `max` validation error key if the value entered is greater than `ngMax`,
  21772. * but does not trigger HTML5 native validation. Takes an expression.
  21773. * @param {string=} step Sets the `step` validation error key if the value entered does not fit the `step` constraint.
  21774. * Can be interpolated.
  21775. * @param {string=} ngStep Like `step`, sets the `max` validation error key if the value entered does not fit the `ngStep` constraint,
  21776. * but does not trigger HTML5 native validation. Takes an expression.
  21777. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21778. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21779. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21780. * `required` when you want to data-bind to the `required` attribute.
  21781. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21782. * minlength.
  21783. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21784. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  21785. * any length.
  21786. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  21787. * that contains the regular expression body that will be converted to a regular expression
  21788. * as in the ngPattern directive.
  21789. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21790. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21791. * If the expression evaluates to a RegExp object, then this is used directly.
  21792. * If the expression evaluates to a string, then it will be converted to a RegExp
  21793. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21794. * `new RegExp('^abc$')`.<br />
  21795. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21796. * start at the index of the last search's match, thus not taking the whole input value into
  21797. * account.
  21798. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21799. * interaction with the input element.
  21800. *
  21801. * @example
  21802. <example name="number-input-directive" module="numberExample">
  21803. <file name="index.html">
  21804. <script>
  21805. angular.module('numberExample', [])
  21806. .controller('ExampleController', ['$scope', function($scope) {
  21807. $scope.example = {
  21808. value: 12
  21809. };
  21810. }]);
  21811. </script>
  21812. <form name="myForm" ng-controller="ExampleController">
  21813. <label>Number:
  21814. <input type="number" name="input" ng-model="example.value"
  21815. min="0" max="99" required>
  21816. </label>
  21817. <div role="alert">
  21818. <span class="error" ng-show="myForm.input.$error.required">
  21819. Required!</span>
  21820. <span class="error" ng-show="myForm.input.$error.number">
  21821. Not valid number!</span>
  21822. </div>
  21823. <tt>value = {{example.value}}</tt><br/>
  21824. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21825. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21826. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21827. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21828. </form>
  21829. </file>
  21830. <file name="protractor.js" type="protractor">
  21831. var value = element(by.binding('example.value'));
  21832. var valid = element(by.binding('myForm.input.$valid'));
  21833. var input = element(by.model('example.value'));
  21834. it('should initialize to model', function() {
  21835. expect(value.getText()).toContain('12');
  21836. expect(valid.getText()).toContain('true');
  21837. });
  21838. it('should be invalid if empty', function() {
  21839. input.clear();
  21840. input.sendKeys('');
  21841. expect(value.getText()).toEqual('value =');
  21842. expect(valid.getText()).toContain('false');
  21843. });
  21844. it('should be invalid if over max', function() {
  21845. input.clear();
  21846. input.sendKeys('123');
  21847. expect(value.getText()).toEqual('value =');
  21848. expect(valid.getText()).toContain('false');
  21849. });
  21850. </file>
  21851. </example>
  21852. */
  21853. 'number': numberInputType,
  21854. /**
  21855. * @ngdoc input
  21856. * @name input[url]
  21857. *
  21858. * @description
  21859. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  21860. * valid URL.
  21861. *
  21862. * <div class="alert alert-warning">
  21863. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  21864. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  21865. * the built-in validators (see the {@link guide/forms Forms guide})
  21866. * </div>
  21867. *
  21868. * @param {string} ngModel Assignable angular expression to data-bind to.
  21869. * @param {string=} name Property name of the form under which the control is published.
  21870. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21871. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21872. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21873. * `required` when you want to data-bind to the `required` attribute.
  21874. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21875. * minlength.
  21876. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21877. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  21878. * any length.
  21879. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  21880. * that contains the regular expression body that will be converted to a regular expression
  21881. * as in the ngPattern directive.
  21882. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21883. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21884. * If the expression evaluates to a RegExp object, then this is used directly.
  21885. * If the expression evaluates to a string, then it will be converted to a RegExp
  21886. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21887. * `new RegExp('^abc$')`.<br />
  21888. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21889. * start at the index of the last search's match, thus not taking the whole input value into
  21890. * account.
  21891. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21892. * interaction with the input element.
  21893. *
  21894. * @example
  21895. <example name="url-input-directive" module="urlExample">
  21896. <file name="index.html">
  21897. <script>
  21898. angular.module('urlExample', [])
  21899. .controller('ExampleController', ['$scope', function($scope) {
  21900. $scope.url = {
  21901. text: 'http://google.com'
  21902. };
  21903. }]);
  21904. </script>
  21905. <form name="myForm" ng-controller="ExampleController">
  21906. <label>URL:
  21907. <input type="url" name="input" ng-model="url.text" required>
  21908. <label>
  21909. <div role="alert">
  21910. <span class="error" ng-show="myForm.input.$error.required">
  21911. Required!</span>
  21912. <span class="error" ng-show="myForm.input.$error.url">
  21913. Not valid url!</span>
  21914. </div>
  21915. <tt>text = {{url.text}}</tt><br/>
  21916. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21917. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21918. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21919. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21920. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  21921. </form>
  21922. </file>
  21923. <file name="protractor.js" type="protractor">
  21924. var text = element(by.binding('url.text'));
  21925. var valid = element(by.binding('myForm.input.$valid'));
  21926. var input = element(by.model('url.text'));
  21927. it('should initialize to model', function() {
  21928. expect(text.getText()).toContain('http://google.com');
  21929. expect(valid.getText()).toContain('true');
  21930. });
  21931. it('should be invalid if empty', function() {
  21932. input.clear();
  21933. input.sendKeys('');
  21934. expect(text.getText()).toEqual('text =');
  21935. expect(valid.getText()).toContain('false');
  21936. });
  21937. it('should be invalid if not url', function() {
  21938. input.clear();
  21939. input.sendKeys('box');
  21940. expect(valid.getText()).toContain('false');
  21941. });
  21942. </file>
  21943. </example>
  21944. */
  21945. 'url': urlInputType,
  21946. /**
  21947. * @ngdoc input
  21948. * @name input[email]
  21949. *
  21950. * @description
  21951. * Text input with email validation. Sets the `email` validation error key if not a valid email
  21952. * address.
  21953. *
  21954. * <div class="alert alert-warning">
  21955. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  21956. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  21957. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  21958. * </div>
  21959. *
  21960. * @param {string} ngModel Assignable angular expression to data-bind to.
  21961. * @param {string=} name Property name of the form under which the control is published.
  21962. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21963. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21964. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21965. * `required` when you want to data-bind to the `required` attribute.
  21966. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21967. * minlength.
  21968. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21969. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  21970. * any length.
  21971. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  21972. * that contains the regular expression body that will be converted to a regular expression
  21973. * as in the ngPattern directive.
  21974. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21975. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21976. * If the expression evaluates to a RegExp object, then this is used directly.
  21977. * If the expression evaluates to a string, then it will be converted to a RegExp
  21978. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21979. * `new RegExp('^abc$')`.<br />
  21980. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21981. * start at the index of the last search's match, thus not taking the whole input value into
  21982. * account.
  21983. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21984. * interaction with the input element.
  21985. *
  21986. * @example
  21987. <example name="email-input-directive" module="emailExample">
  21988. <file name="index.html">
  21989. <script>
  21990. angular.module('emailExample', [])
  21991. .controller('ExampleController', ['$scope', function($scope) {
  21992. $scope.email = {
  21993. text: 'me@example.com'
  21994. };
  21995. }]);
  21996. </script>
  21997. <form name="myForm" ng-controller="ExampleController">
  21998. <label>Email:
  21999. <input type="email" name="input" ng-model="email.text" required>
  22000. </label>
  22001. <div role="alert">
  22002. <span class="error" ng-show="myForm.input.$error.required">
  22003. Required!</span>
  22004. <span class="error" ng-show="myForm.input.$error.email">
  22005. Not valid email!</span>
  22006. </div>
  22007. <tt>text = {{email.text}}</tt><br/>
  22008. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22009. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22010. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22011. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22012. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  22013. </form>
  22014. </file>
  22015. <file name="protractor.js" type="protractor">
  22016. var text = element(by.binding('email.text'));
  22017. var valid = element(by.binding('myForm.input.$valid'));
  22018. var input = element(by.model('email.text'));
  22019. it('should initialize to model', function() {
  22020. expect(text.getText()).toContain('me@example.com');
  22021. expect(valid.getText()).toContain('true');
  22022. });
  22023. it('should be invalid if empty', function() {
  22024. input.clear();
  22025. input.sendKeys('');
  22026. expect(text.getText()).toEqual('text =');
  22027. expect(valid.getText()).toContain('false');
  22028. });
  22029. it('should be invalid if not email', function() {
  22030. input.clear();
  22031. input.sendKeys('xxx');
  22032. expect(valid.getText()).toContain('false');
  22033. });
  22034. </file>
  22035. </example>
  22036. */
  22037. 'email': emailInputType,
  22038. /**
  22039. * @ngdoc input
  22040. * @name input[radio]
  22041. *
  22042. * @description
  22043. * HTML radio button.
  22044. *
  22045. * @param {string} ngModel Assignable angular expression to data-bind to.
  22046. * @param {string} value The value to which the `ngModel` expression should be set when selected.
  22047. * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
  22048. * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
  22049. * @param {string=} name Property name of the form under which the control is published.
  22050. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22051. * interaction with the input element.
  22052. * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
  22053. * is selected. Should be used instead of the `value` attribute if you need
  22054. * a non-string `ngModel` (`boolean`, `array`, ...).
  22055. *
  22056. * @example
  22057. <example name="radio-input-directive" module="radioExample">
  22058. <file name="index.html">
  22059. <script>
  22060. angular.module('radioExample', [])
  22061. .controller('ExampleController', ['$scope', function($scope) {
  22062. $scope.color = {
  22063. name: 'blue'
  22064. };
  22065. $scope.specialValue = {
  22066. "id": "12345",
  22067. "value": "green"
  22068. };
  22069. }]);
  22070. </script>
  22071. <form name="myForm" ng-controller="ExampleController">
  22072. <label>
  22073. <input type="radio" ng-model="color.name" value="red">
  22074. Red
  22075. </label><br/>
  22076. <label>
  22077. <input type="radio" ng-model="color.name" ng-value="specialValue">
  22078. Green
  22079. </label><br/>
  22080. <label>
  22081. <input type="radio" ng-model="color.name" value="blue">
  22082. Blue
  22083. </label><br/>
  22084. <tt>color = {{color.name | json}}</tt><br/>
  22085. </form>
  22086. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  22087. </file>
  22088. <file name="protractor.js" type="protractor">
  22089. it('should change state', function() {
  22090. var inputs = element.all(by.model('color.name'));
  22091. var color = element(by.binding('color.name'));
  22092. expect(color.getText()).toContain('blue');
  22093. inputs.get(0).click();
  22094. expect(color.getText()).toContain('red');
  22095. inputs.get(1).click();
  22096. expect(color.getText()).toContain('green');
  22097. });
  22098. </file>
  22099. </example>
  22100. */
  22101. 'radio': radioInputType,
  22102. /**
  22103. * @ngdoc input
  22104. * @name input[range]
  22105. *
  22106. * @description
  22107. * Native range input with validation and transformation.
  22108. *
  22109. * The model for the range input must always be a `Number`.
  22110. *
  22111. * IE9 and other browsers that do not support the `range` type fall back
  22112. * to a text input without any default values for `min`, `max` and `step`. Model binding,
  22113. * validation and number parsing are nevertheless supported.
  22114. *
  22115. * Browsers that support range (latest Chrome, Safari, Firefox, Edge) treat `input[range]`
  22116. * in a way that never allows the input to hold an invalid value. That means:
  22117. * - any non-numerical value is set to `(max + min) / 2`.
  22118. * - any numerical value that is less than the current min val, or greater than the current max val
  22119. * is set to the min / max val respectively.
  22120. * - additionally, the current `step` is respected, so the nearest value that satisfies a step
  22121. * is used.
  22122. *
  22123. * See the [HTML Spec on input[type=range]](https://www.w3.org/TR/html5/forms.html#range-state-(type=range))
  22124. * for more info.
  22125. *
  22126. * This has the following consequences for Angular:
  22127. *
  22128. * Since the element value should always reflect the current model value, a range input
  22129. * will set the bound ngModel expression to the value that the browser has set for the
  22130. * input element. For example, in the following input `<input type="range" ng-model="model.value">`,
  22131. * if the application sets `model.value = null`, the browser will set the input to `'50'`.
  22132. * Angular will then set the model to `50`, to prevent input and model value being out of sync.
  22133. *
  22134. * That means the model for range will immediately be set to `50` after `ngModel` has been
  22135. * initialized. It also means a range input can never have the required error.
  22136. *
  22137. * This does not only affect changes to the model value, but also to the values of the `min`,
  22138. * `max`, and `step` attributes. When these change in a way that will cause the browser to modify
  22139. * the input value, Angular will also update the model value.
  22140. *
  22141. * Automatic value adjustment also means that a range input element can never have the `required`,
  22142. * `min`, or `max` errors.
  22143. *
  22144. * However, `step` is currently only fully implemented by Firefox. Other browsers have problems
  22145. * when the step value changes dynamically - they do not adjust the element value correctly, but
  22146. * instead may set the `stepMismatch` error. If that's the case, the Angular will set the `step`
  22147. * error on the input, and set the model to `undefined`.
  22148. *
  22149. * Note that `input[range]` is not compatible with`ngMax`, `ngMin`, and `ngStep`, because they do
  22150. * not set the `min` and `max` attributes, which means that the browser won't automatically adjust
  22151. * the input value based on their values, and will always assume min = 0, max = 100, and step = 1.
  22152. *
  22153. * @param {string} ngModel Assignable angular expression to data-bind to.
  22154. * @param {string=} name Property name of the form under which the control is published.
  22155. * @param {string=} min Sets the `min` validation to ensure that the value entered is greater
  22156. * than `min`. Can be interpolated.
  22157. * @param {string=} max Sets the `max` validation to ensure that the value entered is less than `max`.
  22158. * Can be interpolated.
  22159. * @param {string=} step Sets the `step` validation to ensure that the value entered matches the `step`
  22160. * Can be interpolated.
  22161. * @param {string=} ngChange Angular expression to be executed when the ngModel value changes due
  22162. * to user interaction with the input element.
  22163. *
  22164. * @example
  22165. <example name="range-input-directive" module="rangeExample">
  22166. <file name="index.html">
  22167. <script>
  22168. angular.module('rangeExample', [])
  22169. .controller('ExampleController', ['$scope', function($scope) {
  22170. $scope.value = 75;
  22171. $scope.min = 10;
  22172. $scope.max = 90;
  22173. }]);
  22174. </script>
  22175. <form name="myForm" ng-controller="ExampleController">
  22176. Model as range: <input type="range" name="range" ng-model="value" min="{{min}}" max="{{max}}">
  22177. <hr>
  22178. Model as number: <input type="number" ng-model="value"><br>
  22179. Min: <input type="number" ng-model="min"><br>
  22180. Max: <input type="number" ng-model="min"><br>
  22181. value = <code>{{value}}</code><br/>
  22182. myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
  22183. myForm.range.$error = <code>{{myForm.range.$error}}</code>
  22184. </form>
  22185. </file>
  22186. </example>
  22187. * ## Range Input with ngMin & ngMax attributes
  22188. * @example
  22189. <example name="range-input-directive-ng" module="rangeExample">
  22190. <file name="index.html">
  22191. <script>
  22192. angular.module('rangeExample', [])
  22193. .controller('ExampleController', ['$scope', function($scope) {
  22194. $scope.value = 75;
  22195. $scope.min = 10;
  22196. $scope.max = 90;
  22197. }]);
  22198. </script>
  22199. <form name="myForm" ng-controller="ExampleController">
  22200. Model as range: <input type="range" name="range" ng-model="value" ng-min="min" ng-max="max">
  22201. <hr>
  22202. Model as number: <input type="number" ng-model="value"><br>
  22203. Min: <input type="number" ng-model="min"><br>
  22204. Max: <input type="number" ng-model="min"><br>
  22205. value = <code>{{value}}</code><br/>
  22206. myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
  22207. myForm.range.$error = <code>{{myForm.range.$error}}</code>
  22208. </form>
  22209. </file>
  22210. </example>
  22211. */
  22212. 'range': rangeInputType,
  22213. /**
  22214. * @ngdoc input
  22215. * @name input[checkbox]
  22216. *
  22217. * @description
  22218. * HTML checkbox.
  22219. *
  22220. * @param {string} ngModel Assignable angular expression to data-bind to.
  22221. * @param {string=} name Property name of the form under which the control is published.
  22222. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  22223. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  22224. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22225. * interaction with the input element.
  22226. *
  22227. * @example
  22228. <example name="checkbox-input-directive" module="checkboxExample">
  22229. <file name="index.html">
  22230. <script>
  22231. angular.module('checkboxExample', [])
  22232. .controller('ExampleController', ['$scope', function($scope) {
  22233. $scope.checkboxModel = {
  22234. value1 : true,
  22235. value2 : 'YES'
  22236. };
  22237. }]);
  22238. </script>
  22239. <form name="myForm" ng-controller="ExampleController">
  22240. <label>Value1:
  22241. <input type="checkbox" ng-model="checkboxModel.value1">
  22242. </label><br/>
  22243. <label>Value2:
  22244. <input type="checkbox" ng-model="checkboxModel.value2"
  22245. ng-true-value="'YES'" ng-false-value="'NO'">
  22246. </label><br/>
  22247. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  22248. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  22249. </form>
  22250. </file>
  22251. <file name="protractor.js" type="protractor">
  22252. it('should change state', function() {
  22253. var value1 = element(by.binding('checkboxModel.value1'));
  22254. var value2 = element(by.binding('checkboxModel.value2'));
  22255. expect(value1.getText()).toContain('true');
  22256. expect(value2.getText()).toContain('YES');
  22257. element(by.model('checkboxModel.value1')).click();
  22258. element(by.model('checkboxModel.value2')).click();
  22259. expect(value1.getText()).toContain('false');
  22260. expect(value2.getText()).toContain('NO');
  22261. });
  22262. </file>
  22263. </example>
  22264. */
  22265. 'checkbox': checkboxInputType,
  22266. 'hidden': noop,
  22267. 'button': noop,
  22268. 'submit': noop,
  22269. 'reset': noop,
  22270. 'file': noop
  22271. };
  22272. function stringBasedInputType(ctrl) {
  22273. ctrl.$formatters.push(function(value) {
  22274. return ctrl.$isEmpty(value) ? value : value.toString();
  22275. });
  22276. }
  22277. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22278. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22279. stringBasedInputType(ctrl);
  22280. }
  22281. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22282. var type = lowercase(element[0].type);
  22283. // In composition mode, users are still inputing intermediate text buffer,
  22284. // hold the listener until composition is done.
  22285. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  22286. if (!$sniffer.android) {
  22287. var composing = false;
  22288. element.on('compositionstart', function() {
  22289. composing = true;
  22290. });
  22291. element.on('compositionend', function() {
  22292. composing = false;
  22293. listener();
  22294. });
  22295. }
  22296. var timeout;
  22297. var listener = function(ev) {
  22298. if (timeout) {
  22299. $browser.defer.cancel(timeout);
  22300. timeout = null;
  22301. }
  22302. if (composing) return;
  22303. var value = element.val(),
  22304. event = ev && ev.type;
  22305. // By default we will trim the value
  22306. // If the attribute ng-trim exists we will avoid trimming
  22307. // If input type is 'password', the value is never trimmed
  22308. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  22309. value = trim(value);
  22310. }
  22311. // If a control is suffering from bad input (due to native validators), browsers discard its
  22312. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  22313. // control's value is the same empty value twice in a row.
  22314. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  22315. ctrl.$setViewValue(value, event);
  22316. }
  22317. };
  22318. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  22319. // input event on backspace, delete or cut
  22320. if ($sniffer.hasEvent('input')) {
  22321. element.on('input', listener);
  22322. } else {
  22323. var deferListener = function(ev, input, origValue) {
  22324. if (!timeout) {
  22325. timeout = $browser.defer(function() {
  22326. timeout = null;
  22327. if (!input || input.value !== origValue) {
  22328. listener(ev);
  22329. }
  22330. });
  22331. }
  22332. };
  22333. element.on('keydown', /** @this */ function(event) {
  22334. var key = event.keyCode;
  22335. // ignore
  22336. // command modifiers arrows
  22337. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  22338. deferListener(event, this, this.value);
  22339. });
  22340. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  22341. if ($sniffer.hasEvent('paste')) {
  22342. element.on('paste cut', deferListener);
  22343. }
  22344. }
  22345. // if user paste into input using mouse on older browser
  22346. // or form autocomplete on newer browser, we need "change" event to catch it
  22347. element.on('change', listener);
  22348. // Some native input types (date-family) have the ability to change validity without
  22349. // firing any input/change events.
  22350. // For these event types, when native validators are present and the browser supports the type,
  22351. // check for validity changes on various DOM events.
  22352. if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) {
  22353. element.on(PARTIAL_VALIDATION_EVENTS, /** @this */ function(ev) {
  22354. if (!timeout) {
  22355. var validity = this[VALIDITY_STATE_PROPERTY];
  22356. var origBadInput = validity.badInput;
  22357. var origTypeMismatch = validity.typeMismatch;
  22358. timeout = $browser.defer(function() {
  22359. timeout = null;
  22360. if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) {
  22361. listener(ev);
  22362. }
  22363. });
  22364. }
  22365. });
  22366. }
  22367. ctrl.$render = function() {
  22368. // Workaround for Firefox validation #12102.
  22369. var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
  22370. if (element.val() !== value) {
  22371. element.val(value);
  22372. }
  22373. };
  22374. }
  22375. function weekParser(isoWeek, existingDate) {
  22376. if (isDate(isoWeek)) {
  22377. return isoWeek;
  22378. }
  22379. if (isString(isoWeek)) {
  22380. WEEK_REGEXP.lastIndex = 0;
  22381. var parts = WEEK_REGEXP.exec(isoWeek);
  22382. if (parts) {
  22383. var year = +parts[1],
  22384. week = +parts[2],
  22385. hours = 0,
  22386. minutes = 0,
  22387. seconds = 0,
  22388. milliseconds = 0,
  22389. firstThurs = getFirstThursdayOfYear(year),
  22390. addDays = (week - 1) * 7;
  22391. if (existingDate) {
  22392. hours = existingDate.getHours();
  22393. minutes = existingDate.getMinutes();
  22394. seconds = existingDate.getSeconds();
  22395. milliseconds = existingDate.getMilliseconds();
  22396. }
  22397. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  22398. }
  22399. }
  22400. return NaN;
  22401. }
  22402. function createDateParser(regexp, mapping) {
  22403. return function(iso, date) {
  22404. var parts, map;
  22405. if (isDate(iso)) {
  22406. return iso;
  22407. }
  22408. if (isString(iso)) {
  22409. // When a date is JSON'ified to wraps itself inside of an extra
  22410. // set of double quotes. This makes the date parsing code unable
  22411. // to match the date string and parse it as a date.
  22412. if (iso.charAt(0) === '"' && iso.charAt(iso.length - 1) === '"') {
  22413. iso = iso.substring(1, iso.length - 1);
  22414. }
  22415. if (ISO_DATE_REGEXP.test(iso)) {
  22416. return new Date(iso);
  22417. }
  22418. regexp.lastIndex = 0;
  22419. parts = regexp.exec(iso);
  22420. if (parts) {
  22421. parts.shift();
  22422. if (date) {
  22423. map = {
  22424. yyyy: date.getFullYear(),
  22425. MM: date.getMonth() + 1,
  22426. dd: date.getDate(),
  22427. HH: date.getHours(),
  22428. mm: date.getMinutes(),
  22429. ss: date.getSeconds(),
  22430. sss: date.getMilliseconds() / 1000
  22431. };
  22432. } else {
  22433. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  22434. }
  22435. forEach(parts, function(part, index) {
  22436. if (index < mapping.length) {
  22437. map[mapping[index]] = +part;
  22438. }
  22439. });
  22440. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  22441. }
  22442. }
  22443. return NaN;
  22444. };
  22445. }
  22446. function createDateInputType(type, regexp, parseDate, format) {
  22447. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  22448. badInputChecker(scope, element, attr, ctrl);
  22449. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22450. var timezone = ctrl && ctrl.$options.getOption('timezone');
  22451. var previousDate;
  22452. ctrl.$$parserName = type;
  22453. ctrl.$parsers.push(function(value) {
  22454. if (ctrl.$isEmpty(value)) return null;
  22455. if (regexp.test(value)) {
  22456. // Note: We cannot read ctrl.$modelValue, as there might be a different
  22457. // parser/formatter in the processing chain so that the model
  22458. // contains some different data format!
  22459. var parsedDate = parseDate(value, previousDate);
  22460. if (timezone) {
  22461. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  22462. }
  22463. return parsedDate;
  22464. }
  22465. return undefined;
  22466. });
  22467. ctrl.$formatters.push(function(value) {
  22468. if (value && !isDate(value)) {
  22469. throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  22470. }
  22471. if (isValidDate(value)) {
  22472. previousDate = value;
  22473. if (previousDate && timezone) {
  22474. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  22475. }
  22476. return $filter('date')(value, format, timezone);
  22477. } else {
  22478. previousDate = null;
  22479. return '';
  22480. }
  22481. });
  22482. if (isDefined(attr.min) || attr.ngMin) {
  22483. var minVal;
  22484. ctrl.$validators.min = function(value) {
  22485. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  22486. };
  22487. attr.$observe('min', function(val) {
  22488. minVal = parseObservedDateValue(val);
  22489. ctrl.$validate();
  22490. });
  22491. }
  22492. if (isDefined(attr.max) || attr.ngMax) {
  22493. var maxVal;
  22494. ctrl.$validators.max = function(value) {
  22495. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  22496. };
  22497. attr.$observe('max', function(val) {
  22498. maxVal = parseObservedDateValue(val);
  22499. ctrl.$validate();
  22500. });
  22501. }
  22502. function isValidDate(value) {
  22503. // Invalid Date: getTime() returns NaN
  22504. return value && !(value.getTime && value.getTime() !== value.getTime());
  22505. }
  22506. function parseObservedDateValue(val) {
  22507. return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
  22508. }
  22509. };
  22510. }
  22511. function badInputChecker(scope, element, attr, ctrl) {
  22512. var node = element[0];
  22513. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  22514. if (nativeValidation) {
  22515. ctrl.$parsers.push(function(value) {
  22516. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  22517. return validity.badInput || validity.typeMismatch ? undefined : value;
  22518. });
  22519. }
  22520. }
  22521. function numberFormatterParser(ctrl) {
  22522. ctrl.$$parserName = 'number';
  22523. ctrl.$parsers.push(function(value) {
  22524. if (ctrl.$isEmpty(value)) return null;
  22525. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  22526. return undefined;
  22527. });
  22528. ctrl.$formatters.push(function(value) {
  22529. if (!ctrl.$isEmpty(value)) {
  22530. if (!isNumber(value)) {
  22531. throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  22532. }
  22533. value = value.toString();
  22534. }
  22535. return value;
  22536. });
  22537. }
  22538. function parseNumberAttrVal(val) {
  22539. if (isDefined(val) && !isNumber(val)) {
  22540. val = parseFloat(val);
  22541. }
  22542. return !isNumberNaN(val) ? val : undefined;
  22543. }
  22544. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22545. badInputChecker(scope, element, attr, ctrl);
  22546. numberFormatterParser(ctrl);
  22547. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22548. if (isDefined(attr.min) || attr.ngMin) {
  22549. var minVal;
  22550. ctrl.$validators.min = function(value) {
  22551. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  22552. };
  22553. attr.$observe('min', function(val) {
  22554. minVal = parseNumberAttrVal(val);
  22555. // TODO(matsko): implement validateLater to reduce number of validations
  22556. ctrl.$validate();
  22557. });
  22558. }
  22559. if (isDefined(attr.max) || attr.ngMax) {
  22560. var maxVal;
  22561. ctrl.$validators.max = function(value) {
  22562. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  22563. };
  22564. attr.$observe('max', function(val) {
  22565. maxVal = parseNumberAttrVal(val);
  22566. // TODO(matsko): implement validateLater to reduce number of validations
  22567. ctrl.$validate();
  22568. });
  22569. }
  22570. if (isDefined(attr.step) || attr.ngStep) {
  22571. var stepVal;
  22572. ctrl.$validators.step = function(modelValue, viewValue) {
  22573. return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) || viewValue % stepVal === 0;
  22574. };
  22575. attr.$observe('step', function(val) {
  22576. stepVal = parseNumberAttrVal(val);
  22577. // TODO(matsko): implement validateLater to reduce number of validations
  22578. ctrl.$validate();
  22579. });
  22580. }
  22581. }
  22582. function rangeInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22583. badInputChecker(scope, element, attr, ctrl);
  22584. numberFormatterParser(ctrl);
  22585. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22586. var supportsRange = ctrl.$$hasNativeValidators && element[0].type === 'range',
  22587. minVal = supportsRange ? 0 : undefined,
  22588. maxVal = supportsRange ? 100 : undefined,
  22589. stepVal = supportsRange ? 1 : undefined,
  22590. validity = element[0].validity,
  22591. hasMinAttr = isDefined(attr.min),
  22592. hasMaxAttr = isDefined(attr.max),
  22593. hasStepAttr = isDefined(attr.step);
  22594. var originalRender = ctrl.$render;
  22595. ctrl.$render = supportsRange && isDefined(validity.rangeUnderflow) && isDefined(validity.rangeOverflow) ?
  22596. //Browsers that implement range will set these values automatically, but reading the adjusted values after
  22597. //$render would cause the min / max validators to be applied with the wrong value
  22598. function rangeRender() {
  22599. originalRender();
  22600. ctrl.$setViewValue(element.val());
  22601. } :
  22602. originalRender;
  22603. if (hasMinAttr) {
  22604. ctrl.$validators.min = supportsRange ?
  22605. // Since all browsers set the input to a valid value, we don't need to check validity
  22606. function noopMinValidator() { return true; } :
  22607. // non-support browsers validate the min val
  22608. function minValidator(modelValue, viewValue) {
  22609. return ctrl.$isEmpty(viewValue) || isUndefined(minVal) || viewValue >= minVal;
  22610. };
  22611. setInitialValueAndObserver('min', minChange);
  22612. }
  22613. if (hasMaxAttr) {
  22614. ctrl.$validators.max = supportsRange ?
  22615. // Since all browsers set the input to a valid value, we don't need to check validity
  22616. function noopMaxValidator() { return true; } :
  22617. // non-support browsers validate the max val
  22618. function maxValidator(modelValue, viewValue) {
  22619. return ctrl.$isEmpty(viewValue) || isUndefined(maxVal) || viewValue <= maxVal;
  22620. };
  22621. setInitialValueAndObserver('max', maxChange);
  22622. }
  22623. if (hasStepAttr) {
  22624. ctrl.$validators.step = supportsRange ?
  22625. function nativeStepValidator() {
  22626. // Currently, only FF implements the spec on step change correctly (i.e. adjusting the
  22627. // input element value to a valid value). It's possible that other browsers set the stepMismatch
  22628. // validity error instead, so we can at least report an error in that case.
  22629. return !validity.stepMismatch;
  22630. } :
  22631. // ngStep doesn't set the setp attr, so the browser doesn't adjust the input value as setting step would
  22632. function stepValidator(modelValue, viewValue) {
  22633. return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) || viewValue % stepVal === 0;
  22634. };
  22635. setInitialValueAndObserver('step', stepChange);
  22636. }
  22637. function setInitialValueAndObserver(htmlAttrName, changeFn) {
  22638. // interpolated attributes set the attribute value only after a digest, but we need the
  22639. // attribute value when the input is first rendered, so that the browser can adjust the
  22640. // input value based on the min/max value
  22641. element.attr(htmlAttrName, attr[htmlAttrName]);
  22642. attr.$observe(htmlAttrName, changeFn);
  22643. }
  22644. function minChange(val) {
  22645. minVal = parseNumberAttrVal(val);
  22646. // ignore changes before model is initialized
  22647. if (isNumberNaN(ctrl.$modelValue)) {
  22648. return;
  22649. }
  22650. if (supportsRange) {
  22651. var elVal = element.val();
  22652. // IE11 doesn't set the el val correctly if the minVal is greater than the element value
  22653. if (minVal > elVal) {
  22654. elVal = minVal;
  22655. element.val(elVal);
  22656. }
  22657. ctrl.$setViewValue(elVal);
  22658. } else {
  22659. // TODO(matsko): implement validateLater to reduce number of validations
  22660. ctrl.$validate();
  22661. }
  22662. }
  22663. function maxChange(val) {
  22664. maxVal = parseNumberAttrVal(val);
  22665. // ignore changes before model is initialized
  22666. if (isNumberNaN(ctrl.$modelValue)) {
  22667. return;
  22668. }
  22669. if (supportsRange) {
  22670. var elVal = element.val();
  22671. // IE11 doesn't set the el val correctly if the maxVal is less than the element value
  22672. if (maxVal < elVal) {
  22673. element.val(maxVal);
  22674. // IE11 and Chrome don't set the value to the minVal when max < min
  22675. elVal = maxVal < minVal ? minVal : maxVal;
  22676. }
  22677. ctrl.$setViewValue(elVal);
  22678. } else {
  22679. // TODO(matsko): implement validateLater to reduce number of validations
  22680. ctrl.$validate();
  22681. }
  22682. }
  22683. function stepChange(val) {
  22684. stepVal = parseNumberAttrVal(val);
  22685. // ignore changes before model is initialized
  22686. if (isNumberNaN(ctrl.$modelValue)) {
  22687. return;
  22688. }
  22689. // Some browsers don't adjust the input value correctly, but set the stepMismatch error
  22690. if (supportsRange && ctrl.$viewValue !== element.val()) {
  22691. ctrl.$setViewValue(element.val());
  22692. } else {
  22693. // TODO(matsko): implement validateLater to reduce number of validations
  22694. ctrl.$validate();
  22695. }
  22696. }
  22697. }
  22698. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22699. // Note: no badInputChecker here by purpose as `url` is only a validation
  22700. // in browsers, i.e. we can always read out input.value even if it is not valid!
  22701. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22702. stringBasedInputType(ctrl);
  22703. ctrl.$$parserName = 'url';
  22704. ctrl.$validators.url = function(modelValue, viewValue) {
  22705. var value = modelValue || viewValue;
  22706. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  22707. };
  22708. }
  22709. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22710. // Note: no badInputChecker here by purpose as `url` is only a validation
  22711. // in browsers, i.e. we can always read out input.value even if it is not valid!
  22712. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22713. stringBasedInputType(ctrl);
  22714. ctrl.$$parserName = 'email';
  22715. ctrl.$validators.email = function(modelValue, viewValue) {
  22716. var value = modelValue || viewValue;
  22717. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  22718. };
  22719. }
  22720. function radioInputType(scope, element, attr, ctrl) {
  22721. var doTrim = !attr.ngTrim || trim(attr.ngTrim) !== 'false';
  22722. // make the name unique, if not defined
  22723. if (isUndefined(attr.name)) {
  22724. element.attr('name', nextUid());
  22725. }
  22726. var listener = function(ev) {
  22727. var value;
  22728. if (element[0].checked) {
  22729. value = attr.value;
  22730. if (doTrim) {
  22731. value = trim(value);
  22732. }
  22733. ctrl.$setViewValue(value, ev && ev.type);
  22734. }
  22735. };
  22736. element.on('click', listener);
  22737. ctrl.$render = function() {
  22738. var value = attr.value;
  22739. if (doTrim) {
  22740. value = trim(value);
  22741. }
  22742. // Strict comparison would cause a BC
  22743. // eslint-disable-next-line eqeqeq
  22744. element[0].checked = (value == ctrl.$viewValue);
  22745. };
  22746. attr.$observe('value', ctrl.$render);
  22747. }
  22748. function parseConstantExpr($parse, context, name, expression, fallback) {
  22749. var parseFn;
  22750. if (isDefined(expression)) {
  22751. parseFn = $parse(expression);
  22752. if (!parseFn.constant) {
  22753. throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  22754. '`{1}`.', name, expression);
  22755. }
  22756. return parseFn(context);
  22757. }
  22758. return fallback;
  22759. }
  22760. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  22761. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  22762. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  22763. var listener = function(ev) {
  22764. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  22765. };
  22766. element.on('click', listener);
  22767. ctrl.$render = function() {
  22768. element[0].checked = ctrl.$viewValue;
  22769. };
  22770. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  22771. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  22772. // it to a boolean.
  22773. ctrl.$isEmpty = function(value) {
  22774. return value === false;
  22775. };
  22776. ctrl.$formatters.push(function(value) {
  22777. return equals(value, trueValue);
  22778. });
  22779. ctrl.$parsers.push(function(value) {
  22780. return value ? trueValue : falseValue;
  22781. });
  22782. }
  22783. /**
  22784. * @ngdoc directive
  22785. * @name textarea
  22786. * @restrict E
  22787. *
  22788. * @description
  22789. * HTML textarea element control with angular data-binding. The data-binding and validation
  22790. * properties of this element are exactly the same as those of the
  22791. * {@link ng.directive:input input element}.
  22792. *
  22793. * @param {string} ngModel Assignable angular expression to data-bind to.
  22794. * @param {string=} name Property name of the form under which the control is published.
  22795. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22796. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22797. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22798. * `required` when you want to data-bind to the `required` attribute.
  22799. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22800. * minlength.
  22801. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22802. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  22803. * length.
  22804. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22805. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  22806. * If the expression evaluates to a RegExp object, then this is used directly.
  22807. * If the expression evaluates to a string, then it will be converted to a RegExp
  22808. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22809. * `new RegExp('^abc$')`.<br />
  22810. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22811. * start at the index of the last search's match, thus not taking the whole input value into
  22812. * account.
  22813. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22814. * interaction with the input element.
  22815. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  22816. *
  22817. * @knownIssue
  22818. *
  22819. * When specifying the `placeholder` attribute of `<textarea>`, Internet Explorer will temporarily
  22820. * insert the placeholder value as the textarea's content. If the placeholder value contains
  22821. * interpolation (`{{ ... }}`), an error will be logged in the console when Angular tries to update
  22822. * the value of the by-then-removed text node. This doesn't affect the functionality of the
  22823. * textarea, but can be undesirable.
  22824. *
  22825. * You can work around this Internet Explorer issue by using `ng-attr-placeholder` instead of
  22826. * `placeholder` on textareas, whenever you need interpolation in the placeholder value. You can
  22827. * find more details on `ngAttr` in the
  22828. * [Interpolation](guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes) section of the
  22829. * Developer Guide.
  22830. */
  22831. /**
  22832. * @ngdoc directive
  22833. * @name input
  22834. * @restrict E
  22835. *
  22836. * @description
  22837. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  22838. * input state control, and validation.
  22839. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  22840. *
  22841. * <div class="alert alert-warning">
  22842. * **Note:** Not every feature offered is available for all input types.
  22843. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  22844. * </div>
  22845. *
  22846. * @param {string} ngModel Assignable angular expression to data-bind to.
  22847. * @param {string=} name Property name of the form under which the control is published.
  22848. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22849. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  22850. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22851. * minlength.
  22852. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22853. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  22854. * length.
  22855. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22856. * value does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  22857. * If the expression evaluates to a RegExp object, then this is used directly.
  22858. * If the expression evaluates to a string, then it will be converted to a RegExp
  22859. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22860. * `new RegExp('^abc$')`.<br />
  22861. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22862. * start at the index of the last search's match, thus not taking the whole input value into
  22863. * account.
  22864. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22865. * interaction with the input element.
  22866. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  22867. * This parameter is ignored for input[type=password] controls, which will never trim the
  22868. * input.
  22869. *
  22870. * @example
  22871. <example name="input-directive" module="inputExample">
  22872. <file name="index.html">
  22873. <script>
  22874. angular.module('inputExample', [])
  22875. .controller('ExampleController', ['$scope', function($scope) {
  22876. $scope.user = {name: 'guest', last: 'visitor'};
  22877. }]);
  22878. </script>
  22879. <div ng-controller="ExampleController">
  22880. <form name="myForm">
  22881. <label>
  22882. User name:
  22883. <input type="text" name="userName" ng-model="user.name" required>
  22884. </label>
  22885. <div role="alert">
  22886. <span class="error" ng-show="myForm.userName.$error.required">
  22887. Required!</span>
  22888. </div>
  22889. <label>
  22890. Last name:
  22891. <input type="text" name="lastName" ng-model="user.last"
  22892. ng-minlength="3" ng-maxlength="10">
  22893. </label>
  22894. <div role="alert">
  22895. <span class="error" ng-show="myForm.lastName.$error.minlength">
  22896. Too short!</span>
  22897. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  22898. Too long!</span>
  22899. </div>
  22900. </form>
  22901. <hr>
  22902. <tt>user = {{user}}</tt><br/>
  22903. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  22904. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  22905. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  22906. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  22907. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22908. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22909. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  22910. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  22911. </div>
  22912. </file>
  22913. <file name="protractor.js" type="protractor">
  22914. var user = element(by.exactBinding('user'));
  22915. var userNameValid = element(by.binding('myForm.userName.$valid'));
  22916. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  22917. var lastNameError = element(by.binding('myForm.lastName.$error'));
  22918. var formValid = element(by.binding('myForm.$valid'));
  22919. var userNameInput = element(by.model('user.name'));
  22920. var userLastInput = element(by.model('user.last'));
  22921. it('should initialize to model', function() {
  22922. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  22923. expect(userNameValid.getText()).toContain('true');
  22924. expect(formValid.getText()).toContain('true');
  22925. });
  22926. it('should be invalid if empty when required', function() {
  22927. userNameInput.clear();
  22928. userNameInput.sendKeys('');
  22929. expect(user.getText()).toContain('{"last":"visitor"}');
  22930. expect(userNameValid.getText()).toContain('false');
  22931. expect(formValid.getText()).toContain('false');
  22932. });
  22933. it('should be valid if empty when min length is set', function() {
  22934. userLastInput.clear();
  22935. userLastInput.sendKeys('');
  22936. expect(user.getText()).toContain('{"name":"guest","last":""}');
  22937. expect(lastNameValid.getText()).toContain('true');
  22938. expect(formValid.getText()).toContain('true');
  22939. });
  22940. it('should be invalid if less than required min length', function() {
  22941. userLastInput.clear();
  22942. userLastInput.sendKeys('xx');
  22943. expect(user.getText()).toContain('{"name":"guest"}');
  22944. expect(lastNameValid.getText()).toContain('false');
  22945. expect(lastNameError.getText()).toContain('minlength');
  22946. expect(formValid.getText()).toContain('false');
  22947. });
  22948. it('should be invalid if longer than max length', function() {
  22949. userLastInput.clear();
  22950. userLastInput.sendKeys('some ridiculously long name');
  22951. expect(user.getText()).toContain('{"name":"guest"}');
  22952. expect(lastNameValid.getText()).toContain('false');
  22953. expect(lastNameError.getText()).toContain('maxlength');
  22954. expect(formValid.getText()).toContain('false');
  22955. });
  22956. </file>
  22957. </example>
  22958. */
  22959. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  22960. function($browser, $sniffer, $filter, $parse) {
  22961. return {
  22962. restrict: 'E',
  22963. require: ['?ngModel'],
  22964. link: {
  22965. pre: function(scope, element, attr, ctrls) {
  22966. if (ctrls[0]) {
  22967. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  22968. $browser, $filter, $parse);
  22969. }
  22970. }
  22971. }
  22972. };
  22973. }];
  22974. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  22975. /**
  22976. * @ngdoc directive
  22977. * @name ngValue
  22978. *
  22979. * @description
  22980. * Binds the given expression to the value of the element.
  22981. *
  22982. * It is mainly used on {@link input[radio] `input[radio]`} and option elements,
  22983. * so that when the element is selected, the {@link ngModel `ngModel`} of that element (or its
  22984. * {@link select `select`} parent element) is set to the bound value. It is especially useful
  22985. * for dynamically generated lists using {@link ngRepeat `ngRepeat`}, as shown below.
  22986. *
  22987. * It can also be used to achieve one-way binding of a given expression to an input element
  22988. * such as an `input[text]` or a `textarea`, when that element does not use ngModel.
  22989. *
  22990. * @element input
  22991. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  22992. * and `value` property of the element.
  22993. *
  22994. * @example
  22995. <example name="ngValue-directive" module="valueExample">
  22996. <file name="index.html">
  22997. <script>
  22998. angular.module('valueExample', [])
  22999. .controller('ExampleController', ['$scope', function($scope) {
  23000. $scope.names = ['pizza', 'unicorns', 'robots'];
  23001. $scope.my = { favorite: 'unicorns' };
  23002. }]);
  23003. </script>
  23004. <form ng-controller="ExampleController">
  23005. <h2>Which is your favorite?</h2>
  23006. <label ng-repeat="name in names" for="{{name}}">
  23007. {{name}}
  23008. <input type="radio"
  23009. ng-model="my.favorite"
  23010. ng-value="name"
  23011. id="{{name}}"
  23012. name="favorite">
  23013. </label>
  23014. <div>You chose {{my.favorite}}</div>
  23015. </form>
  23016. </file>
  23017. <file name="protractor.js" type="protractor">
  23018. var favorite = element(by.binding('my.favorite'));
  23019. it('should initialize to model', function() {
  23020. expect(favorite.getText()).toContain('unicorns');
  23021. });
  23022. it('should bind the values to the inputs', function() {
  23023. element.all(by.model('my.favorite')).get(0).click();
  23024. expect(favorite.getText()).toContain('pizza');
  23025. });
  23026. </file>
  23027. </example>
  23028. */
  23029. var ngValueDirective = function() {
  23030. /**
  23031. * inputs use the value attribute as their default value if the value property is not set.
  23032. * Once the value property has been set (by adding input), it will not react to changes to
  23033. * the value attribute anymore. Setting both attribute and property fixes this behavior, and
  23034. * makes it possible to use ngValue as a sort of one-way bind.
  23035. */
  23036. function updateElementValue(element, attr, value) {
  23037. element.prop('value', value);
  23038. attr.$set('value', value);
  23039. }
  23040. return {
  23041. restrict: 'A',
  23042. priority: 100,
  23043. compile: function(tpl, tplAttr) {
  23044. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  23045. return function ngValueConstantLink(scope, elm, attr) {
  23046. var value = scope.$eval(attr.ngValue);
  23047. updateElementValue(elm, attr, value);
  23048. };
  23049. } else {
  23050. return function ngValueLink(scope, elm, attr) {
  23051. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  23052. updateElementValue(elm, attr, value);
  23053. });
  23054. };
  23055. }
  23056. }
  23057. };
  23058. };
  23059. /**
  23060. * @ngdoc directive
  23061. * @name ngBind
  23062. * @restrict AC
  23063. *
  23064. * @description
  23065. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  23066. * with the value of a given expression, and to update the text content when the value of that
  23067. * expression changes.
  23068. *
  23069. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  23070. * `{{ expression }}` which is similar but less verbose.
  23071. *
  23072. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  23073. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  23074. * element attribute, it makes the bindings invisible to the user while the page is loading.
  23075. *
  23076. * An alternative solution to this problem would be using the
  23077. * {@link ng.directive:ngCloak ngCloak} directive.
  23078. *
  23079. *
  23080. * @element ANY
  23081. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  23082. *
  23083. * @example
  23084. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  23085. <example module="bindExample" name="ng-bind">
  23086. <file name="index.html">
  23087. <script>
  23088. angular.module('bindExample', [])
  23089. .controller('ExampleController', ['$scope', function($scope) {
  23090. $scope.name = 'Whirled';
  23091. }]);
  23092. </script>
  23093. <div ng-controller="ExampleController">
  23094. <label>Enter name: <input type="text" ng-model="name"></label><br>
  23095. Hello <span ng-bind="name"></span>!
  23096. </div>
  23097. </file>
  23098. <file name="protractor.js" type="protractor">
  23099. it('should check ng-bind', function() {
  23100. var nameInput = element(by.model('name'));
  23101. expect(element(by.binding('name')).getText()).toBe('Whirled');
  23102. nameInput.clear();
  23103. nameInput.sendKeys('world');
  23104. expect(element(by.binding('name')).getText()).toBe('world');
  23105. });
  23106. </file>
  23107. </example>
  23108. */
  23109. var ngBindDirective = ['$compile', function($compile) {
  23110. return {
  23111. restrict: 'AC',
  23112. compile: function ngBindCompile(templateElement) {
  23113. $compile.$$addBindingClass(templateElement);
  23114. return function ngBindLink(scope, element, attr) {
  23115. $compile.$$addBindingInfo(element, attr.ngBind);
  23116. element = element[0];
  23117. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  23118. element.textContent = stringify(value);
  23119. });
  23120. };
  23121. }
  23122. };
  23123. }];
  23124. /**
  23125. * @ngdoc directive
  23126. * @name ngBindTemplate
  23127. *
  23128. * @description
  23129. * The `ngBindTemplate` directive specifies that the element
  23130. * text content should be replaced with the interpolation of the template
  23131. * in the `ngBindTemplate` attribute.
  23132. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  23133. * expressions. This directive is needed since some HTML elements
  23134. * (such as TITLE and OPTION) cannot contain SPAN elements.
  23135. *
  23136. * @element ANY
  23137. * @param {string} ngBindTemplate template of form
  23138. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  23139. *
  23140. * @example
  23141. * Try it here: enter text in text box and watch the greeting change.
  23142. <example module="bindExample" name="ng-bind-template">
  23143. <file name="index.html">
  23144. <script>
  23145. angular.module('bindExample', [])
  23146. .controller('ExampleController', ['$scope', function($scope) {
  23147. $scope.salutation = 'Hello';
  23148. $scope.name = 'World';
  23149. }]);
  23150. </script>
  23151. <div ng-controller="ExampleController">
  23152. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  23153. <label>Name: <input type="text" ng-model="name"></label><br>
  23154. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  23155. </div>
  23156. </file>
  23157. <file name="protractor.js" type="protractor">
  23158. it('should check ng-bind', function() {
  23159. var salutationElem = element(by.binding('salutation'));
  23160. var salutationInput = element(by.model('salutation'));
  23161. var nameInput = element(by.model('name'));
  23162. expect(salutationElem.getText()).toBe('Hello World!');
  23163. salutationInput.clear();
  23164. salutationInput.sendKeys('Greetings');
  23165. nameInput.clear();
  23166. nameInput.sendKeys('user');
  23167. expect(salutationElem.getText()).toBe('Greetings user!');
  23168. });
  23169. </file>
  23170. </example>
  23171. */
  23172. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  23173. return {
  23174. compile: function ngBindTemplateCompile(templateElement) {
  23175. $compile.$$addBindingClass(templateElement);
  23176. return function ngBindTemplateLink(scope, element, attr) {
  23177. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  23178. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  23179. element = element[0];
  23180. attr.$observe('ngBindTemplate', function(value) {
  23181. element.textContent = isUndefined(value) ? '' : value;
  23182. });
  23183. };
  23184. }
  23185. };
  23186. }];
  23187. /**
  23188. * @ngdoc directive
  23189. * @name ngBindHtml
  23190. *
  23191. * @description
  23192. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  23193. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  23194. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  23195. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  23196. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  23197. *
  23198. * You may also bypass sanitization for values you know are safe. To do so, bind to
  23199. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  23200. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  23201. *
  23202. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  23203. * will have an exception (instead of an exploit.)
  23204. *
  23205. * @element ANY
  23206. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  23207. *
  23208. * @example
  23209. <example module="bindHtmlExample" deps="angular-sanitize.js" name="ng-bind-html">
  23210. <file name="index.html">
  23211. <div ng-controller="ExampleController">
  23212. <p ng-bind-html="myHTML"></p>
  23213. </div>
  23214. </file>
  23215. <file name="script.js">
  23216. angular.module('bindHtmlExample', ['ngSanitize'])
  23217. .controller('ExampleController', ['$scope', function($scope) {
  23218. $scope.myHTML =
  23219. 'I am an <code>HTML</code>string with ' +
  23220. '<a href="#">links!</a> and other <em>stuff</em>';
  23221. }]);
  23222. </file>
  23223. <file name="protractor.js" type="protractor">
  23224. it('should check ng-bind-html', function() {
  23225. expect(element(by.binding('myHTML')).getText()).toBe(
  23226. 'I am an HTMLstring with links! and other stuff');
  23227. });
  23228. </file>
  23229. </example>
  23230. */
  23231. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  23232. return {
  23233. restrict: 'A',
  23234. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  23235. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  23236. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function sceValueOf(val) {
  23237. // Unwrap the value to compare the actual inner safe value, not the wrapper object.
  23238. return $sce.valueOf(val);
  23239. });
  23240. $compile.$$addBindingClass(tElement);
  23241. return function ngBindHtmlLink(scope, element, attr) {
  23242. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  23243. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  23244. // The watched value is the unwrapped value. To avoid re-escaping, use the direct getter.
  23245. var value = ngBindHtmlGetter(scope);
  23246. element.html($sce.getTrustedHtml(value) || '');
  23247. });
  23248. };
  23249. }
  23250. };
  23251. }];
  23252. /**
  23253. * @ngdoc directive
  23254. * @name ngChange
  23255. *
  23256. * @description
  23257. * Evaluate the given expression when the user changes the input.
  23258. * The expression is evaluated immediately, unlike the JavaScript onchange event
  23259. * which only triggers at the end of a change (usually, when the user leaves the
  23260. * form element or presses the return key).
  23261. *
  23262. * The `ngChange` expression is only evaluated when a change in the input value causes
  23263. * a new value to be committed to the model.
  23264. *
  23265. * It will not be evaluated:
  23266. * * if the value returned from the `$parsers` transformation pipeline has not changed
  23267. * * if the input has continued to be invalid since the model will stay `null`
  23268. * * if the model is changed programmatically and not by a change to the input value
  23269. *
  23270. *
  23271. * Note, this directive requires `ngModel` to be present.
  23272. *
  23273. * @element input
  23274. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  23275. * in input value.
  23276. *
  23277. * @example
  23278. * <example name="ngChange-directive" module="changeExample">
  23279. * <file name="index.html">
  23280. * <script>
  23281. * angular.module('changeExample', [])
  23282. * .controller('ExampleController', ['$scope', function($scope) {
  23283. * $scope.counter = 0;
  23284. * $scope.change = function() {
  23285. * $scope.counter++;
  23286. * };
  23287. * }]);
  23288. * </script>
  23289. * <div ng-controller="ExampleController">
  23290. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  23291. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  23292. * <label for="ng-change-example2">Confirmed</label><br />
  23293. * <tt>debug = {{confirmed}}</tt><br/>
  23294. * <tt>counter = {{counter}}</tt><br/>
  23295. * </div>
  23296. * </file>
  23297. * <file name="protractor.js" type="protractor">
  23298. * var counter = element(by.binding('counter'));
  23299. * var debug = element(by.binding('confirmed'));
  23300. *
  23301. * it('should evaluate the expression if changing from view', function() {
  23302. * expect(counter.getText()).toContain('0');
  23303. *
  23304. * element(by.id('ng-change-example1')).click();
  23305. *
  23306. * expect(counter.getText()).toContain('1');
  23307. * expect(debug.getText()).toContain('true');
  23308. * });
  23309. *
  23310. * it('should not evaluate the expression if changing from model', function() {
  23311. * element(by.id('ng-change-example2')).click();
  23312. * expect(counter.getText()).toContain('0');
  23313. * expect(debug.getText()).toContain('true');
  23314. * });
  23315. * </file>
  23316. * </example>
  23317. */
  23318. var ngChangeDirective = valueFn({
  23319. restrict: 'A',
  23320. require: 'ngModel',
  23321. link: function(scope, element, attr, ctrl) {
  23322. ctrl.$viewChangeListeners.push(function() {
  23323. scope.$eval(attr.ngChange);
  23324. });
  23325. }
  23326. });
  23327. /* exported
  23328. ngClassDirective,
  23329. ngClassEvenDirective,
  23330. ngClassOddDirective
  23331. */
  23332. function classDirective(name, selector) {
  23333. name = 'ngClass' + name;
  23334. return ['$animate', function($animate) {
  23335. return {
  23336. restrict: 'AC',
  23337. link: function(scope, element, attr) {
  23338. var oldVal;
  23339. scope.$watch(attr[name], ngClassWatchAction, true);
  23340. attr.$observe('class', function(value) {
  23341. ngClassWatchAction(scope.$eval(attr[name]));
  23342. });
  23343. if (name !== 'ngClass') {
  23344. scope.$watch('$index', function($index, old$index) {
  23345. /* eslint-disable no-bitwise */
  23346. var mod = $index & 1;
  23347. if (mod !== (old$index & 1)) {
  23348. var classes = arrayClasses(scope.$eval(attr[name]));
  23349. if (mod === selector) {
  23350. addClasses(classes);
  23351. } else {
  23352. removeClasses(classes);
  23353. }
  23354. }
  23355. /* eslint-enable */
  23356. });
  23357. }
  23358. function addClasses(classes) {
  23359. var newClasses = digestClassCounts(classes, 1);
  23360. attr.$addClass(newClasses);
  23361. }
  23362. function removeClasses(classes) {
  23363. var newClasses = digestClassCounts(classes, -1);
  23364. attr.$removeClass(newClasses);
  23365. }
  23366. function digestClassCounts(classes, count) {
  23367. // Use createMap() to prevent class assumptions involving property
  23368. // names in Object.prototype
  23369. var classCounts = element.data('$classCounts') || createMap();
  23370. var classesToUpdate = [];
  23371. forEach(classes, function(className) {
  23372. if (count > 0 || classCounts[className]) {
  23373. classCounts[className] = (classCounts[className] || 0) + count;
  23374. if (classCounts[className] === +(count > 0)) {
  23375. classesToUpdate.push(className);
  23376. }
  23377. }
  23378. });
  23379. element.data('$classCounts', classCounts);
  23380. return classesToUpdate.join(' ');
  23381. }
  23382. function updateClasses(oldClasses, newClasses) {
  23383. var toAdd = arrayDifference(newClasses, oldClasses);
  23384. var toRemove = arrayDifference(oldClasses, newClasses);
  23385. toAdd = digestClassCounts(toAdd, 1);
  23386. toRemove = digestClassCounts(toRemove, -1);
  23387. if (toAdd && toAdd.length) {
  23388. $animate.addClass(element, toAdd);
  23389. }
  23390. if (toRemove && toRemove.length) {
  23391. $animate.removeClass(element, toRemove);
  23392. }
  23393. }
  23394. function ngClassWatchAction(newVal) {
  23395. // eslint-disable-next-line no-bitwise
  23396. if (selector === true || (scope.$index & 1) === selector) {
  23397. var newClasses = arrayClasses(newVal || []);
  23398. if (!oldVal) {
  23399. addClasses(newClasses);
  23400. } else if (!equals(newVal,oldVal)) {
  23401. var oldClasses = arrayClasses(oldVal);
  23402. updateClasses(oldClasses, newClasses);
  23403. }
  23404. }
  23405. if (isArray(newVal)) {
  23406. oldVal = newVal.map(function(v) { return shallowCopy(v); });
  23407. } else {
  23408. oldVal = shallowCopy(newVal);
  23409. }
  23410. }
  23411. }
  23412. };
  23413. function arrayDifference(tokens1, tokens2) {
  23414. var values = [];
  23415. outer:
  23416. for (var i = 0; i < tokens1.length; i++) {
  23417. var token = tokens1[i];
  23418. for (var j = 0; j < tokens2.length; j++) {
  23419. if (token === tokens2[j]) continue outer;
  23420. }
  23421. values.push(token);
  23422. }
  23423. return values;
  23424. }
  23425. function arrayClasses(classVal) {
  23426. var classes = [];
  23427. if (isArray(classVal)) {
  23428. forEach(classVal, function(v) {
  23429. classes = classes.concat(arrayClasses(v));
  23430. });
  23431. return classes;
  23432. } else if (isString(classVal)) {
  23433. return classVal.split(' ');
  23434. } else if (isObject(classVal)) {
  23435. forEach(classVal, function(v, k) {
  23436. if (v) {
  23437. classes = classes.concat(k.split(' '));
  23438. }
  23439. });
  23440. return classes;
  23441. }
  23442. return classVal;
  23443. }
  23444. }];
  23445. }
  23446. /**
  23447. * @ngdoc directive
  23448. * @name ngClass
  23449. * @restrict AC
  23450. *
  23451. * @description
  23452. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  23453. * an expression that represents all classes to be added.
  23454. *
  23455. * The directive operates in three different ways, depending on which of three types the expression
  23456. * evaluates to:
  23457. *
  23458. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  23459. * names.
  23460. *
  23461. * 2. If the expression evaluates to an object, then for each key-value pair of the
  23462. * object with a truthy value the corresponding key is used as a class name.
  23463. *
  23464. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  23465. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  23466. * to give you more control over what CSS classes appear. See the code below for an example of this.
  23467. *
  23468. *
  23469. * The directive won't add duplicate classes if a particular class was already set.
  23470. *
  23471. * When the expression changes, the previously added classes are removed and only then are the
  23472. * new classes added.
  23473. *
  23474. * @knownIssue
  23475. * You should not use {@link guide/interpolation interpolation} in the value of the `class`
  23476. * attribute, when using the `ngClass` directive on the same element.
  23477. * See {@link guide/interpolation#known-issues here} for more info.
  23478. *
  23479. * @animations
  23480. * | Animation | Occurs |
  23481. * |----------------------------------|-------------------------------------|
  23482. * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element |
  23483. * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element |
  23484. *
  23485. * @element ANY
  23486. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  23487. * of the evaluation can be a string representing space delimited class
  23488. * names, an array, or a map of class names to boolean values. In the case of a map, the
  23489. * names of the properties whose values are truthy will be added as css classes to the
  23490. * element.
  23491. *
  23492. * @example Example that demonstrates basic bindings via ngClass directive.
  23493. <example name="ng-class">
  23494. <file name="index.html">
  23495. <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
  23496. <label>
  23497. <input type="checkbox" ng-model="deleted">
  23498. deleted (apply "strike" class)
  23499. </label><br>
  23500. <label>
  23501. <input type="checkbox" ng-model="important">
  23502. important (apply "bold" class)
  23503. </label><br>
  23504. <label>
  23505. <input type="checkbox" ng-model="error">
  23506. error (apply "has-error" class)
  23507. </label>
  23508. <hr>
  23509. <p ng-class="style">Using String Syntax</p>
  23510. <input type="text" ng-model="style"
  23511. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  23512. <hr>
  23513. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  23514. <input ng-model="style1"
  23515. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  23516. <input ng-model="style2"
  23517. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  23518. <input ng-model="style3"
  23519. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  23520. <hr>
  23521. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  23522. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  23523. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  23524. </file>
  23525. <file name="style.css">
  23526. .strike {
  23527. text-decoration: line-through;
  23528. }
  23529. .bold {
  23530. font-weight: bold;
  23531. }
  23532. .red {
  23533. color: red;
  23534. }
  23535. .has-error {
  23536. color: red;
  23537. background-color: yellow;
  23538. }
  23539. .orange {
  23540. color: orange;
  23541. }
  23542. </file>
  23543. <file name="protractor.js" type="protractor">
  23544. var ps = element.all(by.css('p'));
  23545. it('should let you toggle the class', function() {
  23546. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  23547. expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
  23548. element(by.model('important')).click();
  23549. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  23550. element(by.model('error')).click();
  23551. expect(ps.first().getAttribute('class')).toMatch(/has-error/);
  23552. });
  23553. it('should let you toggle string example', function() {
  23554. expect(ps.get(1).getAttribute('class')).toBe('');
  23555. element(by.model('style')).clear();
  23556. element(by.model('style')).sendKeys('red');
  23557. expect(ps.get(1).getAttribute('class')).toBe('red');
  23558. });
  23559. it('array example should have 3 classes', function() {
  23560. expect(ps.get(2).getAttribute('class')).toBe('');
  23561. element(by.model('style1')).sendKeys('bold');
  23562. element(by.model('style2')).sendKeys('strike');
  23563. element(by.model('style3')).sendKeys('red');
  23564. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  23565. });
  23566. it('array with map example should have 2 classes', function() {
  23567. expect(ps.last().getAttribute('class')).toBe('');
  23568. element(by.model('style4')).sendKeys('bold');
  23569. element(by.model('warning')).click();
  23570. expect(ps.last().getAttribute('class')).toBe('bold orange');
  23571. });
  23572. </file>
  23573. </example>
  23574. ## Animations
  23575. The example below demonstrates how to perform animations using ngClass.
  23576. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-class">
  23577. <file name="index.html">
  23578. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  23579. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  23580. <br>
  23581. <span class="base-class" ng-class="myVar">Sample Text</span>
  23582. </file>
  23583. <file name="style.css">
  23584. .base-class {
  23585. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  23586. }
  23587. .base-class.my-class {
  23588. color: red;
  23589. font-size:3em;
  23590. }
  23591. </file>
  23592. <file name="protractor.js" type="protractor">
  23593. it('should check ng-class', function() {
  23594. expect(element(by.css('.base-class')).getAttribute('class')).not.
  23595. toMatch(/my-class/);
  23596. element(by.id('setbtn')).click();
  23597. expect(element(by.css('.base-class')).getAttribute('class')).
  23598. toMatch(/my-class/);
  23599. element(by.id('clearbtn')).click();
  23600. expect(element(by.css('.base-class')).getAttribute('class')).not.
  23601. toMatch(/my-class/);
  23602. });
  23603. </file>
  23604. </example>
  23605. ## ngClass and pre-existing CSS3 Transitions/Animations
  23606. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  23607. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  23608. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  23609. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  23610. {@link $animate#removeClass $animate.removeClass}.
  23611. */
  23612. var ngClassDirective = classDirective('', true);
  23613. /**
  23614. * @ngdoc directive
  23615. * @name ngClassOdd
  23616. * @restrict AC
  23617. *
  23618. * @description
  23619. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  23620. * {@link ng.directive:ngClass ngClass}, except they work in
  23621. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  23622. *
  23623. * This directive can be applied only within the scope of an
  23624. * {@link ng.directive:ngRepeat ngRepeat}.
  23625. *
  23626. * @element ANY
  23627. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  23628. * of the evaluation can be a string representing space delimited class names or an array.
  23629. *
  23630. * @example
  23631. <example name="ng-class-odd">
  23632. <file name="index.html">
  23633. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  23634. <li ng-repeat="name in names">
  23635. <span ng-class-odd="'odd'" ng-class-even="'even'">
  23636. {{name}}
  23637. </span>
  23638. </li>
  23639. </ol>
  23640. </file>
  23641. <file name="style.css">
  23642. .odd {
  23643. color: red;
  23644. }
  23645. .even {
  23646. color: blue;
  23647. }
  23648. </file>
  23649. <file name="protractor.js" type="protractor">
  23650. it('should check ng-class-odd and ng-class-even', function() {
  23651. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  23652. toMatch(/odd/);
  23653. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  23654. toMatch(/even/);
  23655. });
  23656. </file>
  23657. </example>
  23658. */
  23659. var ngClassOddDirective = classDirective('Odd', 0);
  23660. /**
  23661. * @ngdoc directive
  23662. * @name ngClassEven
  23663. * @restrict AC
  23664. *
  23665. * @description
  23666. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  23667. * {@link ng.directive:ngClass ngClass}, except they work in
  23668. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  23669. *
  23670. * This directive can be applied only within the scope of an
  23671. * {@link ng.directive:ngRepeat ngRepeat}.
  23672. *
  23673. * @element ANY
  23674. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  23675. * result of the evaluation can be a string representing space delimited class names or an array.
  23676. *
  23677. * @example
  23678. <example name="ng-class-even">
  23679. <file name="index.html">
  23680. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  23681. <li ng-repeat="name in names">
  23682. <span ng-class-odd="'odd'" ng-class-even="'even'">
  23683. {{name}} &nbsp; &nbsp; &nbsp;
  23684. </span>
  23685. </li>
  23686. </ol>
  23687. </file>
  23688. <file name="style.css">
  23689. .odd {
  23690. color: red;
  23691. }
  23692. .even {
  23693. color: blue;
  23694. }
  23695. </file>
  23696. <file name="protractor.js" type="protractor">
  23697. it('should check ng-class-odd and ng-class-even', function() {
  23698. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  23699. toMatch(/odd/);
  23700. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  23701. toMatch(/even/);
  23702. });
  23703. </file>
  23704. </example>
  23705. */
  23706. var ngClassEvenDirective = classDirective('Even', 1);
  23707. /**
  23708. * @ngdoc directive
  23709. * @name ngCloak
  23710. * @restrict AC
  23711. *
  23712. * @description
  23713. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  23714. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  23715. * directive to avoid the undesirable flicker effect caused by the html template display.
  23716. *
  23717. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  23718. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  23719. * of the browser view.
  23720. *
  23721. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  23722. * `angular.min.js`.
  23723. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  23724. *
  23725. * ```css
  23726. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  23727. * display: none !important;
  23728. * }
  23729. * ```
  23730. *
  23731. * When this css rule is loaded by the browser, all html elements (including their children) that
  23732. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  23733. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  23734. * the compiled element visible.
  23735. *
  23736. * For the best result, the `angular.js` script must be loaded in the head section of the html
  23737. * document; alternatively, the css rule above must be included in the external stylesheet of the
  23738. * application.
  23739. *
  23740. * @element ANY
  23741. *
  23742. * @example
  23743. <example name="ng-cloak">
  23744. <file name="index.html">
  23745. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  23746. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  23747. </file>
  23748. <file name="protractor.js" type="protractor">
  23749. it('should remove the template directive and css class', function() {
  23750. expect($('#template1').getAttribute('ng-cloak')).
  23751. toBeNull();
  23752. expect($('#template2').getAttribute('ng-cloak')).
  23753. toBeNull();
  23754. });
  23755. </file>
  23756. </example>
  23757. *
  23758. */
  23759. var ngCloakDirective = ngDirective({
  23760. compile: function(element, attr) {
  23761. attr.$set('ngCloak', undefined);
  23762. element.removeClass('ng-cloak');
  23763. }
  23764. });
  23765. /**
  23766. * @ngdoc directive
  23767. * @name ngController
  23768. *
  23769. * @description
  23770. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  23771. * supports the principles behind the Model-View-Controller design pattern.
  23772. *
  23773. * MVC components in angular:
  23774. *
  23775. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  23776. * are accessed through bindings.
  23777. * * View — The template (HTML with data bindings) that is rendered into the View.
  23778. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  23779. * logic behind the application to decorate the scope with functions and values
  23780. *
  23781. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  23782. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  23783. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  23784. * and executed twice.
  23785. *
  23786. * @element ANY
  23787. * @scope
  23788. * @priority 500
  23789. * @param {expression} ngController Name of a constructor function registered with the current
  23790. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  23791. * that on the current scope evaluates to a constructor function.
  23792. *
  23793. * The controller instance can be published into a scope property by specifying
  23794. * `ng-controller="as propertyName"`.
  23795. *
  23796. * If the current `$controllerProvider` is configured to use globals (via
  23797. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  23798. * also be the name of a globally accessible constructor function (not recommended).
  23799. *
  23800. * @example
  23801. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  23802. * greeting are methods declared on the controller (see source tab). These methods can
  23803. * easily be called from the angular markup. Any changes to the data are automatically reflected
  23804. * in the View without the need for a manual update.
  23805. *
  23806. * Two different declaration styles are included below:
  23807. *
  23808. * * one binds methods and properties directly onto the controller using `this`:
  23809. * `ng-controller="SettingsController1 as settings"`
  23810. * * one injects `$scope` into the controller:
  23811. * `ng-controller="SettingsController2"`
  23812. *
  23813. * The second option is more common in the Angular community, and is generally used in boilerplates
  23814. * and in this guide. However, there are advantages to binding properties directly to the controller
  23815. * and avoiding scope.
  23816. *
  23817. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  23818. * multiple controllers apply to an element.
  23819. * * If you are writing your controllers as classes you have easier access to the properties and
  23820. * methods, which will appear on the scope, from inside the controller code.
  23821. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  23822. * inheritance masking primitives.
  23823. *
  23824. * This example demonstrates the `controller as` syntax.
  23825. *
  23826. * <example name="ngControllerAs" module="controllerAsExample">
  23827. * <file name="index.html">
  23828. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  23829. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  23830. * <button ng-click="settings.greet()">greet</button><br/>
  23831. * Contact:
  23832. * <ul>
  23833. * <li ng-repeat="contact in settings.contacts">
  23834. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  23835. * <option>phone</option>
  23836. * <option>email</option>
  23837. * </select>
  23838. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  23839. * <button ng-click="settings.clearContact(contact)">clear</button>
  23840. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  23841. * </li>
  23842. * <li><button ng-click="settings.addContact()">add</button></li>
  23843. * </ul>
  23844. * </div>
  23845. * </file>
  23846. * <file name="app.js">
  23847. * angular.module('controllerAsExample', [])
  23848. * .controller('SettingsController1', SettingsController1);
  23849. *
  23850. * function SettingsController1() {
  23851. * this.name = 'John Smith';
  23852. * this.contacts = [
  23853. * {type: 'phone', value: '408 555 1212'},
  23854. * {type: 'email', value: 'john.smith@example.org'}
  23855. * ];
  23856. * }
  23857. *
  23858. * SettingsController1.prototype.greet = function() {
  23859. * alert(this.name);
  23860. * };
  23861. *
  23862. * SettingsController1.prototype.addContact = function() {
  23863. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  23864. * };
  23865. *
  23866. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  23867. * var index = this.contacts.indexOf(contactToRemove);
  23868. * this.contacts.splice(index, 1);
  23869. * };
  23870. *
  23871. * SettingsController1.prototype.clearContact = function(contact) {
  23872. * contact.type = 'phone';
  23873. * contact.value = '';
  23874. * };
  23875. * </file>
  23876. * <file name="protractor.js" type="protractor">
  23877. * it('should check controller as', function() {
  23878. * var container = element(by.id('ctrl-as-exmpl'));
  23879. * expect(container.element(by.model('settings.name'))
  23880. * .getAttribute('value')).toBe('John Smith');
  23881. *
  23882. * var firstRepeat =
  23883. * container.element(by.repeater('contact in settings.contacts').row(0));
  23884. * var secondRepeat =
  23885. * container.element(by.repeater('contact in settings.contacts').row(1));
  23886. *
  23887. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  23888. * .toBe('408 555 1212');
  23889. *
  23890. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  23891. * .toBe('john.smith@example.org');
  23892. *
  23893. * firstRepeat.element(by.buttonText('clear')).click();
  23894. *
  23895. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  23896. * .toBe('');
  23897. *
  23898. * container.element(by.buttonText('add')).click();
  23899. *
  23900. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  23901. * .element(by.model('contact.value'))
  23902. * .getAttribute('value'))
  23903. * .toBe('yourname@example.org');
  23904. * });
  23905. * </file>
  23906. * </example>
  23907. *
  23908. * This example demonstrates the "attach to `$scope`" style of controller.
  23909. *
  23910. * <example name="ngController" module="controllerExample">
  23911. * <file name="index.html">
  23912. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  23913. * <label>Name: <input type="text" ng-model="name"/></label>
  23914. * <button ng-click="greet()">greet</button><br/>
  23915. * Contact:
  23916. * <ul>
  23917. * <li ng-repeat="contact in contacts">
  23918. * <select ng-model="contact.type" id="select_{{$index}}">
  23919. * <option>phone</option>
  23920. * <option>email</option>
  23921. * </select>
  23922. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  23923. * <button ng-click="clearContact(contact)">clear</button>
  23924. * <button ng-click="removeContact(contact)">X</button>
  23925. * </li>
  23926. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  23927. * </ul>
  23928. * </div>
  23929. * </file>
  23930. * <file name="app.js">
  23931. * angular.module('controllerExample', [])
  23932. * .controller('SettingsController2', ['$scope', SettingsController2]);
  23933. *
  23934. * function SettingsController2($scope) {
  23935. * $scope.name = 'John Smith';
  23936. * $scope.contacts = [
  23937. * {type:'phone', value:'408 555 1212'},
  23938. * {type:'email', value:'john.smith@example.org'}
  23939. * ];
  23940. *
  23941. * $scope.greet = function() {
  23942. * alert($scope.name);
  23943. * };
  23944. *
  23945. * $scope.addContact = function() {
  23946. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  23947. * };
  23948. *
  23949. * $scope.removeContact = function(contactToRemove) {
  23950. * var index = $scope.contacts.indexOf(contactToRemove);
  23951. * $scope.contacts.splice(index, 1);
  23952. * };
  23953. *
  23954. * $scope.clearContact = function(contact) {
  23955. * contact.type = 'phone';
  23956. * contact.value = '';
  23957. * };
  23958. * }
  23959. * </file>
  23960. * <file name="protractor.js" type="protractor">
  23961. * it('should check controller', function() {
  23962. * var container = element(by.id('ctrl-exmpl'));
  23963. *
  23964. * expect(container.element(by.model('name'))
  23965. * .getAttribute('value')).toBe('John Smith');
  23966. *
  23967. * var firstRepeat =
  23968. * container.element(by.repeater('contact in contacts').row(0));
  23969. * var secondRepeat =
  23970. * container.element(by.repeater('contact in contacts').row(1));
  23971. *
  23972. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  23973. * .toBe('408 555 1212');
  23974. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  23975. * .toBe('john.smith@example.org');
  23976. *
  23977. * firstRepeat.element(by.buttonText('clear')).click();
  23978. *
  23979. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  23980. * .toBe('');
  23981. *
  23982. * container.element(by.buttonText('add')).click();
  23983. *
  23984. * expect(container.element(by.repeater('contact in contacts').row(2))
  23985. * .element(by.model('contact.value'))
  23986. * .getAttribute('value'))
  23987. * .toBe('yourname@example.org');
  23988. * });
  23989. * </file>
  23990. *</example>
  23991. */
  23992. var ngControllerDirective = [function() {
  23993. return {
  23994. restrict: 'A',
  23995. scope: true,
  23996. controller: '@',
  23997. priority: 500
  23998. };
  23999. }];
  24000. /**
  24001. * @ngdoc directive
  24002. * @name ngCsp
  24003. *
  24004. * @element html
  24005. * @description
  24006. *
  24007. * Angular has some features that can break certain
  24008. * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
  24009. *
  24010. * If you intend to implement these rules then you must tell Angular not to use these features.
  24011. *
  24012. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  24013. *
  24014. *
  24015. * The following rules affect Angular:
  24016. *
  24017. * * `unsafe-eval`: this rule forbids apps to use `eval` or `Function(string)` generated functions
  24018. * (among other things). Angular makes use of this in the {@link $parse} service to provide a 30%
  24019. * increase in the speed of evaluating Angular expressions.
  24020. *
  24021. * * `unsafe-inline`: this rule forbids apps from inject custom styles into the document. Angular
  24022. * makes use of this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}).
  24023. * To make these directives work when a CSP rule is blocking inline styles, you must link to the
  24024. * `angular-csp.css` in your HTML manually.
  24025. *
  24026. * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking unsafe-eval
  24027. * and automatically deactivates this feature in the {@link $parse} service. This autodetection,
  24028. * however, triggers a CSP error to be logged in the console:
  24029. *
  24030. * ```
  24031. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  24032. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  24033. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  24034. * ```
  24035. *
  24036. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  24037. * directive on an element of the HTML document that appears before the `<script>` tag that loads
  24038. * the `angular.js` file.
  24039. *
  24040. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  24041. *
  24042. * You can specify which of the CSP related Angular features should be deactivated by providing
  24043. * a value for the `ng-csp` attribute. The options are as follows:
  24044. *
  24045. * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
  24046. *
  24047. * * no-unsafe-eval: this stops Angular from optimizing $parse with unsafe eval of strings
  24048. *
  24049. * You can use these values in the following combinations:
  24050. *
  24051. *
  24052. * * No declaration means that Angular will assume that you can do inline styles, but it will do
  24053. * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous versions
  24054. * of Angular.
  24055. *
  24056. * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
  24057. * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous versions
  24058. * of Angular.
  24059. *
  24060. * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can inject
  24061. * inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
  24062. *
  24063. * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
  24064. * run eval - no automatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
  24065. *
  24066. * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
  24067. * styles nor use eval, which is the same as an empty: ng-csp.
  24068. * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
  24069. *
  24070. * @example
  24071. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  24072. ```html
  24073. <!doctype html>
  24074. <html ng-app ng-csp>
  24075. ...
  24076. ...
  24077. </html>
  24078. ```
  24079. * @example
  24080. // Note: the suffix `.csp` in the example name triggers
  24081. // csp mode in our http server!
  24082. <example name="example.csp" module="cspExample" ng-csp="true">
  24083. <file name="index.html">
  24084. <div ng-controller="MainController as ctrl">
  24085. <div>
  24086. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  24087. <span id="counter">
  24088. {{ctrl.counter}}
  24089. </span>
  24090. </div>
  24091. <div>
  24092. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  24093. <span id="evilError">
  24094. {{ctrl.evilError}}
  24095. </span>
  24096. </div>
  24097. </div>
  24098. </file>
  24099. <file name="script.js">
  24100. angular.module('cspExample', [])
  24101. .controller('MainController', function MainController() {
  24102. this.counter = 0;
  24103. this.inc = function() {
  24104. this.counter++;
  24105. };
  24106. this.evil = function() {
  24107. try {
  24108. eval('1+2'); // eslint-disable-line no-eval
  24109. } catch (e) {
  24110. this.evilError = e.message;
  24111. }
  24112. };
  24113. });
  24114. </file>
  24115. <file name="protractor.js" type="protractor">
  24116. var util, webdriver;
  24117. var incBtn = element(by.id('inc'));
  24118. var counter = element(by.id('counter'));
  24119. var evilBtn = element(by.id('evil'));
  24120. var evilError = element(by.id('evilError'));
  24121. function getAndClearSevereErrors() {
  24122. return browser.manage().logs().get('browser').then(function(browserLog) {
  24123. return browserLog.filter(function(logEntry) {
  24124. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  24125. });
  24126. });
  24127. }
  24128. function clearErrors() {
  24129. getAndClearSevereErrors();
  24130. }
  24131. function expectNoErrors() {
  24132. getAndClearSevereErrors().then(function(filteredLog) {
  24133. expect(filteredLog.length).toEqual(0);
  24134. if (filteredLog.length) {
  24135. console.log('browser console errors: ' + util.inspect(filteredLog));
  24136. }
  24137. });
  24138. }
  24139. function expectError(regex) {
  24140. getAndClearSevereErrors().then(function(filteredLog) {
  24141. var found = false;
  24142. filteredLog.forEach(function(log) {
  24143. if (log.message.match(regex)) {
  24144. found = true;
  24145. }
  24146. });
  24147. if (!found) {
  24148. throw new Error('expected an error that matches ' + regex);
  24149. }
  24150. });
  24151. }
  24152. beforeEach(function() {
  24153. util = require('util');
  24154. webdriver = require('selenium-webdriver');
  24155. });
  24156. // For now, we only test on Chrome,
  24157. // as Safari does not load the page with Protractor's injected scripts,
  24158. // and Firefox webdriver always disables content security policy (#6358)
  24159. if (browser.params.browser !== 'chrome') {
  24160. return;
  24161. }
  24162. it('should not report errors when the page is loaded', function() {
  24163. // clear errors so we are not dependent on previous tests
  24164. clearErrors();
  24165. // Need to reload the page as the page is already loaded when
  24166. // we come here
  24167. browser.driver.getCurrentUrl().then(function(url) {
  24168. browser.get(url);
  24169. });
  24170. expectNoErrors();
  24171. });
  24172. it('should evaluate expressions', function() {
  24173. expect(counter.getText()).toEqual('0');
  24174. incBtn.click();
  24175. expect(counter.getText()).toEqual('1');
  24176. expectNoErrors();
  24177. });
  24178. it('should throw and report an error when using "eval"', function() {
  24179. evilBtn.click();
  24180. expect(evilError.getText()).toMatch(/Content Security Policy/);
  24181. expectError(/Content Security Policy/);
  24182. });
  24183. </file>
  24184. </example>
  24185. */
  24186. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  24187. // bootstrap the system (before $parse is instantiated), for this reason we just have
  24188. // the csp() fn that looks for the `ng-csp` attribute anywhere in the current doc
  24189. /**
  24190. * @ngdoc directive
  24191. * @name ngClick
  24192. *
  24193. * @description
  24194. * The ngClick directive allows you to specify custom behavior when
  24195. * an element is clicked.
  24196. *
  24197. * @element ANY
  24198. * @priority 0
  24199. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  24200. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  24201. *
  24202. * @example
  24203. <example name="ng-click">
  24204. <file name="index.html">
  24205. <button ng-click="count = count + 1" ng-init="count=0">
  24206. Increment
  24207. </button>
  24208. <span>
  24209. count: {{count}}
  24210. </span>
  24211. </file>
  24212. <file name="protractor.js" type="protractor">
  24213. it('should check ng-click', function() {
  24214. expect(element(by.binding('count')).getText()).toMatch('0');
  24215. element(by.css('button')).click();
  24216. expect(element(by.binding('count')).getText()).toMatch('1');
  24217. });
  24218. </file>
  24219. </example>
  24220. */
  24221. /*
  24222. * A collection of directives that allows creation of custom event handlers that are defined as
  24223. * angular expressions and are compiled and executed within the current scope.
  24224. */
  24225. var ngEventDirectives = {};
  24226. // For events that might fire synchronously during DOM manipulation
  24227. // we need to execute their event handlers asynchronously using $evalAsync,
  24228. // so that they are not executed in an inconsistent state.
  24229. var forceAsyncEvents = {
  24230. 'blur': true,
  24231. 'focus': true
  24232. };
  24233. forEach(
  24234. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  24235. function(eventName) {
  24236. var directiveName = directiveNormalize('ng-' + eventName);
  24237. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  24238. return {
  24239. restrict: 'A',
  24240. compile: function($element, attr) {
  24241. // We expose the powerful $event object on the scope that provides access to the Window,
  24242. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  24243. // checks at the cost of speed since event handler expressions are not executed as
  24244. // frequently as regular change detection.
  24245. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
  24246. return function ngEventHandler(scope, element) {
  24247. element.on(eventName, function(event) {
  24248. var callback = function() {
  24249. fn(scope, {$event:event});
  24250. };
  24251. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  24252. scope.$evalAsync(callback);
  24253. } else {
  24254. scope.$apply(callback);
  24255. }
  24256. });
  24257. };
  24258. }
  24259. };
  24260. }];
  24261. }
  24262. );
  24263. /**
  24264. * @ngdoc directive
  24265. * @name ngDblclick
  24266. *
  24267. * @description
  24268. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  24269. *
  24270. * @element ANY
  24271. * @priority 0
  24272. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  24273. * a dblclick. (The Event object is available as `$event`)
  24274. *
  24275. * @example
  24276. <example name="ng-dblclick">
  24277. <file name="index.html">
  24278. <button ng-dblclick="count = count + 1" ng-init="count=0">
  24279. Increment (on double click)
  24280. </button>
  24281. count: {{count}}
  24282. </file>
  24283. </example>
  24284. */
  24285. /**
  24286. * @ngdoc directive
  24287. * @name ngMousedown
  24288. *
  24289. * @description
  24290. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  24291. *
  24292. * @element ANY
  24293. * @priority 0
  24294. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  24295. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  24296. *
  24297. * @example
  24298. <example name="ng-mousedown">
  24299. <file name="index.html">
  24300. <button ng-mousedown="count = count + 1" ng-init="count=0">
  24301. Increment (on mouse down)
  24302. </button>
  24303. count: {{count}}
  24304. </file>
  24305. </example>
  24306. */
  24307. /**
  24308. * @ngdoc directive
  24309. * @name ngMouseup
  24310. *
  24311. * @description
  24312. * Specify custom behavior on mouseup event.
  24313. *
  24314. * @element ANY
  24315. * @priority 0
  24316. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  24317. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  24318. *
  24319. * @example
  24320. <example name="ng-mouseup">
  24321. <file name="index.html">
  24322. <button ng-mouseup="count = count + 1" ng-init="count=0">
  24323. Increment (on mouse up)
  24324. </button>
  24325. count: {{count}}
  24326. </file>
  24327. </example>
  24328. */
  24329. /**
  24330. * @ngdoc directive
  24331. * @name ngMouseover
  24332. *
  24333. * @description
  24334. * Specify custom behavior on mouseover event.
  24335. *
  24336. * @element ANY
  24337. * @priority 0
  24338. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  24339. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  24340. *
  24341. * @example
  24342. <example name="ng-mouseover">
  24343. <file name="index.html">
  24344. <button ng-mouseover="count = count + 1" ng-init="count=0">
  24345. Increment (when mouse is over)
  24346. </button>
  24347. count: {{count}}
  24348. </file>
  24349. </example>
  24350. */
  24351. /**
  24352. * @ngdoc directive
  24353. * @name ngMouseenter
  24354. *
  24355. * @description
  24356. * Specify custom behavior on mouseenter event.
  24357. *
  24358. * @element ANY
  24359. * @priority 0
  24360. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  24361. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  24362. *
  24363. * @example
  24364. <example name="ng-mouseenter">
  24365. <file name="index.html">
  24366. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  24367. Increment (when mouse enters)
  24368. </button>
  24369. count: {{count}}
  24370. </file>
  24371. </example>
  24372. */
  24373. /**
  24374. * @ngdoc directive
  24375. * @name ngMouseleave
  24376. *
  24377. * @description
  24378. * Specify custom behavior on mouseleave event.
  24379. *
  24380. * @element ANY
  24381. * @priority 0
  24382. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  24383. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  24384. *
  24385. * @example
  24386. <example name="ng-mouseleave">
  24387. <file name="index.html">
  24388. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  24389. Increment (when mouse leaves)
  24390. </button>
  24391. count: {{count}}
  24392. </file>
  24393. </example>
  24394. */
  24395. /**
  24396. * @ngdoc directive
  24397. * @name ngMousemove
  24398. *
  24399. * @description
  24400. * Specify custom behavior on mousemove event.
  24401. *
  24402. * @element ANY
  24403. * @priority 0
  24404. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  24405. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  24406. *
  24407. * @example
  24408. <example name="ng-mousemove">
  24409. <file name="index.html">
  24410. <button ng-mousemove="count = count + 1" ng-init="count=0">
  24411. Increment (when mouse moves)
  24412. </button>
  24413. count: {{count}}
  24414. </file>
  24415. </example>
  24416. */
  24417. /**
  24418. * @ngdoc directive
  24419. * @name ngKeydown
  24420. *
  24421. * @description
  24422. * Specify custom behavior on keydown event.
  24423. *
  24424. * @element ANY
  24425. * @priority 0
  24426. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  24427. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  24428. *
  24429. * @example
  24430. <example name="ng-keydown">
  24431. <file name="index.html">
  24432. <input ng-keydown="count = count + 1" ng-init="count=0">
  24433. key down count: {{count}}
  24434. </file>
  24435. </example>
  24436. */
  24437. /**
  24438. * @ngdoc directive
  24439. * @name ngKeyup
  24440. *
  24441. * @description
  24442. * Specify custom behavior on keyup event.
  24443. *
  24444. * @element ANY
  24445. * @priority 0
  24446. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  24447. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  24448. *
  24449. * @example
  24450. <example name="ng-keyup">
  24451. <file name="index.html">
  24452. <p>Typing in the input box below updates the key count</p>
  24453. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  24454. <p>Typing in the input box below updates the keycode</p>
  24455. <input ng-keyup="event=$event">
  24456. <p>event keyCode: {{ event.keyCode }}</p>
  24457. <p>event altKey: {{ event.altKey }}</p>
  24458. </file>
  24459. </example>
  24460. */
  24461. /**
  24462. * @ngdoc directive
  24463. * @name ngKeypress
  24464. *
  24465. * @description
  24466. * Specify custom behavior on keypress event.
  24467. *
  24468. * @element ANY
  24469. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  24470. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  24471. * and can be interrogated for keyCode, altKey, etc.)
  24472. *
  24473. * @example
  24474. <example name="ng-keypress">
  24475. <file name="index.html">
  24476. <input ng-keypress="count = count + 1" ng-init="count=0">
  24477. key press count: {{count}}
  24478. </file>
  24479. </example>
  24480. */
  24481. /**
  24482. * @ngdoc directive
  24483. * @name ngSubmit
  24484. *
  24485. * @description
  24486. * Enables binding angular expressions to onsubmit events.
  24487. *
  24488. * Additionally it prevents the default action (which for form means sending the request to the
  24489. * server and reloading the current page), but only if the form does not contain `action`,
  24490. * `data-action`, or `x-action` attributes.
  24491. *
  24492. * <div class="alert alert-warning">
  24493. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  24494. * `ngSubmit` handlers together. See the
  24495. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  24496. * for a detailed discussion of when `ngSubmit` may be triggered.
  24497. * </div>
  24498. *
  24499. * @element form
  24500. * @priority 0
  24501. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  24502. * ({@link guide/expression#-event- Event object is available as `$event`})
  24503. *
  24504. * @example
  24505. <example module="submitExample" name="ng-submit">
  24506. <file name="index.html">
  24507. <script>
  24508. angular.module('submitExample', [])
  24509. .controller('ExampleController', ['$scope', function($scope) {
  24510. $scope.list = [];
  24511. $scope.text = 'hello';
  24512. $scope.submit = function() {
  24513. if ($scope.text) {
  24514. $scope.list.push(this.text);
  24515. $scope.text = '';
  24516. }
  24517. };
  24518. }]);
  24519. </script>
  24520. <form ng-submit="submit()" ng-controller="ExampleController">
  24521. Enter text and hit enter:
  24522. <input type="text" ng-model="text" name="text" />
  24523. <input type="submit" id="submit" value="Submit" />
  24524. <pre>list={{list}}</pre>
  24525. </form>
  24526. </file>
  24527. <file name="protractor.js" type="protractor">
  24528. it('should check ng-submit', function() {
  24529. expect(element(by.binding('list')).getText()).toBe('list=[]');
  24530. element(by.css('#submit')).click();
  24531. expect(element(by.binding('list')).getText()).toContain('hello');
  24532. expect(element(by.model('text')).getAttribute('value')).toBe('');
  24533. });
  24534. it('should ignore empty strings', function() {
  24535. expect(element(by.binding('list')).getText()).toBe('list=[]');
  24536. element(by.css('#submit')).click();
  24537. element(by.css('#submit')).click();
  24538. expect(element(by.binding('list')).getText()).toContain('hello');
  24539. });
  24540. </file>
  24541. </example>
  24542. */
  24543. /**
  24544. * @ngdoc directive
  24545. * @name ngFocus
  24546. *
  24547. * @description
  24548. * Specify custom behavior on focus event.
  24549. *
  24550. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  24551. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  24552. * during an `$apply` to ensure a consistent state.
  24553. *
  24554. * @element window, input, select, textarea, a
  24555. * @priority 0
  24556. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  24557. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  24558. *
  24559. * @example
  24560. * See {@link ng.directive:ngClick ngClick}
  24561. */
  24562. /**
  24563. * @ngdoc directive
  24564. * @name ngBlur
  24565. *
  24566. * @description
  24567. * Specify custom behavior on blur event.
  24568. *
  24569. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  24570. * an element has lost focus.
  24571. *
  24572. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  24573. * (e.g. removing a focussed input),
  24574. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  24575. * during an `$apply` to ensure a consistent state.
  24576. *
  24577. * @element window, input, select, textarea, a
  24578. * @priority 0
  24579. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  24580. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  24581. *
  24582. * @example
  24583. * See {@link ng.directive:ngClick ngClick}
  24584. */
  24585. /**
  24586. * @ngdoc directive
  24587. * @name ngCopy
  24588. *
  24589. * @description
  24590. * Specify custom behavior on copy event.
  24591. *
  24592. * @element window, input, select, textarea, a
  24593. * @priority 0
  24594. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  24595. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  24596. *
  24597. * @example
  24598. <example name="ng-copy">
  24599. <file name="index.html">
  24600. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  24601. copied: {{copied}}
  24602. </file>
  24603. </example>
  24604. */
  24605. /**
  24606. * @ngdoc directive
  24607. * @name ngCut
  24608. *
  24609. * @description
  24610. * Specify custom behavior on cut event.
  24611. *
  24612. * @element window, input, select, textarea, a
  24613. * @priority 0
  24614. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  24615. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  24616. *
  24617. * @example
  24618. <example name="ng-cut">
  24619. <file name="index.html">
  24620. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  24621. cut: {{cut}}
  24622. </file>
  24623. </example>
  24624. */
  24625. /**
  24626. * @ngdoc directive
  24627. * @name ngPaste
  24628. *
  24629. * @description
  24630. * Specify custom behavior on paste event.
  24631. *
  24632. * @element window, input, select, textarea, a
  24633. * @priority 0
  24634. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  24635. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  24636. *
  24637. * @example
  24638. <example name="ng-paste">
  24639. <file name="index.html">
  24640. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  24641. pasted: {{paste}}
  24642. </file>
  24643. </example>
  24644. */
  24645. /**
  24646. * @ngdoc directive
  24647. * @name ngIf
  24648. * @restrict A
  24649. * @multiElement
  24650. *
  24651. * @description
  24652. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  24653. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  24654. * value then the element is removed from the DOM, otherwise a clone of the
  24655. * element is reinserted into the DOM.
  24656. *
  24657. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  24658. * element in the DOM rather than changing its visibility via the `display` css property. A common
  24659. * case when this difference is significant is when using css selectors that rely on an element's
  24660. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  24661. *
  24662. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  24663. * is created when the element is restored. The scope created within `ngIf` inherits from
  24664. * its parent scope using
  24665. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  24666. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  24667. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  24668. * variable within the child scope will override (hide) the value in the parent scope.
  24669. *
  24670. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  24671. * is if an element's class attribute is directly modified after it's compiled, using something like
  24672. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  24673. * the added class will be lost because the original compiled state is used to regenerate the element.
  24674. *
  24675. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  24676. * and `leave` effects.
  24677. *
  24678. * @animations
  24679. * | Animation | Occurs |
  24680. * |----------------------------------|-------------------------------------|
  24681. * | {@link ng.$animate#enter enter} | just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container |
  24682. * | {@link ng.$animate#leave leave} | just before the `ngIf` contents are removed from the DOM |
  24683. *
  24684. * @element ANY
  24685. * @scope
  24686. * @priority 600
  24687. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  24688. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  24689. * element is added to the DOM tree.
  24690. *
  24691. * @example
  24692. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-if">
  24693. <file name="index.html">
  24694. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  24695. Show when checked:
  24696. <span ng-if="checked" class="animate-if">
  24697. This is removed when the checkbox is unchecked.
  24698. </span>
  24699. </file>
  24700. <file name="animations.css">
  24701. .animate-if {
  24702. background:white;
  24703. border:1px solid black;
  24704. padding:10px;
  24705. }
  24706. .animate-if.ng-enter, .animate-if.ng-leave {
  24707. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  24708. }
  24709. .animate-if.ng-enter,
  24710. .animate-if.ng-leave.ng-leave-active {
  24711. opacity:0;
  24712. }
  24713. .animate-if.ng-leave,
  24714. .animate-if.ng-enter.ng-enter-active {
  24715. opacity:1;
  24716. }
  24717. </file>
  24718. </example>
  24719. */
  24720. var ngIfDirective = ['$animate', '$compile', function($animate, $compile) {
  24721. return {
  24722. multiElement: true,
  24723. transclude: 'element',
  24724. priority: 600,
  24725. terminal: true,
  24726. restrict: 'A',
  24727. $$tlb: true,
  24728. link: function($scope, $element, $attr, ctrl, $transclude) {
  24729. var block, childScope, previousElements;
  24730. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  24731. if (value) {
  24732. if (!childScope) {
  24733. $transclude(function(clone, newScope) {
  24734. childScope = newScope;
  24735. clone[clone.length++] = $compile.$$createComment('end ngIf', $attr.ngIf);
  24736. // Note: We only need the first/last node of the cloned nodes.
  24737. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  24738. // by a directive with templateUrl when its template arrives.
  24739. block = {
  24740. clone: clone
  24741. };
  24742. $animate.enter(clone, $element.parent(), $element);
  24743. });
  24744. }
  24745. } else {
  24746. if (previousElements) {
  24747. previousElements.remove();
  24748. previousElements = null;
  24749. }
  24750. if (childScope) {
  24751. childScope.$destroy();
  24752. childScope = null;
  24753. }
  24754. if (block) {
  24755. previousElements = getBlockNodes(block.clone);
  24756. $animate.leave(previousElements).then(function() {
  24757. previousElements = null;
  24758. });
  24759. block = null;
  24760. }
  24761. }
  24762. });
  24763. }
  24764. };
  24765. }];
  24766. /**
  24767. * @ngdoc directive
  24768. * @name ngInclude
  24769. * @restrict ECA
  24770. *
  24771. * @description
  24772. * Fetches, compiles and includes an external HTML fragment.
  24773. *
  24774. * By default, the template URL is restricted to the same domain and protocol as the
  24775. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  24776. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  24777. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  24778. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  24779. * ng.$sce Strict Contextual Escaping}.
  24780. *
  24781. * In addition, the browser's
  24782. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  24783. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  24784. * policy may further restrict whether the template is successfully loaded.
  24785. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  24786. * access on some browsers.
  24787. *
  24788. * @animations
  24789. * | Animation | Occurs |
  24790. * |----------------------------------|-------------------------------------|
  24791. * | {@link ng.$animate#enter enter} | when the expression changes, on the new include |
  24792. * | {@link ng.$animate#leave leave} | when the expression changes, on the old include |
  24793. *
  24794. * The enter and leave animation occur concurrently.
  24795. *
  24796. * @scope
  24797. * @priority 400
  24798. *
  24799. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  24800. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  24801. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  24802. * <div class="alert alert-warning">
  24803. * **Note:** When using onload on SVG elements in IE11, the browser will try to call
  24804. * a function with the name on the window element, which will usually throw a
  24805. * "function is undefined" error. To fix this, you can instead use `data-onload` or a
  24806. * different form that {@link guide/directive#normalization matches} `onload`.
  24807. * </div>
  24808. *
  24809. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  24810. * $anchorScroll} to scroll the viewport after the content is loaded.
  24811. *
  24812. * - If the attribute is not set, disable scrolling.
  24813. * - If the attribute is set without value, enable scrolling.
  24814. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  24815. *
  24816. * @example
  24817. <example module="includeExample" deps="angular-animate.js" animations="true" name="ng-include">
  24818. <file name="index.html">
  24819. <div ng-controller="ExampleController">
  24820. <select ng-model="template" ng-options="t.name for t in templates">
  24821. <option value="">(blank)</option>
  24822. </select>
  24823. url of the template: <code>{{template.url}}</code>
  24824. <hr/>
  24825. <div class="slide-animate-container">
  24826. <div class="slide-animate" ng-include="template.url"></div>
  24827. </div>
  24828. </div>
  24829. </file>
  24830. <file name="script.js">
  24831. angular.module('includeExample', ['ngAnimate'])
  24832. .controller('ExampleController', ['$scope', function($scope) {
  24833. $scope.templates =
  24834. [{ name: 'template1.html', url: 'template1.html'},
  24835. { name: 'template2.html', url: 'template2.html'}];
  24836. $scope.template = $scope.templates[0];
  24837. }]);
  24838. </file>
  24839. <file name="template1.html">
  24840. Content of template1.html
  24841. </file>
  24842. <file name="template2.html">
  24843. Content of template2.html
  24844. </file>
  24845. <file name="animations.css">
  24846. .slide-animate-container {
  24847. position:relative;
  24848. background:white;
  24849. border:1px solid black;
  24850. height:40px;
  24851. overflow:hidden;
  24852. }
  24853. .slide-animate {
  24854. padding:10px;
  24855. }
  24856. .slide-animate.ng-enter, .slide-animate.ng-leave {
  24857. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  24858. position:absolute;
  24859. top:0;
  24860. left:0;
  24861. right:0;
  24862. bottom:0;
  24863. display:block;
  24864. padding:10px;
  24865. }
  24866. .slide-animate.ng-enter {
  24867. top:-50px;
  24868. }
  24869. .slide-animate.ng-enter.ng-enter-active {
  24870. top:0;
  24871. }
  24872. .slide-animate.ng-leave {
  24873. top:0;
  24874. }
  24875. .slide-animate.ng-leave.ng-leave-active {
  24876. top:50px;
  24877. }
  24878. </file>
  24879. <file name="protractor.js" type="protractor">
  24880. var templateSelect = element(by.model('template'));
  24881. var includeElem = element(by.css('[ng-include]'));
  24882. it('should load template1.html', function() {
  24883. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  24884. });
  24885. it('should load template2.html', function() {
  24886. if (browser.params.browser === 'firefox') {
  24887. // Firefox can't handle using selects
  24888. // See https://github.com/angular/protractor/issues/480
  24889. return;
  24890. }
  24891. templateSelect.click();
  24892. templateSelect.all(by.css('option')).get(2).click();
  24893. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  24894. });
  24895. it('should change to blank', function() {
  24896. if (browser.params.browser === 'firefox') {
  24897. // Firefox can't handle using selects
  24898. return;
  24899. }
  24900. templateSelect.click();
  24901. templateSelect.all(by.css('option')).get(0).click();
  24902. expect(includeElem.isPresent()).toBe(false);
  24903. });
  24904. </file>
  24905. </example>
  24906. */
  24907. /**
  24908. * @ngdoc event
  24909. * @name ngInclude#$includeContentRequested
  24910. * @eventType emit on the scope ngInclude was declared in
  24911. * @description
  24912. * Emitted every time the ngInclude content is requested.
  24913. *
  24914. * @param {Object} angularEvent Synthetic event object.
  24915. * @param {String} src URL of content to load.
  24916. */
  24917. /**
  24918. * @ngdoc event
  24919. * @name ngInclude#$includeContentLoaded
  24920. * @eventType emit on the current ngInclude scope
  24921. * @description
  24922. * Emitted every time the ngInclude content is reloaded.
  24923. *
  24924. * @param {Object} angularEvent Synthetic event object.
  24925. * @param {String} src URL of content to load.
  24926. */
  24927. /**
  24928. * @ngdoc event
  24929. * @name ngInclude#$includeContentError
  24930. * @eventType emit on the scope ngInclude was declared in
  24931. * @description
  24932. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  24933. *
  24934. * @param {Object} angularEvent Synthetic event object.
  24935. * @param {String} src URL of content to load.
  24936. */
  24937. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
  24938. function($templateRequest, $anchorScroll, $animate) {
  24939. return {
  24940. restrict: 'ECA',
  24941. priority: 400,
  24942. terminal: true,
  24943. transclude: 'element',
  24944. controller: angular.noop,
  24945. compile: function(element, attr) {
  24946. var srcExp = attr.ngInclude || attr.src,
  24947. onloadExp = attr.onload || '',
  24948. autoScrollExp = attr.autoscroll;
  24949. return function(scope, $element, $attr, ctrl, $transclude) {
  24950. var changeCounter = 0,
  24951. currentScope,
  24952. previousElement,
  24953. currentElement;
  24954. var cleanupLastIncludeContent = function() {
  24955. if (previousElement) {
  24956. previousElement.remove();
  24957. previousElement = null;
  24958. }
  24959. if (currentScope) {
  24960. currentScope.$destroy();
  24961. currentScope = null;
  24962. }
  24963. if (currentElement) {
  24964. $animate.leave(currentElement).then(function() {
  24965. previousElement = null;
  24966. });
  24967. previousElement = currentElement;
  24968. currentElement = null;
  24969. }
  24970. };
  24971. scope.$watch(srcExp, function ngIncludeWatchAction(src) {
  24972. var afterAnimation = function() {
  24973. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  24974. $anchorScroll();
  24975. }
  24976. };
  24977. var thisChangeId = ++changeCounter;
  24978. if (src) {
  24979. //set the 2nd param to true to ignore the template request error so that the inner
  24980. //contents and scope can be cleaned up.
  24981. $templateRequest(src, true).then(function(response) {
  24982. if (scope.$$destroyed) return;
  24983. if (thisChangeId !== changeCounter) return;
  24984. var newScope = scope.$new();
  24985. ctrl.template = response;
  24986. // Note: This will also link all children of ng-include that were contained in the original
  24987. // html. If that content contains controllers, ... they could pollute/change the scope.
  24988. // However, using ng-include on an element with additional content does not make sense...
  24989. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  24990. // function is called before linking the content, which would apply child
  24991. // directives to non existing elements.
  24992. var clone = $transclude(newScope, function(clone) {
  24993. cleanupLastIncludeContent();
  24994. $animate.enter(clone, null, $element).then(afterAnimation);
  24995. });
  24996. currentScope = newScope;
  24997. currentElement = clone;
  24998. currentScope.$emit('$includeContentLoaded', src);
  24999. scope.$eval(onloadExp);
  25000. }, function() {
  25001. if (scope.$$destroyed) return;
  25002. if (thisChangeId === changeCounter) {
  25003. cleanupLastIncludeContent();
  25004. scope.$emit('$includeContentError', src);
  25005. }
  25006. });
  25007. scope.$emit('$includeContentRequested', src);
  25008. } else {
  25009. cleanupLastIncludeContent();
  25010. ctrl.template = null;
  25011. }
  25012. });
  25013. };
  25014. }
  25015. };
  25016. }];
  25017. // This directive is called during the $transclude call of the first `ngInclude` directive.
  25018. // It will replace and compile the content of the element with the loaded template.
  25019. // We need this directive so that the element content is already filled when
  25020. // the link function of another directive on the same element as ngInclude
  25021. // is called.
  25022. var ngIncludeFillContentDirective = ['$compile',
  25023. function($compile) {
  25024. return {
  25025. restrict: 'ECA',
  25026. priority: -400,
  25027. require: 'ngInclude',
  25028. link: function(scope, $element, $attr, ctrl) {
  25029. if (toString.call($element[0]).match(/SVG/)) {
  25030. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  25031. // support innerHTML, so detect this here and try to generate the contents
  25032. // specially.
  25033. $element.empty();
  25034. $compile(jqLiteBuildFragment(ctrl.template, window.document).childNodes)(scope,
  25035. function namespaceAdaptedClone(clone) {
  25036. $element.append(clone);
  25037. }, {futureParentElement: $element});
  25038. return;
  25039. }
  25040. $element.html(ctrl.template);
  25041. $compile($element.contents())(scope);
  25042. }
  25043. };
  25044. }];
  25045. /**
  25046. * @ngdoc directive
  25047. * @name ngInit
  25048. * @restrict AC
  25049. *
  25050. * @description
  25051. * The `ngInit` directive allows you to evaluate an expression in the
  25052. * current scope.
  25053. *
  25054. * <div class="alert alert-danger">
  25055. * This directive can be abused to add unnecessary amounts of logic into your templates.
  25056. * There are only a few appropriate uses of `ngInit`, such as for aliasing special properties of
  25057. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below; and for injecting data via
  25058. * server side scripting. Besides these few cases, you should use {@link guide/controller controllers}
  25059. * rather than `ngInit` to initialize values on a scope.
  25060. * </div>
  25061. *
  25062. * <div class="alert alert-warning">
  25063. * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
  25064. * sure you have parentheses to ensure correct operator precedence:
  25065. * <pre class="prettyprint">
  25066. * `<div ng-init="test1 = ($index | toString)"></div>`
  25067. * </pre>
  25068. * </div>
  25069. *
  25070. * @priority 450
  25071. *
  25072. * @element ANY
  25073. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  25074. *
  25075. * @example
  25076. <example module="initExample" name="ng-init">
  25077. <file name="index.html">
  25078. <script>
  25079. angular.module('initExample', [])
  25080. .controller('ExampleController', ['$scope', function($scope) {
  25081. $scope.list = [['a', 'b'], ['c', 'd']];
  25082. }]);
  25083. </script>
  25084. <div ng-controller="ExampleController">
  25085. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  25086. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  25087. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  25088. </div>
  25089. </div>
  25090. </div>
  25091. </file>
  25092. <file name="protractor.js" type="protractor">
  25093. it('should alias index positions', function() {
  25094. var elements = element.all(by.css('.example-init'));
  25095. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  25096. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  25097. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  25098. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  25099. });
  25100. </file>
  25101. </example>
  25102. */
  25103. var ngInitDirective = ngDirective({
  25104. priority: 450,
  25105. compile: function() {
  25106. return {
  25107. pre: function(scope, element, attrs) {
  25108. scope.$eval(attrs.ngInit);
  25109. }
  25110. };
  25111. }
  25112. });
  25113. /**
  25114. * @ngdoc directive
  25115. * @name ngList
  25116. *
  25117. * @description
  25118. * Text input that converts between a delimited string and an array of strings. The default
  25119. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  25120. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  25121. *
  25122. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  25123. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  25124. * list item is respected. This implies that the user of the directive is responsible for
  25125. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  25126. * tab or newline character.
  25127. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  25128. * when joining the list items back together) and whitespace around each list item is stripped
  25129. * before it is added to the model.
  25130. *
  25131. * ### Example with Validation
  25132. *
  25133. * <example name="ngList-directive" module="listExample">
  25134. * <file name="app.js">
  25135. * angular.module('listExample', [])
  25136. * .controller('ExampleController', ['$scope', function($scope) {
  25137. * $scope.names = ['morpheus', 'neo', 'trinity'];
  25138. * }]);
  25139. * </file>
  25140. * <file name="index.html">
  25141. * <form name="myForm" ng-controller="ExampleController">
  25142. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  25143. * <span role="alert">
  25144. * <span class="error" ng-show="myForm.namesInput.$error.required">
  25145. * Required!</span>
  25146. * </span>
  25147. * <br>
  25148. * <tt>names = {{names}}</tt><br/>
  25149. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  25150. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  25151. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  25152. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  25153. * </form>
  25154. * </file>
  25155. * <file name="protractor.js" type="protractor">
  25156. * var listInput = element(by.model('names'));
  25157. * var names = element(by.exactBinding('names'));
  25158. * var valid = element(by.binding('myForm.namesInput.$valid'));
  25159. * var error = element(by.css('span.error'));
  25160. *
  25161. * it('should initialize to model', function() {
  25162. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  25163. * expect(valid.getText()).toContain('true');
  25164. * expect(error.getCssValue('display')).toBe('none');
  25165. * });
  25166. *
  25167. * it('should be invalid if empty', function() {
  25168. * listInput.clear();
  25169. * listInput.sendKeys('');
  25170. *
  25171. * expect(names.getText()).toContain('');
  25172. * expect(valid.getText()).toContain('false');
  25173. * expect(error.getCssValue('display')).not.toBe('none');
  25174. * });
  25175. * </file>
  25176. * </example>
  25177. *
  25178. * ### Example - splitting on newline
  25179. * <example name="ngList-directive-newlines">
  25180. * <file name="index.html">
  25181. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  25182. * <pre>{{ list | json }}</pre>
  25183. * </file>
  25184. * <file name="protractor.js" type="protractor">
  25185. * it("should split the text by newlines", function() {
  25186. * var listInput = element(by.model('list'));
  25187. * var output = element(by.binding('list | json'));
  25188. * listInput.sendKeys('abc\ndef\nghi');
  25189. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  25190. * });
  25191. * </file>
  25192. * </example>
  25193. *
  25194. * @element input
  25195. * @param {string=} ngList optional delimiter that should be used to split the value.
  25196. */
  25197. var ngListDirective = function() {
  25198. return {
  25199. restrict: 'A',
  25200. priority: 100,
  25201. require: 'ngModel',
  25202. link: function(scope, element, attr, ctrl) {
  25203. var ngList = attr.ngList || ', ';
  25204. var trimValues = attr.ngTrim !== 'false';
  25205. var separator = trimValues ? trim(ngList) : ngList;
  25206. var parse = function(viewValue) {
  25207. // If the viewValue is invalid (say required but empty) it will be `undefined`
  25208. if (isUndefined(viewValue)) return;
  25209. var list = [];
  25210. if (viewValue) {
  25211. forEach(viewValue.split(separator), function(value) {
  25212. if (value) list.push(trimValues ? trim(value) : value);
  25213. });
  25214. }
  25215. return list;
  25216. };
  25217. ctrl.$parsers.push(parse);
  25218. ctrl.$formatters.push(function(value) {
  25219. if (isArray(value)) {
  25220. return value.join(ngList);
  25221. }
  25222. return undefined;
  25223. });
  25224. // Override the standard $isEmpty because an empty array means the input is empty.
  25225. ctrl.$isEmpty = function(value) {
  25226. return !value || !value.length;
  25227. };
  25228. }
  25229. };
  25230. };
  25231. /* global VALID_CLASS: true,
  25232. INVALID_CLASS: true,
  25233. PRISTINE_CLASS: true,
  25234. DIRTY_CLASS: true,
  25235. UNTOUCHED_CLASS: true,
  25236. TOUCHED_CLASS: true,
  25237. $ModelOptionsProvider: true
  25238. */
  25239. var VALID_CLASS = 'ng-valid',
  25240. INVALID_CLASS = 'ng-invalid',
  25241. PRISTINE_CLASS = 'ng-pristine',
  25242. DIRTY_CLASS = 'ng-dirty',
  25243. UNTOUCHED_CLASS = 'ng-untouched',
  25244. TOUCHED_CLASS = 'ng-touched',
  25245. PENDING_CLASS = 'ng-pending',
  25246. EMPTY_CLASS = 'ng-empty',
  25247. NOT_EMPTY_CLASS = 'ng-not-empty';
  25248. var ngModelMinErr = minErr('ngModel');
  25249. /**
  25250. * @ngdoc type
  25251. * @name ngModel.NgModelController
  25252. *
  25253. * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
  25254. * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
  25255. * is set.
  25256. * @property {*} $modelValue The value in the model that the control is bound to.
  25257. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  25258. the control reads value from the DOM. The functions are called in array order, each passing
  25259. its return value through to the next. The last return value is forwarded to the
  25260. {@link ngModel.NgModelController#$validators `$validators`} collection.
  25261. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  25262. `$viewValue`}.
  25263. Returning `undefined` from a parser means a parse error occurred. In that case,
  25264. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  25265. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  25266. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  25267. *
  25268. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  25269. the model value changes. The functions are called in reverse array order, each passing the value through to the
  25270. next. The last return value is used as the actual DOM value.
  25271. Used to format / convert values for display in the control.
  25272. * ```js
  25273. * function formatter(value) {
  25274. * if (value) {
  25275. * return value.toUpperCase();
  25276. * }
  25277. * }
  25278. * ngModel.$formatters.push(formatter);
  25279. * ```
  25280. *
  25281. * @property {Object.<string, function>} $validators A collection of validators that are applied
  25282. * whenever the model value changes. The key value within the object refers to the name of the
  25283. * validator while the function refers to the validation operation. The validation operation is
  25284. * provided with the model value as an argument and must return a true or false value depending
  25285. * on the response of that validation.
  25286. *
  25287. * ```js
  25288. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  25289. * var value = modelValue || viewValue;
  25290. * return /[0-9]+/.test(value) &&
  25291. * /[a-z]+/.test(value) &&
  25292. * /[A-Z]+/.test(value) &&
  25293. * /\W+/.test(value);
  25294. * };
  25295. * ```
  25296. *
  25297. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  25298. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  25299. * is expected to return a promise when it is run during the model validation process. Once the promise
  25300. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  25301. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  25302. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  25303. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  25304. * will only run once all synchronous validators have passed.
  25305. *
  25306. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  25307. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  25308. *
  25309. * ```js
  25310. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  25311. * var value = modelValue || viewValue;
  25312. *
  25313. * // Lookup user by username
  25314. * return $http.get('/api/users/' + value).
  25315. * then(function resolved() {
  25316. * //username exists, this means validation fails
  25317. * return $q.reject('exists');
  25318. * }, function rejected() {
  25319. * //username does not exist, therefore this validation passes
  25320. * return true;
  25321. * });
  25322. * };
  25323. * ```
  25324. *
  25325. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  25326. * view value has changed. It is called with no arguments, and its return value is ignored.
  25327. * This can be used in place of additional $watches against the model value.
  25328. *
  25329. * @property {Object} $error An object hash with all failing validator ids as keys.
  25330. * @property {Object} $pending An object hash with all pending validator ids as keys.
  25331. *
  25332. * @property {boolean} $untouched True if control has not lost focus yet.
  25333. * @property {boolean} $touched True if control has lost focus.
  25334. * @property {boolean} $pristine True if user has not interacted with the control yet.
  25335. * @property {boolean} $dirty True if user has already interacted with the control.
  25336. * @property {boolean} $valid True if there is no error.
  25337. * @property {boolean} $invalid True if at least one error on the control.
  25338. * @property {string} $name The name attribute of the control.
  25339. *
  25340. * @description
  25341. *
  25342. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  25343. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  25344. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  25345. * listening to DOM events.
  25346. * Such DOM related logic should be provided by other directives which make use of
  25347. * `NgModelController` for data-binding to control elements.
  25348. * Angular provides this DOM logic for most {@link input `input`} elements.
  25349. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  25350. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  25351. *
  25352. * @example
  25353. * ### Custom Control Example
  25354. * This example shows how to use `NgModelController` with a custom control to achieve
  25355. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  25356. * collaborate together to achieve the desired result.
  25357. *
  25358. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  25359. * contents be edited in place by the user.
  25360. *
  25361. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  25362. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  25363. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  25364. * that content using the `$sce` service.
  25365. *
  25366. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  25367. <file name="style.css">
  25368. [contenteditable] {
  25369. border: 1px solid black;
  25370. background-color: white;
  25371. min-height: 20px;
  25372. }
  25373. .ng-invalid {
  25374. border: 1px solid red;
  25375. }
  25376. </file>
  25377. <file name="script.js">
  25378. angular.module('customControl', ['ngSanitize']).
  25379. directive('contenteditable', ['$sce', function($sce) {
  25380. return {
  25381. restrict: 'A', // only activate on element attribute
  25382. require: '?ngModel', // get a hold of NgModelController
  25383. link: function(scope, element, attrs, ngModel) {
  25384. if (!ngModel) return; // do nothing if no ng-model
  25385. // Specify how UI should be updated
  25386. ngModel.$render = function() {
  25387. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  25388. };
  25389. // Listen for change events to enable binding
  25390. element.on('blur keyup change', function() {
  25391. scope.$evalAsync(read);
  25392. });
  25393. read(); // initialize
  25394. // Write data to the model
  25395. function read() {
  25396. var html = element.html();
  25397. // When we clear the content editable the browser leaves a <br> behind
  25398. // If strip-br attribute is provided then we strip this out
  25399. if (attrs.stripBr && html === '<br>') {
  25400. html = '';
  25401. }
  25402. ngModel.$setViewValue(html);
  25403. }
  25404. }
  25405. };
  25406. }]);
  25407. </file>
  25408. <file name="index.html">
  25409. <form name="myForm">
  25410. <div contenteditable
  25411. name="myWidget" ng-model="userContent"
  25412. strip-br="true"
  25413. required>Change me!</div>
  25414. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  25415. <hr>
  25416. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  25417. </form>
  25418. </file>
  25419. <file name="protractor.js" type="protractor">
  25420. it('should data-bind and become invalid', function() {
  25421. if (browser.params.browser === 'safari' || browser.params.browser === 'firefox') {
  25422. // SafariDriver can't handle contenteditable
  25423. // and Firefox driver can't clear contenteditables very well
  25424. return;
  25425. }
  25426. var contentEditable = element(by.css('[contenteditable]'));
  25427. var content = 'Change me!';
  25428. expect(contentEditable.getText()).toEqual(content);
  25429. contentEditable.clear();
  25430. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  25431. expect(contentEditable.getText()).toEqual('');
  25432. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  25433. });
  25434. </file>
  25435. * </example>
  25436. *
  25437. *
  25438. */
  25439. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate', '$modelOptions',
  25440. /** @this */ function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate, $modelOptions) {
  25441. this.$viewValue = Number.NaN;
  25442. this.$modelValue = Number.NaN;
  25443. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  25444. this.$validators = {};
  25445. this.$asyncValidators = {};
  25446. this.$parsers = [];
  25447. this.$formatters = [];
  25448. this.$viewChangeListeners = [];
  25449. this.$untouched = true;
  25450. this.$touched = false;
  25451. this.$pristine = true;
  25452. this.$dirty = false;
  25453. this.$valid = true;
  25454. this.$invalid = false;
  25455. this.$error = {}; // keep invalid keys here
  25456. this.$$success = {}; // keep valid keys here
  25457. this.$pending = undefined; // keep pending keys here
  25458. this.$name = $interpolate($attr.name || '', false)($scope);
  25459. this.$$parentForm = nullFormCtrl;
  25460. this.$options = $modelOptions;
  25461. var parsedNgModel = $parse($attr.ngModel),
  25462. parsedNgModelAssign = parsedNgModel.assign,
  25463. ngModelGet = parsedNgModel,
  25464. ngModelSet = parsedNgModelAssign,
  25465. pendingDebounce = null,
  25466. parserValid,
  25467. ctrl = this;
  25468. this.$$initGetterSetters = function() {
  25469. if (ctrl.$options.getOption('getterSetter')) {
  25470. var invokeModelGetter = $parse($attr.ngModel + '()'),
  25471. invokeModelSetter = $parse($attr.ngModel + '($$$p)');
  25472. ngModelGet = function($scope) {
  25473. var modelValue = parsedNgModel($scope);
  25474. if (isFunction(modelValue)) {
  25475. modelValue = invokeModelGetter($scope);
  25476. }
  25477. return modelValue;
  25478. };
  25479. ngModelSet = function($scope, newValue) {
  25480. if (isFunction(parsedNgModel($scope))) {
  25481. invokeModelSetter($scope, {$$$p: newValue});
  25482. } else {
  25483. parsedNgModelAssign($scope, newValue);
  25484. }
  25485. };
  25486. } else if (!parsedNgModel.assign) {
  25487. throw ngModelMinErr('nonassign', 'Expression \'{0}\' is non-assignable. Element: {1}',
  25488. $attr.ngModel, startingTag($element));
  25489. }
  25490. };
  25491. /**
  25492. * @ngdoc method
  25493. * @name ngModel.NgModelController#$render
  25494. *
  25495. * @description
  25496. * Called when the view needs to be updated. It is expected that the user of the ng-model
  25497. * directive will implement this method.
  25498. *
  25499. * The `$render()` method is invoked in the following situations:
  25500. *
  25501. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  25502. * committed value then `$render()` is called to update the input control.
  25503. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  25504. * the `$viewValue` are different from last time.
  25505. *
  25506. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  25507. * `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue`
  25508. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  25509. * invoked if you only change a property on the objects.
  25510. */
  25511. this.$render = noop;
  25512. /**
  25513. * @ngdoc method
  25514. * @name ngModel.NgModelController#$isEmpty
  25515. *
  25516. * @description
  25517. * This is called when we need to determine if the value of an input is empty.
  25518. *
  25519. * For instance, the required directive does this to work out if the input has data or not.
  25520. *
  25521. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  25522. *
  25523. * You can override this for input directives whose concept of being empty is different from the
  25524. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  25525. * implies empty.
  25526. *
  25527. * @param {*} value The value of the input to check for emptiness.
  25528. * @returns {boolean} True if `value` is "empty".
  25529. */
  25530. this.$isEmpty = function(value) {
  25531. // eslint-disable-next-line no-self-compare
  25532. return isUndefined(value) || value === '' || value === null || value !== value;
  25533. };
  25534. this.$$updateEmptyClasses = function(value) {
  25535. if (ctrl.$isEmpty(value)) {
  25536. $animate.removeClass($element, NOT_EMPTY_CLASS);
  25537. $animate.addClass($element, EMPTY_CLASS);
  25538. } else {
  25539. $animate.removeClass($element, EMPTY_CLASS);
  25540. $animate.addClass($element, NOT_EMPTY_CLASS);
  25541. }
  25542. };
  25543. var currentValidationRunId = 0;
  25544. /**
  25545. * @ngdoc method
  25546. * @name ngModel.NgModelController#$setValidity
  25547. *
  25548. * @description
  25549. * Change the validity state, and notify the form.
  25550. *
  25551. * This method can be called within $parsers/$formatters or a custom validation implementation.
  25552. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  25553. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  25554. *
  25555. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  25556. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  25557. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  25558. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  25559. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  25560. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  25561. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  25562. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  25563. * Skipped is used by Angular when validators do not run because of parse errors and
  25564. * when `$asyncValidators` do not run because any of the `$validators` failed.
  25565. */
  25566. addSetValidityMethod({
  25567. ctrl: this,
  25568. $element: $element,
  25569. set: function(object, property) {
  25570. object[property] = true;
  25571. },
  25572. unset: function(object, property) {
  25573. delete object[property];
  25574. },
  25575. $animate: $animate
  25576. });
  25577. /**
  25578. * @ngdoc method
  25579. * @name ngModel.NgModelController#$setPristine
  25580. *
  25581. * @description
  25582. * Sets the control to its pristine state.
  25583. *
  25584. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  25585. * state (`ng-pristine` class). A model is considered to be pristine when the control
  25586. * has not been changed from when first compiled.
  25587. */
  25588. this.$setPristine = function() {
  25589. ctrl.$dirty = false;
  25590. ctrl.$pristine = true;
  25591. $animate.removeClass($element, DIRTY_CLASS);
  25592. $animate.addClass($element, PRISTINE_CLASS);
  25593. };
  25594. /**
  25595. * @ngdoc method
  25596. * @name ngModel.NgModelController#$setDirty
  25597. *
  25598. * @description
  25599. * Sets the control to its dirty state.
  25600. *
  25601. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  25602. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  25603. * from when first compiled.
  25604. */
  25605. this.$setDirty = function() {
  25606. ctrl.$dirty = true;
  25607. ctrl.$pristine = false;
  25608. $animate.removeClass($element, PRISTINE_CLASS);
  25609. $animate.addClass($element, DIRTY_CLASS);
  25610. ctrl.$$parentForm.$setDirty();
  25611. };
  25612. /**
  25613. * @ngdoc method
  25614. * @name ngModel.NgModelController#$setUntouched
  25615. *
  25616. * @description
  25617. * Sets the control to its untouched state.
  25618. *
  25619. * This method can be called to remove the `ng-touched` class and set the control to its
  25620. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  25621. * by default, however this function can be used to restore that state if the model has
  25622. * already been touched by the user.
  25623. */
  25624. this.$setUntouched = function() {
  25625. ctrl.$touched = false;
  25626. ctrl.$untouched = true;
  25627. $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  25628. };
  25629. /**
  25630. * @ngdoc method
  25631. * @name ngModel.NgModelController#$setTouched
  25632. *
  25633. * @description
  25634. * Sets the control to its touched state.
  25635. *
  25636. * This method can be called to remove the `ng-untouched` class and set the control to its
  25637. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  25638. * first focused the control element and then shifted focus away from the control (blur event).
  25639. */
  25640. this.$setTouched = function() {
  25641. ctrl.$touched = true;
  25642. ctrl.$untouched = false;
  25643. $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  25644. };
  25645. /**
  25646. * @ngdoc method
  25647. * @name ngModel.NgModelController#$rollbackViewValue
  25648. *
  25649. * @description
  25650. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  25651. * which may be caused by a pending debounced event or because the input is waiting for a some
  25652. * future event.
  25653. *
  25654. * If you have an input that uses `ng-model-options` to set up debounced updates or updates that
  25655. * depend on special events such as blur, you can have a situation where there is a period when
  25656. * the `$viewValue` is out of sync with the ngModel's `$modelValue`.
  25657. *
  25658. * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update
  25659. * and reset the input to the last committed view value.
  25660. *
  25661. * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`
  25662. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  25663. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  25664. *
  25665. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  25666. * input which may have such events pending. This is important in order to make sure that the
  25667. * input field will be updated with the new model value and any pending operations are cancelled.
  25668. *
  25669. * <example name="ng-model-cancel-update" module="cancel-update-example">
  25670. * <file name="app.js">
  25671. * angular.module('cancel-update-example', [])
  25672. *
  25673. * .controller('CancelUpdateController', ['$scope', function($scope) {
  25674. * $scope.model = {};
  25675. *
  25676. * $scope.setEmpty = function(e, value, rollback) {
  25677. * if (e.keyCode === 27) {
  25678. * e.preventDefault();
  25679. * if (rollback) {
  25680. * $scope.myForm[value].$rollbackViewValue();
  25681. * }
  25682. * $scope.model[value] = '';
  25683. * }
  25684. * };
  25685. * }]);
  25686. * </file>
  25687. * <file name="index.html">
  25688. * <div ng-controller="CancelUpdateController">
  25689. * <p>Both of these inputs are only updated if they are blurred. Hitting escape should
  25690. * empty them. Follow these steps and observe the difference:</p>
  25691. * <ol>
  25692. * <li>Type something in the input. You will see that the model is not yet updated</li>
  25693. * <li>Press the Escape key.
  25694. * <ol>
  25695. * <li> In the first example, nothing happens, because the model is already '', and no
  25696. * update is detected. If you blur the input, the model will be set to the current view.
  25697. * </li>
  25698. * <li> In the second example, the pending update is cancelled, and the input is set back
  25699. * to the last committed view value (''). Blurring the input does nothing.
  25700. * </li>
  25701. * </ol>
  25702. * </li>
  25703. * </ol>
  25704. *
  25705. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  25706. * <div>
  25707. * <p id="inputDescription1">Without $rollbackViewValue():</p>
  25708. * <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1"
  25709. * ng-keydown="setEmpty($event, 'value1')">
  25710. * value1: "{{ model.value1 }}"
  25711. * </div>
  25712. *
  25713. * <div>
  25714. * <p id="inputDescription2">With $rollbackViewValue():</p>
  25715. * <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2"
  25716. * ng-keydown="setEmpty($event, 'value2', true)">
  25717. * value2: "{{ model.value2 }}"
  25718. * </div>
  25719. * </form>
  25720. * </div>
  25721. * </file>
  25722. <file name="style.css">
  25723. div {
  25724. display: table-cell;
  25725. }
  25726. div:nth-child(1) {
  25727. padding-right: 30px;
  25728. }
  25729. </file>
  25730. * </example>
  25731. */
  25732. this.$rollbackViewValue = function() {
  25733. $timeout.cancel(pendingDebounce);
  25734. ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
  25735. ctrl.$render();
  25736. };
  25737. /**
  25738. * @ngdoc method
  25739. * @name ngModel.NgModelController#$validate
  25740. *
  25741. * @description
  25742. * Runs each of the registered validators (first synchronous validators and then
  25743. * asynchronous validators).
  25744. * If the validity changes to invalid, the model will be set to `undefined`,
  25745. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  25746. * If the validity changes to valid, it will set the model to the last available valid
  25747. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  25748. */
  25749. this.$validate = function() {
  25750. // ignore $validate before model is initialized
  25751. if (isNumberNaN(ctrl.$modelValue)) {
  25752. return;
  25753. }
  25754. var viewValue = ctrl.$$lastCommittedViewValue;
  25755. // Note: we use the $$rawModelValue as $modelValue might have been
  25756. // set to undefined during a view -> model update that found validation
  25757. // errors. We can't parse the view here, since that could change
  25758. // the model although neither viewValue nor the model on the scope changed
  25759. var modelValue = ctrl.$$rawModelValue;
  25760. var prevValid = ctrl.$valid;
  25761. var prevModelValue = ctrl.$modelValue;
  25762. var allowInvalid = ctrl.$options.getOption('allowInvalid');
  25763. ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
  25764. // If there was no change in validity, don't update the model
  25765. // This prevents changing an invalid modelValue to undefined
  25766. if (!allowInvalid && prevValid !== allValid) {
  25767. // Note: Don't check ctrl.$valid here, as we could have
  25768. // external validators (e.g. calculated on the server),
  25769. // that just call $setValidity and need the model value
  25770. // to calculate their validity.
  25771. ctrl.$modelValue = allValid ? modelValue : undefined;
  25772. if (ctrl.$modelValue !== prevModelValue) {
  25773. ctrl.$$writeModelToScope();
  25774. }
  25775. }
  25776. });
  25777. };
  25778. this.$$runValidators = function(modelValue, viewValue, doneCallback) {
  25779. currentValidationRunId++;
  25780. var localValidationRunId = currentValidationRunId;
  25781. // check parser error
  25782. if (!processParseErrors()) {
  25783. validationDone(false);
  25784. return;
  25785. }
  25786. if (!processSyncValidators()) {
  25787. validationDone(false);
  25788. return;
  25789. }
  25790. processAsyncValidators();
  25791. function processParseErrors() {
  25792. var errorKey = ctrl.$$parserName || 'parse';
  25793. if (isUndefined(parserValid)) {
  25794. setValidity(errorKey, null);
  25795. } else {
  25796. if (!parserValid) {
  25797. forEach(ctrl.$validators, function(v, name) {
  25798. setValidity(name, null);
  25799. });
  25800. forEach(ctrl.$asyncValidators, function(v, name) {
  25801. setValidity(name, null);
  25802. });
  25803. }
  25804. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  25805. setValidity(errorKey, parserValid);
  25806. return parserValid;
  25807. }
  25808. return true;
  25809. }
  25810. function processSyncValidators() {
  25811. var syncValidatorsValid = true;
  25812. forEach(ctrl.$validators, function(validator, name) {
  25813. var result = validator(modelValue, viewValue);
  25814. syncValidatorsValid = syncValidatorsValid && result;
  25815. setValidity(name, result);
  25816. });
  25817. if (!syncValidatorsValid) {
  25818. forEach(ctrl.$asyncValidators, function(v, name) {
  25819. setValidity(name, null);
  25820. });
  25821. return false;
  25822. }
  25823. return true;
  25824. }
  25825. function processAsyncValidators() {
  25826. var validatorPromises = [];
  25827. var allValid = true;
  25828. forEach(ctrl.$asyncValidators, function(validator, name) {
  25829. var promise = validator(modelValue, viewValue);
  25830. if (!isPromiseLike(promise)) {
  25831. throw ngModelMinErr('nopromise',
  25832. 'Expected asynchronous validator to return a promise but got \'{0}\' instead.', promise);
  25833. }
  25834. setValidity(name, undefined);
  25835. validatorPromises.push(promise.then(function() {
  25836. setValidity(name, true);
  25837. }, function() {
  25838. allValid = false;
  25839. setValidity(name, false);
  25840. }));
  25841. });
  25842. if (!validatorPromises.length) {
  25843. validationDone(true);
  25844. } else {
  25845. $q.all(validatorPromises).then(function() {
  25846. validationDone(allValid);
  25847. }, noop);
  25848. }
  25849. }
  25850. function setValidity(name, isValid) {
  25851. if (localValidationRunId === currentValidationRunId) {
  25852. ctrl.$setValidity(name, isValid);
  25853. }
  25854. }
  25855. function validationDone(allValid) {
  25856. if (localValidationRunId === currentValidationRunId) {
  25857. doneCallback(allValid);
  25858. }
  25859. }
  25860. };
  25861. /**
  25862. * @ngdoc method
  25863. * @name ngModel.NgModelController#$commitViewValue
  25864. *
  25865. * @description
  25866. * Commit a pending update to the `$modelValue`.
  25867. *
  25868. * Updates may be pending by a debounced event or because the input is waiting for a some future
  25869. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  25870. * usually handles calling this in response to input events.
  25871. */
  25872. this.$commitViewValue = function() {
  25873. var viewValue = ctrl.$viewValue;
  25874. $timeout.cancel(pendingDebounce);
  25875. // If the view value has not changed then we should just exit, except in the case where there is
  25876. // a native validator on the element. In this case the validation state may have changed even though
  25877. // the viewValue has stayed empty.
  25878. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
  25879. return;
  25880. }
  25881. ctrl.$$updateEmptyClasses(viewValue);
  25882. ctrl.$$lastCommittedViewValue = viewValue;
  25883. // change to dirty
  25884. if (ctrl.$pristine) {
  25885. this.$setDirty();
  25886. }
  25887. this.$$parseAndValidate();
  25888. };
  25889. this.$$parseAndValidate = function() {
  25890. var viewValue = ctrl.$$lastCommittedViewValue;
  25891. var modelValue = viewValue;
  25892. parserValid = isUndefined(modelValue) ? undefined : true;
  25893. if (parserValid) {
  25894. for (var i = 0; i < ctrl.$parsers.length; i++) {
  25895. modelValue = ctrl.$parsers[i](modelValue);
  25896. if (isUndefined(modelValue)) {
  25897. parserValid = false;
  25898. break;
  25899. }
  25900. }
  25901. }
  25902. if (isNumberNaN(ctrl.$modelValue)) {
  25903. // ctrl.$modelValue has not been touched yet...
  25904. ctrl.$modelValue = ngModelGet($scope);
  25905. }
  25906. var prevModelValue = ctrl.$modelValue;
  25907. var allowInvalid = ctrl.$options.getOption('allowInvalid');
  25908. ctrl.$$rawModelValue = modelValue;
  25909. if (allowInvalid) {
  25910. ctrl.$modelValue = modelValue;
  25911. writeToModelIfNeeded();
  25912. }
  25913. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  25914. // This can happen if e.g. $setViewValue is called from inside a parser
  25915. ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
  25916. if (!allowInvalid) {
  25917. // Note: Don't check ctrl.$valid here, as we could have
  25918. // external validators (e.g. calculated on the server),
  25919. // that just call $setValidity and need the model value
  25920. // to calculate their validity.
  25921. ctrl.$modelValue = allValid ? modelValue : undefined;
  25922. writeToModelIfNeeded();
  25923. }
  25924. });
  25925. function writeToModelIfNeeded() {
  25926. if (ctrl.$modelValue !== prevModelValue) {
  25927. ctrl.$$writeModelToScope();
  25928. }
  25929. }
  25930. };
  25931. this.$$writeModelToScope = function() {
  25932. ngModelSet($scope, ctrl.$modelValue);
  25933. forEach(ctrl.$viewChangeListeners, function(listener) {
  25934. try {
  25935. listener();
  25936. } catch (e) {
  25937. $exceptionHandler(e);
  25938. }
  25939. });
  25940. };
  25941. /**
  25942. * @ngdoc method
  25943. * @name ngModel.NgModelController#$setViewValue
  25944. *
  25945. * @description
  25946. * Update the view value.
  25947. *
  25948. * This method should be called when a control wants to change the view value; typically,
  25949. * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
  25950. * directive calls it when the value of the input changes and {@link ng.directive:select select}
  25951. * calls it when an option is selected.
  25952. *
  25953. * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
  25954. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  25955. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  25956. * **expression** specified in the `ng-model` attribute. Lastly, all the registered change listeners,
  25957. * in the `$viewChangeListeners` list, are called.
  25958. *
  25959. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  25960. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  25961. * `updateOn` events is triggered on the DOM element.
  25962. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  25963. * directive is used with a custom debounce for this particular event.
  25964. * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
  25965. * is specified, once the timer runs out.
  25966. *
  25967. * When used with standard inputs, the view value will always be a string (which is in some cases
  25968. * parsed into another type, such as a `Date` object for `input[date]`.)
  25969. * However, custom controls might also pass objects to this method. In this case, we should make
  25970. * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
  25971. * perform a deep watch of objects, it only looks for a change of identity. If you only change
  25972. * the property of the object then ngModel will not realize that the object has changed and
  25973. * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
  25974. * not change properties of the copy once it has been passed to `$setViewValue`.
  25975. * Otherwise you may cause the model value on the scope to change incorrectly.
  25976. *
  25977. * <div class="alert alert-info">
  25978. * In any case, the value passed to the method should always reflect the current value
  25979. * of the control. For example, if you are calling `$setViewValue` for an input element,
  25980. * you should pass the input DOM value. Otherwise, the control and the scope model become
  25981. * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
  25982. * the control's DOM value in any way. If we want to change the control's DOM value
  25983. * programmatically, we should update the `ngModel` scope expression. Its new value will be
  25984. * picked up by the model controller, which will run it through the `$formatters`, `$render` it
  25985. * to update the DOM, and finally call `$validate` on it.
  25986. * </div>
  25987. *
  25988. * @param {*} value value from the view.
  25989. * @param {string} trigger Event that triggered the update.
  25990. */
  25991. this.$setViewValue = function(value, trigger) {
  25992. ctrl.$viewValue = value;
  25993. if (ctrl.$options.getOption('updateOnDefault')) {
  25994. ctrl.$$debounceViewValueCommit(trigger);
  25995. }
  25996. };
  25997. this.$$debounceViewValueCommit = function(trigger) {
  25998. var options = ctrl.$options,
  25999. debounceDelay = options.getOption('debounce');
  26000. if (isNumber(debounceDelay[trigger])) {
  26001. debounceDelay = debounceDelay[trigger];
  26002. } else if (isNumber(debounceDelay['default'])) {
  26003. debounceDelay = debounceDelay['default'];
  26004. }
  26005. $timeout.cancel(pendingDebounce);
  26006. if (debounceDelay) {
  26007. pendingDebounce = $timeout(function() {
  26008. ctrl.$commitViewValue();
  26009. }, debounceDelay);
  26010. } else if ($rootScope.$$phase) {
  26011. ctrl.$commitViewValue();
  26012. } else {
  26013. $scope.$apply(function() {
  26014. ctrl.$commitViewValue();
  26015. });
  26016. }
  26017. };
  26018. // model -> value
  26019. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  26020. // 1. scope value is 'a'
  26021. // 2. user enters 'b'
  26022. // 3. ng-change kicks in and reverts scope value to 'a'
  26023. // -> scope value did not change since the last digest as
  26024. // ng-change executes in apply phase
  26025. // 4. view should be changed back to 'a'
  26026. $scope.$watch(function ngModelWatch() {
  26027. var modelValue = ngModelGet($scope);
  26028. // if scope model value and ngModel value are out of sync
  26029. // TODO(perf): why not move this to the action fn?
  26030. if (modelValue !== ctrl.$modelValue &&
  26031. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  26032. // eslint-disable-next-line no-self-compare
  26033. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  26034. ) {
  26035. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  26036. parserValid = undefined;
  26037. var formatters = ctrl.$formatters,
  26038. idx = formatters.length;
  26039. var viewValue = modelValue;
  26040. while (idx--) {
  26041. viewValue = formatters[idx](viewValue);
  26042. }
  26043. if (ctrl.$viewValue !== viewValue) {
  26044. ctrl.$$updateEmptyClasses(viewValue);
  26045. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  26046. ctrl.$render();
  26047. // It is possible that model and view value have been updated during render
  26048. ctrl.$$runValidators(ctrl.$modelValue, ctrl.$viewValue, noop);
  26049. }
  26050. }
  26051. return modelValue;
  26052. });
  26053. }];
  26054. /**
  26055. * @ngdoc directive
  26056. * @name ngModel
  26057. *
  26058. * @element input
  26059. * @priority 1
  26060. *
  26061. * @description
  26062. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  26063. * property on the scope using {@link ngModel.NgModelController NgModelController},
  26064. * which is created and exposed by this directive.
  26065. *
  26066. * `ngModel` is responsible for:
  26067. *
  26068. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  26069. * require.
  26070. * - Providing validation behavior (i.e. required, number, email, url).
  26071. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  26072. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
  26073. * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
  26074. * - Registering the control with its parent {@link ng.directive:form form}.
  26075. *
  26076. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  26077. * current scope. If the property doesn't already exist on this scope, it will be created
  26078. * implicitly and added to the scope.
  26079. *
  26080. * For best practices on using `ngModel`, see:
  26081. *
  26082. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  26083. *
  26084. * For basic examples, how to use `ngModel`, see:
  26085. *
  26086. * - {@link ng.directive:input input}
  26087. * - {@link input[text] text}
  26088. * - {@link input[checkbox] checkbox}
  26089. * - {@link input[radio] radio}
  26090. * - {@link input[number] number}
  26091. * - {@link input[email] email}
  26092. * - {@link input[url] url}
  26093. * - {@link input[date] date}
  26094. * - {@link input[datetime-local] datetime-local}
  26095. * - {@link input[time] time}
  26096. * - {@link input[month] month}
  26097. * - {@link input[week] week}
  26098. * - {@link ng.directive:select select}
  26099. * - {@link ng.directive:textarea textarea}
  26100. *
  26101. * # Complex Models (objects or collections)
  26102. *
  26103. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  26104. * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the
  26105. * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered.
  26106. *
  26107. * The model must be assigned an entirely new object or collection before a re-rendering will occur.
  26108. *
  26109. * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression
  26110. * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or
  26111. * if the select is given the `multiple` attribute.
  26112. *
  26113. * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the
  26114. * first level of the object (or only changing the properties of an item in the collection if it's an array) will still
  26115. * not trigger a re-rendering of the model.
  26116. *
  26117. * # CSS classes
  26118. * The following CSS classes are added and removed on the associated input/select/textarea element
  26119. * depending on the validity of the model.
  26120. *
  26121. * - `ng-valid`: the model is valid
  26122. * - `ng-invalid`: the model is invalid
  26123. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  26124. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  26125. * - `ng-pristine`: the control hasn't been interacted with yet
  26126. * - `ng-dirty`: the control has been interacted with
  26127. * - `ng-touched`: the control has been blurred
  26128. * - `ng-untouched`: the control hasn't been blurred
  26129. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  26130. * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
  26131. * by the {@link ngModel.NgModelController#$isEmpty} method
  26132. * - `ng-not-empty`: the view contains a non-empty value
  26133. *
  26134. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  26135. *
  26136. * ## Animation Hooks
  26137. *
  26138. * Animations within models are triggered when any of the associated CSS classes are added and removed
  26139. * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
  26140. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  26141. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  26142. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  26143. *
  26144. * The following example shows a simple way to utilize CSS transitions to style an input element
  26145. * that has been rendered as invalid after it has been validated:
  26146. *
  26147. * <pre>
  26148. * //be sure to include ngAnimate as a module to hook into more
  26149. * //advanced animations
  26150. * .my-input {
  26151. * transition:0.5s linear all;
  26152. * background: white;
  26153. * }
  26154. * .my-input.ng-invalid {
  26155. * background: red;
  26156. * color:white;
  26157. * }
  26158. * </pre>
  26159. *
  26160. * @example
  26161. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample" name="ng-model">
  26162. <file name="index.html">
  26163. <script>
  26164. angular.module('inputExample', [])
  26165. .controller('ExampleController', ['$scope', function($scope) {
  26166. $scope.val = '1';
  26167. }]);
  26168. </script>
  26169. <style>
  26170. .my-input {
  26171. transition:all linear 0.5s;
  26172. background: transparent;
  26173. }
  26174. .my-input.ng-invalid {
  26175. color:white;
  26176. background: red;
  26177. }
  26178. </style>
  26179. <p id="inputDescription">
  26180. Update input to see transitions when valid/invalid.
  26181. Integer is a valid value.
  26182. </p>
  26183. <form name="testForm" ng-controller="ExampleController">
  26184. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  26185. aria-describedby="inputDescription" />
  26186. </form>
  26187. </file>
  26188. * </example>
  26189. *
  26190. * ## Binding to a getter/setter
  26191. *
  26192. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  26193. * function that returns a representation of the model when called with zero arguments, and sets
  26194. * the internal state of a model when called with an argument. It's sometimes useful to use this
  26195. * for models that have an internal representation that's different from what the model exposes
  26196. * to the view.
  26197. *
  26198. * <div class="alert alert-success">
  26199. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  26200. * frequently than other parts of your code.
  26201. * </div>
  26202. *
  26203. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  26204. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  26205. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  26206. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  26207. *
  26208. * The following example shows how to use `ngModel` with a getter/setter:
  26209. *
  26210. * @example
  26211. * <example name="ngModel-getter-setter" module="getterSetterExample">
  26212. <file name="index.html">
  26213. <div ng-controller="ExampleController">
  26214. <form name="userForm">
  26215. <label>Name:
  26216. <input type="text" name="userName"
  26217. ng-model="user.name"
  26218. ng-model-options="{ getterSetter: true }" />
  26219. </label>
  26220. </form>
  26221. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  26222. </div>
  26223. </file>
  26224. <file name="app.js">
  26225. angular.module('getterSetterExample', [])
  26226. .controller('ExampleController', ['$scope', function($scope) {
  26227. var _name = 'Brian';
  26228. $scope.user = {
  26229. name: function(newName) {
  26230. // Note that newName can be undefined for two reasons:
  26231. // 1. Because it is called as a getter and thus called with no arguments
  26232. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  26233. // input is invalid
  26234. return arguments.length ? (_name = newName) : _name;
  26235. }
  26236. };
  26237. }]);
  26238. </file>
  26239. * </example>
  26240. */
  26241. var ngModelDirective = ['$rootScope', function($rootScope) {
  26242. return {
  26243. restrict: 'A',
  26244. require: ['ngModel', '^?form', '^?ngModelOptions'],
  26245. controller: NgModelController,
  26246. // Prelink needs to run before any input directive
  26247. // so that we can set the NgModelOptions in NgModelController
  26248. // before anyone else uses it.
  26249. priority: 1,
  26250. compile: function ngModelCompile(element) {
  26251. // Setup initial state of the control
  26252. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  26253. return {
  26254. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  26255. var modelCtrl = ctrls[0],
  26256. formCtrl = ctrls[1] || modelCtrl.$$parentForm,
  26257. optionsCtrl = ctrls[2];
  26258. if (optionsCtrl) {
  26259. modelCtrl.$options = optionsCtrl.$options;
  26260. }
  26261. modelCtrl.$$initGetterSetters();
  26262. // notify others, especially parent forms
  26263. formCtrl.$addControl(modelCtrl);
  26264. attr.$observe('name', function(newValue) {
  26265. if (modelCtrl.$name !== newValue) {
  26266. modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
  26267. }
  26268. });
  26269. scope.$on('$destroy', function() {
  26270. modelCtrl.$$parentForm.$removeControl(modelCtrl);
  26271. });
  26272. },
  26273. post: function ngModelPostLink(scope, element, attr, ctrls) {
  26274. var modelCtrl = ctrls[0];
  26275. if (modelCtrl.$options.getOption('updateOn')) {
  26276. element.on(modelCtrl.$options.getOption('updateOn'), function(ev) {
  26277. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  26278. });
  26279. }
  26280. element.on('blur', function() {
  26281. if (modelCtrl.$touched) return;
  26282. if ($rootScope.$$phase) {
  26283. scope.$evalAsync(modelCtrl.$setTouched);
  26284. } else {
  26285. scope.$apply(modelCtrl.$setTouched);
  26286. }
  26287. });
  26288. }
  26289. };
  26290. }
  26291. };
  26292. }];
  26293. /**
  26294. * @ngdoc directive
  26295. * @name ngModelOptions
  26296. *
  26297. * @description
  26298. * This directive allows you to modify the behaviour of ngModel and input directives within your
  26299. * application. You can specify an ngModelOptions directive on any element and the settings affect
  26300. * the ngModel and input directives on all descendent elements.
  26301. *
  26302. * The ngModelOptions settings are found by evaluating the value of the ngModelOptions attribute as
  26303. * an Angular expression. This expression should evaluate to an object, whose properties contain
  26304. * the settings.
  26305. *
  26306. * If a setting is not specified as a property on the object for a particular ngModelOptions directive
  26307. * then it will inherit that setting from the first ngModelOptions directive found by traversing up the
  26308. * DOM tree. If there is no ancestor element containing an ngModelOptions directive then the settings in
  26309. * {@link $modelOptions} will be used.
  26310. *
  26311. * For example given the following fragment of HTML
  26312. *
  26313. *
  26314. * ```html
  26315. * <div ng-model-options="{ allowInvalid: true }">
  26316. * <form ng-model-options="{ updateOn: 'blur' }">
  26317. * <input ng-model-options="{ updateOn: 'default' }" />
  26318. * </form>
  26319. * </div>
  26320. * ```
  26321. *
  26322. * the `input` element will have the following settings
  26323. *
  26324. * ```js
  26325. * { allowInvalid: true, updateOn: 'default' }
  26326. * ```
  26327. *
  26328. *
  26329. * ## Triggering and debouncing model updates
  26330. *
  26331. * The `updateOn` and `debounce` properties allow you to specify a custom list of events that will
  26332. * trigger a model update and/or a debouncing delay so that the actual update only takes place when
  26333. * a timer expires; this timer will be reset after another change takes place.
  26334. *
  26335. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  26336. * be different from the value in the actual model. This means that if you update the model you
  26337. * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
  26338. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  26339. *
  26340. * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
  26341. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  26342. * important because `form` controllers are published to the related scope under the name in their
  26343. * `name` attribute.
  26344. *
  26345. * Any pending changes will take place immediately when an enclosing form is submitted via the
  26346. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  26347. * to have access to the updated model.
  26348. *
  26349. * The following example shows how to override immediate updates. Changes on the inputs within the
  26350. * form will update the model only when the control loses focus (blur event). If `escape` key is
  26351. * pressed while the input field is focused, the value is reset to the value in the current model.
  26352. *
  26353. * <example name="ngModelOptions-directive-blur" module="optionsExample">
  26354. * <file name="index.html">
  26355. * <div ng-controller="ExampleController">
  26356. * <form name="userForm">
  26357. * <label>
  26358. * Name:
  26359. * <input type="text" name="userName"
  26360. * ng-model="user.name"
  26361. * ng-model-options="{ updateOn: 'blur' }"
  26362. * ng-keyup="cancel($event)" />
  26363. * </label><br />
  26364. * <label>
  26365. * Other data:
  26366. * <input type="text" ng-model="user.data" />
  26367. * </label><br />
  26368. * </form>
  26369. * <pre>user.name = <span ng-bind="user.name"></span></pre>
  26370. * </div>
  26371. * </file>
  26372. * <file name="app.js">
  26373. * angular.module('optionsExample', [])
  26374. * .controller('ExampleController', ['$scope', function($scope) {
  26375. * $scope.user = { name: 'say', data: '' };
  26376. *
  26377. * $scope.cancel = function(e) {
  26378. * if (e.keyCode === 27) {
  26379. * $scope.userForm.userName.$rollbackViewValue();
  26380. * }
  26381. * };
  26382. * }]);
  26383. * </file>
  26384. * <file name="protractor.js" type="protractor">
  26385. * var model = element(by.binding('user.name'));
  26386. * var input = element(by.model('user.name'));
  26387. * var other = element(by.model('user.data'));
  26388. *
  26389. * it('should allow custom events', function() {
  26390. * input.sendKeys(' hello');
  26391. * input.click();
  26392. * expect(model.getText()).toEqual('say');
  26393. * other.click();
  26394. * expect(model.getText()).toEqual('say hello');
  26395. * });
  26396. *
  26397. * it('should $rollbackViewValue when model changes', function() {
  26398. * input.sendKeys(' hello');
  26399. * expect(input.getAttribute('value')).toEqual('say hello');
  26400. * input.sendKeys(protractor.Key.ESCAPE);
  26401. * expect(input.getAttribute('value')).toEqual('say');
  26402. * other.click();
  26403. * expect(model.getText()).toEqual('say');
  26404. * });
  26405. * </file>
  26406. * </example>
  26407. *
  26408. * The next example shows how to debounce model changes. Model will be updated only 1 sec after last change.
  26409. * If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  26410. *
  26411. * <example name="ngModelOptions-directive-debounce" module="optionsExample">
  26412. * <file name="index.html">
  26413. * <div ng-controller="ExampleController">
  26414. * <form name="userForm">
  26415. * Name:
  26416. * <input type="text" name="userName"
  26417. * ng-model="user.name"
  26418. * ng-model-options="{ debounce: 1000 }" />
  26419. * <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
  26420. * </form>
  26421. * <pre>user.name = <span ng-bind="user.name"></span></pre>
  26422. * </div>
  26423. * </file>
  26424. * <file name="app.js">
  26425. * angular.module('optionsExample', [])
  26426. * .controller('ExampleController', ['$scope', function($scope) {
  26427. * $scope.user = { name: 'say' };
  26428. * }]);
  26429. * </file>
  26430. * </example>
  26431. *
  26432. * ## Model updates and validation
  26433. *
  26434. * The default behaviour in `ngModel` is that the model value is set to `undefined` when the
  26435. * validation determines that the value is invalid. By setting the `allowInvalid` property to true,
  26436. * the model will still be updated even if the value is invalid.
  26437. *
  26438. *
  26439. * ## Connecting to the scope
  26440. *
  26441. * By setting the `getterSetter` property to true you are telling ngModel that the `ngModel` expression
  26442. * on the scope refers to a "getter/setter" function rather than the value itself.
  26443. *
  26444. * The following example shows how to bind to getter/setters:
  26445. *
  26446. * <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  26447. * <file name="index.html">
  26448. * <div ng-controller="ExampleController">
  26449. * <form name="userForm">
  26450. * <label>
  26451. * Name:
  26452. * <input type="text" name="userName"
  26453. * ng-model="user.name"
  26454. * ng-model-options="{ getterSetter: true }" />
  26455. * </label>
  26456. * </form>
  26457. * <pre>user.name = <span ng-bind="user.name()"></span></pre>
  26458. * </div>
  26459. * </file>
  26460. * <file name="app.js">
  26461. * angular.module('getterSetterExample', [])
  26462. * .controller('ExampleController', ['$scope', function($scope) {
  26463. * var _name = 'Brian';
  26464. * $scope.user = {
  26465. * name: function(newName) {
  26466. * return angular.isDefined(newName) ? (_name = newName) : _name;
  26467. * }
  26468. * };
  26469. * }]);
  26470. * </file>
  26471. * </example>
  26472. *
  26473. *
  26474. * ## Specifying timezones
  26475. *
  26476. * You can specify the timezone that date/time input directives expect by providing its name in the
  26477. * `timezone` property.
  26478. *
  26479. * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
  26480. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  26481. * events using an space delimited list. There is a special event called `default` that
  26482. * matches the default events belonging to the control.
  26483. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  26484. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  26485. * custom value for each event. For example:
  26486. * `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
  26487. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  26488. * not validate correctly instead of the default behavior of setting the model to undefined.
  26489. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  26490. * `ngModel` as getters/setters.
  26491. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  26492. * `<input type="date" />`, `<input type="time" />`, ... . It understands UTC/GMT and the
  26493. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  26494. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  26495. * If not specified, the timezone of the browser will be used.
  26496. *
  26497. */
  26498. var ngModelOptionsDirective = ['$modelOptions', function($modelOptions) {
  26499. return {
  26500. restrict: 'A',
  26501. // ngModelOptions needs to run before ngModel and input directives
  26502. priority: 10,
  26503. require: ['ngModelOptions', '?^^ngModelOptions'],
  26504. controller: function NgModelOptionsController() {},
  26505. link: {
  26506. pre: function ngModelOptionsPreLinkFn(scope, element, attrs, ctrls) {
  26507. var optionsCtrl = ctrls[0];
  26508. var parentOptions = ctrls[1] ? ctrls[1].$options : $modelOptions;
  26509. optionsCtrl.$options = parentOptions.createChild(scope.$eval(attrs.ngModelOptions));
  26510. }
  26511. }
  26512. };
  26513. }];
  26514. /**
  26515. * @ngdoc provider
  26516. * @name $modelOptionsProvider
  26517. * @description
  26518. *
  26519. * Here, you can change the default settings from which {@link ngModelOptions}
  26520. * directives inherit.
  26521. *
  26522. * See the {@link ngModelOptions} directive for a list of the available options.
  26523. */
  26524. function $ModelOptionsProvider() {
  26525. return {
  26526. /**
  26527. * @ngdoc property
  26528. * @name $modelOptionsProvider#defaultOptions
  26529. * @type {Object}
  26530. * @description
  26531. * The default options to fall back on when there are no more ngModelOption
  26532. * directives as ancestors.
  26533. * Use this property to specify the defaultOptions for the application as a whole.
  26534. *
  26535. * The initial default options are:
  26536. *
  26537. * * `updateOn`: `default`
  26538. * * `debounce`: `0`
  26539. * * `allowInvalid`: `undefined`
  26540. * * `getterSetter`: `undefined`
  26541. * * `timezone`: 'undefined'
  26542. */
  26543. defaultOptions: {
  26544. updateOn: 'default',
  26545. debounce: 0
  26546. },
  26547. /**
  26548. * @ngdoc service
  26549. * @name $modelOptions
  26550. * @type ModelOptions
  26551. * @description
  26552. *
  26553. * This service provides the application wide default {@link ModelOptions} options that
  26554. * will be used by {@link ngModel} directives if no {@link ngModelOptions} directive is
  26555. * specified.
  26556. */
  26557. $get: function() {
  26558. return new ModelOptions(this.defaultOptions);
  26559. }
  26560. };
  26561. }
  26562. /**
  26563. * @ngdoc type
  26564. * @name ModelOptions
  26565. * @description
  26566. * A container for the options set by the {@link ngModelOptions} directive
  26567. * and the {@link $modelOptions} service.
  26568. */
  26569. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  26570. function ModelOptions(options, parentOptions) {
  26571. // Extend the parent's options with these new ones
  26572. var _options = extend({}, parentOptions, options);
  26573. // do extra processing on the options
  26574. // updateOn and updateOnDefault
  26575. if (isDefined(_options.updateOn) && _options.updateOn.trim()) {
  26576. _options.updateOnDefault = false;
  26577. // extract "default" pseudo-event from list of events that can trigger a model update
  26578. _options.updateOn = trim(_options.updateOn.replace(DEFAULT_REGEXP, function() {
  26579. _options.updateOnDefault = true;
  26580. return ' ';
  26581. }));
  26582. } else if (parentOptions) {
  26583. _options.updateOn = parentOptions.updateOn;
  26584. _options.updateOnDefault = parentOptions.updateOnDefault;
  26585. } else {
  26586. _options.updateOnDefault = true;
  26587. }
  26588. /**
  26589. * @ngdoc method
  26590. * @name ModelOptions#getOption
  26591. * @param {string} name the name of the option to retrieve
  26592. * @returns {*} the value of the option
  26593. * @description
  26594. * Returns the value of the given option
  26595. */
  26596. this.getOption = function(name) { return _options[name]; };
  26597. /**
  26598. * @ngdoc method
  26599. * @name ModelOptions#createChild
  26600. * @param {Object} options a hash of options for the new child that will override the parent's options
  26601. * @return {ModelOptions} a new `ModelOptions` object initialized with the given options.
  26602. */
  26603. this.createChild = function(options) {
  26604. return new ModelOptions(options, _options);
  26605. };
  26606. }
  26607. // helper methods
  26608. function addSetValidityMethod(context) {
  26609. var ctrl = context.ctrl,
  26610. $element = context.$element,
  26611. classCache = {},
  26612. set = context.set,
  26613. unset = context.unset,
  26614. $animate = context.$animate;
  26615. classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
  26616. ctrl.$setValidity = setValidity;
  26617. function setValidity(validationErrorKey, state, controller) {
  26618. if (isUndefined(state)) {
  26619. createAndSet('$pending', validationErrorKey, controller);
  26620. } else {
  26621. unsetAndCleanup('$pending', validationErrorKey, controller);
  26622. }
  26623. if (!isBoolean(state)) {
  26624. unset(ctrl.$error, validationErrorKey, controller);
  26625. unset(ctrl.$$success, validationErrorKey, controller);
  26626. } else {
  26627. if (state) {
  26628. unset(ctrl.$error, validationErrorKey, controller);
  26629. set(ctrl.$$success, validationErrorKey, controller);
  26630. } else {
  26631. set(ctrl.$error, validationErrorKey, controller);
  26632. unset(ctrl.$$success, validationErrorKey, controller);
  26633. }
  26634. }
  26635. if (ctrl.$pending) {
  26636. cachedToggleClass(PENDING_CLASS, true);
  26637. ctrl.$valid = ctrl.$invalid = undefined;
  26638. toggleValidationCss('', null);
  26639. } else {
  26640. cachedToggleClass(PENDING_CLASS, false);
  26641. ctrl.$valid = isObjectEmpty(ctrl.$error);
  26642. ctrl.$invalid = !ctrl.$valid;
  26643. toggleValidationCss('', ctrl.$valid);
  26644. }
  26645. // re-read the state as the set/unset methods could have
  26646. // combined state in ctrl.$error[validationError] (used for forms),
  26647. // where setting/unsetting only increments/decrements the value,
  26648. // and does not replace it.
  26649. var combinedState;
  26650. if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
  26651. combinedState = undefined;
  26652. } else if (ctrl.$error[validationErrorKey]) {
  26653. combinedState = false;
  26654. } else if (ctrl.$$success[validationErrorKey]) {
  26655. combinedState = true;
  26656. } else {
  26657. combinedState = null;
  26658. }
  26659. toggleValidationCss(validationErrorKey, combinedState);
  26660. ctrl.$$parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
  26661. }
  26662. function createAndSet(name, value, controller) {
  26663. if (!ctrl[name]) {
  26664. ctrl[name] = {};
  26665. }
  26666. set(ctrl[name], value, controller);
  26667. }
  26668. function unsetAndCleanup(name, value, controller) {
  26669. if (ctrl[name]) {
  26670. unset(ctrl[name], value, controller);
  26671. }
  26672. if (isObjectEmpty(ctrl[name])) {
  26673. ctrl[name] = undefined;
  26674. }
  26675. }
  26676. function cachedToggleClass(className, switchValue) {
  26677. if (switchValue && !classCache[className]) {
  26678. $animate.addClass($element, className);
  26679. classCache[className] = true;
  26680. } else if (!switchValue && classCache[className]) {
  26681. $animate.removeClass($element, className);
  26682. classCache[className] = false;
  26683. }
  26684. }
  26685. function toggleValidationCss(validationErrorKey, isValid) {
  26686. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  26687. cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
  26688. cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
  26689. }
  26690. }
  26691. function isObjectEmpty(obj) {
  26692. if (obj) {
  26693. for (var prop in obj) {
  26694. if (obj.hasOwnProperty(prop)) {
  26695. return false;
  26696. }
  26697. }
  26698. }
  26699. return true;
  26700. }
  26701. /**
  26702. * @ngdoc directive
  26703. * @name ngNonBindable
  26704. * @restrict AC
  26705. * @priority 1000
  26706. *
  26707. * @description
  26708. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  26709. * DOM element. This is useful if the element contains what appears to be Angular directives and
  26710. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  26711. * displays snippets of code, for instance.
  26712. *
  26713. * @element ANY
  26714. *
  26715. * @example
  26716. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  26717. * but the one wrapped in `ngNonBindable` is left alone.
  26718. *
  26719. * @example
  26720. <example name="ng-non-bindable">
  26721. <file name="index.html">
  26722. <div>Normal: {{1 + 2}}</div>
  26723. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  26724. </file>
  26725. <file name="protractor.js" type="protractor">
  26726. it('should check ng-non-bindable', function() {
  26727. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  26728. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  26729. });
  26730. </file>
  26731. </example>
  26732. */
  26733. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  26734. /* exported ngOptionsDirective */
  26735. /* global jqLiteRemove */
  26736. var ngOptionsMinErr = minErr('ngOptions');
  26737. /**
  26738. * @ngdoc directive
  26739. * @name ngOptions
  26740. * @restrict A
  26741. *
  26742. * @description
  26743. *
  26744. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  26745. * elements for the `<select>` element using the array or object obtained by evaluating the
  26746. * `ngOptions` comprehension expression.
  26747. *
  26748. * In many cases, {@link ng.directive:ngRepeat ngRepeat} can be used on `<option>` elements instead of
  26749. * `ngOptions` to achieve a similar result. However, `ngOptions` provides some benefits:
  26750. * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  26751. * comprehension expression
  26752. * - reduced memory consumption by not creating a new scope for each repeated instance
  26753. * - increased render speed by creating the options in a documentFragment instead of individually
  26754. *
  26755. * When an item in the `<select>` menu is selected, the array element or object property
  26756. * represented by the selected option will be bound to the model identified by the `ngModel`
  26757. * directive.
  26758. *
  26759. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  26760. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  26761. * option. See example below for demonstration.
  26762. *
  26763. * ## Complex Models (objects or collections)
  26764. *
  26765. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  26766. * binding the select to a model that is an object or a collection.
  26767. *
  26768. * One issue occurs if you want to preselect an option. For example, if you set
  26769. * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
  26770. * because the objects are not identical. So by default, you should always reference the item in your collection
  26771. * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
  26772. *
  26773. * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
  26774. * of the item not by reference, but by the result of the `track by` expression. For example, if your
  26775. * collection items have an id property, you would `track by item.id`.
  26776. *
  26777. * A different issue with objects or collections is that ngModel won't detect if an object property or
  26778. * a collection item changes. For that reason, `ngOptions` additionally watches the model using
  26779. * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
  26780. * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
  26781. * has not changed identity, but only a property on the object or an item in the collection changes.
  26782. *
  26783. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  26784. * if the model is an array). This means that changing a property deeper than the first level inside the
  26785. * object/collection will not trigger a re-rendering.
  26786. *
  26787. * ## `select` **`as`**
  26788. *
  26789. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  26790. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  26791. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  26792. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  26793. *
  26794. *
  26795. * ### `select` **`as`** and **`track by`**
  26796. *
  26797. * <div class="alert alert-warning">
  26798. * Be careful when using `select` **`as`** and **`track by`** in the same expression.
  26799. * </div>
  26800. *
  26801. * Given this array of items on the $scope:
  26802. *
  26803. * ```js
  26804. * $scope.items = [{
  26805. * id: 1,
  26806. * label: 'aLabel',
  26807. * subItem: { name: 'aSubItem' }
  26808. * }, {
  26809. * id: 2,
  26810. * label: 'bLabel',
  26811. * subItem: { name: 'bSubItem' }
  26812. * }];
  26813. * ```
  26814. *
  26815. * This will work:
  26816. *
  26817. * ```html
  26818. * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
  26819. * ```
  26820. * ```js
  26821. * $scope.selected = $scope.items[0];
  26822. * ```
  26823. *
  26824. * but this will not work:
  26825. *
  26826. * ```html
  26827. * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
  26828. * ```
  26829. * ```js
  26830. * $scope.selected = $scope.items[0].subItem;
  26831. * ```
  26832. *
  26833. * In both examples, the **`track by`** expression is applied successfully to each `item` in the
  26834. * `items` array. Because the selected option has been set programmatically in the controller, the
  26835. * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
  26836. * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
  26837. * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
  26838. * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
  26839. * is not matched against any `<option>` and the `<select>` appears as having no selected value.
  26840. *
  26841. *
  26842. * @param {string} ngModel Assignable angular expression to data-bind to.
  26843. * @param {string=} name Property name of the form under which the control is published.
  26844. * @param {string=} required The control is considered valid only if value is entered.
  26845. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  26846. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  26847. * `required` when you want to data-bind to the `required` attribute.
  26848. * @param {comprehension_expression=} ngOptions in one of the following forms:
  26849. *
  26850. * * for array data sources:
  26851. * * `label` **`for`** `value` **`in`** `array`
  26852. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  26853. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  26854. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  26855. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  26856. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  26857. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  26858. * (for including a filter with `track by`)
  26859. * * for object data sources:
  26860. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  26861. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  26862. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  26863. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  26864. * * `select` **`as`** `label` **`group by`** `group`
  26865. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  26866. * * `select` **`as`** `label` **`disable when`** `disable`
  26867. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  26868. *
  26869. * Where:
  26870. *
  26871. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  26872. * * `value`: local variable which will refer to each item in the `array` or each property value
  26873. * of `object` during iteration.
  26874. * * `key`: local variable which will refer to a property name in `object` during iteration.
  26875. * * `label`: The result of this expression will be the label for `<option>` element. The
  26876. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  26877. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  26878. * element. If not specified, `select` expression will default to `value`.
  26879. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  26880. * DOM element.
  26881. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  26882. * element. Return `true` to disable.
  26883. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  26884. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  26885. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  26886. * even when the options are recreated (e.g. reloaded from the server).
  26887. *
  26888. * @example
  26889. <example module="selectExample" name="select">
  26890. <file name="index.html">
  26891. <script>
  26892. angular.module('selectExample', [])
  26893. .controller('ExampleController', ['$scope', function($scope) {
  26894. $scope.colors = [
  26895. {name:'black', shade:'dark'},
  26896. {name:'white', shade:'light', notAnOption: true},
  26897. {name:'red', shade:'dark'},
  26898. {name:'blue', shade:'dark', notAnOption: true},
  26899. {name:'yellow', shade:'light', notAnOption: false}
  26900. ];
  26901. $scope.myColor = $scope.colors[2]; // red
  26902. }]);
  26903. </script>
  26904. <div ng-controller="ExampleController">
  26905. <ul>
  26906. <li ng-repeat="color in colors">
  26907. <label>Name: <input ng-model="color.name"></label>
  26908. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  26909. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  26910. </li>
  26911. <li>
  26912. <button ng-click="colors.push({})">add</button>
  26913. </li>
  26914. </ul>
  26915. <hr/>
  26916. <label>Color (null not allowed):
  26917. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  26918. </label><br/>
  26919. <label>Color (null allowed):
  26920. <span class="nullable">
  26921. <select ng-model="myColor" ng-options="color.name for color in colors">
  26922. <option value="">-- choose color --</option>
  26923. </select>
  26924. </span></label><br/>
  26925. <label>Color grouped by shade:
  26926. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  26927. </select>
  26928. </label><br/>
  26929. <label>Color grouped by shade, with some disabled:
  26930. <select ng-model="myColor"
  26931. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  26932. </select>
  26933. </label><br/>
  26934. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  26935. <br/>
  26936. <hr/>
  26937. Currently selected: {{ {selected_color:myColor} }}
  26938. <div style="border:solid 1px black; height:20px"
  26939. ng-style="{'background-color':myColor.name}">
  26940. </div>
  26941. </div>
  26942. </file>
  26943. <file name="protractor.js" type="protractor">
  26944. it('should check ng-options', function() {
  26945. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  26946. element.all(by.model('myColor')).first().click();
  26947. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  26948. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  26949. element(by.css('.nullable select[ng-model="myColor"]')).click();
  26950. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  26951. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  26952. });
  26953. </file>
  26954. </example>
  26955. */
  26956. /* eslint-disable max-len */
  26957. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
  26958. 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]+?))?$/;
  26959. // 1: value expression (valueFn)
  26960. // 2: label expression (displayFn)
  26961. // 3: group by expression (groupByFn)
  26962. // 4: disable when expression (disableWhenFn)
  26963. // 5: array item variable name
  26964. // 6: object item key variable name
  26965. // 7: object item value variable name
  26966. // 8: collection expression
  26967. // 9: track by expression
  26968. /* eslint-enable */
  26969. var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, $document, $parse) {
  26970. function parseOptionsExpression(optionsExp, selectElement, scope) {
  26971. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  26972. if (!(match)) {
  26973. throw ngOptionsMinErr('iexp',
  26974. 'Expected expression in form of ' +
  26975. '\'_select_ (as _label_)? for (_key_,)?_value_ in _collection_\'' +
  26976. ' but got \'{0}\'. Element: {1}',
  26977. optionsExp, startingTag(selectElement));
  26978. }
  26979. // Extract the parts from the ngOptions expression
  26980. // The variable name for the value of the item in the collection
  26981. var valueName = match[5] || match[7];
  26982. // The variable name for the key of the item in the collection
  26983. var keyName = match[6];
  26984. // An expression that generates the viewValue for an option if there is a label expression
  26985. var selectAs = / as /.test(match[0]) && match[1];
  26986. // An expression that is used to track the id of each object in the options collection
  26987. var trackBy = match[9];
  26988. // An expression that generates the viewValue for an option if there is no label expression
  26989. var valueFn = $parse(match[2] ? match[1] : valueName);
  26990. var selectAsFn = selectAs && $parse(selectAs);
  26991. var viewValueFn = selectAsFn || valueFn;
  26992. var trackByFn = trackBy && $parse(trackBy);
  26993. // Get the value by which we are going to track the option
  26994. // if we have a trackFn then use that (passing scope and locals)
  26995. // otherwise just hash the given viewValue
  26996. var getTrackByValueFn = trackBy ?
  26997. function(value, locals) { return trackByFn(scope, locals); } :
  26998. function getHashOfValue(value) { return hashKey(value); };
  26999. var getTrackByValue = function(value, key) {
  27000. return getTrackByValueFn(value, getLocals(value, key));
  27001. };
  27002. var displayFn = $parse(match[2] || match[1]);
  27003. var groupByFn = $parse(match[3] || '');
  27004. var disableWhenFn = $parse(match[4] || '');
  27005. var valuesFn = $parse(match[8]);
  27006. var locals = {};
  27007. var getLocals = keyName ? function(value, key) {
  27008. locals[keyName] = key;
  27009. locals[valueName] = value;
  27010. return locals;
  27011. } : function(value) {
  27012. locals[valueName] = value;
  27013. return locals;
  27014. };
  27015. function Option(selectValue, viewValue, label, group, disabled) {
  27016. this.selectValue = selectValue;
  27017. this.viewValue = viewValue;
  27018. this.label = label;
  27019. this.group = group;
  27020. this.disabled = disabled;
  27021. }
  27022. function getOptionValuesKeys(optionValues) {
  27023. var optionValuesKeys;
  27024. if (!keyName && isArrayLike(optionValues)) {
  27025. optionValuesKeys = optionValues;
  27026. } else {
  27027. // if object, extract keys, in enumeration order, unsorted
  27028. optionValuesKeys = [];
  27029. for (var itemKey in optionValues) {
  27030. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  27031. optionValuesKeys.push(itemKey);
  27032. }
  27033. }
  27034. }
  27035. return optionValuesKeys;
  27036. }
  27037. return {
  27038. trackBy: trackBy,
  27039. getTrackByValue: getTrackByValue,
  27040. getWatchables: $parse(valuesFn, function(optionValues) {
  27041. // Create a collection of things that we would like to watch (watchedArray)
  27042. // so that they can all be watched using a single $watchCollection
  27043. // that only runs the handler once if anything changes
  27044. var watchedArray = [];
  27045. optionValues = optionValues || [];
  27046. var optionValuesKeys = getOptionValuesKeys(optionValues);
  27047. var optionValuesLength = optionValuesKeys.length;
  27048. for (var index = 0; index < optionValuesLength; index++) {
  27049. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  27050. var value = optionValues[key];
  27051. var locals = getLocals(value, key);
  27052. var selectValue = getTrackByValueFn(value, locals);
  27053. watchedArray.push(selectValue);
  27054. // Only need to watch the displayFn if there is a specific label expression
  27055. if (match[2] || match[1]) {
  27056. var label = displayFn(scope, locals);
  27057. watchedArray.push(label);
  27058. }
  27059. // Only need to watch the disableWhenFn if there is a specific disable expression
  27060. if (match[4]) {
  27061. var disableWhen = disableWhenFn(scope, locals);
  27062. watchedArray.push(disableWhen);
  27063. }
  27064. }
  27065. return watchedArray;
  27066. }),
  27067. getOptions: function() {
  27068. var optionItems = [];
  27069. var selectValueMap = {};
  27070. // The option values were already computed in the `getWatchables` fn,
  27071. // which must have been called to trigger `getOptions`
  27072. var optionValues = valuesFn(scope) || [];
  27073. var optionValuesKeys = getOptionValuesKeys(optionValues);
  27074. var optionValuesLength = optionValuesKeys.length;
  27075. for (var index = 0; index < optionValuesLength; index++) {
  27076. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  27077. var value = optionValues[key];
  27078. var locals = getLocals(value, key);
  27079. var viewValue = viewValueFn(scope, locals);
  27080. var selectValue = getTrackByValueFn(viewValue, locals);
  27081. var label = displayFn(scope, locals);
  27082. var group = groupByFn(scope, locals);
  27083. var disabled = disableWhenFn(scope, locals);
  27084. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  27085. optionItems.push(optionItem);
  27086. selectValueMap[selectValue] = optionItem;
  27087. }
  27088. return {
  27089. items: optionItems,
  27090. selectValueMap: selectValueMap,
  27091. getOptionFromViewValue: function(value) {
  27092. return selectValueMap[getTrackByValue(value)];
  27093. },
  27094. getViewValueFromOption: function(option) {
  27095. // If the viewValue could be an object that may be mutated by the application,
  27096. // we need to make a copy and not return the reference to the value on the option.
  27097. return trackBy ? angular.copy(option.viewValue) : option.viewValue;
  27098. }
  27099. };
  27100. }
  27101. };
  27102. }
  27103. // we can't just jqLite('<option>') since jqLite is not smart enough
  27104. // to create it in <select> and IE barfs otherwise.
  27105. var optionTemplate = window.document.createElement('option'),
  27106. optGroupTemplate = window.document.createElement('optgroup');
  27107. function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
  27108. var selectCtrl = ctrls[0];
  27109. var ngModelCtrl = ctrls[1];
  27110. var multiple = attr.multiple;
  27111. // The emptyOption allows the application developer to provide their own custom "empty"
  27112. // option when the viewValue does not match any of the option values.
  27113. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  27114. if (children[i].value === '') {
  27115. selectCtrl.emptyOption = children.eq(i);
  27116. break;
  27117. }
  27118. }
  27119. var providedEmptyOption = !!selectCtrl.emptyOption;
  27120. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  27121. unknownOption.val('?');
  27122. var options;
  27123. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  27124. // This stores the newly created options before they are appended to the select.
  27125. // Since the contents are removed from the fragment when it is appended,
  27126. // we only need to create it once.
  27127. var listFragment = $document[0].createDocumentFragment();
  27128. // Overwrite the implementation. ngOptions doesn't use hashes
  27129. selectCtrl.generateUnknownOptionValue = function(val) {
  27130. return '?';
  27131. };
  27132. // Update the controller methods for multiple selectable options
  27133. if (!multiple) {
  27134. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  27135. var selectedOption = options.selectValueMap[selectElement.val()];
  27136. var option = options.getOptionFromViewValue(value);
  27137. // Make sure to remove the selected attribute from the previously selected option
  27138. // Otherwise, screen readers might get confused
  27139. if (selectedOption) selectedOption.element.removeAttribute('selected');
  27140. if (option) {
  27141. // Don't update the option when it is already selected.
  27142. // For example, the browser will select the first option by default. In that case,
  27143. // most properties are set automatically - except the `selected` attribute, which we
  27144. // set always
  27145. if (selectElement[0].value !== option.selectValue) {
  27146. selectCtrl.removeUnknownOption();
  27147. selectCtrl.unselectEmptyOption();
  27148. selectElement[0].value = option.selectValue;
  27149. option.element.selected = true;
  27150. }
  27151. option.element.setAttribute('selected', 'selected');
  27152. } else {
  27153. if (providedEmptyOption) {
  27154. selectCtrl.selectEmptyOption();
  27155. } else if (selectCtrl.unknownOption.parent().length) {
  27156. selectCtrl.updateUnknownOption(value);
  27157. } else {
  27158. selectCtrl.renderUnknownOption(value);
  27159. }
  27160. }
  27161. };
  27162. selectCtrl.readValue = function readNgOptionsValue() {
  27163. var selectedOption = options.selectValueMap[selectElement.val()];
  27164. if (selectedOption && !selectedOption.disabled) {
  27165. selectCtrl.unselectEmptyOption();
  27166. selectCtrl.removeUnknownOption();
  27167. return options.getViewValueFromOption(selectedOption);
  27168. }
  27169. return null;
  27170. };
  27171. // If we are using `track by` then we must watch the tracked value on the model
  27172. // since ngModel only watches for object identity change
  27173. // FIXME: When a user selects an option, this watch will fire needlessly
  27174. if (ngOptions.trackBy) {
  27175. scope.$watch(
  27176. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  27177. function() { ngModelCtrl.$render(); }
  27178. );
  27179. }
  27180. } else {
  27181. selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
  27182. options.items.forEach(function(option) {
  27183. option.element.selected = false;
  27184. });
  27185. if (value) {
  27186. value.forEach(function(item) {
  27187. var option = options.getOptionFromViewValue(item);
  27188. if (option) option.element.selected = true;
  27189. });
  27190. }
  27191. };
  27192. selectCtrl.readValue = function readNgOptionsMultiple() {
  27193. var selectedValues = selectElement.val() || [],
  27194. selections = [];
  27195. forEach(selectedValues, function(value) {
  27196. var option = options.selectValueMap[value];
  27197. if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
  27198. });
  27199. return selections;
  27200. };
  27201. // If we are using `track by` then we must watch these tracked values on the model
  27202. // since ngModel only watches for object identity change
  27203. if (ngOptions.trackBy) {
  27204. scope.$watchCollection(function() {
  27205. if (isArray(ngModelCtrl.$viewValue)) {
  27206. return ngModelCtrl.$viewValue.map(function(value) {
  27207. return ngOptions.getTrackByValue(value);
  27208. });
  27209. }
  27210. }, function() {
  27211. ngModelCtrl.$render();
  27212. });
  27213. }
  27214. }
  27215. if (providedEmptyOption) {
  27216. // we need to remove it before calling selectElement.empty() because otherwise IE will
  27217. // remove the label from the element. wtf?
  27218. selectCtrl.emptyOption.remove();
  27219. // compile the element since there might be bindings in it
  27220. $compile(selectCtrl.emptyOption)(scope);
  27221. // remove the class, which is added automatically because we recompile the element and it
  27222. // becomes the compilation root
  27223. selectCtrl.emptyOption.removeClass('ng-scope');
  27224. }
  27225. selectElement.empty();
  27226. // We need to do this here to ensure that the options object is defined
  27227. // when we first hit it in writeNgOptionsValue
  27228. updateOptions();
  27229. // We will re-render the option elements if the option values or labels change
  27230. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  27231. // ------------------------------------------------------------------ //
  27232. function addOptionElement(option, parent) {
  27233. var optionElement = optionTemplate.cloneNode(false);
  27234. parent.appendChild(optionElement);
  27235. updateOptionElement(option, optionElement);
  27236. }
  27237. function updateOptionElement(option, element) {
  27238. option.element = element;
  27239. element.disabled = option.disabled;
  27240. // NOTE: The label must be set before the value, otherwise IE10/11/EDGE create unresponsive
  27241. // selects in certain circumstances when multiple selects are next to each other and display
  27242. // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
  27243. // See https://github.com/angular/angular.js/issues/11314 for more info.
  27244. // This is unfortunately untestable with unit / e2e tests
  27245. if (option.label !== element.label) {
  27246. element.label = option.label;
  27247. element.textContent = option.label;
  27248. }
  27249. if (option.value !== element.value) element.value = option.selectValue;
  27250. }
  27251. function updateOptions() {
  27252. var previousValue = options && selectCtrl.readValue();
  27253. // We must remove all current options, but cannot simply set innerHTML = null
  27254. // since the providedEmptyOption might have an ngIf on it that inserts comments which we
  27255. // must preserve.
  27256. // Instead, iterate over the current option elements and remove them or their optgroup
  27257. // parents
  27258. if (options) {
  27259. for (var i = options.items.length - 1; i >= 0; i--) {
  27260. var option = options.items[i];
  27261. if (isDefined(option.group)) {
  27262. jqLiteRemove(option.element.parentNode);
  27263. } else {
  27264. jqLiteRemove(option.element);
  27265. }
  27266. }
  27267. }
  27268. options = ngOptions.getOptions();
  27269. var groupElementMap = {};
  27270. // Ensure that the empty option is always there if it was explicitly provided
  27271. if (providedEmptyOption) {
  27272. selectElement.prepend(selectCtrl.emptyOption);
  27273. }
  27274. options.items.forEach(function addOption(option) {
  27275. var groupElement;
  27276. if (isDefined(option.group)) {
  27277. // This option is to live in a group
  27278. // See if we have already created this group
  27279. groupElement = groupElementMap[option.group];
  27280. if (!groupElement) {
  27281. groupElement = optGroupTemplate.cloneNode(false);
  27282. listFragment.appendChild(groupElement);
  27283. // Update the label on the group element
  27284. // "null" is special cased because of Safari
  27285. groupElement.label = option.group === null ? 'null' : option.group;
  27286. // Store it for use later
  27287. groupElementMap[option.group] = groupElement;
  27288. }
  27289. addOptionElement(option, groupElement);
  27290. } else {
  27291. // This option is not in a group
  27292. addOptionElement(option, listFragment);
  27293. }
  27294. });
  27295. selectElement[0].appendChild(listFragment);
  27296. ngModelCtrl.$render();
  27297. // Check to see if the value has changed due to the update to the options
  27298. if (!ngModelCtrl.$isEmpty(previousValue)) {
  27299. var nextValue = selectCtrl.readValue();
  27300. var isNotPrimitive = ngOptions.trackBy || multiple;
  27301. if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
  27302. ngModelCtrl.$setViewValue(nextValue);
  27303. ngModelCtrl.$render();
  27304. }
  27305. }
  27306. }
  27307. }
  27308. return {
  27309. restrict: 'A',
  27310. terminal: true,
  27311. require: ['select', 'ngModel'],
  27312. link: {
  27313. pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
  27314. // Deactivate the SelectController.register method to prevent
  27315. // option directives from accidentally registering themselves
  27316. // (and unwanted $destroy handlers etc.)
  27317. ctrls[0].registerOption = noop;
  27318. },
  27319. post: ngOptionsPostLink
  27320. }
  27321. };
  27322. }];
  27323. /**
  27324. * @ngdoc directive
  27325. * @name ngPluralize
  27326. * @restrict EA
  27327. *
  27328. * @description
  27329. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  27330. * These rules are bundled with angular.js, but can be overridden
  27331. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  27332. * by specifying the mappings between
  27333. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  27334. * and the strings to be displayed.
  27335. *
  27336. * # Plural categories and explicit number rules
  27337. * There are two
  27338. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  27339. * in Angular's default en-US locale: "one" and "other".
  27340. *
  27341. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  27342. * any number that is not 1), an explicit number rule can only match one number. For example, the
  27343. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  27344. * and explicit number rules throughout the rest of this documentation.
  27345. *
  27346. * # Configuring ngPluralize
  27347. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  27348. * You can also provide an optional attribute, `offset`.
  27349. *
  27350. * The value of the `count` attribute can be either a string or an {@link guide/expression
  27351. * Angular expression}; these are evaluated on the current scope for its bound value.
  27352. *
  27353. * The `when` attribute specifies the mappings between plural categories and the actual
  27354. * string to be displayed. The value of the attribute should be a JSON object.
  27355. *
  27356. * The following example shows how to configure ngPluralize:
  27357. *
  27358. * ```html
  27359. * <ng-pluralize count="personCount"
  27360. when="{'0': 'Nobody is viewing.',
  27361. * 'one': '1 person is viewing.',
  27362. * 'other': '{} people are viewing.'}">
  27363. * </ng-pluralize>
  27364. *```
  27365. *
  27366. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  27367. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  27368. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  27369. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  27370. * show "a dozen people are viewing".
  27371. *
  27372. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  27373. * into pluralized strings. In the previous example, Angular will replace `{}` with
  27374. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  27375. * for <span ng-non-bindable>{{numberExpression}}</span>.
  27376. *
  27377. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  27378. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  27379. *
  27380. * # Configuring ngPluralize with offset
  27381. * The `offset` attribute allows further customization of pluralized text, which can result in
  27382. * a better user experience. For example, instead of the message "4 people are viewing this document",
  27383. * you might display "John, Kate and 2 others are viewing this document".
  27384. * The offset attribute allows you to offset a number by any desired value.
  27385. * Let's take a look at an example:
  27386. *
  27387. * ```html
  27388. * <ng-pluralize count="personCount" offset=2
  27389. * when="{'0': 'Nobody is viewing.',
  27390. * '1': '{{person1}} is viewing.',
  27391. * '2': '{{person1}} and {{person2}} are viewing.',
  27392. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  27393. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  27394. * </ng-pluralize>
  27395. * ```
  27396. *
  27397. * Notice that we are still using two plural categories(one, other), but we added
  27398. * three explicit number rules 0, 1 and 2.
  27399. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  27400. * When three people view the document, no explicit number rule is found, so
  27401. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  27402. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  27403. * is shown.
  27404. *
  27405. * Note that when you specify offsets, you must provide explicit number rules for
  27406. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  27407. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  27408. * plural categories "one" and "other".
  27409. *
  27410. * @param {string|expression} count The variable to be bound to.
  27411. * @param {string} when The mapping between plural category to its corresponding strings.
  27412. * @param {number=} offset Offset to deduct from the total number.
  27413. *
  27414. * @example
  27415. <example module="pluralizeExample" name="ng-pluralize">
  27416. <file name="index.html">
  27417. <script>
  27418. angular.module('pluralizeExample', [])
  27419. .controller('ExampleController', ['$scope', function($scope) {
  27420. $scope.person1 = 'Igor';
  27421. $scope.person2 = 'Misko';
  27422. $scope.personCount = 1;
  27423. }]);
  27424. </script>
  27425. <div ng-controller="ExampleController">
  27426. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  27427. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  27428. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  27429. <!--- Example with simple pluralization rules for en locale --->
  27430. Without Offset:
  27431. <ng-pluralize count="personCount"
  27432. when="{'0': 'Nobody is viewing.',
  27433. 'one': '1 person is viewing.',
  27434. 'other': '{} people are viewing.'}">
  27435. </ng-pluralize><br>
  27436. <!--- Example with offset --->
  27437. With Offset(2):
  27438. <ng-pluralize count="personCount" offset=2
  27439. when="{'0': 'Nobody is viewing.',
  27440. '1': '{{person1}} is viewing.',
  27441. '2': '{{person1}} and {{person2}} are viewing.',
  27442. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  27443. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  27444. </ng-pluralize>
  27445. </div>
  27446. </file>
  27447. <file name="protractor.js" type="protractor">
  27448. it('should show correct pluralized string', function() {
  27449. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  27450. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  27451. var countInput = element(by.model('personCount'));
  27452. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  27453. expect(withOffset.getText()).toEqual('Igor is viewing.');
  27454. countInput.clear();
  27455. countInput.sendKeys('0');
  27456. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  27457. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  27458. countInput.clear();
  27459. countInput.sendKeys('2');
  27460. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  27461. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  27462. countInput.clear();
  27463. countInput.sendKeys('3');
  27464. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  27465. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  27466. countInput.clear();
  27467. countInput.sendKeys('4');
  27468. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  27469. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  27470. });
  27471. it('should show data-bound names', function() {
  27472. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  27473. var personCount = element(by.model('personCount'));
  27474. var person1 = element(by.model('person1'));
  27475. var person2 = element(by.model('person2'));
  27476. personCount.clear();
  27477. personCount.sendKeys('4');
  27478. person1.clear();
  27479. person1.sendKeys('Di');
  27480. person2.clear();
  27481. person2.sendKeys('Vojta');
  27482. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  27483. });
  27484. </file>
  27485. </example>
  27486. */
  27487. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  27488. var BRACE = /{}/g,
  27489. IS_WHEN = /^when(Minus)?(.+)$/;
  27490. return {
  27491. link: function(scope, element, attr) {
  27492. var numberExp = attr.count,
  27493. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  27494. offset = attr.offset || 0,
  27495. whens = scope.$eval(whenExp) || {},
  27496. whensExpFns = {},
  27497. startSymbol = $interpolate.startSymbol(),
  27498. endSymbol = $interpolate.endSymbol(),
  27499. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  27500. watchRemover = angular.noop,
  27501. lastCount;
  27502. forEach(attr, function(expression, attributeName) {
  27503. var tmpMatch = IS_WHEN.exec(attributeName);
  27504. if (tmpMatch) {
  27505. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  27506. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  27507. }
  27508. });
  27509. forEach(whens, function(expression, key) {
  27510. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  27511. });
  27512. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  27513. var count = parseFloat(newVal);
  27514. var countIsNaN = isNumberNaN(count);
  27515. if (!countIsNaN && !(count in whens)) {
  27516. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  27517. // Otherwise, check it against pluralization rules in $locale service.
  27518. count = $locale.pluralCat(count - offset);
  27519. }
  27520. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  27521. // In JS `NaN !== NaN`, so we have to explicitly check.
  27522. if ((count !== lastCount) && !(countIsNaN && isNumberNaN(lastCount))) {
  27523. watchRemover();
  27524. var whenExpFn = whensExpFns[count];
  27525. if (isUndefined(whenExpFn)) {
  27526. if (newVal != null) {
  27527. $log.debug('ngPluralize: no rule defined for \'' + count + '\' in ' + whenExp);
  27528. }
  27529. watchRemover = noop;
  27530. updateElementText();
  27531. } else {
  27532. watchRemover = scope.$watch(whenExpFn, updateElementText);
  27533. }
  27534. lastCount = count;
  27535. }
  27536. });
  27537. function updateElementText(newText) {
  27538. element.text(newText || '');
  27539. }
  27540. }
  27541. };
  27542. }];
  27543. /* exported ngRepeatDirective */
  27544. /**
  27545. * @ngdoc directive
  27546. * @name ngRepeat
  27547. * @multiElement
  27548. *
  27549. * @description
  27550. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  27551. * instance gets its own scope, where the given loop variable is set to the current collection item,
  27552. * and `$index` is set to the item index or key.
  27553. *
  27554. * Special properties are exposed on the local scope of each template instance, including:
  27555. *
  27556. * | Variable | Type | Details |
  27557. * |-----------|-----------------|-----------------------------------------------------------------------------|
  27558. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  27559. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  27560. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  27561. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  27562. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  27563. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  27564. *
  27565. * <div class="alert alert-info">
  27566. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  27567. * This may be useful when, for instance, nesting ngRepeats.
  27568. * </div>
  27569. *
  27570. *
  27571. * # Iterating over object properties
  27572. *
  27573. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  27574. * syntax:
  27575. *
  27576. * ```js
  27577. * <div ng-repeat="(key, value) in myObj"> ... </div>
  27578. * ```
  27579. *
  27580. * However, there are a limitations compared to array iteration:
  27581. *
  27582. * - The JavaScript specification does not define the order of keys
  27583. * returned for an object, so Angular relies on the order returned by the browser
  27584. * when running `for key in myObj`. Browsers generally follow the strategy of providing
  27585. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  27586. * and reinstated. See the
  27587. * [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
  27588. *
  27589. * - `ngRepeat` will silently *ignore* object keys starting with `$`, because
  27590. * it's a prefix used by Angular for public (`$`) and private (`$$`) properties.
  27591. *
  27592. * - The built-in filters {@link ng.orderBy orderBy} and {@link ng.filter filter} do not work with
  27593. * objects, and will throw an error if used with one.
  27594. *
  27595. * If you are hitting any of these limitations, the recommended workaround is to convert your object into an array
  27596. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  27597. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  27598. * or implement a `$watch` on the object yourself.
  27599. *
  27600. *
  27601. * # Tracking and Duplicates
  27602. *
  27603. * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
  27604. * the collection. When a change happens, ngRepeat then makes the corresponding changes to the DOM:
  27605. *
  27606. * * When an item is added, a new instance of the template is added to the DOM.
  27607. * * When an item is removed, its template instance is removed from the DOM.
  27608. * * When items are reordered, their respective templates are reordered in the DOM.
  27609. *
  27610. * To minimize creation of DOM elements, `ngRepeat` uses a function
  27611. * to "keep track" of all items in the collection and their corresponding DOM elements.
  27612. * For example, if an item is added to the collection, ngRepeat will know that all other items
  27613. * already have DOM elements, and will not re-render them.
  27614. *
  27615. * The default tracking function (which tracks items by their identity) does not allow
  27616. * duplicate items in arrays. This is because when there are duplicates, it is not possible
  27617. * to maintain a one-to-one mapping between collection items and DOM elements.
  27618. *
  27619. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  27620. * with your own using the `track by` expression.
  27621. *
  27622. * For example, you may track items by the index of each item in the collection, using the
  27623. * special scope property `$index`:
  27624. * ```html
  27625. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  27626. * {{n}}
  27627. * </div>
  27628. * ```
  27629. *
  27630. * You may also use arbitrary expressions in `track by`, including references to custom functions
  27631. * on the scope:
  27632. * ```html
  27633. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  27634. * {{n}}
  27635. * </div>
  27636. * ```
  27637. *
  27638. * <div class="alert alert-success">
  27639. * If you are working with objects that have an identifier property, you should track
  27640. * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
  27641. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  27642. * JavaScript objects in the collection have been substituted for new ones. For large collections,
  27643. * this significantly improves rendering performance. If you don't have a unique identifier,
  27644. * `track by $index` can also provide a performance boost.
  27645. * </div>
  27646. * ```html
  27647. * <div ng-repeat="model in collection track by model.id">
  27648. * {{model.name}}
  27649. * </div>
  27650. * ```
  27651. *
  27652. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  27653. * `$id` function, which tracks items by their identity:
  27654. * ```html
  27655. * <div ng-repeat="obj in collection track by $id(obj)">
  27656. * {{obj.prop}}
  27657. * </div>
  27658. * ```
  27659. *
  27660. * <div class="alert alert-warning">
  27661. * **Note:** `track by` must always be the last expression:
  27662. * </div>
  27663. * ```
  27664. * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
  27665. * {{model.name}}
  27666. * </div>
  27667. * ```
  27668. *
  27669. * # Special repeat start and end points
  27670. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  27671. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  27672. * 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)
  27673. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  27674. *
  27675. * The example below makes use of this feature:
  27676. * ```html
  27677. * <header ng-repeat-start="item in items">
  27678. * Header {{ item }}
  27679. * </header>
  27680. * <div class="body">
  27681. * Body {{ item }}
  27682. * </div>
  27683. * <footer ng-repeat-end>
  27684. * Footer {{ item }}
  27685. * </footer>
  27686. * ```
  27687. *
  27688. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  27689. * ```html
  27690. * <header>
  27691. * Header A
  27692. * </header>
  27693. * <div class="body">
  27694. * Body A
  27695. * </div>
  27696. * <footer>
  27697. * Footer A
  27698. * </footer>
  27699. * <header>
  27700. * Header B
  27701. * </header>
  27702. * <div class="body">
  27703. * Body B
  27704. * </div>
  27705. * <footer>
  27706. * Footer B
  27707. * </footer>
  27708. * ```
  27709. *
  27710. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  27711. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  27712. *
  27713. * @animations
  27714. * | Animation | Occurs |
  27715. * |----------------------------------|-------------------------------------|
  27716. * | {@link ng.$animate#enter enter} | when a new item is added to the list or when an item is revealed after a filter |
  27717. * | {@link ng.$animate#leave leave} | when an item is removed from the list or when an item is filtered out |
  27718. * | {@link ng.$animate#move move } | when an adjacent item is filtered out causing a reorder or when the item contents are reordered |
  27719. *
  27720. * See the example below for defining CSS animations with ngRepeat.
  27721. *
  27722. * @element ANY
  27723. * @scope
  27724. * @priority 1000
  27725. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  27726. * formats are currently supported:
  27727. *
  27728. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  27729. * is a scope expression giving the collection to enumerate.
  27730. *
  27731. * For example: `album in artist.albums`.
  27732. *
  27733. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  27734. * and `expression` is the scope expression giving the collection to enumerate.
  27735. *
  27736. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  27737. *
  27738. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  27739. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  27740. * is specified, ng-repeat associates elements by identity. It is an error to have
  27741. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  27742. * mapped to the same DOM element, which is not possible.)
  27743. *
  27744. * Note that the tracking expression must come last, after any filters, and the alias expression.
  27745. *
  27746. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  27747. * will be associated by item identity in the array.
  27748. *
  27749. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  27750. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  27751. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  27752. * element in the same way in the DOM.
  27753. *
  27754. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  27755. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  27756. * property is same.
  27757. *
  27758. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  27759. * to items in conjunction with a tracking expression.
  27760. *
  27761. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  27762. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  27763. * when a filter is active on the repeater, but the filtered result set is empty.
  27764. *
  27765. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  27766. * the items have been processed through the filter.
  27767. *
  27768. * 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
  27769. * (and not as operator, inside an expression).
  27770. *
  27771. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
  27772. *
  27773. * @example
  27774. * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed
  27775. * results by name or by age. New (entering) and removed (leaving) items are animated.
  27776. <example module="ngRepeat" name="ngRepeat" deps="angular-animate.js" animations="true" name="ng-repeat">
  27777. <file name="index.html">
  27778. <div ng-controller="repeatController">
  27779. I have {{friends.length}} friends. They are:
  27780. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  27781. <ul class="example-animate-container">
  27782. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  27783. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  27784. </li>
  27785. <li class="animate-repeat" ng-if="results.length === 0">
  27786. <strong>No results found...</strong>
  27787. </li>
  27788. </ul>
  27789. </div>
  27790. </file>
  27791. <file name="script.js">
  27792. angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
  27793. $scope.friends = [
  27794. {name:'John', age:25, gender:'boy'},
  27795. {name:'Jessie', age:30, gender:'girl'},
  27796. {name:'Johanna', age:28, gender:'girl'},
  27797. {name:'Joy', age:15, gender:'girl'},
  27798. {name:'Mary', age:28, gender:'girl'},
  27799. {name:'Peter', age:95, gender:'boy'},
  27800. {name:'Sebastian', age:50, gender:'boy'},
  27801. {name:'Erika', age:27, gender:'girl'},
  27802. {name:'Patrick', age:40, gender:'boy'},
  27803. {name:'Samantha', age:60, gender:'girl'}
  27804. ];
  27805. });
  27806. </file>
  27807. <file name="animations.css">
  27808. .example-animate-container {
  27809. background:white;
  27810. border:1px solid black;
  27811. list-style:none;
  27812. margin:0;
  27813. padding:0 10px;
  27814. }
  27815. .animate-repeat {
  27816. line-height:30px;
  27817. list-style:none;
  27818. box-sizing:border-box;
  27819. }
  27820. .animate-repeat.ng-move,
  27821. .animate-repeat.ng-enter,
  27822. .animate-repeat.ng-leave {
  27823. transition:all linear 0.5s;
  27824. }
  27825. .animate-repeat.ng-leave.ng-leave-active,
  27826. .animate-repeat.ng-move,
  27827. .animate-repeat.ng-enter {
  27828. opacity:0;
  27829. max-height:0;
  27830. }
  27831. .animate-repeat.ng-leave,
  27832. .animate-repeat.ng-move.ng-move-active,
  27833. .animate-repeat.ng-enter.ng-enter-active {
  27834. opacity:1;
  27835. max-height:30px;
  27836. }
  27837. </file>
  27838. <file name="protractor.js" type="protractor">
  27839. var friends = element.all(by.repeater('friend in friends'));
  27840. it('should render initial data set', function() {
  27841. expect(friends.count()).toBe(10);
  27842. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  27843. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  27844. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  27845. expect(element(by.binding('friends.length')).getText())
  27846. .toMatch("I have 10 friends. They are:");
  27847. });
  27848. it('should update repeater when filter predicate changes', function() {
  27849. expect(friends.count()).toBe(10);
  27850. element(by.model('q')).sendKeys('ma');
  27851. expect(friends.count()).toBe(2);
  27852. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  27853. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  27854. });
  27855. </file>
  27856. </example>
  27857. */
  27858. var ngRepeatDirective = ['$parse', '$animate', '$compile', function($parse, $animate, $compile) {
  27859. var NG_REMOVED = '$$NG_REMOVED';
  27860. var ngRepeatMinErr = minErr('ngRepeat');
  27861. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  27862. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  27863. scope[valueIdentifier] = value;
  27864. if (keyIdentifier) scope[keyIdentifier] = key;
  27865. scope.$index = index;
  27866. scope.$first = (index === 0);
  27867. scope.$last = (index === (arrayLength - 1));
  27868. scope.$middle = !(scope.$first || scope.$last);
  27869. // eslint-disable-next-line no-bitwise
  27870. scope.$odd = !(scope.$even = (index & 1) === 0);
  27871. };
  27872. var getBlockStart = function(block) {
  27873. return block.clone[0];
  27874. };
  27875. var getBlockEnd = function(block) {
  27876. return block.clone[block.clone.length - 1];
  27877. };
  27878. return {
  27879. restrict: 'A',
  27880. multiElement: true,
  27881. transclude: 'element',
  27882. priority: 1000,
  27883. terminal: true,
  27884. $$tlb: true,
  27885. compile: function ngRepeatCompile($element, $attr) {
  27886. var expression = $attr.ngRepeat;
  27887. var ngRepeatEndComment = $compile.$$createComment('end ngRepeat', expression);
  27888. 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*$/);
  27889. if (!match) {
  27890. throw ngRepeatMinErr('iexp', 'Expected expression in form of \'_item_ in _collection_[ track by _id_]\' but got \'{0}\'.',
  27891. expression);
  27892. }
  27893. var lhs = match[1];
  27894. var rhs = match[2];
  27895. var aliasAs = match[3];
  27896. var trackByExp = match[4];
  27897. match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
  27898. if (!match) {
  27899. throw ngRepeatMinErr('iidexp', '\'_item_\' in \'_item_ in _collection_\' should be an identifier or \'(_key_, _value_)\' expression, but got \'{0}\'.',
  27900. lhs);
  27901. }
  27902. var valueIdentifier = match[3] || match[1];
  27903. var keyIdentifier = match[2];
  27904. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  27905. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  27906. throw ngRepeatMinErr('badident', 'alias \'{0}\' is invalid --- must be a valid JS identifier which is not a reserved name.',
  27907. aliasAs);
  27908. }
  27909. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  27910. var hashFnLocals = {$id: hashKey};
  27911. if (trackByExp) {
  27912. trackByExpGetter = $parse(trackByExp);
  27913. } else {
  27914. trackByIdArrayFn = function(key, value) {
  27915. return hashKey(value);
  27916. };
  27917. trackByIdObjFn = function(key) {
  27918. return key;
  27919. };
  27920. }
  27921. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  27922. if (trackByExpGetter) {
  27923. trackByIdExpFn = function(key, value, index) {
  27924. // assign key, value, and $index to the locals so that they can be used in hash functions
  27925. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  27926. hashFnLocals[valueIdentifier] = value;
  27927. hashFnLocals.$index = index;
  27928. return trackByExpGetter($scope, hashFnLocals);
  27929. };
  27930. }
  27931. // Store a list of elements from previous run. This is a hash where key is the item from the
  27932. // iterator, and the value is objects with following properties.
  27933. // - scope: bound scope
  27934. // - element: previous element.
  27935. // - index: position
  27936. //
  27937. // We are using no-proto object so that we don't need to guard against inherited props via
  27938. // hasOwnProperty.
  27939. var lastBlockMap = createMap();
  27940. //watch props
  27941. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  27942. var index, length,
  27943. previousNode = $element[0], // node that cloned nodes should be inserted after
  27944. // initialized to the comment node anchor
  27945. nextNode,
  27946. // Same as lastBlockMap but it has the current state. It will become the
  27947. // lastBlockMap on the next iteration.
  27948. nextBlockMap = createMap(),
  27949. collectionLength,
  27950. key, value, // key/value of iteration
  27951. trackById,
  27952. trackByIdFn,
  27953. collectionKeys,
  27954. block, // last object information {scope, element, id}
  27955. nextBlockOrder,
  27956. elementsToRemove;
  27957. if (aliasAs) {
  27958. $scope[aliasAs] = collection;
  27959. }
  27960. if (isArrayLike(collection)) {
  27961. collectionKeys = collection;
  27962. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  27963. } else {
  27964. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  27965. // if object, extract keys, in enumeration order, unsorted
  27966. collectionKeys = [];
  27967. for (var itemKey in collection) {
  27968. if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
  27969. collectionKeys.push(itemKey);
  27970. }
  27971. }
  27972. }
  27973. collectionLength = collectionKeys.length;
  27974. nextBlockOrder = new Array(collectionLength);
  27975. // locate existing items
  27976. for (index = 0; index < collectionLength; index++) {
  27977. key = (collection === collectionKeys) ? index : collectionKeys[index];
  27978. value = collection[key];
  27979. trackById = trackByIdFn(key, value, index);
  27980. if (lastBlockMap[trackById]) {
  27981. // found previously seen block
  27982. block = lastBlockMap[trackById];
  27983. delete lastBlockMap[trackById];
  27984. nextBlockMap[trackById] = block;
  27985. nextBlockOrder[index] = block;
  27986. } else if (nextBlockMap[trackById]) {
  27987. // if collision detected. restore lastBlockMap and throw an error
  27988. forEach(nextBlockOrder, function(block) {
  27989. if (block && block.scope) lastBlockMap[block.id] = block;
  27990. });
  27991. throw ngRepeatMinErr('dupes',
  27992. 'Duplicates in a repeater are not allowed. Use \'track by\' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}',
  27993. expression, trackById, value);
  27994. } else {
  27995. // new never before seen block
  27996. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  27997. nextBlockMap[trackById] = true;
  27998. }
  27999. }
  28000. // remove leftover items
  28001. for (var blockKey in lastBlockMap) {
  28002. block = lastBlockMap[blockKey];
  28003. elementsToRemove = getBlockNodes(block.clone);
  28004. $animate.leave(elementsToRemove);
  28005. if (elementsToRemove[0].parentNode) {
  28006. // if the element was not removed yet because of pending animation, mark it as deleted
  28007. // so that we can ignore it later
  28008. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  28009. elementsToRemove[index][NG_REMOVED] = true;
  28010. }
  28011. }
  28012. block.scope.$destroy();
  28013. }
  28014. // we are not using forEach for perf reasons (trying to avoid #call)
  28015. for (index = 0; index < collectionLength; index++) {
  28016. key = (collection === collectionKeys) ? index : collectionKeys[index];
  28017. value = collection[key];
  28018. block = nextBlockOrder[index];
  28019. if (block.scope) {
  28020. // if we have already seen this object, then we need to reuse the
  28021. // associated scope/element
  28022. nextNode = previousNode;
  28023. // skip nodes that are already pending removal via leave animation
  28024. do {
  28025. nextNode = nextNode.nextSibling;
  28026. } while (nextNode && nextNode[NG_REMOVED]);
  28027. if (getBlockStart(block) !== nextNode) {
  28028. // existing item which got moved
  28029. $animate.move(getBlockNodes(block.clone), null, previousNode);
  28030. }
  28031. previousNode = getBlockEnd(block);
  28032. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  28033. } else {
  28034. // new item which we don't know about
  28035. $transclude(function ngRepeatTransclude(clone, scope) {
  28036. block.scope = scope;
  28037. // http://jsperf.com/clone-vs-createcomment
  28038. var endNode = ngRepeatEndComment.cloneNode(false);
  28039. clone[clone.length++] = endNode;
  28040. $animate.enter(clone, null, previousNode);
  28041. previousNode = endNode;
  28042. // Note: We only need the first/last node of the cloned nodes.
  28043. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  28044. // by a directive with templateUrl when its template arrives.
  28045. block.clone = clone;
  28046. nextBlockMap[block.id] = block;
  28047. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  28048. });
  28049. }
  28050. }
  28051. lastBlockMap = nextBlockMap;
  28052. });
  28053. };
  28054. }
  28055. };
  28056. }];
  28057. var NG_HIDE_CLASS = 'ng-hide';
  28058. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  28059. /**
  28060. * @ngdoc directive
  28061. * @name ngShow
  28062. * @multiElement
  28063. *
  28064. * @description
  28065. * The `ngShow` directive shows or hides the given HTML element based on the expression
  28066. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  28067. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  28068. * in AngularJS and sets the display style to none (using an !important flag).
  28069. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  28070. *
  28071. * ```html
  28072. * <!-- when $scope.myValue is truthy (element is visible) -->
  28073. * <div ng-show="myValue"></div>
  28074. *
  28075. * <!-- when $scope.myValue is falsy (element is hidden) -->
  28076. * <div ng-show="myValue" class="ng-hide"></div>
  28077. * ```
  28078. *
  28079. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
  28080. * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
  28081. * from the element causing the element not to appear hidden.
  28082. *
  28083. * ## Why is !important used?
  28084. *
  28085. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  28086. * can be easily overridden by heavier selectors. For example, something as simple
  28087. * as changing the display style on a HTML list item would make hidden elements appear visible.
  28088. * This also becomes a bigger issue when dealing with CSS frameworks.
  28089. *
  28090. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  28091. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  28092. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  28093. *
  28094. * ### Overriding `.ng-hide`
  28095. *
  28096. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  28097. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  28098. * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
  28099. * with extra animation classes that can be added.
  28100. *
  28101. * ```css
  28102. * .ng-hide:not(.ng-hide-animate) {
  28103. * /&#42; this is just another form of hiding an element &#42;/
  28104. * display: block!important;
  28105. * position: absolute;
  28106. * top: -9999px;
  28107. * left: -9999px;
  28108. * }
  28109. * ```
  28110. *
  28111. * By default you don't need to override in CSS anything and the animations will work around the display style.
  28112. *
  28113. * ## A note about animations with `ngShow`
  28114. *
  28115. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  28116. * is true and false. This system works like the animation system present with ngClass except that
  28117. * you must also include the !important flag to override the display property
  28118. * so that you can perform an animation when the element is hidden during the time of the animation.
  28119. *
  28120. * ```css
  28121. * //
  28122. * //a working example can be found at the bottom of this page
  28123. * //
  28124. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  28125. * /&#42; this is required as of 1.3x to properly
  28126. * apply all styling in a show/hide animation &#42;/
  28127. * transition: 0s linear all;
  28128. * }
  28129. *
  28130. * .my-element.ng-hide-add-active,
  28131. * .my-element.ng-hide-remove-active {
  28132. * /&#42; the transition is defined in the active class &#42;/
  28133. * transition: 1s linear all;
  28134. * }
  28135. *
  28136. * .my-element.ng-hide-add { ... }
  28137. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  28138. * .my-element.ng-hide-remove { ... }
  28139. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  28140. * ```
  28141. *
  28142. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display
  28143. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  28144. *
  28145. * @animations
  28146. * | Animation | Occurs |
  28147. * |----------------------------------|-------------------------------------|
  28148. * | {@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 |
  28149. * | {@link $animate#removeClass removeClass} `.ng-hide` | after the `ngShow` expression evaluates to a truthy value and just before contents are set to visible |
  28150. *
  28151. * @element ANY
  28152. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  28153. * then the element is shown or hidden respectively.
  28154. *
  28155. * @example
  28156. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show">
  28157. <file name="index.html">
  28158. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
  28159. <div>
  28160. Show:
  28161. <div class="check-element animate-show" ng-show="checked">
  28162. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  28163. </div>
  28164. </div>
  28165. <div>
  28166. Hide:
  28167. <div class="check-element animate-show" ng-hide="checked">
  28168. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  28169. </div>
  28170. </div>
  28171. </file>
  28172. <file name="glyphicons.css">
  28173. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  28174. </file>
  28175. <file name="animations.css">
  28176. .animate-show {
  28177. line-height: 20px;
  28178. opacity: 1;
  28179. padding: 10px;
  28180. border: 1px solid black;
  28181. background: white;
  28182. }
  28183. .animate-show.ng-hide-add, .animate-show.ng-hide-remove {
  28184. transition: all linear 0.5s;
  28185. }
  28186. .animate-show.ng-hide {
  28187. line-height: 0;
  28188. opacity: 0;
  28189. padding: 0 10px;
  28190. }
  28191. .check-element {
  28192. padding: 10px;
  28193. border: 1px solid black;
  28194. background: white;
  28195. }
  28196. </file>
  28197. <file name="protractor.js" type="protractor">
  28198. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  28199. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  28200. it('should check ng-show / ng-hide', function() {
  28201. expect(thumbsUp.isDisplayed()).toBeFalsy();
  28202. expect(thumbsDown.isDisplayed()).toBeTruthy();
  28203. element(by.model('checked')).click();
  28204. expect(thumbsUp.isDisplayed()).toBeTruthy();
  28205. expect(thumbsDown.isDisplayed()).toBeFalsy();
  28206. });
  28207. </file>
  28208. </example>
  28209. */
  28210. var ngShowDirective = ['$animate', function($animate) {
  28211. return {
  28212. restrict: 'A',
  28213. multiElement: true,
  28214. link: function(scope, element, attr) {
  28215. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  28216. // we're adding a temporary, animation-specific class for ng-hide since this way
  28217. // we can control when the element is actually displayed on screen without having
  28218. // to have a global/greedy CSS selector that breaks when other animations are run.
  28219. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  28220. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  28221. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  28222. });
  28223. });
  28224. }
  28225. };
  28226. }];
  28227. /**
  28228. * @ngdoc directive
  28229. * @name ngHide
  28230. * @multiElement
  28231. *
  28232. * @description
  28233. * The `ngHide` directive shows or hides the given HTML element based on the expression
  28234. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  28235. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  28236. * in AngularJS and sets the display style to none (using an !important flag).
  28237. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  28238. *
  28239. * ```html
  28240. * <!-- when $scope.myValue is truthy (element is hidden) -->
  28241. * <div ng-hide="myValue" class="ng-hide"></div>
  28242. *
  28243. * <!-- when $scope.myValue is falsy (element is visible) -->
  28244. * <div ng-hide="myValue"></div>
  28245. * ```
  28246. *
  28247. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
  28248. * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
  28249. * from the element causing the element not to appear hidden.
  28250. *
  28251. * ## Why is !important used?
  28252. *
  28253. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  28254. * can be easily overridden by heavier selectors. For example, something as simple
  28255. * as changing the display style on a HTML list item would make hidden elements appear visible.
  28256. * This also becomes a bigger issue when dealing with CSS frameworks.
  28257. *
  28258. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  28259. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  28260. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  28261. *
  28262. * ### Overriding `.ng-hide`
  28263. *
  28264. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  28265. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  28266. * class in CSS:
  28267. *
  28268. * ```css
  28269. * .ng-hide {
  28270. * /&#42; this is just another form of hiding an element &#42;/
  28271. * display: block!important;
  28272. * position: absolute;
  28273. * top: -9999px;
  28274. * left: -9999px;
  28275. * }
  28276. * ```
  28277. *
  28278. * By default you don't need to override in CSS anything and the animations will work around the display style.
  28279. *
  28280. * ## A note about animations with `ngHide`
  28281. *
  28282. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  28283. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  28284. * CSS class is added and removed for you instead of your own CSS class.
  28285. *
  28286. * ```css
  28287. * //
  28288. * //a working example can be found at the bottom of this page
  28289. * //
  28290. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  28291. * transition: 0.5s linear all;
  28292. * }
  28293. *
  28294. * .my-element.ng-hide-add { ... }
  28295. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  28296. * .my-element.ng-hide-remove { ... }
  28297. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  28298. * ```
  28299. *
  28300. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display
  28301. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  28302. *
  28303. * @animations
  28304. * | Animation | Occurs |
  28305. * |----------------------------------|-------------------------------------|
  28306. * | {@link $animate#addClass addClass} `.ng-hide` | after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden |
  28307. * | {@link $animate#removeClass removeClass} `.ng-hide` | after the `ngHide` expression evaluates to a non truthy value and just before contents are set to visible |
  28308. *
  28309. *
  28310. * @element ANY
  28311. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  28312. * the element is shown or hidden respectively.
  28313. *
  28314. * @example
  28315. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide">
  28316. <file name="index.html">
  28317. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
  28318. <div>
  28319. Show:
  28320. <div class="check-element animate-hide" ng-show="checked">
  28321. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  28322. </div>
  28323. </div>
  28324. <div>
  28325. Hide:
  28326. <div class="check-element animate-hide" ng-hide="checked">
  28327. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  28328. </div>
  28329. </div>
  28330. </file>
  28331. <file name="glyphicons.css">
  28332. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  28333. </file>
  28334. <file name="animations.css">
  28335. .animate-hide {
  28336. transition: all linear 0.5s;
  28337. line-height: 20px;
  28338. opacity: 1;
  28339. padding: 10px;
  28340. border: 1px solid black;
  28341. background: white;
  28342. }
  28343. .animate-hide.ng-hide {
  28344. line-height: 0;
  28345. opacity: 0;
  28346. padding: 0 10px;
  28347. }
  28348. .check-element {
  28349. padding: 10px;
  28350. border: 1px solid black;
  28351. background: white;
  28352. }
  28353. </file>
  28354. <file name="protractor.js" type="protractor">
  28355. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  28356. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  28357. it('should check ng-show / ng-hide', function() {
  28358. expect(thumbsUp.isDisplayed()).toBeFalsy();
  28359. expect(thumbsDown.isDisplayed()).toBeTruthy();
  28360. element(by.model('checked')).click();
  28361. expect(thumbsUp.isDisplayed()).toBeTruthy();
  28362. expect(thumbsDown.isDisplayed()).toBeFalsy();
  28363. });
  28364. </file>
  28365. </example>
  28366. */
  28367. var ngHideDirective = ['$animate', function($animate) {
  28368. return {
  28369. restrict: 'A',
  28370. multiElement: true,
  28371. link: function(scope, element, attr) {
  28372. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  28373. // The comment inside of the ngShowDirective explains why we add and
  28374. // remove a temporary class for the show/hide animation
  28375. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  28376. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  28377. });
  28378. });
  28379. }
  28380. };
  28381. }];
  28382. /**
  28383. * @ngdoc directive
  28384. * @name ngStyle
  28385. * @restrict AC
  28386. *
  28387. * @description
  28388. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  28389. *
  28390. * @knownIssue
  28391. * You should not use {@link guide/interpolation interpolation} in the value of the `style`
  28392. * attribute, when using the `ngStyle` directive on the same element.
  28393. * See {@link guide/interpolation#known-issues here} for more info.
  28394. *
  28395. * @element ANY
  28396. * @param {expression} ngStyle
  28397. *
  28398. * {@link guide/expression Expression} which evals to an
  28399. * object whose keys are CSS style names and values are corresponding values for those CSS
  28400. * keys.
  28401. *
  28402. * Since some CSS style names are not valid keys for an object, they must be quoted.
  28403. * See the 'background-color' style in the example below.
  28404. *
  28405. * @example
  28406. <example name="ng-style">
  28407. <file name="index.html">
  28408. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  28409. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  28410. <input type="button" value="clear" ng-click="myStyle={}">
  28411. <br/>
  28412. <span ng-style="myStyle">Sample Text</span>
  28413. <pre>myStyle={{myStyle}}</pre>
  28414. </file>
  28415. <file name="style.css">
  28416. span {
  28417. color: black;
  28418. }
  28419. </file>
  28420. <file name="protractor.js" type="protractor">
  28421. var colorSpan = element(by.css('span'));
  28422. it('should check ng-style', function() {
  28423. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  28424. element(by.css('input[value=\'set color\']')).click();
  28425. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  28426. element(by.css('input[value=clear]')).click();
  28427. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  28428. });
  28429. </file>
  28430. </example>
  28431. */
  28432. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  28433. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  28434. if (oldStyles && (newStyles !== oldStyles)) {
  28435. forEach(oldStyles, function(val, style) { element.css(style, '');});
  28436. }
  28437. if (newStyles) element.css(newStyles);
  28438. }, true);
  28439. });
  28440. /**
  28441. * @ngdoc directive
  28442. * @name ngSwitch
  28443. * @restrict EA
  28444. *
  28445. * @description
  28446. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  28447. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  28448. * as specified in the template.
  28449. *
  28450. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  28451. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  28452. * matches the value obtained from the evaluated expression. In other words, you define a container element
  28453. * (where you place the directive), place an expression on the **`on="..."` attribute**
  28454. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  28455. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  28456. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  28457. * attribute is displayed.
  28458. *
  28459. * <div class="alert alert-info">
  28460. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  28461. * as literal string values to match against.
  28462. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  28463. * value of the expression `$scope.someVal`.
  28464. * </div>
  28465. * @animations
  28466. * | Animation | Occurs |
  28467. * |----------------------------------|-------------------------------------|
  28468. * | {@link ng.$animate#enter enter} | after the ngSwitch contents change and the matched child element is placed inside the container |
  28469. * | {@link ng.$animate#leave leave} | after the ngSwitch contents change and just before the former contents are removed from the DOM |
  28470. *
  28471. * @usage
  28472. *
  28473. * ```
  28474. * <ANY ng-switch="expression">
  28475. * <ANY ng-switch-when="matchValue1">...</ANY>
  28476. * <ANY ng-switch-when="matchValue2">...</ANY>
  28477. * <ANY ng-switch-default>...</ANY>
  28478. * </ANY>
  28479. * ```
  28480. *
  28481. *
  28482. * @scope
  28483. * @priority 1200
  28484. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  28485. * On child elements add:
  28486. *
  28487. * * `ngSwitchWhen`: the case statement to match against. If match then this
  28488. * case will be displayed. If the same match appears multiple times, all the
  28489. * elements will be displayed. It is possible to associate mutiple values to
  28490. * the same `ngSwitchWhen` by defining the optional attribute
  28491. * `ngSwitchWhenSeparator`. The separator will be used to split the value of
  28492. * the `ngSwitchWhen` attribute into multiple tokens, and the element will show
  28493. * if any of the `ngSwitch` evaluates to any of these tokens.
  28494. * * `ngSwitchDefault`: the default case when no other case match. If there
  28495. * are multiple default cases, all of them will be displayed when no other
  28496. * case match.
  28497. *
  28498. *
  28499. * @example
  28500. <example module="switchExample" deps="angular-animate.js" animations="true" name="ng-switch">
  28501. <file name="index.html">
  28502. <div ng-controller="ExampleController">
  28503. <select ng-model="selection" ng-options="item for item in items">
  28504. </select>
  28505. <code>selection={{selection}}</code>
  28506. <hr/>
  28507. <div class="animate-switch-container"
  28508. ng-switch on="selection">
  28509. <div class="animate-switch" ng-switch-when="settings|options" ng-switch-when-separator="|">Settings Div</div>
  28510. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  28511. <div class="animate-switch" ng-switch-default>default</div>
  28512. </div>
  28513. </div>
  28514. </file>
  28515. <file name="script.js">
  28516. angular.module('switchExample', ['ngAnimate'])
  28517. .controller('ExampleController', ['$scope', function($scope) {
  28518. $scope.items = ['settings', 'home', 'options', 'other'];
  28519. $scope.selection = $scope.items[0];
  28520. }]);
  28521. </file>
  28522. <file name="animations.css">
  28523. .animate-switch-container {
  28524. position:relative;
  28525. background:white;
  28526. border:1px solid black;
  28527. height:40px;
  28528. overflow:hidden;
  28529. }
  28530. .animate-switch {
  28531. padding:10px;
  28532. }
  28533. .animate-switch.ng-animate {
  28534. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  28535. position:absolute;
  28536. top:0;
  28537. left:0;
  28538. right:0;
  28539. bottom:0;
  28540. }
  28541. .animate-switch.ng-leave.ng-leave-active,
  28542. .animate-switch.ng-enter {
  28543. top:-50px;
  28544. }
  28545. .animate-switch.ng-leave,
  28546. .animate-switch.ng-enter.ng-enter-active {
  28547. top:0;
  28548. }
  28549. </file>
  28550. <file name="protractor.js" type="protractor">
  28551. var switchElem = element(by.css('[ng-switch]'));
  28552. var select = element(by.model('selection'));
  28553. it('should start in settings', function() {
  28554. expect(switchElem.getText()).toMatch(/Settings Div/);
  28555. });
  28556. it('should change to home', function() {
  28557. select.all(by.css('option')).get(1).click();
  28558. expect(switchElem.getText()).toMatch(/Home Span/);
  28559. });
  28560. it('should change to settings via "options"', function() {
  28561. select.all(by.css('option')).get(2).click();
  28562. expect(switchElem.getText()).toMatch(/Settings Div/);
  28563. });
  28564. it('should select default', function() {
  28565. select.all(by.css('option')).get(3).click();
  28566. expect(switchElem.getText()).toMatch(/default/);
  28567. });
  28568. </file>
  28569. </example>
  28570. */
  28571. var ngSwitchDirective = ['$animate', '$compile', function($animate, $compile) {
  28572. return {
  28573. require: 'ngSwitch',
  28574. // asks for $scope to fool the BC controller module
  28575. controller: ['$scope', function NgSwitchController() {
  28576. this.cases = {};
  28577. }],
  28578. link: function(scope, element, attr, ngSwitchController) {
  28579. var watchExpr = attr.ngSwitch || attr.on,
  28580. selectedTranscludes = [],
  28581. selectedElements = [],
  28582. previousLeaveAnimations = [],
  28583. selectedScopes = [];
  28584. var spliceFactory = function(array, index) {
  28585. return function() { array.splice(index, 1); };
  28586. };
  28587. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  28588. var i, ii;
  28589. for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
  28590. $animate.cancel(previousLeaveAnimations[i]);
  28591. }
  28592. previousLeaveAnimations.length = 0;
  28593. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  28594. var selected = getBlockNodes(selectedElements[i].clone);
  28595. selectedScopes[i].$destroy();
  28596. var promise = previousLeaveAnimations[i] = $animate.leave(selected);
  28597. promise.then(spliceFactory(previousLeaveAnimations, i));
  28598. }
  28599. selectedElements.length = 0;
  28600. selectedScopes.length = 0;
  28601. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  28602. forEach(selectedTranscludes, function(selectedTransclude) {
  28603. selectedTransclude.transclude(function(caseElement, selectedScope) {
  28604. selectedScopes.push(selectedScope);
  28605. var anchor = selectedTransclude.element;
  28606. caseElement[caseElement.length++] = $compile.$$createComment('end ngSwitchWhen');
  28607. var block = { clone: caseElement };
  28608. selectedElements.push(block);
  28609. $animate.enter(caseElement, anchor.parent(), anchor);
  28610. });
  28611. });
  28612. }
  28613. });
  28614. }
  28615. };
  28616. }];
  28617. var ngSwitchWhenDirective = ngDirective({
  28618. transclude: 'element',
  28619. priority: 1200,
  28620. require: '^ngSwitch',
  28621. multiElement: true,
  28622. link: function(scope, element, attrs, ctrl, $transclude) {
  28623. var cases = attrs.ngSwitchWhen.split(attrs.ngSwitchWhenSeparator).sort().filter(
  28624. // Filter duplicate cases
  28625. function(element, index, array) { return array[index - 1] !== element; }
  28626. );
  28627. forEach(cases, function(whenCase) {
  28628. ctrl.cases['!' + whenCase] = (ctrl.cases['!' + whenCase] || []);
  28629. ctrl.cases['!' + whenCase].push({ transclude: $transclude, element: element });
  28630. });
  28631. }
  28632. });
  28633. var ngSwitchDefaultDirective = ngDirective({
  28634. transclude: 'element',
  28635. priority: 1200,
  28636. require: '^ngSwitch',
  28637. multiElement: true,
  28638. link: function(scope, element, attr, ctrl, $transclude) {
  28639. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  28640. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  28641. }
  28642. });
  28643. /**
  28644. * @ngdoc directive
  28645. * @name ngTransclude
  28646. * @restrict EAC
  28647. *
  28648. * @description
  28649. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  28650. *
  28651. * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name
  28652. * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.
  28653. *
  28654. * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing
  28655. * content of this element will be removed before the transcluded content is inserted.
  28656. * If the transcluded content is empty, the existing content is left intact. This lets you provide fallback content in the case
  28657. * that no transcluded content is provided.
  28658. *
  28659. * @element ANY
  28660. *
  28661. * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty
  28662. * or its value is the same as the name of the attribute then the default slot is used.
  28663. *
  28664. * @example
  28665. * ### Basic transclusion
  28666. * This example demonstrates basic transclusion of content into a component directive.
  28667. * <example name="simpleTranscludeExample" module="transcludeExample">
  28668. * <file name="index.html">
  28669. * <script>
  28670. * angular.module('transcludeExample', [])
  28671. * .directive('pane', function(){
  28672. * return {
  28673. * restrict: 'E',
  28674. * transclude: true,
  28675. * scope: { title:'@' },
  28676. * template: '<div style="border: 1px solid black;">' +
  28677. * '<div style="background-color: gray">{{title}}</div>' +
  28678. * '<ng-transclude></ng-transclude>' +
  28679. * '</div>'
  28680. * };
  28681. * })
  28682. * .controller('ExampleController', ['$scope', function($scope) {
  28683. * $scope.title = 'Lorem Ipsum';
  28684. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  28685. * }]);
  28686. * </script>
  28687. * <div ng-controller="ExampleController">
  28688. * <input ng-model="title" aria-label="title"> <br/>
  28689. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  28690. * <pane title="{{title}}"><span>{{text}}</span></pane>
  28691. * </div>
  28692. * </file>
  28693. * <file name="protractor.js" type="protractor">
  28694. * it('should have transcluded', function() {
  28695. * var titleElement = element(by.model('title'));
  28696. * titleElement.clear();
  28697. * titleElement.sendKeys('TITLE');
  28698. * var textElement = element(by.model('text'));
  28699. * textElement.clear();
  28700. * textElement.sendKeys('TEXT');
  28701. * expect(element(by.binding('title')).getText()).toEqual('TITLE');
  28702. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  28703. * });
  28704. * </file>
  28705. * </example>
  28706. *
  28707. * @example
  28708. * ### Transclude fallback content
  28709. * This example shows how to use `NgTransclude` with fallback content, that
  28710. * is displayed if no transcluded content is provided.
  28711. *
  28712. * <example module="transcludeFallbackContentExample" name="ng-transclude">
  28713. * <file name="index.html">
  28714. * <script>
  28715. * angular.module('transcludeFallbackContentExample', [])
  28716. * .directive('myButton', function(){
  28717. * return {
  28718. * restrict: 'E',
  28719. * transclude: true,
  28720. * scope: true,
  28721. * template: '<button style="cursor: pointer;">' +
  28722. * '<ng-transclude>' +
  28723. * '<b style="color: red;">Button1</b>' +
  28724. * '</ng-transclude>' +
  28725. * '</button>'
  28726. * };
  28727. * });
  28728. * </script>
  28729. * <!-- fallback button content -->
  28730. * <my-button id="fallback"></my-button>
  28731. * <!-- modified button content -->
  28732. * <my-button id="modified">
  28733. * <i style="color: green;">Button2</i>
  28734. * </my-button>
  28735. * </file>
  28736. * <file name="protractor.js" type="protractor">
  28737. * it('should have different transclude element content', function() {
  28738. * expect(element(by.id('fallback')).getText()).toBe('Button1');
  28739. * expect(element(by.id('modified')).getText()).toBe('Button2');
  28740. * });
  28741. * </file>
  28742. * </example>
  28743. *
  28744. * @example
  28745. * ### Multi-slot transclusion
  28746. * This example demonstrates using multi-slot transclusion in a component directive.
  28747. * <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample">
  28748. * <file name="index.html">
  28749. * <style>
  28750. * .title, .footer {
  28751. * background-color: gray
  28752. * }
  28753. * </style>
  28754. * <div ng-controller="ExampleController">
  28755. * <input ng-model="title" aria-label="title"> <br/>
  28756. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  28757. * <pane>
  28758. * <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
  28759. * <pane-body><p>{{text}}</p></pane-body>
  28760. * </pane>
  28761. * </div>
  28762. * </file>
  28763. * <file name="app.js">
  28764. * angular.module('multiSlotTranscludeExample', [])
  28765. * .directive('pane', function() {
  28766. * return {
  28767. * restrict: 'E',
  28768. * transclude: {
  28769. * 'title': '?paneTitle',
  28770. * 'body': 'paneBody',
  28771. * 'footer': '?paneFooter'
  28772. * },
  28773. * template: '<div style="border: 1px solid black;">' +
  28774. * '<div class="title" ng-transclude="title">Fallback Title</div>' +
  28775. * '<div ng-transclude="body"></div>' +
  28776. * '<div class="footer" ng-transclude="footer">Fallback Footer</div>' +
  28777. * '</div>'
  28778. * };
  28779. * })
  28780. * .controller('ExampleController', ['$scope', function($scope) {
  28781. * $scope.title = 'Lorem Ipsum';
  28782. * $scope.link = 'https://google.com';
  28783. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  28784. * }]);
  28785. * </file>
  28786. * <file name="protractor.js" type="protractor">
  28787. * it('should have transcluded the title and the body', function() {
  28788. * var titleElement = element(by.model('title'));
  28789. * titleElement.clear();
  28790. * titleElement.sendKeys('TITLE');
  28791. * var textElement = element(by.model('text'));
  28792. * textElement.clear();
  28793. * textElement.sendKeys('TEXT');
  28794. * expect(element(by.css('.title')).getText()).toEqual('TITLE');
  28795. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  28796. * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer');
  28797. * });
  28798. * </file>
  28799. * </example>
  28800. */
  28801. var ngTranscludeMinErr = minErr('ngTransclude');
  28802. var ngTranscludeDirective = ['$compile', function($compile) {
  28803. return {
  28804. restrict: 'EAC',
  28805. terminal: true,
  28806. compile: function ngTranscludeCompile(tElement) {
  28807. // Remove and cache any original content to act as a fallback
  28808. var fallbackLinkFn = $compile(tElement.contents());
  28809. tElement.empty();
  28810. return function ngTranscludePostLink($scope, $element, $attrs, controller, $transclude) {
  28811. if (!$transclude) {
  28812. throw ngTranscludeMinErr('orphan',
  28813. 'Illegal use of ngTransclude directive in the template! ' +
  28814. 'No parent directive that requires a transclusion found. ' +
  28815. 'Element: {0}',
  28816. startingTag($element));
  28817. }
  28818. // If the attribute is of the form: `ng-transclude="ng-transclude"` then treat it like the default
  28819. if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) {
  28820. $attrs.ngTransclude = '';
  28821. }
  28822. var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot;
  28823. // If the slot is required and no transclusion content is provided then this call will throw an error
  28824. $transclude(ngTranscludeCloneAttachFn, null, slotName);
  28825. // If the slot is optional and no transclusion content is provided then use the fallback content
  28826. if (slotName && !$transclude.isSlotFilled(slotName)) {
  28827. useFallbackContent();
  28828. }
  28829. function ngTranscludeCloneAttachFn(clone, transcludedScope) {
  28830. if (clone.length) {
  28831. $element.append(clone);
  28832. } else {
  28833. useFallbackContent();
  28834. // There is nothing linked against the transcluded scope since no content was available,
  28835. // so it should be safe to clean up the generated scope.
  28836. transcludedScope.$destroy();
  28837. }
  28838. }
  28839. function useFallbackContent() {
  28840. // Since this is the fallback content rather than the transcluded content,
  28841. // we link against the scope of this directive rather than the transcluded scope
  28842. fallbackLinkFn($scope, function(clone) {
  28843. $element.append(clone);
  28844. });
  28845. }
  28846. };
  28847. }
  28848. };
  28849. }];
  28850. /**
  28851. * @ngdoc directive
  28852. * @name script
  28853. * @restrict E
  28854. *
  28855. * @description
  28856. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  28857. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  28858. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  28859. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  28860. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  28861. *
  28862. * @param {string} type Must be set to `'text/ng-template'`.
  28863. * @param {string} id Cache name of the template.
  28864. *
  28865. * @example
  28866. <example name="script-tag">
  28867. <file name="index.html">
  28868. <script type="text/ng-template" id="/tpl.html">
  28869. Content of the template.
  28870. </script>
  28871. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  28872. <div id="tpl-content" ng-include src="currentTpl"></div>
  28873. </file>
  28874. <file name="protractor.js" type="protractor">
  28875. it('should load template defined inside script tag', function() {
  28876. element(by.css('#tpl-link')).click();
  28877. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  28878. });
  28879. </file>
  28880. </example>
  28881. */
  28882. var scriptDirective = ['$templateCache', function($templateCache) {
  28883. return {
  28884. restrict: 'E',
  28885. terminal: true,
  28886. compile: function(element, attr) {
  28887. if (attr.type === 'text/ng-template') {
  28888. var templateUrl = attr.id,
  28889. text = element[0].text;
  28890. $templateCache.put(templateUrl, text);
  28891. }
  28892. }
  28893. };
  28894. }];
  28895. /* exported selectDirective, optionDirective */
  28896. var noopNgModelController = { $setViewValue: noop, $render: noop };
  28897. /**
  28898. * @ngdoc type
  28899. * @name select.SelectController
  28900. * @description
  28901. * The controller for the `<select>` directive. This provides support for reading
  28902. * and writing the selected value(s) of the control and also coordinates dynamically
  28903. * added `<option>` elements, perhaps by an `ngRepeat` directive.
  28904. */
  28905. var SelectController =
  28906. ['$element', '$scope', /** @this */ function($element, $scope) {
  28907. var self = this,
  28908. optionsMap = new HashMap();
  28909. self.selectValueMap = {}; // Keys are the hashed values, values the original values
  28910. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  28911. self.ngModelCtrl = noopNgModelController;
  28912. self.multiple = false;
  28913. // The "unknown" option is one that is prepended to the list if the viewValue
  28914. // does not match any of the options. When it is rendered the value of the unknown
  28915. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  28916. //
  28917. // We can't just jqLite('<option>') since jqLite is not smart enough
  28918. // to create it in <select> and IE barfs otherwise.
  28919. self.unknownOption = jqLite(window.document.createElement('option'));
  28920. self.renderUnknownOption = function(val) {
  28921. var unknownVal = self.generateUnknownOptionValue(val);
  28922. self.unknownOption.val(unknownVal);
  28923. $element.prepend(self.unknownOption);
  28924. setOptionAsSelected(self.unknownOption);
  28925. $element.val(unknownVal);
  28926. };
  28927. self.updateUnknownOption = function(val) {
  28928. var unknownVal = self.generateUnknownOptionValue(val);
  28929. self.unknownOption.val(unknownVal);
  28930. setOptionAsSelected(self.unknownOption);
  28931. $element.val(unknownVal);
  28932. };
  28933. self.generateUnknownOptionValue = function(val) {
  28934. return '? ' + hashKey(val) + ' ?';
  28935. };
  28936. self.removeUnknownOption = function() {
  28937. if (self.unknownOption.parent()) self.unknownOption.remove();
  28938. };
  28939. // The empty option is an option with the value '' that te application developer can
  28940. // provide inside the select. When the model changes to a value that doesn't match an option,
  28941. // it is selected - so if an empty option is provided, no unknown option is generated.
  28942. // However, the empty option is not removed when the model matches an option. It is always selectable
  28943. // and indicates that a "null" selection has been made.
  28944. self.emptyOption = undefined;
  28945. self.selectEmptyOption = function() {
  28946. if (self.emptyOption) {
  28947. $element.val('');
  28948. setOptionAsSelected(self.emptyOption);
  28949. }
  28950. };
  28951. self.unselectEmptyOption = function() {
  28952. if (self.emptyOption) {
  28953. self.emptyOption.removeAttr('selected');
  28954. }
  28955. };
  28956. $scope.$on('$destroy', function() {
  28957. // disable unknown option so that we don't do work when the whole select is being destroyed
  28958. self.renderUnknownOption = noop;
  28959. });
  28960. // Read the value of the select control, the implementation of this changes depending
  28961. // upon whether the select can have multiple values and whether ngOptions is at work.
  28962. self.readValue = function readSingleValue() {
  28963. var val = $element.val();
  28964. // ngValue added option values are stored in the selectValueMap, normal interpolations are not
  28965. var realVal = val in self.selectValueMap ? self.selectValueMap[val] : val;
  28966. if (self.hasOption(realVal)) {
  28967. return realVal;
  28968. }
  28969. return null;
  28970. };
  28971. // Write the value to the select control, the implementation of this changes depending
  28972. // upon whether the select can have multiple values and whether ngOptions is at work.
  28973. self.writeValue = function writeSingleValue(value) {
  28974. // Make sure to remove the selected attribute from the previously selected option
  28975. // Otherwise, screen readers might get confused
  28976. var currentlySelectedOption = $element[0].options[$element[0].selectedIndex];
  28977. if (currentlySelectedOption) currentlySelectedOption.removeAttribute('selected');
  28978. if (self.hasOption(value)) {
  28979. self.removeUnknownOption();
  28980. var hashedVal = hashKey(value);
  28981. $element.val(hashedVal in self.selectValueMap ? hashedVal : value);
  28982. // Set selected attribute and property on selected option for screen readers
  28983. var selectedOption = $element[0].options[$element[0].selectedIndex];
  28984. setOptionAsSelected(jqLite(selectedOption));
  28985. } else {
  28986. if (value == null && self.emptyOption) {
  28987. self.removeUnknownOption();
  28988. self.selectEmptyOption();
  28989. } else if (self.unknownOption.parent().length) {
  28990. self.updateUnknownOption(value);
  28991. } else {
  28992. self.renderUnknownOption(value);
  28993. }
  28994. }
  28995. };
  28996. // Tell the select control that an option, with the given value, has been added
  28997. self.addOption = function(value, element) {
  28998. // Skip comment nodes, as they only pollute the `optionsMap`
  28999. if (element[0].nodeType === NODE_TYPE_COMMENT) return;
  29000. assertNotHasOwnProperty(value, '"option value"');
  29001. if (value === '') {
  29002. self.emptyOption = element;
  29003. }
  29004. var count = optionsMap.get(value) || 0;
  29005. optionsMap.put(value, count + 1);
  29006. // Only render at the end of a digest. This improves render performance when many options
  29007. // are added during a digest and ensures all relevant options are correctly marked as selected
  29008. scheduleRender();
  29009. };
  29010. // Tell the select control that an option, with the given value, has been removed
  29011. self.removeOption = function(value) {
  29012. var count = optionsMap.get(value);
  29013. if (count) {
  29014. if (count === 1) {
  29015. optionsMap.remove(value);
  29016. if (value === '') {
  29017. self.emptyOption = undefined;
  29018. }
  29019. } else {
  29020. optionsMap.put(value, count - 1);
  29021. }
  29022. }
  29023. };
  29024. // Check whether the select control has an option matching the given value
  29025. self.hasOption = function(value) {
  29026. return !!optionsMap.get(value);
  29027. };
  29028. var renderScheduled = false;
  29029. function scheduleRender() {
  29030. if (renderScheduled) return;
  29031. renderScheduled = true;
  29032. $scope.$$postDigest(function() {
  29033. renderScheduled = false;
  29034. self.ngModelCtrl.$render();
  29035. });
  29036. }
  29037. var updateScheduled = false;
  29038. function scheduleViewValueUpdate(renderAfter) {
  29039. if (updateScheduled) return;
  29040. updateScheduled = true;
  29041. $scope.$$postDigest(function() {
  29042. updateScheduled = false;
  29043. self.ngModelCtrl.$setViewValue(self.readValue());
  29044. if (renderAfter) self.ngModelCtrl.$render();
  29045. });
  29046. }
  29047. self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
  29048. if (optionAttrs.$attr.ngValue) {
  29049. // The value attribute is set by ngValue
  29050. var oldVal, hashedVal = NaN;
  29051. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  29052. var removal;
  29053. var previouslySelected = optionElement.prop('selected');
  29054. if (isDefined(hashedVal)) {
  29055. self.removeOption(oldVal);
  29056. delete self.selectValueMap[hashedVal];
  29057. removal = true;
  29058. }
  29059. hashedVal = hashKey(newVal);
  29060. oldVal = newVal;
  29061. self.selectValueMap[hashedVal] = newVal;
  29062. self.addOption(newVal, optionElement);
  29063. // Set the attribute directly instead of using optionAttrs.$set - this stops the observer
  29064. // from firing a second time. Other $observers on value will also get the result of the
  29065. // ngValue expression, not the hashed value
  29066. optionElement.attr('value', hashedVal);
  29067. if (removal && previouslySelected) {
  29068. scheduleViewValueUpdate();
  29069. }
  29070. });
  29071. } else if (interpolateValueFn) {
  29072. // The value attribute is interpolated
  29073. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  29074. // This method is overwritten in ngOptions and has side-effects!
  29075. self.readValue();
  29076. var removal;
  29077. var previouslySelected = optionElement.prop('selected');
  29078. if (isDefined(oldVal)) {
  29079. self.removeOption(oldVal);
  29080. removal = true;
  29081. }
  29082. oldVal = newVal;
  29083. self.addOption(newVal, optionElement);
  29084. if (removal && previouslySelected) {
  29085. scheduleViewValueUpdate();
  29086. }
  29087. });
  29088. } else if (interpolateTextFn) {
  29089. // The text content is interpolated
  29090. optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
  29091. optionAttrs.$set('value', newVal);
  29092. var previouslySelected = optionElement.prop('selected');
  29093. if (oldVal !== newVal) {
  29094. self.removeOption(oldVal);
  29095. }
  29096. self.addOption(newVal, optionElement);
  29097. if (oldVal && previouslySelected) {
  29098. scheduleViewValueUpdate();
  29099. }
  29100. });
  29101. } else {
  29102. // The value attribute is static
  29103. self.addOption(optionAttrs.value, optionElement);
  29104. }
  29105. optionAttrs.$observe('disabled', function(newVal) {
  29106. // Since model updates will also select disabled options (like ngOptions),
  29107. // we only have to handle options becoming disabled, not enabled
  29108. if (newVal === 'true' || newVal && optionElement.prop('selected')) {
  29109. if (self.multiple) {
  29110. scheduleViewValueUpdate(true);
  29111. } else {
  29112. self.ngModelCtrl.$setViewValue(null);
  29113. self.ngModelCtrl.$render();
  29114. }
  29115. }
  29116. });
  29117. optionElement.on('$destroy', function() {
  29118. var currentValue = self.readValue();
  29119. var removeValue = optionAttrs.value;
  29120. self.removeOption(removeValue);
  29121. self.ngModelCtrl.$render();
  29122. if (self.multiple && currentValue && currentValue.indexOf(removeValue) !== -1 ||
  29123. currentValue === removeValue
  29124. ) {
  29125. // When multiple (selected) options are destroyed at the same time, we don't want
  29126. // to run a model update for each of them. Instead, run a single update in the $$postDigest
  29127. scheduleViewValueUpdate(true);
  29128. }
  29129. });
  29130. };
  29131. function setOptionAsSelected(optionEl) {
  29132. optionEl.prop('selected', true); // needed for IE
  29133. optionEl.attr('selected', true);
  29134. }
  29135. }];
  29136. /**
  29137. * @ngdoc directive
  29138. * @name select
  29139. * @restrict E
  29140. *
  29141. * @description
  29142. * HTML `select` element with angular data-binding.
  29143. *
  29144. * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
  29145. * between the scope and the `<select>` control (including setting default values).
  29146. * It also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
  29147. * {@link ngOptions `ngOptions`} directives.
  29148. *
  29149. * When an item in the `<select>` menu is selected, the value of the selected option will be bound
  29150. * to the model identified by the `ngModel` directive. With static or repeated options, this is
  29151. * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
  29152. * Value and textContent can be interpolated.
  29153. *
  29154. * ## Matching model and option values
  29155. *
  29156. * In general, the match between the model and an option is evaluated by strictly comparing the model
  29157. * value against the value of the available options.
  29158. *
  29159. * If you are setting the option value with the option's `value` attribute, or textContent, the
  29160. * value will always be a `string` which means that the model value must also be a string.
  29161. * Otherwise the `select` directive cannot match them correctly.
  29162. *
  29163. * To bind the model to a non-string value, you can use one of the following strategies:
  29164. * - the {@link ng.ngOptions `ngOptions`} directive
  29165. * ({@link ng.select#using-select-with-ngoptions-and-setting-a-default-value})
  29166. * - the {@link ng.ngValue `ngValue`} directive, which allows arbitrary expressions to be
  29167. * option values ({@link ng.select#using-ngvalue-to-bind-the-model-to-an-array-of-objects Example})
  29168. * - model $parsers / $formatters to convert the string value
  29169. * ({@link ng.select#binding-select-to-a-non-string-value-via-ngmodel-parsing-formatting Example})
  29170. *
  29171. * If the viewValue of `ngModel` does not match any of the options, then the control
  29172. * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
  29173. *
  29174. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  29175. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  29176. * option. See example below for demonstration.
  29177. *
  29178. * ## Choosing between `ngRepeat` and `ngOptions`
  29179. *
  29180. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  29181. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits:
  29182. * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  29183. * comprehension expression
  29184. * - reduced memory consumption by not creating a new scope for each repeated instance
  29185. * - increased render speed by creating the options in a documentFragment instead of individually
  29186. *
  29187. * Specifically, select with repeated options slows down significantly starting at 2000 options in
  29188. * Chrome and Internet Explorer / Edge.
  29189. *
  29190. *
  29191. * @param {string} ngModel Assignable angular expression to data-bind to.
  29192. * @param {string=} name Property name of the form under which the control is published.
  29193. * @param {string=} multiple Allows multiple options to be selected. The selected values will be
  29194. * bound to the model as an array.
  29195. * @param {string=} required Sets `required` validation error key if the value is not entered.
  29196. * @param {string=} ngRequired Adds required attribute and required validation constraint to
  29197. * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
  29198. * when you want to data-bind to the required attribute.
  29199. * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
  29200. * interaction with the select element.
  29201. * @param {string=} ngOptions sets the options that the select is populated with and defines what is
  29202. * set on the model on selection. See {@link ngOptions `ngOptions`}.
  29203. *
  29204. * @example
  29205. * ### Simple `select` elements with static options
  29206. *
  29207. * <example name="static-select" module="staticSelect">
  29208. * <file name="index.html">
  29209. * <div ng-controller="ExampleController">
  29210. * <form name="myForm">
  29211. * <label for="singleSelect"> Single select: </label><br>
  29212. * <select name="singleSelect" ng-model="data.singleSelect">
  29213. * <option value="option-1">Option 1</option>
  29214. * <option value="option-2">Option 2</option>
  29215. * </select><br>
  29216. *
  29217. * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
  29218. * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
  29219. * <option value="">---Please select---</option> <!-- not selected / blank option -->
  29220. * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
  29221. * <option value="option-2">Option 2</option>
  29222. * </select><br>
  29223. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  29224. * <tt>singleSelect = {{data.singleSelect}}</tt>
  29225. *
  29226. * <hr>
  29227. * <label for="multipleSelect"> Multiple select: </label><br>
  29228. * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
  29229. * <option value="option-1">Option 1</option>
  29230. * <option value="option-2">Option 2</option>
  29231. * <option value="option-3">Option 3</option>
  29232. * </select><br>
  29233. * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
  29234. * </form>
  29235. * </div>
  29236. * </file>
  29237. * <file name="app.js">
  29238. * angular.module('staticSelect', [])
  29239. * .controller('ExampleController', ['$scope', function($scope) {
  29240. * $scope.data = {
  29241. * singleSelect: null,
  29242. * multipleSelect: [],
  29243. * option1: 'option-1'
  29244. * };
  29245. *
  29246. * $scope.forceUnknownOption = function() {
  29247. * $scope.data.singleSelect = 'nonsense';
  29248. * };
  29249. * }]);
  29250. * </file>
  29251. *</example>
  29252. *
  29253. * ### Using `ngRepeat` to generate `select` options
  29254. * <example name="select-ngrepeat" module="ngrepeatSelect">
  29255. * <file name="index.html">
  29256. * <div ng-controller="ExampleController">
  29257. * <form name="myForm">
  29258. * <label for="repeatSelect"> Repeat select: </label>
  29259. * <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
  29260. * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
  29261. * </select>
  29262. * </form>
  29263. * <hr>
  29264. * <tt>model = {{data.model}}</tt><br/>
  29265. * </div>
  29266. * </file>
  29267. * <file name="app.js">
  29268. * angular.module('ngrepeatSelect', [])
  29269. * .controller('ExampleController', ['$scope', function($scope) {
  29270. * $scope.data = {
  29271. * model: null,
  29272. * availableOptions: [
  29273. * {id: '1', name: 'Option A'},
  29274. * {id: '2', name: 'Option B'},
  29275. * {id: '3', name: 'Option C'}
  29276. * ]
  29277. * };
  29278. * }]);
  29279. * </file>
  29280. *</example>
  29281. *
  29282. * ### Using `ngValue` to bind the model to an array of objects
  29283. * <example name="select-ngvalue" module="ngvalueSelect">
  29284. * <file name="index.html">
  29285. * <div ng-controller="ExampleController">
  29286. * <form name="myForm">
  29287. * <label for="ngvalueselect"> ngvalue select: </label>
  29288. * <select size="6" name="ngvalueselect" ng-model="data.model" multiple>
  29289. * <option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option>
  29290. * </select>
  29291. * </form>
  29292. * <hr>
  29293. * <pre>model = {{data.model | json}}</pre><br/>
  29294. * </div>
  29295. * </file>
  29296. * <file name="app.js">
  29297. * angular.module('ngvalueSelect', [])
  29298. * .controller('ExampleController', ['$scope', function($scope) {
  29299. * $scope.data = {
  29300. * model: null,
  29301. * availableOptions: [
  29302. {value: 'myString', name: 'string'},
  29303. {value: 1, name: 'integer'},
  29304. {value: true, name: 'boolean'},
  29305. {value: null, name: 'null'},
  29306. {value: {prop: 'value'}, name: 'object'},
  29307. {value: ['a'], name: 'array'}
  29308. * ]
  29309. * };
  29310. * }]);
  29311. * </file>
  29312. *</example>
  29313. *
  29314. * ### Using `select` with `ngOptions` and setting a default value
  29315. * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
  29316. *
  29317. * <example name="select-with-default-values" module="defaultValueSelect">
  29318. * <file name="index.html">
  29319. * <div ng-controller="ExampleController">
  29320. * <form name="myForm">
  29321. * <label for="mySelect">Make a choice:</label>
  29322. * <select name="mySelect" id="mySelect"
  29323. * ng-options="option.name for option in data.availableOptions track by option.id"
  29324. * ng-model="data.selectedOption"></select>
  29325. * </form>
  29326. * <hr>
  29327. * <tt>option = {{data.selectedOption}}</tt><br/>
  29328. * </div>
  29329. * </file>
  29330. * <file name="app.js">
  29331. * angular.module('defaultValueSelect', [])
  29332. * .controller('ExampleController', ['$scope', function($scope) {
  29333. * $scope.data = {
  29334. * availableOptions: [
  29335. * {id: '1', name: 'Option A'},
  29336. * {id: '2', name: 'Option B'},
  29337. * {id: '3', name: 'Option C'}
  29338. * ],
  29339. * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
  29340. * };
  29341. * }]);
  29342. * </file>
  29343. *</example>
  29344. *
  29345. *
  29346. * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
  29347. *
  29348. * <example name="select-with-non-string-options" module="nonStringSelect">
  29349. * <file name="index.html">
  29350. * <select ng-model="model.id" convert-to-number>
  29351. * <option value="0">Zero</option>
  29352. * <option value="1">One</option>
  29353. * <option value="2">Two</option>
  29354. * </select>
  29355. * {{ model }}
  29356. * </file>
  29357. * <file name="app.js">
  29358. * angular.module('nonStringSelect', [])
  29359. * .run(function($rootScope) {
  29360. * $rootScope.model = { id: 2 };
  29361. * })
  29362. * .directive('convertToNumber', function() {
  29363. * return {
  29364. * require: 'ngModel',
  29365. * link: function(scope, element, attrs, ngModel) {
  29366. * ngModel.$parsers.push(function(val) {
  29367. * return parseInt(val, 10);
  29368. * });
  29369. * ngModel.$formatters.push(function(val) {
  29370. * return '' + val;
  29371. * });
  29372. * }
  29373. * };
  29374. * });
  29375. * </file>
  29376. * <file name="protractor.js" type="protractor">
  29377. * it('should initialize to model', function() {
  29378. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  29379. * });
  29380. * </file>
  29381. * </example>
  29382. *
  29383. */
  29384. var selectDirective = function() {
  29385. return {
  29386. restrict: 'E',
  29387. require: ['select', '?ngModel'],
  29388. controller: SelectController,
  29389. priority: 1,
  29390. link: {
  29391. pre: selectPreLink,
  29392. post: selectPostLink
  29393. }
  29394. };
  29395. function selectPreLink(scope, element, attr, ctrls) {
  29396. var selectCtrl = ctrls[0];
  29397. var ngModelCtrl = ctrls[1];
  29398. // if ngModel is not defined, we don't need to do anything but set the registerOption
  29399. // function to noop, so options don't get added internally
  29400. if (!ngModelCtrl) {
  29401. selectCtrl.registerOption = noop;
  29402. return;
  29403. }
  29404. selectCtrl.ngModelCtrl = ngModelCtrl;
  29405. // When the selected item(s) changes we delegate getting the value of the select control
  29406. // to the `readValue` method, which can be changed if the select can have multiple
  29407. // selected values or if the options are being generated by `ngOptions`
  29408. element.on('change', function() {
  29409. selectCtrl.removeUnknownOption();
  29410. scope.$apply(function() {
  29411. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  29412. });
  29413. });
  29414. // If the select allows multiple values then we need to modify how we read and write
  29415. // values from and to the control; also what it means for the value to be empty and
  29416. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  29417. // doesn't trigger rendering if only an item in the array changes.
  29418. if (attr.multiple) {
  29419. selectCtrl.multiple = true;
  29420. // Read value now needs to check each option to see if it is selected
  29421. selectCtrl.readValue = function readMultipleValue() {
  29422. var array = [];
  29423. forEach(element.find('option'), function(option) {
  29424. if (option.selected && !option.disabled) {
  29425. var val = option.value;
  29426. array.push(val in selectCtrl.selectValueMap ? selectCtrl.selectValueMap[val] : val);
  29427. }
  29428. });
  29429. return array;
  29430. };
  29431. // Write value now needs to set the selected property of each matching option
  29432. selectCtrl.writeValue = function writeMultipleValue(value) {
  29433. var items = new HashMap(value);
  29434. forEach(element.find('option'), function(option) {
  29435. option.selected = isDefined(items.get(option.value)) || isDefined(items.get(selectCtrl.selectValueMap[option.value]));
  29436. });
  29437. };
  29438. // we have to do it on each watch since ngModel watches reference, but
  29439. // we need to work of an array, so we need to see if anything was inserted/removed
  29440. var lastView, lastViewRef = NaN;
  29441. scope.$watch(function selectMultipleWatch() {
  29442. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  29443. lastView = shallowCopy(ngModelCtrl.$viewValue);
  29444. ngModelCtrl.$render();
  29445. }
  29446. lastViewRef = ngModelCtrl.$viewValue;
  29447. });
  29448. // If we are a multiple select then value is now a collection
  29449. // so the meaning of $isEmpty changes
  29450. ngModelCtrl.$isEmpty = function(value) {
  29451. return !value || value.length === 0;
  29452. };
  29453. }
  29454. }
  29455. function selectPostLink(scope, element, attrs, ctrls) {
  29456. // if ngModel is not defined, we don't need to do anything
  29457. var ngModelCtrl = ctrls[1];
  29458. if (!ngModelCtrl) return;
  29459. var selectCtrl = ctrls[0];
  29460. // We delegate rendering to the `writeValue` method, which can be changed
  29461. // if the select can have multiple selected values or if the options are being
  29462. // generated by `ngOptions`.
  29463. // This must be done in the postLink fn to prevent $render to be called before
  29464. // all nodes have been linked correctly.
  29465. ngModelCtrl.$render = function() {
  29466. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  29467. };
  29468. }
  29469. };
  29470. // The option directive is purely designed to communicate the existence (or lack of)
  29471. // of dynamically created (and destroyed) option elements to their containing select
  29472. // directive via its controller.
  29473. var optionDirective = ['$interpolate', function($interpolate) {
  29474. return {
  29475. restrict: 'E',
  29476. priority: 100,
  29477. compile: function(element, attr) {
  29478. var interpolateValueFn, interpolateTextFn;
  29479. if (isDefined(attr.ngValue)) {
  29480. // Will be handled by registerOption
  29481. } else if (isDefined(attr.value)) {
  29482. // If the value attribute is defined, check if it contains an interpolation
  29483. interpolateValueFn = $interpolate(attr.value, true);
  29484. } else {
  29485. // If the value attribute is not defined then we fall back to the
  29486. // text content of the option element, which may be interpolated
  29487. interpolateTextFn = $interpolate(element.text(), true);
  29488. if (!interpolateTextFn) {
  29489. attr.$set('value', element.text());
  29490. }
  29491. }
  29492. return function(scope, element, attr) {
  29493. // This is an optimization over using ^^ since we don't want to have to search
  29494. // all the way to the root of the DOM for every single option element
  29495. var selectCtrlName = '$selectController',
  29496. parent = element.parent(),
  29497. selectCtrl = parent.data(selectCtrlName) ||
  29498. parent.parent().data(selectCtrlName); // in case we are in optgroup
  29499. if (selectCtrl) {
  29500. selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
  29501. }
  29502. };
  29503. }
  29504. };
  29505. }];
  29506. /**
  29507. * @ngdoc directive
  29508. * @name ngRequired
  29509. * @restrict A
  29510. *
  29511. * @description
  29512. *
  29513. * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  29514. * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be
  29515. * applied to custom controls.
  29516. *
  29517. * The directive sets the `required` attribute on the element if the Angular expression inside
  29518. * `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we
  29519. * cannot use interpolation inside `required`. See the {@link guide/interpolation interpolation guide}
  29520. * for more info.
  29521. *
  29522. * The validator will set the `required` error key to true if the `required` attribute is set and
  29523. * calling {@link ngModel.NgModelController#$isEmpty `NgModelController.$isEmpty`} with the
  29524. * {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} returns `true`. For example, the
  29525. * `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing
  29526. * custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based.
  29527. *
  29528. * @example
  29529. * <example name="ngRequiredDirective" module="ngRequiredExample">
  29530. * <file name="index.html">
  29531. * <script>
  29532. * angular.module('ngRequiredExample', [])
  29533. * .controller('ExampleController', ['$scope', function($scope) {
  29534. * $scope.required = true;
  29535. * }]);
  29536. * </script>
  29537. * <div ng-controller="ExampleController">
  29538. * <form name="form">
  29539. * <label for="required">Toggle required: </label>
  29540. * <input type="checkbox" ng-model="required" id="required" />
  29541. * <br>
  29542. * <label for="input">This input must be filled if `required` is true: </label>
  29543. * <input type="text" ng-model="model" id="input" name="input" ng-required="required" /><br>
  29544. * <hr>
  29545. * required error set? = <code>{{form.input.$error.required}}</code><br>
  29546. * model = <code>{{model}}</code>
  29547. * </form>
  29548. * </div>
  29549. * </file>
  29550. * <file name="protractor.js" type="protractor">
  29551. var required = element(by.binding('form.input.$error.required'));
  29552. var model = element(by.binding('model'));
  29553. var input = element(by.id('input'));
  29554. it('should set the required error', function() {
  29555. expect(required.getText()).toContain('true');
  29556. input.sendKeys('123');
  29557. expect(required.getText()).not.toContain('true');
  29558. expect(model.getText()).toContain('123');
  29559. });
  29560. * </file>
  29561. * </example>
  29562. */
  29563. var requiredDirective = function() {
  29564. return {
  29565. restrict: 'A',
  29566. require: '?ngModel',
  29567. link: function(scope, elm, attr, ctrl) {
  29568. if (!ctrl) return;
  29569. attr.required = true; // force truthy in case we are on non input element
  29570. ctrl.$validators.required = function(modelValue, viewValue) {
  29571. return !attr.required || !ctrl.$isEmpty(viewValue);
  29572. };
  29573. attr.$observe('required', function() {
  29574. ctrl.$validate();
  29575. });
  29576. }
  29577. };
  29578. };
  29579. /**
  29580. * @ngdoc directive
  29581. * @name ngPattern
  29582. *
  29583. * @description
  29584. *
  29585. * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  29586. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  29587. *
  29588. * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  29589. * does not match a RegExp which is obtained by evaluating the Angular expression given in the
  29590. * `ngPattern` attribute value:
  29591. * * If the expression evaluates to a RegExp object, then this is used directly.
  29592. * * If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it
  29593. * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  29594. *
  29595. * <div class="alert alert-info">
  29596. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  29597. * start at the index of the last search's match, thus not taking the whole input value into
  29598. * account.
  29599. * </div>
  29600. *
  29601. * <div class="alert alert-info">
  29602. * **Note:** This directive is also added when the plain `pattern` attribute is used, with two
  29603. * differences:
  29604. * <ol>
  29605. * <li>
  29606. * `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is
  29607. * not available.
  29608. * </li>
  29609. * <li>
  29610. * The `ngPattern` attribute must be an expression, while the `pattern` value must be
  29611. * interpolated.
  29612. * </li>
  29613. * </ol>
  29614. * </div>
  29615. *
  29616. * @example
  29617. * <example name="ngPatternDirective" module="ngPatternExample">
  29618. * <file name="index.html">
  29619. * <script>
  29620. * angular.module('ngPatternExample', [])
  29621. * .controller('ExampleController', ['$scope', function($scope) {
  29622. * $scope.regex = '\\d+';
  29623. * }]);
  29624. * </script>
  29625. * <div ng-controller="ExampleController">
  29626. * <form name="form">
  29627. * <label for="regex">Set a pattern (regex string): </label>
  29628. * <input type="text" ng-model="regex" id="regex" />
  29629. * <br>
  29630. * <label for="input">This input is restricted by the current pattern: </label>
  29631. * <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
  29632. * <hr>
  29633. * input valid? = <code>{{form.input.$valid}}</code><br>
  29634. * model = <code>{{model}}</code>
  29635. * </form>
  29636. * </div>
  29637. * </file>
  29638. * <file name="protractor.js" type="protractor">
  29639. var model = element(by.binding('model'));
  29640. var input = element(by.id('input'));
  29641. it('should validate the input with the default pattern', function() {
  29642. input.sendKeys('aaa');
  29643. expect(model.getText()).not.toContain('aaa');
  29644. input.clear().then(function() {
  29645. input.sendKeys('123');
  29646. expect(model.getText()).toContain('123');
  29647. });
  29648. });
  29649. * </file>
  29650. * </example>
  29651. */
  29652. var patternDirective = function() {
  29653. return {
  29654. restrict: 'A',
  29655. require: '?ngModel',
  29656. link: function(scope, elm, attr, ctrl) {
  29657. if (!ctrl) return;
  29658. var regexp, patternExp = attr.ngPattern || attr.pattern;
  29659. attr.$observe('pattern', function(regex) {
  29660. if (isString(regex) && regex.length > 0) {
  29661. regex = new RegExp('^' + regex + '$');
  29662. }
  29663. if (regex && !regex.test) {
  29664. throw minErr('ngPattern')('noregexp',
  29665. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  29666. regex, startingTag(elm));
  29667. }
  29668. regexp = regex || undefined;
  29669. ctrl.$validate();
  29670. });
  29671. ctrl.$validators.pattern = function(modelValue, viewValue) {
  29672. // HTML5 pattern constraint validates the input value, so we validate the viewValue
  29673. return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
  29674. };
  29675. }
  29676. };
  29677. };
  29678. /**
  29679. * @ngdoc directive
  29680. * @name ngMaxlength
  29681. *
  29682. * @description
  29683. *
  29684. * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  29685. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  29686. *
  29687. * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  29688. * is longer than the integer obtained by evaluating the Angular expression given in the
  29689. * `ngMaxlength` attribute value.
  29690. *
  29691. * <div class="alert alert-info">
  29692. * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two
  29693. * differences:
  29694. * <ol>
  29695. * <li>
  29696. * `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint
  29697. * validation is not available.
  29698. * </li>
  29699. * <li>
  29700. * The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be
  29701. * interpolated.
  29702. * </li>
  29703. * </ol>
  29704. * </div>
  29705. *
  29706. * @example
  29707. * <example name="ngMaxlengthDirective" module="ngMaxlengthExample">
  29708. * <file name="index.html">
  29709. * <script>
  29710. * angular.module('ngMaxlengthExample', [])
  29711. * .controller('ExampleController', ['$scope', function($scope) {
  29712. * $scope.maxlength = 5;
  29713. * }]);
  29714. * </script>
  29715. * <div ng-controller="ExampleController">
  29716. * <form name="form">
  29717. * <label for="maxlength">Set a maxlength: </label>
  29718. * <input type="number" ng-model="maxlength" id="maxlength" />
  29719. * <br>
  29720. * <label for="input">This input is restricted by the current maxlength: </label>
  29721. * <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br>
  29722. * <hr>
  29723. * input valid? = <code>{{form.input.$valid}}</code><br>
  29724. * model = <code>{{model}}</code>
  29725. * </form>
  29726. * </div>
  29727. * </file>
  29728. * <file name="protractor.js" type="protractor">
  29729. var model = element(by.binding('model'));
  29730. var input = element(by.id('input'));
  29731. it('should validate the input with the default maxlength', function() {
  29732. input.sendKeys('abcdef');
  29733. expect(model.getText()).not.toContain('abcdef');
  29734. input.clear().then(function() {
  29735. input.sendKeys('abcde');
  29736. expect(model.getText()).toContain('abcde');
  29737. });
  29738. });
  29739. * </file>
  29740. * </example>
  29741. */
  29742. var maxlengthDirective = function() {
  29743. return {
  29744. restrict: 'A',
  29745. require: '?ngModel',
  29746. link: function(scope, elm, attr, ctrl) {
  29747. if (!ctrl) return;
  29748. var maxlength = -1;
  29749. attr.$observe('maxlength', function(value) {
  29750. var intVal = toInt(value);
  29751. maxlength = isNumberNaN(intVal) ? -1 : intVal;
  29752. ctrl.$validate();
  29753. });
  29754. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  29755. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  29756. };
  29757. }
  29758. };
  29759. };
  29760. /**
  29761. * @ngdoc directive
  29762. * @name ngMinlength
  29763. *
  29764. * @description
  29765. *
  29766. * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  29767. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  29768. *
  29769. * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  29770. * is shorter than the integer obtained by evaluating the Angular expression given in the
  29771. * `ngMinlength` attribute value.
  29772. *
  29773. * <div class="alert alert-info">
  29774. * **Note:** This directive is also added when the plain `minlength` attribute is used, with two
  29775. * differences:
  29776. * <ol>
  29777. * <li>
  29778. * `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint
  29779. * validation is not available.
  29780. * </li>
  29781. * <li>
  29782. * The `ngMinlength` value must be an expression, while the `minlength` value must be
  29783. * interpolated.
  29784. * </li>
  29785. * </ol>
  29786. * </div>
  29787. *
  29788. * @example
  29789. * <example name="ngMinlengthDirective" module="ngMinlengthExample">
  29790. * <file name="index.html">
  29791. * <script>
  29792. * angular.module('ngMinlengthExample', [])
  29793. * .controller('ExampleController', ['$scope', function($scope) {
  29794. * $scope.minlength = 3;
  29795. * }]);
  29796. * </script>
  29797. * <div ng-controller="ExampleController">
  29798. * <form name="form">
  29799. * <label for="minlength">Set a minlength: </label>
  29800. * <input type="number" ng-model="minlength" id="minlength" />
  29801. * <br>
  29802. * <label for="input">This input is restricted by the current minlength: </label>
  29803. * <input type="text" ng-model="model" id="input" name="input" ng-minlength="minlength" /><br>
  29804. * <hr>
  29805. * input valid? = <code>{{form.input.$valid}}</code><br>
  29806. * model = <code>{{model}}</code>
  29807. * </form>
  29808. * </div>
  29809. * </file>
  29810. * <file name="protractor.js" type="protractor">
  29811. var model = element(by.binding('model'));
  29812. var input = element(by.id('input'));
  29813. it('should validate the input with the default minlength', function() {
  29814. input.sendKeys('ab');
  29815. expect(model.getText()).not.toContain('ab');
  29816. input.sendKeys('abc');
  29817. expect(model.getText()).toContain('abc');
  29818. });
  29819. * </file>
  29820. * </example>
  29821. */
  29822. var minlengthDirective = function() {
  29823. return {
  29824. restrict: 'A',
  29825. require: '?ngModel',
  29826. link: function(scope, elm, attr, ctrl) {
  29827. if (!ctrl) return;
  29828. var minlength = 0;
  29829. attr.$observe('minlength', function(value) {
  29830. minlength = toInt(value) || 0;
  29831. ctrl.$validate();
  29832. });
  29833. ctrl.$validators.minlength = function(modelValue, viewValue) {
  29834. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  29835. };
  29836. }
  29837. };
  29838. };
  29839. if (window.angular.bootstrap) {
  29840. //AngularJS is already loaded, so we can return here...
  29841. if (window.console) {
  29842. console.log('WARNING: Tried to load angular more than once.');
  29843. }
  29844. return;
  29845. }
  29846. //try to bind to jquery now so that one can write jqLite(document).ready()
  29847. //but we will rebind on bootstrap again.
  29848. bindJQuery();
  29849. publishExternalAPI(angular);
  29850. angular.module("ngLocale", [], ["$provide", function($provide) {
  29851. var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
  29852. function getDecimals(n) {
  29853. n = n + '';
  29854. var i = n.indexOf('.');
  29855. return (i == -1) ? 0 : n.length - i - 1;
  29856. }
  29857. function getVF(n, opt_precision) {
  29858. var v = opt_precision;
  29859. if (undefined === v) {
  29860. v = Math.min(getDecimals(n), 3);
  29861. }
  29862. var base = Math.pow(10, v);
  29863. var f = ((n * base) | 0) % base;
  29864. return {v: v, f: f};
  29865. }
  29866. $provide.value("$locale", {
  29867. "DATETIME_FORMATS": {
  29868. "AMPMS": [
  29869. "AM",
  29870. "PM"
  29871. ],
  29872. "DAY": [
  29873. "Sunday",
  29874. "Monday",
  29875. "Tuesday",
  29876. "Wednesday",
  29877. "Thursday",
  29878. "Friday",
  29879. "Saturday"
  29880. ],
  29881. "ERANAMES": [
  29882. "Before Christ",
  29883. "Anno Domini"
  29884. ],
  29885. "ERAS": [
  29886. "BC",
  29887. "AD"
  29888. ],
  29889. "FIRSTDAYOFWEEK": 6,
  29890. "MONTH": [
  29891. "January",
  29892. "February",
  29893. "March",
  29894. "April",
  29895. "May",
  29896. "June",
  29897. "July",
  29898. "August",
  29899. "September",
  29900. "October",
  29901. "November",
  29902. "December"
  29903. ],
  29904. "SHORTDAY": [
  29905. "Sun",
  29906. "Mon",
  29907. "Tue",
  29908. "Wed",
  29909. "Thu",
  29910. "Fri",
  29911. "Sat"
  29912. ],
  29913. "SHORTMONTH": [
  29914. "Jan",
  29915. "Feb",
  29916. "Mar",
  29917. "Apr",
  29918. "May",
  29919. "Jun",
  29920. "Jul",
  29921. "Aug",
  29922. "Sep",
  29923. "Oct",
  29924. "Nov",
  29925. "Dec"
  29926. ],
  29927. "STANDALONEMONTH": [
  29928. "January",
  29929. "February",
  29930. "March",
  29931. "April",
  29932. "May",
  29933. "June",
  29934. "July",
  29935. "August",
  29936. "September",
  29937. "October",
  29938. "November",
  29939. "December"
  29940. ],
  29941. "WEEKENDRANGE": [
  29942. 5,
  29943. 6
  29944. ],
  29945. "fullDate": "EEEE, MMMM d, y",
  29946. "longDate": "MMMM d, y",
  29947. "medium": "MMM d, y h:mm:ss a",
  29948. "mediumDate": "MMM d, y",
  29949. "mediumTime": "h:mm:ss a",
  29950. "short": "M/d/yy h:mm a",
  29951. "shortDate": "M/d/yy",
  29952. "shortTime": "h:mm a"
  29953. },
  29954. "NUMBER_FORMATS": {
  29955. "CURRENCY_SYM": "$",
  29956. "DECIMAL_SEP": ".",
  29957. "GROUP_SEP": ",",
  29958. "PATTERNS": [
  29959. {
  29960. "gSize": 3,
  29961. "lgSize": 3,
  29962. "maxFrac": 3,
  29963. "minFrac": 0,
  29964. "minInt": 1,
  29965. "negPre": "-",
  29966. "negSuf": "",
  29967. "posPre": "",
  29968. "posSuf": ""
  29969. },
  29970. {
  29971. "gSize": 3,
  29972. "lgSize": 3,
  29973. "maxFrac": 2,
  29974. "minFrac": 2,
  29975. "minInt": 1,
  29976. "negPre": "-\u00a4",
  29977. "negSuf": "",
  29978. "posPre": "\u00a4",
  29979. "posSuf": ""
  29980. }
  29981. ]
  29982. },
  29983. "id": "en-us",
  29984. "localeID": "en_US",
  29985. "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;}
  29986. });
  29987. }]);
  29988. jqLite(window.document).ready(function() {
  29989. angularInit(window.document, bootstrap);
  29990. });
  29991. })(window);
  29992. !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>');