angular.js 1.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191
  1. /**
  2. * @license AngularJS v1.6.7
  3. * (c) 2010-2017 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window) {'use strict';
  7. /* exported
  8. minErrConfig,
  9. errorHandlingConfig,
  10. isValidObjectMaxDepth
  11. */
  12. var minErrConfig = {
  13. objectMaxDepth: 5
  14. };
  15. /**
  16. * @ngdoc function
  17. * @name angular.errorHandlingConfig
  18. * @module ng
  19. * @kind function
  20. *
  21. * @description
  22. * Configure several aspects of error handling in AngularJS if used as a setter or return the
  23. * current configuration if used as a getter. The following options are supported:
  24. *
  25. * - **objectMaxDepth**: The maximum depth to which objects are traversed when stringified for error messages.
  26. *
  27. * Omitted or undefined options will leave the corresponding configuration values unchanged.
  28. *
  29. * @param {Object=} config - The configuration object. May only contain the options that need to be
  30. * updated. Supported keys:
  31. *
  32. * * `objectMaxDepth` **{Number}** - The max depth for stringifying objects. Setting to a
  33. * non-positive or non-numeric value, removes the max depth limit.
  34. * Default: 5
  35. */
  36. function errorHandlingConfig(config) {
  37. if (isObject(config)) {
  38. if (isDefined(config.objectMaxDepth)) {
  39. minErrConfig.objectMaxDepth = isValidObjectMaxDepth(config.objectMaxDepth) ? config.objectMaxDepth : NaN;
  40. }
  41. } else {
  42. return minErrConfig;
  43. }
  44. }
  45. /**
  46. * @private
  47. * @param {Number} maxDepth
  48. * @return {boolean}
  49. */
  50. function isValidObjectMaxDepth(maxDepth) {
  51. return isNumber(maxDepth) && maxDepth > 0;
  52. }
  53. /**
  54. * @description
  55. *
  56. * This object provides a utility for producing rich Error messages within
  57. * Angular. It can be called as follows:
  58. *
  59. * var exampleMinErr = minErr('example');
  60. * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
  61. *
  62. * The above creates an instance of minErr in the example namespace. The
  63. * resulting error will have a namespaced error code of example.one. The
  64. * resulting error will replace {0} with the value of foo, and {1} with the
  65. * value of bar. The object is not restricted in the number of arguments it can
  66. * take.
  67. *
  68. * If fewer arguments are specified than necessary for interpolation, the extra
  69. * interpolation markers will be preserved in the final string.
  70. *
  71. * Since data will be parsed statically during a build step, some restrictions
  72. * are applied with respect to how minErr instances are created and called.
  73. * Instances should have names of the form namespaceMinErr for a minErr created
  74. * using minErr('namespace') . Error codes, namespaces and template strings
  75. * should all be static strings, not variables or general expressions.
  76. *
  77. * @param {string} module The namespace to use for the new minErr instance.
  78. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
  79. * error from returned function, for cases when a particular type of error is useful.
  80. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
  81. */
  82. function minErr(module, ErrorConstructor) {
  83. ErrorConstructor = ErrorConstructor || Error;
  84. return function() {
  85. var code = arguments[0],
  86. template = arguments[1],
  87. message = '[' + (module ? module + ':' : '') + code + '] ',
  88. templateArgs = sliceArgs(arguments, 2).map(function(arg) {
  89. return toDebugString(arg, minErrConfig.objectMaxDepth);
  90. }),
  91. paramPrefix, i;
  92. message += template.replace(/\{\d+\}/g, function(match) {
  93. var index = +match.slice(1, -1);
  94. if (index < templateArgs.length) {
  95. return templateArgs[index];
  96. }
  97. return match;
  98. });
  99. message += '\nhttp://errors.angularjs.org/1.6.7/' +
  100. (module ? module + '/' : '') + code;
  101. for (i = 0, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
  102. message += paramPrefix + 'p' + i + '=' + encodeURIComponent(templateArgs[i]);
  103. }
  104. return new ErrorConstructor(message);
  105. };
  106. }
  107. /* We need to tell ESLint what variables are being exported */
  108. /* exported
  109. angular,
  110. msie,
  111. jqLite,
  112. jQuery,
  113. slice,
  114. splice,
  115. push,
  116. toString,
  117. minErrConfig,
  118. errorHandlingConfig,
  119. isValidObjectMaxDepth,
  120. ngMinErr,
  121. angularModule,
  122. uid,
  123. REGEX_STRING_REGEXP,
  124. VALIDITY_STATE_PROPERTY,
  125. lowercase,
  126. uppercase,
  127. manualLowercase,
  128. manualUppercase,
  129. nodeName_,
  130. isArrayLike,
  131. forEach,
  132. forEachSorted,
  133. reverseParams,
  134. nextUid,
  135. setHashKey,
  136. extend,
  137. toInt,
  138. inherit,
  139. merge,
  140. noop,
  141. identity,
  142. valueFn,
  143. isUndefined,
  144. isDefined,
  145. isObject,
  146. isBlankObject,
  147. isString,
  148. isNumber,
  149. isNumberNaN,
  150. isDate,
  151. isError,
  152. isArray,
  153. isFunction,
  154. isRegExp,
  155. isWindow,
  156. isScope,
  157. isFile,
  158. isFormData,
  159. isBlob,
  160. isBoolean,
  161. isPromiseLike,
  162. trim,
  163. escapeForRegexp,
  164. isElement,
  165. makeMap,
  166. includes,
  167. arrayRemove,
  168. copy,
  169. simpleCompare,
  170. equals,
  171. csp,
  172. jq,
  173. concat,
  174. sliceArgs,
  175. bind,
  176. toJsonReplacer,
  177. toJson,
  178. fromJson,
  179. convertTimezoneToLocal,
  180. timezoneToOffset,
  181. startingTag,
  182. tryDecodeURIComponent,
  183. parseKeyValue,
  184. toKeyValue,
  185. encodeUriSegment,
  186. encodeUriQuery,
  187. angularInit,
  188. bootstrap,
  189. getTestability,
  190. snake_case,
  191. bindJQuery,
  192. assertArg,
  193. assertArgFn,
  194. assertNotHasOwnProperty,
  195. getter,
  196. getBlockNodes,
  197. hasOwnProperty,
  198. createMap,
  199. stringify,
  200. NODE_TYPE_ELEMENT,
  201. NODE_TYPE_ATTRIBUTE,
  202. NODE_TYPE_TEXT,
  203. NODE_TYPE_COMMENT,
  204. NODE_TYPE_DOCUMENT,
  205. NODE_TYPE_DOCUMENT_FRAGMENT
  206. */
  207. ////////////////////////////////////
  208. /**
  209. * @ngdoc module
  210. * @name ng
  211. * @module ng
  212. * @installation
  213. * @description
  214. *
  215. * The ng module is loaded by default when an AngularJS application is started. The module itself
  216. * contains the essential components for an AngularJS application to function. The table below
  217. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  218. * components available within this core module.
  219. *
  220. */
  221. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  222. // The name of a form control's ValidityState property.
  223. // This is used so that it's possible for internal tests to create mock ValidityStates.
  224. var VALIDITY_STATE_PROPERTY = 'validity';
  225. var hasOwnProperty = Object.prototype.hasOwnProperty;
  226. /**
  227. * @ngdoc function
  228. * @name angular.lowercase
  229. * @module ng
  230. * @kind function
  231. *
  232. * @deprecated
  233. * sinceVersion="1.5.0"
  234. * removeVersion="1.7.0"
  235. * Use [String.prototype.toLowerCase](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase) instead.
  236. *
  237. * @description Converts the specified string to lowercase.
  238. * @param {string} string String to be converted to lowercase.
  239. * @returns {string} Lowercased string.
  240. */
  241. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  242. /**
  243. * @ngdoc function
  244. * @name angular.uppercase
  245. * @module ng
  246. * @kind function
  247. *
  248. * @deprecated
  249. * sinceVersion="1.5.0"
  250. * removeVersion="1.7.0"
  251. * Use [String.prototype.toUpperCase](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) instead.
  252. *
  253. * @description Converts the specified string to uppercase.
  254. * @param {string} string String to be converted to uppercase.
  255. * @returns {string} Uppercased string.
  256. */
  257. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  258. var manualLowercase = function(s) {
  259. /* eslint-disable no-bitwise */
  260. return isString(s)
  261. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  262. : s;
  263. /* eslint-enable */
  264. };
  265. var manualUppercase = function(s) {
  266. /* eslint-disable no-bitwise */
  267. return isString(s)
  268. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  269. : s;
  270. /* eslint-enable */
  271. };
  272. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  273. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  274. // with correct but slower alternatives. See https://github.com/angular/angular.js/issues/11387
  275. if ('i' !== 'I'.toLowerCase()) {
  276. lowercase = manualLowercase;
  277. uppercase = manualUppercase;
  278. }
  279. var
  280. msie, // holds major version number for IE, or NaN if UA is not IE.
  281. jqLite, // delay binding since jQuery could be loaded after us.
  282. jQuery, // delay binding
  283. slice = [].slice,
  284. splice = [].splice,
  285. push = [].push,
  286. toString = Object.prototype.toString,
  287. getPrototypeOf = Object.getPrototypeOf,
  288. ngMinErr = minErr('ng'),
  289. /** @name angular */
  290. angular = window.angular || (window.angular = {}),
  291. angularModule,
  292. uid = 0;
  293. // Support: IE 9-11 only
  294. /**
  295. * documentMode is an IE-only property
  296. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  297. */
  298. msie = window.document.documentMode;
  299. /**
  300. * @private
  301. * @param {*} obj
  302. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  303. * String ...)
  304. */
  305. function isArrayLike(obj) {
  306. // `null`, `undefined` and `window` are not array-like
  307. if (obj == null || isWindow(obj)) return false;
  308. // arrays, strings and jQuery/jqLite objects are array like
  309. // * jqLite is either the jQuery or jqLite constructor function
  310. // * we have to check the existence of jqLite first as this method is called
  311. // via the forEach method when constructing the jqLite object in the first place
  312. if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
  313. // Support: iOS 8.2 (not reproducible in simulator)
  314. // "length" in obj used to prevent JIT error (gh-11508)
  315. var length = 'length' in Object(obj) && obj.length;
  316. // NodeList objects (with `item` method) and
  317. // other objects with suitable length characteristics are array-like
  318. return isNumber(length) &&
  319. (length >= 0 && ((length - 1) in obj || obj instanceof Array) || typeof obj.item === 'function');
  320. }
  321. /**
  322. * @ngdoc function
  323. * @name angular.forEach
  324. * @module ng
  325. * @kind function
  326. *
  327. * @description
  328. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  329. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  330. * is the value of an object property or an array element, `key` is the object property key or
  331. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  332. *
  333. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  334. * using the `hasOwnProperty` method.
  335. *
  336. * Unlike ES262's
  337. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  338. * providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  339. * return the value provided.
  340. *
  341. ```js
  342. var values = {name: 'misko', gender: 'male'};
  343. var log = [];
  344. angular.forEach(values, function(value, key) {
  345. this.push(key + ': ' + value);
  346. }, log);
  347. expect(log).toEqual(['name: misko', 'gender: male']);
  348. ```
  349. *
  350. * @param {Object|Array} obj Object to iterate over.
  351. * @param {Function} iterator Iterator function.
  352. * @param {Object=} context Object to become context (`this`) for the iterator function.
  353. * @returns {Object|Array} Reference to `obj`.
  354. */
  355. function forEach(obj, iterator, context) {
  356. var key, length;
  357. if (obj) {
  358. if (isFunction(obj)) {
  359. for (key in obj) {
  360. if (key !== 'prototype' && key !== 'length' && key !== 'name' && obj.hasOwnProperty(key)) {
  361. iterator.call(context, obj[key], key, obj);
  362. }
  363. }
  364. } else if (isArray(obj) || isArrayLike(obj)) {
  365. var isPrimitive = typeof obj !== 'object';
  366. for (key = 0, length = obj.length; key < length; key++) {
  367. if (isPrimitive || key in obj) {
  368. iterator.call(context, obj[key], key, obj);
  369. }
  370. }
  371. } else if (obj.forEach && obj.forEach !== forEach) {
  372. obj.forEach(iterator, context, obj);
  373. } else if (isBlankObject(obj)) {
  374. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  375. for (key in obj) {
  376. iterator.call(context, obj[key], key, obj);
  377. }
  378. } else if (typeof obj.hasOwnProperty === 'function') {
  379. // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
  380. for (key in obj) {
  381. if (obj.hasOwnProperty(key)) {
  382. iterator.call(context, obj[key], key, obj);
  383. }
  384. }
  385. } else {
  386. // Slow path for objects which do not have a method `hasOwnProperty`
  387. for (key in obj) {
  388. if (hasOwnProperty.call(obj, key)) {
  389. iterator.call(context, obj[key], key, obj);
  390. }
  391. }
  392. }
  393. }
  394. return obj;
  395. }
  396. function forEachSorted(obj, iterator, context) {
  397. var keys = Object.keys(obj).sort();
  398. for (var i = 0; i < keys.length; i++) {
  399. iterator.call(context, obj[keys[i]], keys[i]);
  400. }
  401. return keys;
  402. }
  403. /**
  404. * when using forEach the params are value, key, but it is often useful to have key, value.
  405. * @param {function(string, *)} iteratorFn
  406. * @returns {function(*, string)}
  407. */
  408. function reverseParams(iteratorFn) {
  409. return function(value, key) {iteratorFn(key, value);};
  410. }
  411. /**
  412. * A consistent way of creating unique IDs in angular.
  413. *
  414. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  415. * we hit number precision issues in JavaScript.
  416. *
  417. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  418. *
  419. * @returns {number} an unique alpha-numeric string
  420. */
  421. function nextUid() {
  422. return ++uid;
  423. }
  424. /**
  425. * Set or clear the hashkey for an object.
  426. * @param obj object
  427. * @param h the hashkey (!truthy to delete the hashkey)
  428. */
  429. function setHashKey(obj, h) {
  430. if (h) {
  431. obj.$$hashKey = h;
  432. } else {
  433. delete obj.$$hashKey;
  434. }
  435. }
  436. function baseExtend(dst, objs, deep) {
  437. var h = dst.$$hashKey;
  438. for (var i = 0, ii = objs.length; i < ii; ++i) {
  439. var obj = objs[i];
  440. if (!isObject(obj) && !isFunction(obj)) continue;
  441. var keys = Object.keys(obj);
  442. for (var j = 0, jj = keys.length; j < jj; j++) {
  443. var key = keys[j];
  444. var src = obj[key];
  445. if (deep && isObject(src)) {
  446. if (isDate(src)) {
  447. dst[key] = new Date(src.valueOf());
  448. } else if (isRegExp(src)) {
  449. dst[key] = new RegExp(src);
  450. } else if (src.nodeName) {
  451. dst[key] = src.cloneNode(true);
  452. } else if (isElement(src)) {
  453. dst[key] = src.clone();
  454. } else {
  455. if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
  456. baseExtend(dst[key], [src], true);
  457. }
  458. } else {
  459. dst[key] = src;
  460. }
  461. }
  462. }
  463. setHashKey(dst, h);
  464. return dst;
  465. }
  466. /**
  467. * @ngdoc function
  468. * @name angular.extend
  469. * @module ng
  470. * @kind function
  471. *
  472. * @description
  473. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  474. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  475. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  476. *
  477. * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
  478. * {@link angular.merge} for this.
  479. *
  480. * @param {Object} dst Destination object.
  481. * @param {...Object} src Source object(s).
  482. * @returns {Object} Reference to `dst`.
  483. */
  484. function extend(dst) {
  485. return baseExtend(dst, slice.call(arguments, 1), false);
  486. }
  487. /**
  488. * @ngdoc function
  489. * @name angular.merge
  490. * @module ng
  491. * @kind function
  492. *
  493. * @description
  494. * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  495. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  496. * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
  497. *
  498. * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
  499. * objects, performing a deep copy.
  500. *
  501. * @deprecated
  502. * sinceVersion="1.6.5"
  503. * This function is deprecated, but will not be removed in the 1.x lifecycle.
  504. * There are edge cases (see {@link angular.merge#known-issues known issues}) that are not
  505. * supported by this function. We suggest
  506. * using [lodash's merge()](https://lodash.com/docs/4.17.4#merge) instead.
  507. *
  508. * @knownIssue
  509. * This is a list of (known) object types that are not handled correctly by this function:
  510. * - [`Blob`](https://developer.mozilla.org/docs/Web/API/Blob)
  511. * - [`MediaStream`](https://developer.mozilla.org/docs/Web/API/MediaStream)
  512. * - [`CanvasGradient`](https://developer.mozilla.org/docs/Web/API/CanvasGradient)
  513. * - AngularJS {@link $rootScope.Scope scopes};
  514. *
  515. * @param {Object} dst Destination object.
  516. * @param {...Object} src Source object(s).
  517. * @returns {Object} Reference to `dst`.
  518. */
  519. function merge(dst) {
  520. return baseExtend(dst, slice.call(arguments, 1), true);
  521. }
  522. function toInt(str) {
  523. return parseInt(str, 10);
  524. }
  525. var isNumberNaN = Number.isNaN || function isNumberNaN(num) {
  526. // eslint-disable-next-line no-self-compare
  527. return num !== num;
  528. };
  529. function inherit(parent, extra) {
  530. return extend(Object.create(parent), extra);
  531. }
  532. /**
  533. * @ngdoc function
  534. * @name angular.noop
  535. * @module ng
  536. * @kind function
  537. *
  538. * @description
  539. * A function that performs no operations. This function can be useful when writing code in the
  540. * functional style.
  541. ```js
  542. function foo(callback) {
  543. var result = calculateResult();
  544. (callback || angular.noop)(result);
  545. }
  546. ```
  547. */
  548. function noop() {}
  549. noop.$inject = [];
  550. /**
  551. * @ngdoc function
  552. * @name angular.identity
  553. * @module ng
  554. * @kind function
  555. *
  556. * @description
  557. * A function that returns its first argument. This function is useful when writing code in the
  558. * functional style.
  559. *
  560. ```js
  561. function transformer(transformationFn, value) {
  562. return (transformationFn || angular.identity)(value);
  563. };
  564. // E.g.
  565. function getResult(fn, input) {
  566. return (fn || angular.identity)(input);
  567. };
  568. getResult(function(n) { return n * 2; }, 21); // returns 42
  569. getResult(null, 21); // returns 21
  570. getResult(undefined, 21); // returns 21
  571. ```
  572. *
  573. * @param {*} value to be returned.
  574. * @returns {*} the value passed in.
  575. */
  576. function identity($) {return $;}
  577. identity.$inject = [];
  578. function valueFn(value) {return function valueRef() {return value;};}
  579. function hasCustomToString(obj) {
  580. return isFunction(obj.toString) && obj.toString !== toString;
  581. }
  582. /**
  583. * @ngdoc function
  584. * @name angular.isUndefined
  585. * @module ng
  586. * @kind function
  587. *
  588. * @description
  589. * Determines if a reference is undefined.
  590. *
  591. * @param {*} value Reference to check.
  592. * @returns {boolean} True if `value` is undefined.
  593. */
  594. function isUndefined(value) {return typeof value === 'undefined';}
  595. /**
  596. * @ngdoc function
  597. * @name angular.isDefined
  598. * @module ng
  599. * @kind function
  600. *
  601. * @description
  602. * Determines if a reference is defined.
  603. *
  604. * @param {*} value Reference to check.
  605. * @returns {boolean} True if `value` is defined.
  606. */
  607. function isDefined(value) {return typeof value !== 'undefined';}
  608. /**
  609. * @ngdoc function
  610. * @name angular.isObject
  611. * @module ng
  612. * @kind function
  613. *
  614. * @description
  615. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  616. * considered to be objects. Note that JavaScript arrays are objects.
  617. *
  618. * @param {*} value Reference to check.
  619. * @returns {boolean} True if `value` is an `Object` but not `null`.
  620. */
  621. function isObject(value) {
  622. // http://jsperf.com/isobject4
  623. return value !== null && typeof value === 'object';
  624. }
  625. /**
  626. * Determine if a value is an object with a null prototype
  627. *
  628. * @returns {boolean} True if `value` is an `Object` with a null prototype
  629. */
  630. function isBlankObject(value) {
  631. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  632. }
  633. /**
  634. * @ngdoc function
  635. * @name angular.isString
  636. * @module ng
  637. * @kind function
  638. *
  639. * @description
  640. * Determines if a reference is a `String`.
  641. *
  642. * @param {*} value Reference to check.
  643. * @returns {boolean} True if `value` is a `String`.
  644. */
  645. function isString(value) {return typeof value === 'string';}
  646. /**
  647. * @ngdoc function
  648. * @name angular.isNumber
  649. * @module ng
  650. * @kind function
  651. *
  652. * @description
  653. * Determines if a reference is a `Number`.
  654. *
  655. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  656. *
  657. * If you wish to exclude these then you can use the native
  658. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  659. * method.
  660. *
  661. * @param {*} value Reference to check.
  662. * @returns {boolean} True if `value` is a `Number`.
  663. */
  664. function isNumber(value) {return typeof value === 'number';}
  665. /**
  666. * @ngdoc function
  667. * @name angular.isDate
  668. * @module ng
  669. * @kind function
  670. *
  671. * @description
  672. * Determines if a value is a date.
  673. *
  674. * @param {*} value Reference to check.
  675. * @returns {boolean} True if `value` is a `Date`.
  676. */
  677. function isDate(value) {
  678. return toString.call(value) === '[object Date]';
  679. }
  680. /**
  681. * @ngdoc function
  682. * @name angular.isArray
  683. * @module ng
  684. * @kind function
  685. *
  686. * @description
  687. * Determines if a reference is an `Array`. Alias of Array.isArray.
  688. *
  689. * @param {*} value Reference to check.
  690. * @returns {boolean} True if `value` is an `Array`.
  691. */
  692. var isArray = Array.isArray;
  693. /**
  694. * @description
  695. * Determines if a reference is an `Error`.
  696. * Loosely based on https://www.npmjs.com/package/iserror
  697. *
  698. * @param {*} value Reference to check.
  699. * @returns {boolean} True if `value` is an `Error`.
  700. */
  701. function isError(value) {
  702. var tag = toString.call(value);
  703. switch (tag) {
  704. case '[object Error]': return true;
  705. case '[object Exception]': return true;
  706. case '[object DOMException]': return true;
  707. default: return value instanceof Error;
  708. }
  709. }
  710. /**
  711. * @ngdoc function
  712. * @name angular.isFunction
  713. * @module ng
  714. * @kind function
  715. *
  716. * @description
  717. * Determines if a reference is a `Function`.
  718. *
  719. * @param {*} value Reference to check.
  720. * @returns {boolean} True if `value` is a `Function`.
  721. */
  722. function isFunction(value) {return typeof value === 'function';}
  723. /**
  724. * Determines if a value is a regular expression object.
  725. *
  726. * @private
  727. * @param {*} value Reference to check.
  728. * @returns {boolean} True if `value` is a `RegExp`.
  729. */
  730. function isRegExp(value) {
  731. return toString.call(value) === '[object RegExp]';
  732. }
  733. /**
  734. * Checks if `obj` is a window object.
  735. *
  736. * @private
  737. * @param {*} obj Object to check
  738. * @returns {boolean} True if `obj` is a window obj.
  739. */
  740. function isWindow(obj) {
  741. return obj && obj.window === obj;
  742. }
  743. function isScope(obj) {
  744. return obj && obj.$evalAsync && obj.$watch;
  745. }
  746. function isFile(obj) {
  747. return toString.call(obj) === '[object File]';
  748. }
  749. function isFormData(obj) {
  750. return toString.call(obj) === '[object FormData]';
  751. }
  752. function isBlob(obj) {
  753. return toString.call(obj) === '[object Blob]';
  754. }
  755. function isBoolean(value) {
  756. return typeof value === 'boolean';
  757. }
  758. function isPromiseLike(obj) {
  759. return obj && isFunction(obj.then);
  760. }
  761. var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array]$/;
  762. function isTypedArray(value) {
  763. return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
  764. }
  765. function isArrayBuffer(obj) {
  766. return toString.call(obj) === '[object ArrayBuffer]';
  767. }
  768. var trim = function(value) {
  769. return isString(value) ? value.trim() : value;
  770. };
  771. // Copied from:
  772. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  773. // Prereq: s is a string.
  774. var escapeForRegexp = function(s) {
  775. return s
  776. .replace(/([-()[\]{}+?*.$^|,:#<!\\])/g, '\\$1')
  777. // eslint-disable-next-line no-control-regex
  778. .replace(/\x08/g, '\\x08');
  779. };
  780. /**
  781. * @ngdoc function
  782. * @name angular.isElement
  783. * @module ng
  784. * @kind function
  785. *
  786. * @description
  787. * Determines if a reference is a DOM element (or wrapped jQuery element).
  788. *
  789. * @param {*} value Reference to check.
  790. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  791. */
  792. function isElement(node) {
  793. return !!(node &&
  794. (node.nodeName // We are a direct element.
  795. || (node.prop && node.attr && node.find))); // We have an on and find method part of jQuery API.
  796. }
  797. /**
  798. * @param str 'key1,key2,...'
  799. * @returns {object} in the form of {key1:true, key2:true, ...}
  800. */
  801. function makeMap(str) {
  802. var obj = {}, items = str.split(','), i;
  803. for (i = 0; i < items.length; i++) {
  804. obj[items[i]] = true;
  805. }
  806. return obj;
  807. }
  808. function nodeName_(element) {
  809. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  810. }
  811. function includes(array, obj) {
  812. return Array.prototype.indexOf.call(array, obj) !== -1;
  813. }
  814. function arrayRemove(array, value) {
  815. var index = array.indexOf(value);
  816. if (index >= 0) {
  817. array.splice(index, 1);
  818. }
  819. return index;
  820. }
  821. /**
  822. * @ngdoc function
  823. * @name angular.copy
  824. * @module ng
  825. * @kind function
  826. *
  827. * @description
  828. * Creates a deep copy of `source`, which should be an object or an array.
  829. *
  830. * * If no destination is supplied, a copy of the object or array is created.
  831. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  832. * are deleted and then all elements/properties from the source are copied to it.
  833. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  834. * * If `source` is identical to `destination` an exception will be thrown.
  835. *
  836. * <br />
  837. * <div class="alert alert-warning">
  838. * Only enumerable properties are taken into account. Non-enumerable properties (both on `source`
  839. * and on `destination`) will be ignored.
  840. * </div>
  841. *
  842. * @param {*} source The source that will be used to make a copy.
  843. * Can be any type, including primitives, `null`, and `undefined`.
  844. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  845. * provided, must be of the same type as `source`.
  846. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  847. *
  848. * @example
  849. <example module="copyExample" name="angular-copy">
  850. <file name="index.html">
  851. <div ng-controller="ExampleController">
  852. <form novalidate class="simple-form">
  853. <label>Name: <input type="text" ng-model="user.name" /></label><br />
  854. <label>Age: <input type="number" ng-model="user.age" /></label><br />
  855. Gender: <label><input type="radio" ng-model="user.gender" value="male" />male</label>
  856. <label><input type="radio" ng-model="user.gender" value="female" />female</label><br />
  857. <button ng-click="reset()">RESET</button>
  858. <button ng-click="update(user)">SAVE</button>
  859. </form>
  860. <pre>form = {{user | json}}</pre>
  861. <pre>leader = {{leader | json}}</pre>
  862. </div>
  863. </file>
  864. <file name="script.js">
  865. // Module: copyExample
  866. angular.
  867. module('copyExample', []).
  868. controller('ExampleController', ['$scope', function($scope) {
  869. $scope.leader = {};
  870. $scope.reset = function() {
  871. // Example with 1 argument
  872. $scope.user = angular.copy($scope.leader);
  873. };
  874. $scope.update = function(user) {
  875. // Example with 2 arguments
  876. angular.copy(user, $scope.leader);
  877. };
  878. $scope.reset();
  879. }]);
  880. </file>
  881. </example>
  882. */
  883. function copy(source, destination, maxDepth) {
  884. var stackSource = [];
  885. var stackDest = [];
  886. maxDepth = isValidObjectMaxDepth(maxDepth) ? maxDepth : NaN;
  887. if (destination) {
  888. if (isTypedArray(destination) || isArrayBuffer(destination)) {
  889. throw ngMinErr('cpta', 'Can\'t copy! TypedArray destination cannot be mutated.');
  890. }
  891. if (source === destination) {
  892. throw ngMinErr('cpi', 'Can\'t copy! Source and destination are identical.');
  893. }
  894. // Empty the destination object
  895. if (isArray(destination)) {
  896. destination.length = 0;
  897. } else {
  898. forEach(destination, function(value, key) {
  899. if (key !== '$$hashKey') {
  900. delete destination[key];
  901. }
  902. });
  903. }
  904. stackSource.push(source);
  905. stackDest.push(destination);
  906. return copyRecurse(source, destination, maxDepth);
  907. }
  908. return copyElement(source, maxDepth);
  909. function copyRecurse(source, destination, maxDepth) {
  910. maxDepth--;
  911. if (maxDepth < 0) {
  912. return '...';
  913. }
  914. var h = destination.$$hashKey;
  915. var key;
  916. if (isArray(source)) {
  917. for (var i = 0, ii = source.length; i < ii; i++) {
  918. destination.push(copyElement(source[i], maxDepth));
  919. }
  920. } else if (isBlankObject(source)) {
  921. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  922. for (key in source) {
  923. destination[key] = copyElement(source[key], maxDepth);
  924. }
  925. } else if (source && typeof source.hasOwnProperty === 'function') {
  926. // Slow path, which must rely on hasOwnProperty
  927. for (key in source) {
  928. if (source.hasOwnProperty(key)) {
  929. destination[key] = copyElement(source[key], maxDepth);
  930. }
  931. }
  932. } else {
  933. // Slowest path --- hasOwnProperty can't be called as a method
  934. for (key in source) {
  935. if (hasOwnProperty.call(source, key)) {
  936. destination[key] = copyElement(source[key], maxDepth);
  937. }
  938. }
  939. }
  940. setHashKey(destination, h);
  941. return destination;
  942. }
  943. function copyElement(source, maxDepth) {
  944. // Simple values
  945. if (!isObject(source)) {
  946. return source;
  947. }
  948. // Already copied values
  949. var index = stackSource.indexOf(source);
  950. if (index !== -1) {
  951. return stackDest[index];
  952. }
  953. if (isWindow(source) || isScope(source)) {
  954. throw ngMinErr('cpws',
  955. 'Can\'t copy! Making copies of Window or Scope instances is not supported.');
  956. }
  957. var needsRecurse = false;
  958. var destination = copyType(source);
  959. if (destination === undefined) {
  960. destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
  961. needsRecurse = true;
  962. }
  963. stackSource.push(source);
  964. stackDest.push(destination);
  965. return needsRecurse
  966. ? copyRecurse(source, destination, maxDepth)
  967. : destination;
  968. }
  969. function copyType(source) {
  970. switch (toString.call(source)) {
  971. case '[object Int8Array]':
  972. case '[object Int16Array]':
  973. case '[object Int32Array]':
  974. case '[object Float32Array]':
  975. case '[object Float64Array]':
  976. case '[object Uint8Array]':
  977. case '[object Uint8ClampedArray]':
  978. case '[object Uint16Array]':
  979. case '[object Uint32Array]':
  980. return new source.constructor(copyElement(source.buffer), source.byteOffset, source.length);
  981. case '[object ArrayBuffer]':
  982. // Support: IE10
  983. if (!source.slice) {
  984. // If we're in this case we know the environment supports ArrayBuffer
  985. /* eslint-disable no-undef */
  986. var copied = new ArrayBuffer(source.byteLength);
  987. new Uint8Array(copied).set(new Uint8Array(source));
  988. /* eslint-enable */
  989. return copied;
  990. }
  991. return source.slice(0);
  992. case '[object Boolean]':
  993. case '[object Number]':
  994. case '[object String]':
  995. case '[object Date]':
  996. return new source.constructor(source.valueOf());
  997. case '[object RegExp]':
  998. var re = new RegExp(source.source, source.toString().match(/[^/]*$/)[0]);
  999. re.lastIndex = source.lastIndex;
  1000. return re;
  1001. case '[object Blob]':
  1002. return new source.constructor([source], {type: source.type});
  1003. }
  1004. if (isFunction(source.cloneNode)) {
  1005. return source.cloneNode(true);
  1006. }
  1007. }
  1008. }
  1009. // eslint-disable-next-line no-self-compare
  1010. function simpleCompare(a, b) { return a === b || (a !== a && b !== b); }
  1011. /**
  1012. * @ngdoc function
  1013. * @name angular.equals
  1014. * @module ng
  1015. * @kind function
  1016. *
  1017. * @description
  1018. * Determines if two objects or two values are equivalent. Supports value types, regular
  1019. * expressions, arrays and objects.
  1020. *
  1021. * Two objects or values are considered equivalent if at least one of the following is true:
  1022. *
  1023. * * Both objects or values pass `===` comparison.
  1024. * * Both objects or values are of the same type and all of their properties are equal by
  1025. * comparing them with `angular.equals`.
  1026. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  1027. * * Both values represent the same regular expression (In JavaScript,
  1028. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  1029. * representation matches).
  1030. *
  1031. * During a property comparison, properties of `function` type and properties with names
  1032. * that begin with `$` are ignored.
  1033. *
  1034. * Scope and DOMWindow objects are being compared only by identify (`===`).
  1035. *
  1036. * @param {*} o1 Object or value to compare.
  1037. * @param {*} o2 Object or value to compare.
  1038. * @returns {boolean} True if arguments are equal.
  1039. *
  1040. * @example
  1041. <example module="equalsExample" name="equalsExample">
  1042. <file name="index.html">
  1043. <div ng-controller="ExampleController">
  1044. <form novalidate>
  1045. <h3>User 1</h3>
  1046. Name: <input type="text" ng-model="user1.name">
  1047. Age: <input type="number" ng-model="user1.age">
  1048. <h3>User 2</h3>
  1049. Name: <input type="text" ng-model="user2.name">
  1050. Age: <input type="number" ng-model="user2.age">
  1051. <div>
  1052. <br/>
  1053. <input type="button" value="Compare" ng-click="compare()">
  1054. </div>
  1055. User 1: <pre>{{user1 | json}}</pre>
  1056. User 2: <pre>{{user2 | json}}</pre>
  1057. Equal: <pre>{{result}}</pre>
  1058. </form>
  1059. </div>
  1060. </file>
  1061. <file name="script.js">
  1062. angular.module('equalsExample', []).controller('ExampleController', ['$scope', function($scope) {
  1063. $scope.user1 = {};
  1064. $scope.user2 = {};
  1065. $scope.compare = function() {
  1066. $scope.result = angular.equals($scope.user1, $scope.user2);
  1067. };
  1068. }]);
  1069. </file>
  1070. </example>
  1071. */
  1072. function equals(o1, o2) {
  1073. if (o1 === o2) return true;
  1074. if (o1 === null || o2 === null) return false;
  1075. // eslint-disable-next-line no-self-compare
  1076. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  1077. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  1078. if (t1 === t2 && t1 === 'object') {
  1079. if (isArray(o1)) {
  1080. if (!isArray(o2)) return false;
  1081. if ((length = o1.length) === o2.length) {
  1082. for (key = 0; key < length; key++) {
  1083. if (!equals(o1[key], o2[key])) return false;
  1084. }
  1085. return true;
  1086. }
  1087. } else if (isDate(o1)) {
  1088. if (!isDate(o2)) return false;
  1089. return simpleCompare(o1.getTime(), o2.getTime());
  1090. } else if (isRegExp(o1)) {
  1091. if (!isRegExp(o2)) return false;
  1092. return o1.toString() === o2.toString();
  1093. } else {
  1094. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  1095. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  1096. keySet = createMap();
  1097. for (key in o1) {
  1098. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  1099. if (!equals(o1[key], o2[key])) return false;
  1100. keySet[key] = true;
  1101. }
  1102. for (key in o2) {
  1103. if (!(key in keySet) &&
  1104. key.charAt(0) !== '$' &&
  1105. isDefined(o2[key]) &&
  1106. !isFunction(o2[key])) return false;
  1107. }
  1108. return true;
  1109. }
  1110. }
  1111. return false;
  1112. }
  1113. var csp = function() {
  1114. if (!isDefined(csp.rules)) {
  1115. var ngCspElement = (window.document.querySelector('[ng-csp]') ||
  1116. window.document.querySelector('[data-ng-csp]'));
  1117. if (ngCspElement) {
  1118. var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
  1119. ngCspElement.getAttribute('data-ng-csp');
  1120. csp.rules = {
  1121. noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
  1122. noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
  1123. };
  1124. } else {
  1125. csp.rules = {
  1126. noUnsafeEval: noUnsafeEval(),
  1127. noInlineStyle: false
  1128. };
  1129. }
  1130. }
  1131. return csp.rules;
  1132. function noUnsafeEval() {
  1133. try {
  1134. // eslint-disable-next-line no-new, no-new-func
  1135. new Function('');
  1136. return false;
  1137. } catch (e) {
  1138. return true;
  1139. }
  1140. }
  1141. };
  1142. /**
  1143. * @ngdoc directive
  1144. * @module ng
  1145. * @name ngJq
  1146. *
  1147. * @element ANY
  1148. * @param {string=} ngJq the name of the library available under `window`
  1149. * to be used for angular.element
  1150. * @description
  1151. * Use this directive to force the angular.element library. This should be
  1152. * used to force either jqLite by leaving ng-jq blank or setting the name of
  1153. * the jquery variable under window (eg. jQuery).
  1154. *
  1155. * Since angular looks for this directive when it is loaded (doesn't wait for the
  1156. * DOMContentLoaded event), it must be placed on an element that comes before the script
  1157. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  1158. * others ignored.
  1159. *
  1160. * @example
  1161. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  1162. ```html
  1163. <!doctype html>
  1164. <html ng-app ng-jq>
  1165. ...
  1166. ...
  1167. </html>
  1168. ```
  1169. * @example
  1170. * This example shows how to use a jQuery based library of a different name.
  1171. * The library name must be available at the top most 'window'.
  1172. ```html
  1173. <!doctype html>
  1174. <html ng-app ng-jq="jQueryLib">
  1175. ...
  1176. ...
  1177. </html>
  1178. ```
  1179. */
  1180. var jq = function() {
  1181. if (isDefined(jq.name_)) return jq.name_;
  1182. var el;
  1183. var i, ii = ngAttrPrefixes.length, prefix, name;
  1184. for (i = 0; i < ii; ++i) {
  1185. prefix = ngAttrPrefixes[i];
  1186. el = window.document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]');
  1187. if (el) {
  1188. name = el.getAttribute(prefix + 'jq');
  1189. break;
  1190. }
  1191. }
  1192. return (jq.name_ = name);
  1193. };
  1194. function concat(array1, array2, index) {
  1195. return array1.concat(slice.call(array2, index));
  1196. }
  1197. function sliceArgs(args, startIndex) {
  1198. return slice.call(args, startIndex || 0);
  1199. }
  1200. /**
  1201. * @ngdoc function
  1202. * @name angular.bind
  1203. * @module ng
  1204. * @kind function
  1205. *
  1206. * @description
  1207. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  1208. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  1209. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  1210. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  1211. *
  1212. * @param {Object} self Context which `fn` should be evaluated in.
  1213. * @param {function()} fn Function to be bound.
  1214. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  1215. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  1216. */
  1217. function bind(self, fn) {
  1218. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  1219. if (isFunction(fn) && !(fn instanceof RegExp)) {
  1220. return curryArgs.length
  1221. ? function() {
  1222. return arguments.length
  1223. ? fn.apply(self, concat(curryArgs, arguments, 0))
  1224. : fn.apply(self, curryArgs);
  1225. }
  1226. : function() {
  1227. return arguments.length
  1228. ? fn.apply(self, arguments)
  1229. : fn.call(self);
  1230. };
  1231. } else {
  1232. // In IE, native methods are not functions so they cannot be bound (note: they don't need to be).
  1233. return fn;
  1234. }
  1235. }
  1236. function toJsonReplacer(key, value) {
  1237. var val = value;
  1238. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  1239. val = undefined;
  1240. } else if (isWindow(value)) {
  1241. val = '$WINDOW';
  1242. } else if (value && window.document === value) {
  1243. val = '$DOCUMENT';
  1244. } else if (isScope(value)) {
  1245. val = '$SCOPE';
  1246. }
  1247. return val;
  1248. }
  1249. /**
  1250. * @ngdoc function
  1251. * @name angular.toJson
  1252. * @module ng
  1253. * @kind function
  1254. *
  1255. * @description
  1256. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  1257. * stripped since angular uses this notation internally.
  1258. *
  1259. * @param {Object|Array|Date|string|number|boolean} obj Input to be serialized into JSON.
  1260. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  1261. * If set to an integer, the JSON output will contain that many spaces per indentation.
  1262. * @returns {string|undefined} JSON-ified string representing `obj`.
  1263. * @knownIssue
  1264. *
  1265. * The Safari browser throws a `RangeError` instead of returning `null` when it tries to stringify a `Date`
  1266. * object with an invalid date value. The only reliable way to prevent this is to monkeypatch the
  1267. * `Date.prototype.toJSON` method as follows:
  1268. *
  1269. * ```
  1270. * var _DatetoJSON = Date.prototype.toJSON;
  1271. * Date.prototype.toJSON = function() {
  1272. * try {
  1273. * return _DatetoJSON.call(this);
  1274. * } catch(e) {
  1275. * if (e instanceof RangeError) {
  1276. * return null;
  1277. * }
  1278. * throw e;
  1279. * }
  1280. * };
  1281. * ```
  1282. *
  1283. * See https://github.com/angular/angular.js/pull/14221 for more information.
  1284. */
  1285. function toJson(obj, pretty) {
  1286. if (isUndefined(obj)) return undefined;
  1287. if (!isNumber(pretty)) {
  1288. pretty = pretty ? 2 : null;
  1289. }
  1290. return JSON.stringify(obj, toJsonReplacer, pretty);
  1291. }
  1292. /**
  1293. * @ngdoc function
  1294. * @name angular.fromJson
  1295. * @module ng
  1296. * @kind function
  1297. *
  1298. * @description
  1299. * Deserializes a JSON string.
  1300. *
  1301. * @param {string} json JSON string to deserialize.
  1302. * @returns {Object|Array|string|number} Deserialized JSON string.
  1303. */
  1304. function fromJson(json) {
  1305. return isString(json)
  1306. ? JSON.parse(json)
  1307. : json;
  1308. }
  1309. var ALL_COLONS = /:/g;
  1310. function timezoneToOffset(timezone, fallback) {
  1311. // Support: IE 9-11 only, Edge 13-15+
  1312. // IE/Edge do not "understand" colon (`:`) in timezone
  1313. timezone = timezone.replace(ALL_COLONS, '');
  1314. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  1315. return isNumberNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  1316. }
  1317. function addDateMinutes(date, minutes) {
  1318. date = new Date(date.getTime());
  1319. date.setMinutes(date.getMinutes() + minutes);
  1320. return date;
  1321. }
  1322. function convertTimezoneToLocal(date, timezone, reverse) {
  1323. reverse = reverse ? -1 : 1;
  1324. var dateTimezoneOffset = date.getTimezoneOffset();
  1325. var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  1326. return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));
  1327. }
  1328. /**
  1329. * @returns {string} Returns the string representation of the element.
  1330. */
  1331. function startingTag(element) {
  1332. element = jqLite(element).clone().empty();
  1333. var elemHtml = jqLite('<div>').append(element).html();
  1334. try {
  1335. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  1336. elemHtml.
  1337. match(/^(<[^>]+>)/)[1].
  1338. replace(/^<([\w-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
  1339. } catch (e) {
  1340. return lowercase(elemHtml);
  1341. }
  1342. }
  1343. /////////////////////////////////////////////////
  1344. /**
  1345. * Tries to decode the URI component without throwing an exception.
  1346. *
  1347. * @private
  1348. * @param str value potential URI component to check.
  1349. * @returns {boolean} True if `value` can be decoded
  1350. * with the decodeURIComponent function.
  1351. */
  1352. function tryDecodeURIComponent(value) {
  1353. try {
  1354. return decodeURIComponent(value);
  1355. } catch (e) {
  1356. // Ignore any invalid uri component.
  1357. }
  1358. }
  1359. /**
  1360. * Parses an escaped url query string into key-value pairs.
  1361. * @returns {Object.<string,boolean|Array>}
  1362. */
  1363. function parseKeyValue(/**string*/keyValue) {
  1364. var obj = {};
  1365. forEach((keyValue || '').split('&'), function(keyValue) {
  1366. var splitPoint, key, val;
  1367. if (keyValue) {
  1368. key = keyValue = keyValue.replace(/\+/g,'%20');
  1369. splitPoint = keyValue.indexOf('=');
  1370. if (splitPoint !== -1) {
  1371. key = keyValue.substring(0, splitPoint);
  1372. val = keyValue.substring(splitPoint + 1);
  1373. }
  1374. key = tryDecodeURIComponent(key);
  1375. if (isDefined(key)) {
  1376. val = isDefined(val) ? tryDecodeURIComponent(val) : true;
  1377. if (!hasOwnProperty.call(obj, key)) {
  1378. obj[key] = val;
  1379. } else if (isArray(obj[key])) {
  1380. obj[key].push(val);
  1381. } else {
  1382. obj[key] = [obj[key],val];
  1383. }
  1384. }
  1385. }
  1386. });
  1387. return obj;
  1388. }
  1389. function toKeyValue(obj) {
  1390. var parts = [];
  1391. forEach(obj, function(value, key) {
  1392. if (isArray(value)) {
  1393. forEach(value, function(arrayValue) {
  1394. parts.push(encodeUriQuery(key, true) +
  1395. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1396. });
  1397. } else {
  1398. parts.push(encodeUriQuery(key, true) +
  1399. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1400. }
  1401. });
  1402. return parts.length ? parts.join('&') : '';
  1403. }
  1404. /**
  1405. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1406. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1407. * segments:
  1408. * segment = *pchar
  1409. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1410. * pct-encoded = "%" HEXDIG HEXDIG
  1411. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1412. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1413. * / "*" / "+" / "," / ";" / "="
  1414. */
  1415. function encodeUriSegment(val) {
  1416. return encodeUriQuery(val, true).
  1417. replace(/%26/gi, '&').
  1418. replace(/%3D/gi, '=').
  1419. replace(/%2B/gi, '+');
  1420. }
  1421. /**
  1422. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1423. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1424. * encoded per http://tools.ietf.org/html/rfc3986:
  1425. * query = *( pchar / "/" / "?" )
  1426. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1427. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1428. * pct-encoded = "%" HEXDIG HEXDIG
  1429. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1430. * / "*" / "+" / "," / ";" / "="
  1431. */
  1432. function encodeUriQuery(val, pctEncodeSpaces) {
  1433. return encodeURIComponent(val).
  1434. replace(/%40/gi, '@').
  1435. replace(/%3A/gi, ':').
  1436. replace(/%24/g, '$').
  1437. replace(/%2C/gi, ',').
  1438. replace(/%3B/gi, ';').
  1439. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1440. }
  1441. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1442. function getNgAttribute(element, ngAttr) {
  1443. var attr, i, ii = ngAttrPrefixes.length;
  1444. for (i = 0; i < ii; ++i) {
  1445. attr = ngAttrPrefixes[i] + ngAttr;
  1446. if (isString(attr = element.getAttribute(attr))) {
  1447. return attr;
  1448. }
  1449. }
  1450. return null;
  1451. }
  1452. function allowAutoBootstrap(document) {
  1453. var script = document.currentScript;
  1454. if (!script) {
  1455. // Support: IE 9-11 only
  1456. // IE does not have `document.currentScript`
  1457. return true;
  1458. }
  1459. // If the `currentScript` property has been clobbered just return false, since this indicates a probable attack
  1460. if (!(script instanceof window.HTMLScriptElement || script instanceof window.SVGScriptElement)) {
  1461. return false;
  1462. }
  1463. var attributes = script.attributes;
  1464. var srcs = [attributes.getNamedItem('src'), attributes.getNamedItem('href'), attributes.getNamedItem('xlink:href')];
  1465. return srcs.every(function(src) {
  1466. if (!src) {
  1467. return true;
  1468. }
  1469. if (!src.value) {
  1470. return false;
  1471. }
  1472. var link = document.createElement('a');
  1473. link.href = src.value;
  1474. if (document.location.origin === link.origin) {
  1475. // Same-origin resources are always allowed, even for non-whitelisted schemes.
  1476. return true;
  1477. }
  1478. // Disabled bootstrapping unless angular.js was loaded from a known scheme used on the web.
  1479. // This is to prevent angular.js bundled with browser extensions from being used to bypass the
  1480. // content security policy in web pages and other browser extensions.
  1481. switch (link.protocol) {
  1482. case 'http:':
  1483. case 'https:':
  1484. case 'ftp:':
  1485. case 'blob:':
  1486. case 'file:':
  1487. case 'data:':
  1488. return true;
  1489. default:
  1490. return false;
  1491. }
  1492. });
  1493. }
  1494. // Cached as it has to run during loading so that document.currentScript is available.
  1495. var isAutoBootstrapAllowed = allowAutoBootstrap(window.document);
  1496. /**
  1497. * @ngdoc directive
  1498. * @name ngApp
  1499. * @module ng
  1500. *
  1501. * @element ANY
  1502. * @param {angular.Module} ngApp an optional application
  1503. * {@link angular.module module} name to load.
  1504. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1505. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1506. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1507. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1508. * tracking down the root of these bugs.
  1509. *
  1510. * @description
  1511. *
  1512. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1513. * designates the **root element** of the application and is typically placed near the root element
  1514. * of the page - e.g. on the `<body>` or `<html>` tags.
  1515. *
  1516. * There are a few things to keep in mind when using `ngApp`:
  1517. * - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1518. * found in the document will be used to define the root element to auto-bootstrap as an
  1519. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1520. * {@link angular.bootstrap} instead.
  1521. * - AngularJS applications cannot be nested within each other.
  1522. * - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`.
  1523. * This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and
  1524. * {@link ngRoute.ngView `ngView`}.
  1525. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1526. * causing animations to stop working and making the injector inaccessible from outside the app.
  1527. *
  1528. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1529. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1530. * should contain the application code needed or have dependencies on other modules that will
  1531. * contain the code. See {@link angular.module} for more information.
  1532. *
  1533. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1534. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1535. * would not be resolved to `3`.
  1536. *
  1537. * @example
  1538. *
  1539. * ### Simple Usage
  1540. *
  1541. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1542. *
  1543. <example module="ngAppDemo" name="ng-app">
  1544. <file name="index.html">
  1545. <div ng-controller="ngAppDemoController">
  1546. I can add: {{a}} + {{b}} = {{ a+b }}
  1547. </div>
  1548. </file>
  1549. <file name="script.js">
  1550. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1551. $scope.a = 1;
  1552. $scope.b = 2;
  1553. });
  1554. </file>
  1555. </example>
  1556. *
  1557. * @example
  1558. *
  1559. * ### With `ngStrictDi`
  1560. *
  1561. * Using `ngStrictDi`, you would see something like this:
  1562. *
  1563. <example ng-app-included="true" name="strict-di">
  1564. <file name="index.html">
  1565. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1566. <div ng-controller="GoodController1">
  1567. I can add: {{a}} + {{b}} = {{ a+b }}
  1568. <p>This renders because the controller does not fail to
  1569. instantiate, by using explicit annotation style (see
  1570. script.js for details)
  1571. </p>
  1572. </div>
  1573. <div ng-controller="GoodController2">
  1574. Name: <input ng-model="name"><br />
  1575. Hello, {{name}}!
  1576. <p>This renders because the controller does not fail to
  1577. instantiate, by using explicit annotation style
  1578. (see script.js for details)
  1579. </p>
  1580. </div>
  1581. <div ng-controller="BadController">
  1582. I can add: {{a}} + {{b}} = {{ a+b }}
  1583. <p>The controller could not be instantiated, due to relying
  1584. on automatic function annotations (which are disabled in
  1585. strict mode). As such, the content of this section is not
  1586. interpolated, and there should be an error in your web console.
  1587. </p>
  1588. </div>
  1589. </div>
  1590. </file>
  1591. <file name="script.js">
  1592. angular.module('ngAppStrictDemo', [])
  1593. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1594. // rather than an explicit annotation
  1595. .controller('BadController', function($scope) {
  1596. $scope.a = 1;
  1597. $scope.b = 2;
  1598. })
  1599. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1600. // due to using explicit annotations using the array style and $inject property, respectively.
  1601. .controller('GoodController1', ['$scope', function($scope) {
  1602. $scope.a = 1;
  1603. $scope.b = 2;
  1604. }])
  1605. .controller('GoodController2', GoodController2);
  1606. function GoodController2($scope) {
  1607. $scope.name = 'World';
  1608. }
  1609. GoodController2.$inject = ['$scope'];
  1610. </file>
  1611. <file name="style.css">
  1612. div[ng-controller] {
  1613. margin-bottom: 1em;
  1614. -webkit-border-radius: 4px;
  1615. border-radius: 4px;
  1616. border: 1px solid;
  1617. padding: .5em;
  1618. }
  1619. div[ng-controller^=Good] {
  1620. border-color: #d6e9c6;
  1621. background-color: #dff0d8;
  1622. color: #3c763d;
  1623. }
  1624. div[ng-controller^=Bad] {
  1625. border-color: #ebccd1;
  1626. background-color: #f2dede;
  1627. color: #a94442;
  1628. margin-bottom: 0;
  1629. }
  1630. </file>
  1631. </example>
  1632. */
  1633. function angularInit(element, bootstrap) {
  1634. var appElement,
  1635. module,
  1636. config = {};
  1637. // The element `element` has priority over any other element.
  1638. forEach(ngAttrPrefixes, function(prefix) {
  1639. var name = prefix + 'app';
  1640. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1641. appElement = element;
  1642. module = element.getAttribute(name);
  1643. }
  1644. });
  1645. forEach(ngAttrPrefixes, function(prefix) {
  1646. var name = prefix + 'app';
  1647. var candidate;
  1648. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1649. appElement = candidate;
  1650. module = candidate.getAttribute(name);
  1651. }
  1652. });
  1653. if (appElement) {
  1654. if (!isAutoBootstrapAllowed) {
  1655. window.console.error('Angular: disabling automatic bootstrap. <script> protocol indicates ' +
  1656. 'an extension, document.location.href does not match.');
  1657. return;
  1658. }
  1659. config.strictDi = getNgAttribute(appElement, 'strict-di') !== null;
  1660. bootstrap(appElement, module ? [module] : [], config);
  1661. }
  1662. }
  1663. /**
  1664. * @ngdoc function
  1665. * @name angular.bootstrap
  1666. * @module ng
  1667. * @description
  1668. * Use this function to manually start up angular application.
  1669. *
  1670. * For more information, see the {@link guide/bootstrap Bootstrap guide}.
  1671. *
  1672. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1673. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1674. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1675. * multiple instances of Angular try to work on the DOM.
  1676. *
  1677. * <div class="alert alert-warning">
  1678. * **Note:** Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1679. * They must use {@link ng.directive:ngApp ngApp}.
  1680. * </div>
  1681. *
  1682. * <div class="alert alert-warning">
  1683. * **Note:** Do not bootstrap the app on an element with a directive that uses {@link ng.$compile#transclusion transclusion},
  1684. * such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and {@link ngRoute.ngView `ngView`}.
  1685. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1686. * causing animations to stop working and making the injector inaccessible from outside the app.
  1687. * </div>
  1688. *
  1689. * ```html
  1690. * <!doctype html>
  1691. * <html>
  1692. * <body>
  1693. * <div ng-controller="WelcomeController">
  1694. * {{greeting}}
  1695. * </div>
  1696. *
  1697. * <script src="angular.js"></script>
  1698. * <script>
  1699. * var app = angular.module('demo', [])
  1700. * .controller('WelcomeController', function($scope) {
  1701. * $scope.greeting = 'Welcome!';
  1702. * });
  1703. * angular.bootstrap(document, ['demo']);
  1704. * </script>
  1705. * </body>
  1706. * </html>
  1707. * ```
  1708. *
  1709. * @param {DOMElement} element DOM element which is the root of angular application.
  1710. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1711. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1712. * function that will be invoked by the injector as a `config` block.
  1713. * See: {@link angular.module modules}
  1714. * @param {Object=} config an object for defining configuration options for the application. The
  1715. * following keys are supported:
  1716. *
  1717. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1718. * assist in finding bugs which break minified code. Defaults to `false`.
  1719. *
  1720. * @returns {auto.$injector} Returns the newly created injector for this app.
  1721. */
  1722. function bootstrap(element, modules, config) {
  1723. if (!isObject(config)) config = {};
  1724. var defaultConfig = {
  1725. strictDi: false
  1726. };
  1727. config = extend(defaultConfig, config);
  1728. var doBootstrap = function() {
  1729. element = jqLite(element);
  1730. if (element.injector()) {
  1731. var tag = (element[0] === window.document) ? 'document' : startingTag(element);
  1732. // Encode angle brackets to prevent input from being sanitized to empty string #8683.
  1733. throw ngMinErr(
  1734. 'btstrpd',
  1735. 'App already bootstrapped with this element \'{0}\'',
  1736. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1737. }
  1738. modules = modules || [];
  1739. modules.unshift(['$provide', function($provide) {
  1740. $provide.value('$rootElement', element);
  1741. }]);
  1742. if (config.debugInfoEnabled) {
  1743. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1744. modules.push(['$compileProvider', function($compileProvider) {
  1745. $compileProvider.debugInfoEnabled(true);
  1746. }]);
  1747. }
  1748. modules.unshift('ng');
  1749. var injector = createInjector(modules, config.strictDi);
  1750. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1751. function bootstrapApply(scope, element, compile, injector) {
  1752. scope.$apply(function() {
  1753. element.data('$injector', injector);
  1754. compile(element)(scope);
  1755. });
  1756. }]
  1757. );
  1758. return injector;
  1759. };
  1760. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1761. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1762. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1763. config.debugInfoEnabled = true;
  1764. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1765. }
  1766. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1767. return doBootstrap();
  1768. }
  1769. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1770. angular.resumeBootstrap = function(extraModules) {
  1771. forEach(extraModules, function(module) {
  1772. modules.push(module);
  1773. });
  1774. return doBootstrap();
  1775. };
  1776. if (isFunction(angular.resumeDeferredBootstrap)) {
  1777. angular.resumeDeferredBootstrap();
  1778. }
  1779. }
  1780. /**
  1781. * @ngdoc function
  1782. * @name angular.reloadWithDebugInfo
  1783. * @module ng
  1784. * @description
  1785. * Use this function to reload the current application with debug information turned on.
  1786. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1787. *
  1788. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1789. */
  1790. function reloadWithDebugInfo() {
  1791. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1792. window.location.reload();
  1793. }
  1794. /**
  1795. * @name angular.getTestability
  1796. * @module ng
  1797. * @description
  1798. * Get the testability service for the instance of Angular on the given
  1799. * element.
  1800. * @param {DOMElement} element DOM element which is the root of angular application.
  1801. */
  1802. function getTestability(rootElement) {
  1803. var injector = angular.element(rootElement).injector();
  1804. if (!injector) {
  1805. throw ngMinErr('test',
  1806. 'no injector found for element argument to getTestability');
  1807. }
  1808. return injector.get('$$testability');
  1809. }
  1810. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1811. function snake_case(name, separator) {
  1812. separator = separator || '_';
  1813. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1814. return (pos ? separator : '') + letter.toLowerCase();
  1815. });
  1816. }
  1817. var bindJQueryFired = false;
  1818. function bindJQuery() {
  1819. var originalCleanData;
  1820. if (bindJQueryFired) {
  1821. return;
  1822. }
  1823. // bind to jQuery if present;
  1824. var jqName = jq();
  1825. jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
  1826. !jqName ? undefined : // use jqLite
  1827. window[jqName]; // use jQuery specified by `ngJq`
  1828. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1829. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1830. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1831. // versions. It will not work for sure with jQuery <1.7, though.
  1832. if (jQuery && jQuery.fn.on) {
  1833. jqLite = jQuery;
  1834. extend(jQuery.fn, {
  1835. scope: JQLitePrototype.scope,
  1836. isolateScope: JQLitePrototype.isolateScope,
  1837. controller: /** @type {?} */ (JQLitePrototype).controller,
  1838. injector: JQLitePrototype.injector,
  1839. inheritedData: JQLitePrototype.inheritedData
  1840. });
  1841. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1842. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1843. // the $destroy event on all removed nodes.
  1844. originalCleanData = jQuery.cleanData;
  1845. jQuery.cleanData = function(elems) {
  1846. var events;
  1847. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1848. events = jQuery._data(elem, 'events');
  1849. if (events && events.$destroy) {
  1850. jQuery(elem).triggerHandler('$destroy');
  1851. }
  1852. }
  1853. originalCleanData(elems);
  1854. };
  1855. } else {
  1856. jqLite = JQLite;
  1857. }
  1858. angular.element = jqLite;
  1859. // Prevent double-proxying.
  1860. bindJQueryFired = true;
  1861. }
  1862. /**
  1863. * throw error if the argument is falsy.
  1864. */
  1865. function assertArg(arg, name, reason) {
  1866. if (!arg) {
  1867. throw ngMinErr('areq', 'Argument \'{0}\' is {1}', (name || '?'), (reason || 'required'));
  1868. }
  1869. return arg;
  1870. }
  1871. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1872. if (acceptArrayAnnotation && isArray(arg)) {
  1873. arg = arg[arg.length - 1];
  1874. }
  1875. assertArg(isFunction(arg), name, 'not a function, got ' +
  1876. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1877. return arg;
  1878. }
  1879. /**
  1880. * throw error if the name given is hasOwnProperty
  1881. * @param {String} name the name to test
  1882. * @param {String} context the context in which the name is used, such as module or directive
  1883. */
  1884. function assertNotHasOwnProperty(name, context) {
  1885. if (name === 'hasOwnProperty') {
  1886. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1887. }
  1888. }
  1889. /**
  1890. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1891. * @param {Object} obj starting object
  1892. * @param {String} path path to traverse
  1893. * @param {boolean} [bindFnToScope=true]
  1894. * @returns {Object} value as accessible by path
  1895. */
  1896. //TODO(misko): this function needs to be removed
  1897. function getter(obj, path, bindFnToScope) {
  1898. if (!path) return obj;
  1899. var keys = path.split('.');
  1900. var key;
  1901. var lastInstance = obj;
  1902. var len = keys.length;
  1903. for (var i = 0; i < len; i++) {
  1904. key = keys[i];
  1905. if (obj) {
  1906. obj = (lastInstance = obj)[key];
  1907. }
  1908. }
  1909. if (!bindFnToScope && isFunction(obj)) {
  1910. return bind(lastInstance, obj);
  1911. }
  1912. return obj;
  1913. }
  1914. /**
  1915. * Return the DOM siblings between the first and last node in the given array.
  1916. * @param {Array} array like object
  1917. * @returns {Array} the inputted object or a jqLite collection containing the nodes
  1918. */
  1919. function getBlockNodes(nodes) {
  1920. // TODO(perf): update `nodes` instead of creating a new object?
  1921. var node = nodes[0];
  1922. var endNode = nodes[nodes.length - 1];
  1923. var blockNodes;
  1924. for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
  1925. if (blockNodes || nodes[i] !== node) {
  1926. if (!blockNodes) {
  1927. blockNodes = jqLite(slice.call(nodes, 0, i));
  1928. }
  1929. blockNodes.push(node);
  1930. }
  1931. }
  1932. return blockNodes || nodes;
  1933. }
  1934. /**
  1935. * Creates a new object without a prototype. This object is useful for lookup without having to
  1936. * guard against prototypically inherited properties via hasOwnProperty.
  1937. *
  1938. * Related micro-benchmarks:
  1939. * - http://jsperf.com/object-create2
  1940. * - http://jsperf.com/proto-map-lookup/2
  1941. * - http://jsperf.com/for-in-vs-object-keys2
  1942. *
  1943. * @returns {Object}
  1944. */
  1945. function createMap() {
  1946. return Object.create(null);
  1947. }
  1948. function stringify(value) {
  1949. if (value == null) { // null || undefined
  1950. return '';
  1951. }
  1952. switch (typeof value) {
  1953. case 'string':
  1954. break;
  1955. case 'number':
  1956. value = '' + value;
  1957. break;
  1958. default:
  1959. if (hasCustomToString(value) && !isArray(value) && !isDate(value)) {
  1960. value = value.toString();
  1961. } else {
  1962. value = toJson(value);
  1963. }
  1964. }
  1965. return value;
  1966. }
  1967. var NODE_TYPE_ELEMENT = 1;
  1968. var NODE_TYPE_ATTRIBUTE = 2;
  1969. var NODE_TYPE_TEXT = 3;
  1970. var NODE_TYPE_COMMENT = 8;
  1971. var NODE_TYPE_DOCUMENT = 9;
  1972. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1973. /**
  1974. * @ngdoc type
  1975. * @name angular.Module
  1976. * @module ng
  1977. * @description
  1978. *
  1979. * Interface for configuring angular {@link angular.module modules}.
  1980. */
  1981. function setupModuleLoader(window) {
  1982. var $injectorMinErr = minErr('$injector');
  1983. var ngMinErr = minErr('ng');
  1984. function ensure(obj, name, factory) {
  1985. return obj[name] || (obj[name] = factory());
  1986. }
  1987. var angular = ensure(window, 'angular', Object);
  1988. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1989. angular.$$minErr = angular.$$minErr || minErr;
  1990. return ensure(angular, 'module', function() {
  1991. /** @type {Object.<string, angular.Module>} */
  1992. var modules = {};
  1993. /**
  1994. * @ngdoc function
  1995. * @name angular.module
  1996. * @module ng
  1997. * @description
  1998. *
  1999. * The `angular.module` is a global place for creating, registering and retrieving Angular
  2000. * modules.
  2001. * All modules (angular core or 3rd party) that should be available to an application must be
  2002. * registered using this mechanism.
  2003. *
  2004. * Passing one argument retrieves an existing {@link angular.Module},
  2005. * whereas passing more than one argument creates a new {@link angular.Module}
  2006. *
  2007. *
  2008. * # Module
  2009. *
  2010. * A module is a collection of services, directives, controllers, filters, and configuration information.
  2011. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  2012. *
  2013. * ```js
  2014. * // Create a new module
  2015. * var myModule = angular.module('myModule', []);
  2016. *
  2017. * // register a new service
  2018. * myModule.value('appName', 'MyCoolApp');
  2019. *
  2020. * // configure existing services inside initialization blocks.
  2021. * myModule.config(['$locationProvider', function($locationProvider) {
  2022. * // Configure existing providers
  2023. * $locationProvider.hashPrefix('!');
  2024. * }]);
  2025. * ```
  2026. *
  2027. * Then you can create an injector and load your modules like this:
  2028. *
  2029. * ```js
  2030. * var injector = angular.injector(['ng', 'myModule'])
  2031. * ```
  2032. *
  2033. * However it's more likely that you'll just use
  2034. * {@link ng.directive:ngApp ngApp} or
  2035. * {@link angular.bootstrap} to simplify this process for you.
  2036. *
  2037. * @param {!string} name The name of the module to create or retrieve.
  2038. * @param {!Array.<string>=} requires If specified then new module is being created. If
  2039. * unspecified then the module is being retrieved for further configuration.
  2040. * @param {Function=} configFn Optional configuration function for the module. Same as
  2041. * {@link angular.Module#config Module#config()}.
  2042. * @returns {angular.Module} new module with the {@link angular.Module} api.
  2043. */
  2044. return function module(name, requires, configFn) {
  2045. var info = {};
  2046. var assertNotHasOwnProperty = function(name, context) {
  2047. if (name === 'hasOwnProperty') {
  2048. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  2049. }
  2050. };
  2051. assertNotHasOwnProperty(name, 'module');
  2052. if (requires && modules.hasOwnProperty(name)) {
  2053. modules[name] = null;
  2054. }
  2055. return ensure(modules, name, function() {
  2056. if (!requires) {
  2057. throw $injectorMinErr('nomod', 'Module \'{0}\' is not available! You either misspelled ' +
  2058. 'the module name or forgot to load it. If registering a module ensure that you ' +
  2059. 'specify the dependencies as the second argument.', name);
  2060. }
  2061. /** @type {!Array.<Array.<*>>} */
  2062. var invokeQueue = [];
  2063. /** @type {!Array.<Function>} */
  2064. var configBlocks = [];
  2065. /** @type {!Array.<Function>} */
  2066. var runBlocks = [];
  2067. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  2068. /** @type {angular.Module} */
  2069. var moduleInstance = {
  2070. // Private state
  2071. _invokeQueue: invokeQueue,
  2072. _configBlocks: configBlocks,
  2073. _runBlocks: runBlocks,
  2074. /**
  2075. * @ngdoc method
  2076. * @name angular.Module#info
  2077. * @module ng
  2078. *
  2079. * @param {Object=} info Information about the module
  2080. * @returns {Object|Module} The current info object for this module if called as a getter,
  2081. * or `this` if called as a setter.
  2082. *
  2083. * @description
  2084. * Read and write custom information about this module.
  2085. * For example you could put the version of the module in here.
  2086. *
  2087. * ```js
  2088. * angular.module('myModule', []).info({ version: '1.0.0' });
  2089. * ```
  2090. *
  2091. * The version could then be read back out by accessing the module elsewhere:
  2092. *
  2093. * ```
  2094. * var version = angular.module('myModule').info().version;
  2095. * ```
  2096. *
  2097. * You can also retrieve this information during runtime via the
  2098. * {@link $injector#modules `$injector.modules`} property:
  2099. *
  2100. * ```js
  2101. * var version = $injector.modules['myModule'].info().version;
  2102. * ```
  2103. */
  2104. info: function(value) {
  2105. if (isDefined(value)) {
  2106. if (!isObject(value)) throw ngMinErr('aobj', 'Argument \'{0}\' must be an object', 'value');
  2107. info = value;
  2108. return this;
  2109. }
  2110. return info;
  2111. },
  2112. /**
  2113. * @ngdoc property
  2114. * @name angular.Module#requires
  2115. * @module ng
  2116. *
  2117. * @description
  2118. * Holds the list of modules which the injector will load before the current module is
  2119. * loaded.
  2120. */
  2121. requires: requires,
  2122. /**
  2123. * @ngdoc property
  2124. * @name angular.Module#name
  2125. * @module ng
  2126. *
  2127. * @description
  2128. * Name of the module.
  2129. */
  2130. name: name,
  2131. /**
  2132. * @ngdoc method
  2133. * @name angular.Module#provider
  2134. * @module ng
  2135. * @param {string} name service name
  2136. * @param {Function} providerType Construction function for creating new instance of the
  2137. * service.
  2138. * @description
  2139. * See {@link auto.$provide#provider $provide.provider()}.
  2140. */
  2141. provider: invokeLaterAndSetModuleName('$provide', 'provider'),
  2142. /**
  2143. * @ngdoc method
  2144. * @name angular.Module#factory
  2145. * @module ng
  2146. * @param {string} name service name
  2147. * @param {Function} providerFunction Function for creating new instance of the service.
  2148. * @description
  2149. * See {@link auto.$provide#factory $provide.factory()}.
  2150. */
  2151. factory: invokeLaterAndSetModuleName('$provide', 'factory'),
  2152. /**
  2153. * @ngdoc method
  2154. * @name angular.Module#service
  2155. * @module ng
  2156. * @param {string} name service name
  2157. * @param {Function} constructor A constructor function that will be instantiated.
  2158. * @description
  2159. * See {@link auto.$provide#service $provide.service()}.
  2160. */
  2161. service: invokeLaterAndSetModuleName('$provide', 'service'),
  2162. /**
  2163. * @ngdoc method
  2164. * @name angular.Module#value
  2165. * @module ng
  2166. * @param {string} name service name
  2167. * @param {*} object Service instance object.
  2168. * @description
  2169. * See {@link auto.$provide#value $provide.value()}.
  2170. */
  2171. value: invokeLater('$provide', 'value'),
  2172. /**
  2173. * @ngdoc method
  2174. * @name angular.Module#constant
  2175. * @module ng
  2176. * @param {string} name constant name
  2177. * @param {*} object Constant value.
  2178. * @description
  2179. * Because the constants are fixed, they get applied before other provide methods.
  2180. * See {@link auto.$provide#constant $provide.constant()}.
  2181. */
  2182. constant: invokeLater('$provide', 'constant', 'unshift'),
  2183. /**
  2184. * @ngdoc method
  2185. * @name angular.Module#decorator
  2186. * @module ng
  2187. * @param {string} name The name of the service to decorate.
  2188. * @param {Function} decorFn This function will be invoked when the service needs to be
  2189. * instantiated and should return the decorated service instance.
  2190. * @description
  2191. * See {@link auto.$provide#decorator $provide.decorator()}.
  2192. */
  2193. decorator: invokeLaterAndSetModuleName('$provide', 'decorator', configBlocks),
  2194. /**
  2195. * @ngdoc method
  2196. * @name angular.Module#animation
  2197. * @module ng
  2198. * @param {string} name animation name
  2199. * @param {Function} animationFactory Factory function for creating new instance of an
  2200. * animation.
  2201. * @description
  2202. *
  2203. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  2204. *
  2205. *
  2206. * Defines an animation hook that can be later used with
  2207. * {@link $animate $animate} service and directives that use this service.
  2208. *
  2209. * ```js
  2210. * module.animation('.animation-name', function($inject1, $inject2) {
  2211. * return {
  2212. * eventName : function(element, done) {
  2213. * //code to run the animation
  2214. * //once complete, then run done()
  2215. * return function cancellationFunction(element) {
  2216. * //code to cancel the animation
  2217. * }
  2218. * }
  2219. * }
  2220. * })
  2221. * ```
  2222. *
  2223. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  2224. * {@link ngAnimate ngAnimate module} for more information.
  2225. */
  2226. animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
  2227. /**
  2228. * @ngdoc method
  2229. * @name angular.Module#filter
  2230. * @module ng
  2231. * @param {string} name Filter name - this must be a valid angular expression identifier
  2232. * @param {Function} filterFactory Factory function for creating new instance of filter.
  2233. * @description
  2234. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  2235. *
  2236. * <div class="alert alert-warning">
  2237. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  2238. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  2239. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  2240. * (`myapp_subsection_filterx`).
  2241. * </div>
  2242. */
  2243. filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
  2244. /**
  2245. * @ngdoc method
  2246. * @name angular.Module#controller
  2247. * @module ng
  2248. * @param {string|Object} name Controller name, or an object map of controllers where the
  2249. * keys are the names and the values are the constructors.
  2250. * @param {Function} constructor Controller constructor function.
  2251. * @description
  2252. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  2253. */
  2254. controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
  2255. /**
  2256. * @ngdoc method
  2257. * @name angular.Module#directive
  2258. * @module ng
  2259. * @param {string|Object} name Directive name, or an object map of directives where the
  2260. * keys are the names and the values are the factories.
  2261. * @param {Function} directiveFactory Factory function for creating new instance of
  2262. * directives.
  2263. * @description
  2264. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  2265. */
  2266. directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
  2267. /**
  2268. * @ngdoc method
  2269. * @name angular.Module#component
  2270. * @module ng
  2271. * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp)
  2272. * @param {Object} options Component definition object (a simplified
  2273. * {@link ng.$compile#directive-definition-object directive definition object})
  2274. *
  2275. * @description
  2276. * See {@link ng.$compileProvider#component $compileProvider.component()}.
  2277. */
  2278. component: invokeLaterAndSetModuleName('$compileProvider', 'component'),
  2279. /**
  2280. * @ngdoc method
  2281. * @name angular.Module#config
  2282. * @module ng
  2283. * @param {Function} configFn Execute this function on module load. Useful for service
  2284. * configuration.
  2285. * @description
  2286. * Use this method to register work which needs to be performed on module loading.
  2287. * For more about how to configure services, see
  2288. * {@link providers#provider-recipe Provider Recipe}.
  2289. */
  2290. config: config,
  2291. /**
  2292. * @ngdoc method
  2293. * @name angular.Module#run
  2294. * @module ng
  2295. * @param {Function} initializationFn Execute this function after injector creation.
  2296. * Useful for application initialization.
  2297. * @description
  2298. * Use this method to register work which should be performed when the injector is done
  2299. * loading all modules.
  2300. */
  2301. run: function(block) {
  2302. runBlocks.push(block);
  2303. return this;
  2304. }
  2305. };
  2306. if (configFn) {
  2307. config(configFn);
  2308. }
  2309. return moduleInstance;
  2310. /**
  2311. * @param {string} provider
  2312. * @param {string} method
  2313. * @param {String=} insertMethod
  2314. * @returns {angular.Module}
  2315. */
  2316. function invokeLater(provider, method, insertMethod, queue) {
  2317. if (!queue) queue = invokeQueue;
  2318. return function() {
  2319. queue[insertMethod || 'push']([provider, method, arguments]);
  2320. return moduleInstance;
  2321. };
  2322. }
  2323. /**
  2324. * @param {string} provider
  2325. * @param {string} method
  2326. * @returns {angular.Module}
  2327. */
  2328. function invokeLaterAndSetModuleName(provider, method, queue) {
  2329. if (!queue) queue = invokeQueue;
  2330. return function(recipeName, factoryFunction) {
  2331. if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
  2332. queue.push([provider, method, arguments]);
  2333. return moduleInstance;
  2334. };
  2335. }
  2336. });
  2337. };
  2338. });
  2339. }
  2340. /* global shallowCopy: true */
  2341. /**
  2342. * Creates a shallow copy of an object, an array or a primitive.
  2343. *
  2344. * Assumes that there are no proto properties for objects.
  2345. */
  2346. function shallowCopy(src, dst) {
  2347. if (isArray(src)) {
  2348. dst = dst || [];
  2349. for (var i = 0, ii = src.length; i < ii; i++) {
  2350. dst[i] = src[i];
  2351. }
  2352. } else if (isObject(src)) {
  2353. dst = dst || {};
  2354. for (var key in src) {
  2355. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  2356. dst[key] = src[key];
  2357. }
  2358. }
  2359. }
  2360. return dst || src;
  2361. }
  2362. /* exported toDebugString */
  2363. function serializeObject(obj, maxDepth) {
  2364. var seen = [];
  2365. // There is no direct way to stringify object until reaching a specific depth
  2366. // and a very deep object can cause a performance issue, so we copy the object
  2367. // based on this specific depth and then stringify it.
  2368. if (isValidObjectMaxDepth(maxDepth)) {
  2369. // This file is also included in `angular-loader`, so `copy()` might not always be available in
  2370. // the closure. Therefore, it is lazily retrieved as `angular.copy()` when needed.
  2371. obj = angular.copy(obj, null, maxDepth);
  2372. }
  2373. return JSON.stringify(obj, function(key, val) {
  2374. val = toJsonReplacer(key, val);
  2375. if (isObject(val)) {
  2376. if (seen.indexOf(val) >= 0) return '...';
  2377. seen.push(val);
  2378. }
  2379. return val;
  2380. });
  2381. }
  2382. function toDebugString(obj, maxDepth) {
  2383. if (typeof obj === 'function') {
  2384. return obj.toString().replace(/ \{[\s\S]*$/, '');
  2385. } else if (isUndefined(obj)) {
  2386. return 'undefined';
  2387. } else if (typeof obj !== 'string') {
  2388. return serializeObject(obj, maxDepth);
  2389. }
  2390. return obj;
  2391. }
  2392. /* global angularModule: true,
  2393. version: true,
  2394. $CompileProvider,
  2395. htmlAnchorDirective,
  2396. inputDirective,
  2397. inputDirective,
  2398. formDirective,
  2399. scriptDirective,
  2400. selectDirective,
  2401. optionDirective,
  2402. ngBindDirective,
  2403. ngBindHtmlDirective,
  2404. ngBindTemplateDirective,
  2405. ngClassDirective,
  2406. ngClassEvenDirective,
  2407. ngClassOddDirective,
  2408. ngCloakDirective,
  2409. ngControllerDirective,
  2410. ngFormDirective,
  2411. ngHideDirective,
  2412. ngIfDirective,
  2413. ngIncludeDirective,
  2414. ngIncludeFillContentDirective,
  2415. ngInitDirective,
  2416. ngNonBindableDirective,
  2417. ngPluralizeDirective,
  2418. ngRepeatDirective,
  2419. ngShowDirective,
  2420. ngStyleDirective,
  2421. ngSwitchDirective,
  2422. ngSwitchWhenDirective,
  2423. ngSwitchDefaultDirective,
  2424. ngOptionsDirective,
  2425. ngTranscludeDirective,
  2426. ngModelDirective,
  2427. ngListDirective,
  2428. ngChangeDirective,
  2429. patternDirective,
  2430. patternDirective,
  2431. requiredDirective,
  2432. requiredDirective,
  2433. minlengthDirective,
  2434. minlengthDirective,
  2435. maxlengthDirective,
  2436. maxlengthDirective,
  2437. ngValueDirective,
  2438. ngModelOptionsDirective,
  2439. ngAttributeAliasDirectives,
  2440. ngEventDirectives,
  2441. $AnchorScrollProvider,
  2442. $AnimateProvider,
  2443. $CoreAnimateCssProvider,
  2444. $$CoreAnimateJsProvider,
  2445. $$CoreAnimateQueueProvider,
  2446. $$AnimateRunnerFactoryProvider,
  2447. $$AnimateAsyncRunFactoryProvider,
  2448. $BrowserProvider,
  2449. $CacheFactoryProvider,
  2450. $ControllerProvider,
  2451. $DateProvider,
  2452. $DocumentProvider,
  2453. $$IsDocumentHiddenProvider,
  2454. $ExceptionHandlerProvider,
  2455. $FilterProvider,
  2456. $$ForceReflowProvider,
  2457. $InterpolateProvider,
  2458. $IntervalProvider,
  2459. $HttpProvider,
  2460. $HttpParamSerializerProvider,
  2461. $HttpParamSerializerJQLikeProvider,
  2462. $HttpBackendProvider,
  2463. $xhrFactoryProvider,
  2464. $jsonpCallbacksProvider,
  2465. $LocationProvider,
  2466. $LogProvider,
  2467. $$MapProvider,
  2468. $ParseProvider,
  2469. $RootScopeProvider,
  2470. $QProvider,
  2471. $$QProvider,
  2472. $$SanitizeUriProvider,
  2473. $SceProvider,
  2474. $SceDelegateProvider,
  2475. $SnifferProvider,
  2476. $TemplateCacheProvider,
  2477. $TemplateRequestProvider,
  2478. $$TestabilityProvider,
  2479. $TimeoutProvider,
  2480. $$RAFProvider,
  2481. $WindowProvider,
  2482. $$jqLiteProvider,
  2483. $$CookieReaderProvider
  2484. */
  2485. /**
  2486. * @ngdoc object
  2487. * @name angular.version
  2488. * @module ng
  2489. * @description
  2490. * An object that contains information about the current AngularJS version.
  2491. *
  2492. * This object has the following properties:
  2493. *
  2494. * - `full` – `{string}` – Full version string, such as "0.9.18".
  2495. * - `major` – `{number}` – Major version number, such as "0".
  2496. * - `minor` – `{number}` – Minor version number, such as "9".
  2497. * - `dot` – `{number}` – Dot version number, such as "18".
  2498. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  2499. */
  2500. var version = {
  2501. // These placeholder strings will be replaced by grunt's `build` task.
  2502. // They need to be double- or single-quoted.
  2503. full: '1.6.7',
  2504. major: 1,
  2505. minor: 6,
  2506. dot: 7,
  2507. codeName: 'imperial-backstroke'
  2508. };
  2509. function publishExternalAPI(angular) {
  2510. extend(angular, {
  2511. 'errorHandlingConfig': errorHandlingConfig,
  2512. 'bootstrap': bootstrap,
  2513. 'copy': copy,
  2514. 'extend': extend,
  2515. 'merge': merge,
  2516. 'equals': equals,
  2517. 'element': jqLite,
  2518. 'forEach': forEach,
  2519. 'injector': createInjector,
  2520. 'noop': noop,
  2521. 'bind': bind,
  2522. 'toJson': toJson,
  2523. 'fromJson': fromJson,
  2524. 'identity': identity,
  2525. 'isUndefined': isUndefined,
  2526. 'isDefined': isDefined,
  2527. 'isString': isString,
  2528. 'isFunction': isFunction,
  2529. 'isObject': isObject,
  2530. 'isNumber': isNumber,
  2531. 'isElement': isElement,
  2532. 'isArray': isArray,
  2533. 'version': version,
  2534. 'isDate': isDate,
  2535. 'lowercase': lowercase,
  2536. 'uppercase': uppercase,
  2537. 'callbacks': {$$counter: 0},
  2538. 'getTestability': getTestability,
  2539. 'reloadWithDebugInfo': reloadWithDebugInfo,
  2540. '$$minErr': minErr,
  2541. '$$csp': csp,
  2542. '$$encodeUriSegment': encodeUriSegment,
  2543. '$$encodeUriQuery': encodeUriQuery,
  2544. '$$stringify': stringify
  2545. });
  2546. angularModule = setupModuleLoader(window);
  2547. angularModule('ng', ['ngLocale'], ['$provide',
  2548. function ngModule($provide) {
  2549. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  2550. $provide.provider({
  2551. $$sanitizeUri: $$SanitizeUriProvider
  2552. });
  2553. $provide.provider('$compile', $CompileProvider).
  2554. directive({
  2555. a: htmlAnchorDirective,
  2556. input: inputDirective,
  2557. textarea: inputDirective,
  2558. form: formDirective,
  2559. script: scriptDirective,
  2560. select: selectDirective,
  2561. option: optionDirective,
  2562. ngBind: ngBindDirective,
  2563. ngBindHtml: ngBindHtmlDirective,
  2564. ngBindTemplate: ngBindTemplateDirective,
  2565. ngClass: ngClassDirective,
  2566. ngClassEven: ngClassEvenDirective,
  2567. ngClassOdd: ngClassOddDirective,
  2568. ngCloak: ngCloakDirective,
  2569. ngController: ngControllerDirective,
  2570. ngForm: ngFormDirective,
  2571. ngHide: ngHideDirective,
  2572. ngIf: ngIfDirective,
  2573. ngInclude: ngIncludeDirective,
  2574. ngInit: ngInitDirective,
  2575. ngNonBindable: ngNonBindableDirective,
  2576. ngPluralize: ngPluralizeDirective,
  2577. ngRepeat: ngRepeatDirective,
  2578. ngShow: ngShowDirective,
  2579. ngStyle: ngStyleDirective,
  2580. ngSwitch: ngSwitchDirective,
  2581. ngSwitchWhen: ngSwitchWhenDirective,
  2582. ngSwitchDefault: ngSwitchDefaultDirective,
  2583. ngOptions: ngOptionsDirective,
  2584. ngTransclude: ngTranscludeDirective,
  2585. ngModel: ngModelDirective,
  2586. ngList: ngListDirective,
  2587. ngChange: ngChangeDirective,
  2588. pattern: patternDirective,
  2589. ngPattern: patternDirective,
  2590. required: requiredDirective,
  2591. ngRequired: requiredDirective,
  2592. minlength: minlengthDirective,
  2593. ngMinlength: minlengthDirective,
  2594. maxlength: maxlengthDirective,
  2595. ngMaxlength: maxlengthDirective,
  2596. ngValue: ngValueDirective,
  2597. ngModelOptions: ngModelOptionsDirective
  2598. }).
  2599. directive({
  2600. ngInclude: ngIncludeFillContentDirective
  2601. }).
  2602. directive(ngAttributeAliasDirectives).
  2603. directive(ngEventDirectives);
  2604. $provide.provider({
  2605. $anchorScroll: $AnchorScrollProvider,
  2606. $animate: $AnimateProvider,
  2607. $animateCss: $CoreAnimateCssProvider,
  2608. $$animateJs: $$CoreAnimateJsProvider,
  2609. $$animateQueue: $$CoreAnimateQueueProvider,
  2610. $$AnimateRunner: $$AnimateRunnerFactoryProvider,
  2611. $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,
  2612. $browser: $BrowserProvider,
  2613. $cacheFactory: $CacheFactoryProvider,
  2614. $controller: $ControllerProvider,
  2615. $document: $DocumentProvider,
  2616. $$isDocumentHidden: $$IsDocumentHiddenProvider,
  2617. $exceptionHandler: $ExceptionHandlerProvider,
  2618. $filter: $FilterProvider,
  2619. $$forceReflow: $$ForceReflowProvider,
  2620. $interpolate: $InterpolateProvider,
  2621. $interval: $IntervalProvider,
  2622. $http: $HttpProvider,
  2623. $httpParamSerializer: $HttpParamSerializerProvider,
  2624. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  2625. $httpBackend: $HttpBackendProvider,
  2626. $xhrFactory: $xhrFactoryProvider,
  2627. $jsonpCallbacks: $jsonpCallbacksProvider,
  2628. $location: $LocationProvider,
  2629. $log: $LogProvider,
  2630. $parse: $ParseProvider,
  2631. $rootScope: $RootScopeProvider,
  2632. $q: $QProvider,
  2633. $$q: $$QProvider,
  2634. $sce: $SceProvider,
  2635. $sceDelegate: $SceDelegateProvider,
  2636. $sniffer: $SnifferProvider,
  2637. $templateCache: $TemplateCacheProvider,
  2638. $templateRequest: $TemplateRequestProvider,
  2639. $$testability: $$TestabilityProvider,
  2640. $timeout: $TimeoutProvider,
  2641. $window: $WindowProvider,
  2642. $$rAF: $$RAFProvider,
  2643. $$jqLite: $$jqLiteProvider,
  2644. $$Map: $$MapProvider,
  2645. $$cookieReader: $$CookieReaderProvider
  2646. });
  2647. }
  2648. ])
  2649. .info({ angularVersion: '1.6.7' });
  2650. }
  2651. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2652. * Any commits to this file should be reviewed with security in mind. *
  2653. * Changes to this file can potentially create security vulnerabilities. *
  2654. * An approval from 2 Core members with history of modifying *
  2655. * this file is required. *
  2656. * *
  2657. * Does the change somehow allow for arbitrary javascript to be executed? *
  2658. * Or allows for someone to change the prototype of built-in objects? *
  2659. * Or gives undesired access to variables likes document or window? *
  2660. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2661. /* global
  2662. JQLitePrototype: true,
  2663. BOOLEAN_ATTR: true,
  2664. ALIASED_ATTR: true
  2665. */
  2666. //////////////////////////////////
  2667. //JQLite
  2668. //////////////////////////////////
  2669. /**
  2670. * @ngdoc function
  2671. * @name angular.element
  2672. * @module ng
  2673. * @kind function
  2674. *
  2675. * @description
  2676. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2677. *
  2678. * If jQuery is available, `angular.element` is an alias for the
  2679. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2680. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
  2681. *
  2682. * jqLite is a tiny, API-compatible subset of jQuery that allows
  2683. * Angular to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
  2684. * commonly needed functionality with the goal of having a very small footprint.
  2685. *
  2686. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
  2687. * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
  2688. * specific version of jQuery if multiple versions exist on the page.
  2689. *
  2690. * <div class="alert alert-info">**Note:** All element references in Angular are always wrapped with jQuery or
  2691. * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div>
  2692. *
  2693. * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements
  2694. * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
  2695. * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.</div>
  2696. *
  2697. * ## Angular's jqLite
  2698. * jqLite provides only the following jQuery methods:
  2699. *
  2700. * - [`addClass()`](http://api.jquery.com/addClass/) - Does not support a function as first argument
  2701. * - [`after()`](http://api.jquery.com/after/)
  2702. * - [`append()`](http://api.jquery.com/append/)
  2703. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2704. * - [`bind()`](http://api.jquery.com/bind/) (_deprecated_, use [`on()`](http://api.jquery.com/on/)) - Does not support namespaces, selectors or eventData
  2705. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2706. * - [`clone()`](http://api.jquery.com/clone/)
  2707. * - [`contents()`](http://api.jquery.com/contents/)
  2708. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
  2709. * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
  2710. * - [`data()`](http://api.jquery.com/data/)
  2711. * - [`detach()`](http://api.jquery.com/detach/)
  2712. * - [`empty()`](http://api.jquery.com/empty/)
  2713. * - [`eq()`](http://api.jquery.com/eq/)
  2714. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2715. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2716. * - [`html()`](http://api.jquery.com/html/)
  2717. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2718. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2719. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
  2720. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2721. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2722. * - [`prepend()`](http://api.jquery.com/prepend/)
  2723. * - [`prop()`](http://api.jquery.com/prop/)
  2724. * - [`ready()`](http://api.jquery.com/ready/) (_deprecated_, use `angular.element(callback)` instead of `angular.element(document).ready(callback)`)
  2725. * - [`remove()`](http://api.jquery.com/remove/)
  2726. * - [`removeAttr()`](http://api.jquery.com/removeAttr/) - Does not support multiple attributes
  2727. * - [`removeClass()`](http://api.jquery.com/removeClass/) - Does not support a function as first argument
  2728. * - [`removeData()`](http://api.jquery.com/removeData/)
  2729. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2730. * - [`text()`](http://api.jquery.com/text/)
  2731. * - [`toggleClass()`](http://api.jquery.com/toggleClass/) - Does not support a function as first argument
  2732. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers
  2733. * - [`unbind()`](http://api.jquery.com/unbind/) (_deprecated_, use [`off()`](http://api.jquery.com/off/)) - Does not support namespaces or event object as parameter
  2734. * - [`val()`](http://api.jquery.com/val/)
  2735. * - [`wrap()`](http://api.jquery.com/wrap/)
  2736. *
  2737. * ## jQuery/jqLite Extras
  2738. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2739. *
  2740. * ### Events
  2741. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2742. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2743. * element before it is removed.
  2744. *
  2745. * ### Methods
  2746. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2747. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2748. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2749. * `'ngModel'`).
  2750. * - `injector()` - retrieves the injector of the current element or its parent.
  2751. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2752. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2753. * be enabled.
  2754. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2755. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2756. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2757. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2758. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2759. * parent element is reached.
  2760. *
  2761. * @knownIssue You cannot spy on `angular.element` if you are using Jasmine version 1.x. See
  2762. * https://github.com/angular/angular.js/issues/14251 for more information.
  2763. *
  2764. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2765. * @returns {Object} jQuery object.
  2766. */
  2767. JQLite.expando = 'ng339';
  2768. var jqCache = JQLite.cache = {},
  2769. jqId = 1;
  2770. /*
  2771. * !!! This is an undocumented "private" function !!!
  2772. */
  2773. JQLite._data = function(node) {
  2774. //jQuery always returns an object on cache miss
  2775. return this.cache[node[this.expando]] || {};
  2776. };
  2777. function jqNextId() { return ++jqId; }
  2778. var DASH_LOWERCASE_REGEXP = /-([a-z])/g;
  2779. var MS_HACK_REGEXP = /^-ms-/;
  2780. var MOUSE_EVENT_MAP = { mouseleave: 'mouseout', mouseenter: 'mouseover' };
  2781. var jqLiteMinErr = minErr('jqLite');
  2782. /**
  2783. * Converts kebab-case to camelCase.
  2784. * There is also a special case for the ms prefix starting with a lowercase letter.
  2785. * @param name Name to normalize
  2786. */
  2787. function cssKebabToCamel(name) {
  2788. return kebabToCamel(name.replace(MS_HACK_REGEXP, 'ms-'));
  2789. }
  2790. function fnCamelCaseReplace(all, letter) {
  2791. return letter.toUpperCase();
  2792. }
  2793. /**
  2794. * Converts kebab-case to camelCase.
  2795. * @param name Name to normalize
  2796. */
  2797. function kebabToCamel(name) {
  2798. return name
  2799. .replace(DASH_LOWERCASE_REGEXP, fnCamelCaseReplace);
  2800. }
  2801. var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
  2802. var HTML_REGEXP = /<|&#?\w+;/;
  2803. var TAG_NAME_REGEXP = /<([\w:-]+)/;
  2804. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
  2805. var wrapMap = {
  2806. 'option': [1, '<select multiple="multiple">', '</select>'],
  2807. 'thead': [1, '<table>', '</table>'],
  2808. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2809. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2810. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2811. '_default': [0, '', '']
  2812. };
  2813. wrapMap.optgroup = wrapMap.option;
  2814. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2815. wrapMap.th = wrapMap.td;
  2816. function jqLiteIsTextNode(html) {
  2817. return !HTML_REGEXP.test(html);
  2818. }
  2819. function jqLiteAcceptsData(node) {
  2820. // The window object can accept data but has no nodeType
  2821. // Otherwise we are only interested in elements (1) and documents (9)
  2822. var nodeType = node.nodeType;
  2823. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2824. }
  2825. function jqLiteHasData(node) {
  2826. for (var key in jqCache[node.ng339]) {
  2827. return true;
  2828. }
  2829. return false;
  2830. }
  2831. function jqLiteBuildFragment(html, context) {
  2832. var tmp, tag, wrap,
  2833. fragment = context.createDocumentFragment(),
  2834. nodes = [], i;
  2835. if (jqLiteIsTextNode(html)) {
  2836. // Convert non-html into a text node
  2837. nodes.push(context.createTextNode(html));
  2838. } else {
  2839. // Convert html into DOM nodes
  2840. tmp = fragment.appendChild(context.createElement('div'));
  2841. tag = (TAG_NAME_REGEXP.exec(html) || ['', ''])[1].toLowerCase();
  2842. wrap = wrapMap[tag] || wrapMap._default;
  2843. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, '<$1></$2>') + wrap[2];
  2844. // Descend through wrappers to the right content
  2845. i = wrap[0];
  2846. while (i--) {
  2847. tmp = tmp.lastChild;
  2848. }
  2849. nodes = concat(nodes, tmp.childNodes);
  2850. tmp = fragment.firstChild;
  2851. tmp.textContent = '';
  2852. }
  2853. // Remove wrapper from fragment
  2854. fragment.textContent = '';
  2855. fragment.innerHTML = ''; // Clear inner HTML
  2856. forEach(nodes, function(node) {
  2857. fragment.appendChild(node);
  2858. });
  2859. return fragment;
  2860. }
  2861. function jqLiteParseHTML(html, context) {
  2862. context = context || window.document;
  2863. var parsed;
  2864. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2865. return [context.createElement(parsed[1])];
  2866. }
  2867. if ((parsed = jqLiteBuildFragment(html, context))) {
  2868. return parsed.childNodes;
  2869. }
  2870. return [];
  2871. }
  2872. function jqLiteWrapNode(node, wrapper) {
  2873. var parent = node.parentNode;
  2874. if (parent) {
  2875. parent.replaceChild(wrapper, node);
  2876. }
  2877. wrapper.appendChild(node);
  2878. }
  2879. // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
  2880. var jqLiteContains = window.Node.prototype.contains || /** @this */ function(arg) {
  2881. // eslint-disable-next-line no-bitwise
  2882. return !!(this.compareDocumentPosition(arg) & 16);
  2883. };
  2884. /////////////////////////////////////////////
  2885. function JQLite(element) {
  2886. if (element instanceof JQLite) {
  2887. return element;
  2888. }
  2889. var argIsString;
  2890. if (isString(element)) {
  2891. element = trim(element);
  2892. argIsString = true;
  2893. }
  2894. if (!(this instanceof JQLite)) {
  2895. if (argIsString && element.charAt(0) !== '<') {
  2896. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2897. }
  2898. return new JQLite(element);
  2899. }
  2900. if (argIsString) {
  2901. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2902. } else if (isFunction(element)) {
  2903. jqLiteReady(element);
  2904. } else {
  2905. jqLiteAddNodes(this, element);
  2906. }
  2907. }
  2908. function jqLiteClone(element) {
  2909. return element.cloneNode(true);
  2910. }
  2911. function jqLiteDealoc(element, onlyDescendants) {
  2912. if (!onlyDescendants && jqLiteAcceptsData(element)) jqLite.cleanData([element]);
  2913. if (element.querySelectorAll) {
  2914. jqLite.cleanData(element.querySelectorAll('*'));
  2915. }
  2916. }
  2917. function jqLiteOff(element, type, fn, unsupported) {
  2918. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2919. var expandoStore = jqLiteExpandoStore(element);
  2920. var events = expandoStore && expandoStore.events;
  2921. var handle = expandoStore && expandoStore.handle;
  2922. if (!handle) return; //no listeners registered
  2923. if (!type) {
  2924. for (type in events) {
  2925. if (type !== '$destroy') {
  2926. element.removeEventListener(type, handle);
  2927. }
  2928. delete events[type];
  2929. }
  2930. } else {
  2931. var removeHandler = function(type) {
  2932. var listenerFns = events[type];
  2933. if (isDefined(fn)) {
  2934. arrayRemove(listenerFns || [], fn);
  2935. }
  2936. if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
  2937. element.removeEventListener(type, handle);
  2938. delete events[type];
  2939. }
  2940. };
  2941. forEach(type.split(' '), function(type) {
  2942. removeHandler(type);
  2943. if (MOUSE_EVENT_MAP[type]) {
  2944. removeHandler(MOUSE_EVENT_MAP[type]);
  2945. }
  2946. });
  2947. }
  2948. }
  2949. function jqLiteRemoveData(element, name) {
  2950. var expandoId = element.ng339;
  2951. var expandoStore = expandoId && jqCache[expandoId];
  2952. if (expandoStore) {
  2953. if (name) {
  2954. delete expandoStore.data[name];
  2955. return;
  2956. }
  2957. if (expandoStore.handle) {
  2958. if (expandoStore.events.$destroy) {
  2959. expandoStore.handle({}, '$destroy');
  2960. }
  2961. jqLiteOff(element);
  2962. }
  2963. delete jqCache[expandoId];
  2964. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2965. }
  2966. }
  2967. function jqLiteExpandoStore(element, createIfNecessary) {
  2968. var expandoId = element.ng339,
  2969. expandoStore = expandoId && jqCache[expandoId];
  2970. if (createIfNecessary && !expandoStore) {
  2971. element.ng339 = expandoId = jqNextId();
  2972. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2973. }
  2974. return expandoStore;
  2975. }
  2976. function jqLiteData(element, key, value) {
  2977. if (jqLiteAcceptsData(element)) {
  2978. var prop;
  2979. var isSimpleSetter = isDefined(value);
  2980. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2981. var massGetter = !key;
  2982. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2983. var data = expandoStore && expandoStore.data;
  2984. if (isSimpleSetter) { // data('key', value)
  2985. data[kebabToCamel(key)] = value;
  2986. } else {
  2987. if (massGetter) { // data()
  2988. return data;
  2989. } else {
  2990. if (isSimpleGetter) { // data('key')
  2991. // don't force creation of expandoStore if it doesn't exist yet
  2992. return data && data[kebabToCamel(key)];
  2993. } else { // mass-setter: data({key1: val1, key2: val2})
  2994. for (prop in key) {
  2995. data[kebabToCamel(prop)] = key[prop];
  2996. }
  2997. }
  2998. }
  2999. }
  3000. }
  3001. }
  3002. function jqLiteHasClass(element, selector) {
  3003. if (!element.getAttribute) return false;
  3004. return ((' ' + (element.getAttribute('class') || '') + ' ').replace(/[\n\t]/g, ' ').
  3005. indexOf(' ' + selector + ' ') > -1);
  3006. }
  3007. function jqLiteRemoveClass(element, cssClasses) {
  3008. if (cssClasses && element.setAttribute) {
  3009. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  3010. .replace(/[\n\t]/g, ' ');
  3011. var newClasses = existingClasses;
  3012. forEach(cssClasses.split(' '), function(cssClass) {
  3013. cssClass = trim(cssClass);
  3014. newClasses = newClasses.replace(' ' + cssClass + ' ', ' ');
  3015. });
  3016. if (newClasses !== existingClasses) {
  3017. element.setAttribute('class', trim(newClasses));
  3018. }
  3019. }
  3020. }
  3021. function jqLiteAddClass(element, cssClasses) {
  3022. if (cssClasses && element.setAttribute) {
  3023. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  3024. .replace(/[\n\t]/g, ' ');
  3025. var newClasses = existingClasses;
  3026. forEach(cssClasses.split(' '), function(cssClass) {
  3027. cssClass = trim(cssClass);
  3028. if (newClasses.indexOf(' ' + cssClass + ' ') === -1) {
  3029. newClasses += cssClass + ' ';
  3030. }
  3031. });
  3032. if (newClasses !== existingClasses) {
  3033. element.setAttribute('class', trim(newClasses));
  3034. }
  3035. }
  3036. }
  3037. function jqLiteAddNodes(root, elements) {
  3038. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  3039. if (elements) {
  3040. // if a Node (the most common case)
  3041. if (elements.nodeType) {
  3042. root[root.length++] = elements;
  3043. } else {
  3044. var length = elements.length;
  3045. // if an Array or NodeList and not a Window
  3046. if (typeof length === 'number' && elements.window !== elements) {
  3047. if (length) {
  3048. for (var i = 0; i < length; i++) {
  3049. root[root.length++] = elements[i];
  3050. }
  3051. }
  3052. } else {
  3053. root[root.length++] = elements;
  3054. }
  3055. }
  3056. }
  3057. }
  3058. function jqLiteController(element, name) {
  3059. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  3060. }
  3061. function jqLiteInheritedData(element, name, value) {
  3062. // if element is the document object work with the html element instead
  3063. // this makes $(document).scope() possible
  3064. if (element.nodeType === NODE_TYPE_DOCUMENT) {
  3065. element = element.documentElement;
  3066. }
  3067. var names = isArray(name) ? name : [name];
  3068. while (element) {
  3069. for (var i = 0, ii = names.length; i < ii; i++) {
  3070. if (isDefined(value = jqLite.data(element, names[i]))) return value;
  3071. }
  3072. // If dealing with a document fragment node with a host element, and no parent, use the host
  3073. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  3074. // to lookup parent controllers.
  3075. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  3076. }
  3077. }
  3078. function jqLiteEmpty(element) {
  3079. jqLiteDealoc(element, true);
  3080. while (element.firstChild) {
  3081. element.removeChild(element.firstChild);
  3082. }
  3083. }
  3084. function jqLiteRemove(element, keepData) {
  3085. if (!keepData) jqLiteDealoc(element);
  3086. var parent = element.parentNode;
  3087. if (parent) parent.removeChild(element);
  3088. }
  3089. function jqLiteDocumentLoaded(action, win) {
  3090. win = win || window;
  3091. if (win.document.readyState === 'complete') {
  3092. // Force the action to be run async for consistent behavior
  3093. // from the action's point of view
  3094. // i.e. it will definitely not be in a $apply
  3095. win.setTimeout(action);
  3096. } else {
  3097. // No need to unbind this handler as load is only ever called once
  3098. jqLite(win).on('load', action);
  3099. }
  3100. }
  3101. function jqLiteReady(fn) {
  3102. function trigger() {
  3103. window.document.removeEventListener('DOMContentLoaded', trigger);
  3104. window.removeEventListener('load', trigger);
  3105. fn();
  3106. }
  3107. // check if document is already loaded
  3108. if (window.document.readyState === 'complete') {
  3109. window.setTimeout(fn);
  3110. } else {
  3111. // We can not use jqLite since we are not done loading and jQuery could be loaded later.
  3112. // Works for modern browsers and IE9
  3113. window.document.addEventListener('DOMContentLoaded', trigger);
  3114. // Fallback to window.onload for others
  3115. window.addEventListener('load', trigger);
  3116. }
  3117. }
  3118. //////////////////////////////////////////
  3119. // Functions which are declared directly.
  3120. //////////////////////////////////////////
  3121. var JQLitePrototype = JQLite.prototype = {
  3122. ready: jqLiteReady,
  3123. toString: function() {
  3124. var value = [];
  3125. forEach(this, function(e) { value.push('' + e);});
  3126. return '[' + value.join(', ') + ']';
  3127. },
  3128. eq: function(index) {
  3129. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  3130. },
  3131. length: 0,
  3132. push: push,
  3133. sort: [].sort,
  3134. splice: [].splice
  3135. };
  3136. //////////////////////////////////////////
  3137. // Functions iterating getter/setters.
  3138. // these functions return self on setter and
  3139. // value on get.
  3140. //////////////////////////////////////////
  3141. var BOOLEAN_ATTR = {};
  3142. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  3143. BOOLEAN_ATTR[lowercase(value)] = value;
  3144. });
  3145. var BOOLEAN_ELEMENTS = {};
  3146. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  3147. BOOLEAN_ELEMENTS[value] = true;
  3148. });
  3149. var ALIASED_ATTR = {
  3150. 'ngMinlength': 'minlength',
  3151. 'ngMaxlength': 'maxlength',
  3152. 'ngMin': 'min',
  3153. 'ngMax': 'max',
  3154. 'ngPattern': 'pattern',
  3155. 'ngStep': 'step'
  3156. };
  3157. function getBooleanAttrName(element, name) {
  3158. // check dom last since we will most likely fail on name
  3159. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  3160. // booleanAttr is here twice to minimize DOM access
  3161. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  3162. }
  3163. function getAliasedAttrName(name) {
  3164. return ALIASED_ATTR[name];
  3165. }
  3166. forEach({
  3167. data: jqLiteData,
  3168. removeData: jqLiteRemoveData,
  3169. hasData: jqLiteHasData,
  3170. cleanData: function jqLiteCleanData(nodes) {
  3171. for (var i = 0, ii = nodes.length; i < ii; i++) {
  3172. jqLiteRemoveData(nodes[i]);
  3173. }
  3174. }
  3175. }, function(fn, name) {
  3176. JQLite[name] = fn;
  3177. });
  3178. forEach({
  3179. data: jqLiteData,
  3180. inheritedData: jqLiteInheritedData,
  3181. scope: function(element) {
  3182. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  3183. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  3184. },
  3185. isolateScope: function(element) {
  3186. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  3187. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  3188. },
  3189. controller: jqLiteController,
  3190. injector: function(element) {
  3191. return jqLiteInheritedData(element, '$injector');
  3192. },
  3193. removeAttr: function(element, name) {
  3194. element.removeAttribute(name);
  3195. },
  3196. hasClass: jqLiteHasClass,
  3197. css: function(element, name, value) {
  3198. name = cssKebabToCamel(name);
  3199. if (isDefined(value)) {
  3200. element.style[name] = value;
  3201. } else {
  3202. return element.style[name];
  3203. }
  3204. },
  3205. attr: function(element, name, value) {
  3206. var ret;
  3207. var nodeType = element.nodeType;
  3208. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT ||
  3209. !element.getAttribute) {
  3210. return;
  3211. }
  3212. var lowercasedName = lowercase(name);
  3213. var isBooleanAttr = BOOLEAN_ATTR[lowercasedName];
  3214. if (isDefined(value)) {
  3215. // setter
  3216. if (value === null || (value === false && isBooleanAttr)) {
  3217. element.removeAttribute(name);
  3218. } else {
  3219. element.setAttribute(name, isBooleanAttr ? lowercasedName : value);
  3220. }
  3221. } else {
  3222. // getter
  3223. ret = element.getAttribute(name);
  3224. if (isBooleanAttr && ret !== null) {
  3225. ret = lowercasedName;
  3226. }
  3227. // Normalize non-existing attributes to undefined (as jQuery).
  3228. return ret === null ? undefined : ret;
  3229. }
  3230. },
  3231. prop: function(element, name, value) {
  3232. if (isDefined(value)) {
  3233. element[name] = value;
  3234. } else {
  3235. return element[name];
  3236. }
  3237. },
  3238. text: (function() {
  3239. getText.$dv = '';
  3240. return getText;
  3241. function getText(element, value) {
  3242. if (isUndefined(value)) {
  3243. var nodeType = element.nodeType;
  3244. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  3245. }
  3246. element.textContent = value;
  3247. }
  3248. })(),
  3249. val: function(element, value) {
  3250. if (isUndefined(value)) {
  3251. if (element.multiple && nodeName_(element) === 'select') {
  3252. var result = [];
  3253. forEach(element.options, function(option) {
  3254. if (option.selected) {
  3255. result.push(option.value || option.text);
  3256. }
  3257. });
  3258. return result;
  3259. }
  3260. return element.value;
  3261. }
  3262. element.value = value;
  3263. },
  3264. html: function(element, value) {
  3265. if (isUndefined(value)) {
  3266. return element.innerHTML;
  3267. }
  3268. jqLiteDealoc(element, true);
  3269. element.innerHTML = value;
  3270. },
  3271. empty: jqLiteEmpty
  3272. }, function(fn, name) {
  3273. /**
  3274. * Properties: writes return selection, reads return first value
  3275. */
  3276. JQLite.prototype[name] = function(arg1, arg2) {
  3277. var i, key;
  3278. var nodeCount = this.length;
  3279. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  3280. // in a way that survives minification.
  3281. // jqLiteEmpty takes no arguments but is a setter.
  3282. if (fn !== jqLiteEmpty &&
  3283. (isUndefined((fn.length === 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
  3284. if (isObject(arg1)) {
  3285. // we are a write, but the object properties are the key/values
  3286. for (i = 0; i < nodeCount; i++) {
  3287. if (fn === jqLiteData) {
  3288. // data() takes the whole object in jQuery
  3289. fn(this[i], arg1);
  3290. } else {
  3291. for (key in arg1) {
  3292. fn(this[i], key, arg1[key]);
  3293. }
  3294. }
  3295. }
  3296. // return self for chaining
  3297. return this;
  3298. } else {
  3299. // we are a read, so read the first child.
  3300. // TODO: do we still need this?
  3301. var value = fn.$dv;
  3302. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  3303. var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
  3304. for (var j = 0; j < jj; j++) {
  3305. var nodeValue = fn(this[j], arg1, arg2);
  3306. value = value ? value + nodeValue : nodeValue;
  3307. }
  3308. return value;
  3309. }
  3310. } else {
  3311. // we are a write, so apply to all children
  3312. for (i = 0; i < nodeCount; i++) {
  3313. fn(this[i], arg1, arg2);
  3314. }
  3315. // return self for chaining
  3316. return this;
  3317. }
  3318. };
  3319. });
  3320. function createEventHandler(element, events) {
  3321. var eventHandler = function(event, type) {
  3322. // jQuery specific api
  3323. event.isDefaultPrevented = function() {
  3324. return event.defaultPrevented;
  3325. };
  3326. var eventFns = events[type || event.type];
  3327. var eventFnsLength = eventFns ? eventFns.length : 0;
  3328. if (!eventFnsLength) return;
  3329. if (isUndefined(event.immediatePropagationStopped)) {
  3330. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  3331. event.stopImmediatePropagation = function() {
  3332. event.immediatePropagationStopped = true;
  3333. if (event.stopPropagation) {
  3334. event.stopPropagation();
  3335. }
  3336. if (originalStopImmediatePropagation) {
  3337. originalStopImmediatePropagation.call(event);
  3338. }
  3339. };
  3340. }
  3341. event.isImmediatePropagationStopped = function() {
  3342. return event.immediatePropagationStopped === true;
  3343. };
  3344. // Some events have special handlers that wrap the real handler
  3345. var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
  3346. // Copy event handlers in case event handlers array is modified during execution.
  3347. if ((eventFnsLength > 1)) {
  3348. eventFns = shallowCopy(eventFns);
  3349. }
  3350. for (var i = 0; i < eventFnsLength; i++) {
  3351. if (!event.isImmediatePropagationStopped()) {
  3352. handlerWrapper(element, event, eventFns[i]);
  3353. }
  3354. }
  3355. };
  3356. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  3357. // events on `element`
  3358. eventHandler.elem = element;
  3359. return eventHandler;
  3360. }
  3361. function defaultHandlerWrapper(element, event, handler) {
  3362. handler.call(element, event);
  3363. }
  3364. function specialMouseHandlerWrapper(target, event, handler) {
  3365. // Refer to jQuery's implementation of mouseenter & mouseleave
  3366. // Read about mouseenter and mouseleave:
  3367. // http://www.quirksmode.org/js/events_mouse.html#link8
  3368. var related = event.relatedTarget;
  3369. // For mousenter/leave call the handler if related is outside the target.
  3370. // NB: No relatedTarget if the mouse left/entered the browser window
  3371. if (!related || (related !== target && !jqLiteContains.call(target, related))) {
  3372. handler.call(target, event);
  3373. }
  3374. }
  3375. //////////////////////////////////////////
  3376. // Functions iterating traversal.
  3377. // These functions chain results into a single
  3378. // selector.
  3379. //////////////////////////////////////////
  3380. forEach({
  3381. removeData: jqLiteRemoveData,
  3382. on: function jqLiteOn(element, type, fn, unsupported) {
  3383. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  3384. // Do not add event handlers to non-elements because they will not be cleaned up.
  3385. if (!jqLiteAcceptsData(element)) {
  3386. return;
  3387. }
  3388. var expandoStore = jqLiteExpandoStore(element, true);
  3389. var events = expandoStore.events;
  3390. var handle = expandoStore.handle;
  3391. if (!handle) {
  3392. handle = expandoStore.handle = createEventHandler(element, events);
  3393. }
  3394. // http://jsperf.com/string-indexof-vs-split
  3395. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  3396. var i = types.length;
  3397. var addHandler = function(type, specialHandlerWrapper, noEventListener) {
  3398. var eventFns = events[type];
  3399. if (!eventFns) {
  3400. eventFns = events[type] = [];
  3401. eventFns.specialHandlerWrapper = specialHandlerWrapper;
  3402. if (type !== '$destroy' && !noEventListener) {
  3403. element.addEventListener(type, handle);
  3404. }
  3405. }
  3406. eventFns.push(fn);
  3407. };
  3408. while (i--) {
  3409. type = types[i];
  3410. if (MOUSE_EVENT_MAP[type]) {
  3411. addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
  3412. addHandler(type, undefined, true);
  3413. } else {
  3414. addHandler(type);
  3415. }
  3416. }
  3417. },
  3418. off: jqLiteOff,
  3419. one: function(element, type, fn) {
  3420. element = jqLite(element);
  3421. //add the listener twice so that when it is called
  3422. //you can remove the original function and still be
  3423. //able to call element.off(ev, fn) normally
  3424. element.on(type, function onFn() {
  3425. element.off(type, fn);
  3426. element.off(type, onFn);
  3427. });
  3428. element.on(type, fn);
  3429. },
  3430. replaceWith: function(element, replaceNode) {
  3431. var index, parent = element.parentNode;
  3432. jqLiteDealoc(element);
  3433. forEach(new JQLite(replaceNode), function(node) {
  3434. if (index) {
  3435. parent.insertBefore(node, index.nextSibling);
  3436. } else {
  3437. parent.replaceChild(node, element);
  3438. }
  3439. index = node;
  3440. });
  3441. },
  3442. children: function(element) {
  3443. var children = [];
  3444. forEach(element.childNodes, function(element) {
  3445. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3446. children.push(element);
  3447. }
  3448. });
  3449. return children;
  3450. },
  3451. contents: function(element) {
  3452. return element.contentDocument || element.childNodes || [];
  3453. },
  3454. append: function(element, node) {
  3455. var nodeType = element.nodeType;
  3456. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  3457. node = new JQLite(node);
  3458. for (var i = 0, ii = node.length; i < ii; i++) {
  3459. var child = node[i];
  3460. element.appendChild(child);
  3461. }
  3462. },
  3463. prepend: function(element, node) {
  3464. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3465. var index = element.firstChild;
  3466. forEach(new JQLite(node), function(child) {
  3467. element.insertBefore(child, index);
  3468. });
  3469. }
  3470. },
  3471. wrap: function(element, wrapNode) {
  3472. jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);
  3473. },
  3474. remove: jqLiteRemove,
  3475. detach: function(element) {
  3476. jqLiteRemove(element, true);
  3477. },
  3478. after: function(element, newElement) {
  3479. var index = element, parent = element.parentNode;
  3480. if (parent) {
  3481. newElement = new JQLite(newElement);
  3482. for (var i = 0, ii = newElement.length; i < ii; i++) {
  3483. var node = newElement[i];
  3484. parent.insertBefore(node, index.nextSibling);
  3485. index = node;
  3486. }
  3487. }
  3488. },
  3489. addClass: jqLiteAddClass,
  3490. removeClass: jqLiteRemoveClass,
  3491. toggleClass: function(element, selector, condition) {
  3492. if (selector) {
  3493. forEach(selector.split(' '), function(className) {
  3494. var classCondition = condition;
  3495. if (isUndefined(classCondition)) {
  3496. classCondition = !jqLiteHasClass(element, className);
  3497. }
  3498. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  3499. });
  3500. }
  3501. },
  3502. parent: function(element) {
  3503. var parent = element.parentNode;
  3504. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  3505. },
  3506. next: function(element) {
  3507. return element.nextElementSibling;
  3508. },
  3509. find: function(element, selector) {
  3510. if (element.getElementsByTagName) {
  3511. return element.getElementsByTagName(selector);
  3512. } else {
  3513. return [];
  3514. }
  3515. },
  3516. clone: jqLiteClone,
  3517. triggerHandler: function(element, event, extraParameters) {
  3518. var dummyEvent, eventFnsCopy, handlerArgs;
  3519. var eventName = event.type || event;
  3520. var expandoStore = jqLiteExpandoStore(element);
  3521. var events = expandoStore && expandoStore.events;
  3522. var eventFns = events && events[eventName];
  3523. if (eventFns) {
  3524. // Create a dummy event to pass to the handlers
  3525. dummyEvent = {
  3526. preventDefault: function() { this.defaultPrevented = true; },
  3527. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  3528. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  3529. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  3530. stopPropagation: noop,
  3531. type: eventName,
  3532. target: element
  3533. };
  3534. // If a custom event was provided then extend our dummy event with it
  3535. if (event.type) {
  3536. dummyEvent = extend(dummyEvent, event);
  3537. }
  3538. // Copy event handlers in case event handlers array is modified during execution.
  3539. eventFnsCopy = shallowCopy(eventFns);
  3540. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  3541. forEach(eventFnsCopy, function(fn) {
  3542. if (!dummyEvent.isImmediatePropagationStopped()) {
  3543. fn.apply(element, handlerArgs);
  3544. }
  3545. });
  3546. }
  3547. }
  3548. }, function(fn, name) {
  3549. /**
  3550. * chaining functions
  3551. */
  3552. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  3553. var value;
  3554. for (var i = 0, ii = this.length; i < ii; i++) {
  3555. if (isUndefined(value)) {
  3556. value = fn(this[i], arg1, arg2, arg3);
  3557. if (isDefined(value)) {
  3558. // any function which returns a value needs to be wrapped
  3559. value = jqLite(value);
  3560. }
  3561. } else {
  3562. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  3563. }
  3564. }
  3565. return isDefined(value) ? value : this;
  3566. };
  3567. });
  3568. // bind legacy bind/unbind to on/off
  3569. JQLite.prototype.bind = JQLite.prototype.on;
  3570. JQLite.prototype.unbind = JQLite.prototype.off;
  3571. // Provider for private $$jqLite service
  3572. /** @this */
  3573. function $$jqLiteProvider() {
  3574. this.$get = function $$jqLite() {
  3575. return extend(JQLite, {
  3576. hasClass: function(node, classes) {
  3577. if (node.attr) node = node[0];
  3578. return jqLiteHasClass(node, classes);
  3579. },
  3580. addClass: function(node, classes) {
  3581. if (node.attr) node = node[0];
  3582. return jqLiteAddClass(node, classes);
  3583. },
  3584. removeClass: function(node, classes) {
  3585. if (node.attr) node = node[0];
  3586. return jqLiteRemoveClass(node, classes);
  3587. }
  3588. });
  3589. };
  3590. }
  3591. /**
  3592. * Computes a hash of an 'obj'.
  3593. * Hash of a:
  3594. * string is string
  3595. * number is number as string
  3596. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  3597. * that is also assigned to the $$hashKey property of the object.
  3598. *
  3599. * @param obj
  3600. * @returns {string} hash string such that the same input will have the same hash string.
  3601. * The resulting string key is in 'type:hashKey' format.
  3602. */
  3603. function hashKey(obj, nextUidFn) {
  3604. var key = obj && obj.$$hashKey;
  3605. if (key) {
  3606. if (typeof key === 'function') {
  3607. key = obj.$$hashKey();
  3608. }
  3609. return key;
  3610. }
  3611. var objType = typeof obj;
  3612. if (objType === 'function' || (objType === 'object' && obj !== null)) {
  3613. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  3614. } else {
  3615. key = objType + ':' + obj;
  3616. }
  3617. return key;
  3618. }
  3619. // A minimal ES2015 Map implementation.
  3620. // Should be bug/feature equivalent to the native implementations of supported browsers
  3621. // (for the features required in Angular).
  3622. // See https://kangax.github.io/compat-table/es6/#test-Map
  3623. var nanKey = Object.create(null);
  3624. function NgMapShim() {
  3625. this._keys = [];
  3626. this._values = [];
  3627. this._lastKey = NaN;
  3628. this._lastIndex = -1;
  3629. }
  3630. NgMapShim.prototype = {
  3631. _idx: function(key) {
  3632. if (key === this._lastKey) {
  3633. return this._lastIndex;
  3634. }
  3635. this._lastKey = key;
  3636. this._lastIndex = this._keys.indexOf(key);
  3637. return this._lastIndex;
  3638. },
  3639. _transformKey: function(key) {
  3640. return isNumberNaN(key) ? nanKey : key;
  3641. },
  3642. get: function(key) {
  3643. key = this._transformKey(key);
  3644. var idx = this._idx(key);
  3645. if (idx !== -1) {
  3646. return this._values[idx];
  3647. }
  3648. },
  3649. set: function(key, value) {
  3650. key = this._transformKey(key);
  3651. var idx = this._idx(key);
  3652. if (idx === -1) {
  3653. idx = this._lastIndex = this._keys.length;
  3654. }
  3655. this._keys[idx] = key;
  3656. this._values[idx] = value;
  3657. // Support: IE11
  3658. // Do not `return this` to simulate the partial IE11 implementation
  3659. },
  3660. delete: function(key) {
  3661. key = this._transformKey(key);
  3662. var idx = this._idx(key);
  3663. if (idx === -1) {
  3664. return false;
  3665. }
  3666. this._keys.splice(idx, 1);
  3667. this._values.splice(idx, 1);
  3668. this._lastKey = NaN;
  3669. this._lastIndex = -1;
  3670. return true;
  3671. }
  3672. };
  3673. // For now, always use `NgMapShim`, even if `window.Map` is available. Some native implementations
  3674. // are still buggy (often in subtle ways) and can cause hard-to-debug failures. When native `Map`
  3675. // implementations get more stable, we can reconsider switching to `window.Map` (when available).
  3676. var NgMap = NgMapShim;
  3677. var $$MapProvider = [/** @this */function() {
  3678. this.$get = [function() {
  3679. return NgMap;
  3680. }];
  3681. }];
  3682. /**
  3683. * @ngdoc function
  3684. * @module ng
  3685. * @name angular.injector
  3686. * @kind function
  3687. *
  3688. * @description
  3689. * Creates an injector object that can be used for retrieving services as well as for
  3690. * dependency injection (see {@link guide/di dependency injection}).
  3691. *
  3692. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3693. * {@link angular.module}. The `ng` module must be explicitly added.
  3694. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3695. * disallows argument name annotation inference.
  3696. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3697. *
  3698. * @example
  3699. * Typical usage
  3700. * ```js
  3701. * // create an injector
  3702. * var $injector = angular.injector(['ng']);
  3703. *
  3704. * // use the injector to kick off your application
  3705. * // use the type inference to auto inject arguments, or use implicit injection
  3706. * $injector.invoke(function($rootScope, $compile, $document) {
  3707. * $compile($document)($rootScope);
  3708. * $rootScope.$digest();
  3709. * });
  3710. * ```
  3711. *
  3712. * Sometimes you want to get access to the injector of a currently running Angular app
  3713. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  3714. * application has been bootstrapped. You can do this using the extra `injector()` added
  3715. * to JQuery/jqLite elements. See {@link angular.element}.
  3716. *
  3717. * *This is fairly rare but could be the case if a third party library is injecting the
  3718. * markup.*
  3719. *
  3720. * In the following example a new block of HTML containing a `ng-controller`
  3721. * directive is added to the end of the document body by JQuery. We then compile and link
  3722. * it into the current AngularJS scope.
  3723. *
  3724. * ```js
  3725. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3726. * $(document.body).append($div);
  3727. *
  3728. * angular.element(document).injector().invoke(function($compile) {
  3729. * var scope = angular.element($div).scope();
  3730. * $compile($div)(scope);
  3731. * });
  3732. * ```
  3733. */
  3734. /**
  3735. * @ngdoc module
  3736. * @name auto
  3737. * @installation
  3738. * @description
  3739. *
  3740. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3741. */
  3742. var ARROW_ARG = /^([^(]+?)=>/;
  3743. var FN_ARGS = /^[^(]*\(\s*([^)]*)\)/m;
  3744. var FN_ARG_SPLIT = /,/;
  3745. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3746. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3747. var $injectorMinErr = minErr('$injector');
  3748. function stringifyFn(fn) {
  3749. return Function.prototype.toString.call(fn);
  3750. }
  3751. function extractArgs(fn) {
  3752. var fnText = stringifyFn(fn).replace(STRIP_COMMENTS, ''),
  3753. args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
  3754. return args;
  3755. }
  3756. function anonFn(fn) {
  3757. // For anonymous functions, showing at the very least the function signature can help in
  3758. // debugging.
  3759. var args = extractArgs(fn);
  3760. if (args) {
  3761. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3762. }
  3763. return 'fn';
  3764. }
  3765. function annotate(fn, strictDi, name) {
  3766. var $inject,
  3767. argDecl,
  3768. last;
  3769. if (typeof fn === 'function') {
  3770. if (!($inject = fn.$inject)) {
  3771. $inject = [];
  3772. if (fn.length) {
  3773. if (strictDi) {
  3774. if (!isString(name) || !name) {
  3775. name = fn.name || anonFn(fn);
  3776. }
  3777. throw $injectorMinErr('strictdi',
  3778. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3779. }
  3780. argDecl = extractArgs(fn);
  3781. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3782. arg.replace(FN_ARG, function(all, underscore, name) {
  3783. $inject.push(name);
  3784. });
  3785. });
  3786. }
  3787. fn.$inject = $inject;
  3788. }
  3789. } else if (isArray(fn)) {
  3790. last = fn.length - 1;
  3791. assertArgFn(fn[last], 'fn');
  3792. $inject = fn.slice(0, last);
  3793. } else {
  3794. assertArgFn(fn, 'fn', true);
  3795. }
  3796. return $inject;
  3797. }
  3798. ///////////////////////////////////////
  3799. /**
  3800. * @ngdoc service
  3801. * @name $injector
  3802. *
  3803. * @description
  3804. *
  3805. * `$injector` is used to retrieve object instances as defined by
  3806. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3807. * and load modules.
  3808. *
  3809. * The following always holds true:
  3810. *
  3811. * ```js
  3812. * var $injector = angular.injector();
  3813. * expect($injector.get('$injector')).toBe($injector);
  3814. * expect($injector.invoke(function($injector) {
  3815. * return $injector;
  3816. * })).toBe($injector);
  3817. * ```
  3818. *
  3819. * ## Injection Function Annotation
  3820. *
  3821. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3822. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3823. *
  3824. * ```js
  3825. * // inferred (only works if code not minified/obfuscated)
  3826. * $injector.invoke(function(serviceA){});
  3827. *
  3828. * // annotated
  3829. * function explicit(serviceA) {};
  3830. * explicit.$inject = ['serviceA'];
  3831. * $injector.invoke(explicit);
  3832. *
  3833. * // inline
  3834. * $injector.invoke(['serviceA', function(serviceA){}]);
  3835. * ```
  3836. *
  3837. * ### Inference
  3838. *
  3839. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3840. * can then be parsed and the function arguments can be extracted. This method of discovering
  3841. * annotations is disallowed when the injector is in strict mode.
  3842. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3843. * argument names.
  3844. *
  3845. * ### `$inject` Annotation
  3846. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3847. *
  3848. * ### Inline
  3849. * As an array of injection names, where the last item in the array is the function to call.
  3850. */
  3851. /**
  3852. * @ngdoc property
  3853. * @name $injector#modules
  3854. * @type {Object}
  3855. * @description
  3856. * A hash containing all the modules that have been loaded into the
  3857. * $injector.
  3858. *
  3859. * You can use this property to find out information about a module via the
  3860. * {@link angular.Module#info `myModule.info(...)`} method.
  3861. *
  3862. * For example:
  3863. *
  3864. * ```
  3865. * var info = $injector.modules['ngAnimate'].info();
  3866. * ```
  3867. *
  3868. * **Do not use this property to attempt to modify the modules after the application
  3869. * has been bootstrapped.**
  3870. */
  3871. /**
  3872. * @ngdoc method
  3873. * @name $injector#get
  3874. *
  3875. * @description
  3876. * Return an instance of the service.
  3877. *
  3878. * @param {string} name The name of the instance to retrieve.
  3879. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  3880. * @return {*} The instance.
  3881. */
  3882. /**
  3883. * @ngdoc method
  3884. * @name $injector#invoke
  3885. *
  3886. * @description
  3887. * Invoke the method and supply the method arguments from the `$injector`.
  3888. *
  3889. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  3890. * injected according to the {@link guide/di $inject Annotation} rules.
  3891. * @param {Object=} self The `this` for the invoked method.
  3892. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3893. * object first, before the `$injector` is consulted.
  3894. * @returns {*} the value returned by the invoked `fn` function.
  3895. */
  3896. /**
  3897. * @ngdoc method
  3898. * @name $injector#has
  3899. *
  3900. * @description
  3901. * Allows the user to query if the particular service exists.
  3902. *
  3903. * @param {string} name Name of the service to query.
  3904. * @returns {boolean} `true` if injector has given service.
  3905. */
  3906. /**
  3907. * @ngdoc method
  3908. * @name $injector#instantiate
  3909. * @description
  3910. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3911. * operator, and supplies all of the arguments to the constructor function as specified by the
  3912. * constructor annotation.
  3913. *
  3914. * @param {Function} Type Annotated constructor function.
  3915. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3916. * object first, before the `$injector` is consulted.
  3917. * @returns {Object} new instance of `Type`.
  3918. */
  3919. /**
  3920. * @ngdoc method
  3921. * @name $injector#annotate
  3922. *
  3923. * @description
  3924. * Returns an array of service names which the function is requesting for injection. This API is
  3925. * used by the injector to determine which services need to be injected into the function when the
  3926. * function is invoked. There are three ways in which the function can be annotated with the needed
  3927. * dependencies.
  3928. *
  3929. * #### Argument names
  3930. *
  3931. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3932. * by converting the function into a string using `toString()` method and extracting the argument
  3933. * names.
  3934. * ```js
  3935. * // Given
  3936. * function MyController($scope, $route) {
  3937. * // ...
  3938. * }
  3939. *
  3940. * // Then
  3941. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3942. * ```
  3943. *
  3944. * You can disallow this method by using strict injection mode.
  3945. *
  3946. * This method does not work with code minification / obfuscation. For this reason the following
  3947. * annotation strategies are supported.
  3948. *
  3949. * #### The `$inject` property
  3950. *
  3951. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3952. * represent names of services to be injected into the function.
  3953. * ```js
  3954. * // Given
  3955. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3956. * // ...
  3957. * }
  3958. * // Define function dependencies
  3959. * MyController['$inject'] = ['$scope', '$route'];
  3960. *
  3961. * // Then
  3962. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3963. * ```
  3964. *
  3965. * #### The array notation
  3966. *
  3967. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3968. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3969. * a way that survives minification is a better choice:
  3970. *
  3971. * ```js
  3972. * // We wish to write this (not minification / obfuscation safe)
  3973. * injector.invoke(function($compile, $rootScope) {
  3974. * // ...
  3975. * });
  3976. *
  3977. * // We are forced to write break inlining
  3978. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3979. * // ...
  3980. * };
  3981. * tmpFn.$inject = ['$compile', '$rootScope'];
  3982. * injector.invoke(tmpFn);
  3983. *
  3984. * // To better support inline function the inline annotation is supported
  3985. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3986. * // ...
  3987. * }]);
  3988. *
  3989. * // Therefore
  3990. * expect(injector.annotate(
  3991. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3992. * ).toEqual(['$compile', '$rootScope']);
  3993. * ```
  3994. *
  3995. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3996. * be retrieved as described above.
  3997. *
  3998. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3999. *
  4000. * @returns {Array.<string>} The names of the services which the function requires.
  4001. */
  4002. /**
  4003. * @ngdoc method
  4004. * @name $injector#loadNewModules
  4005. *
  4006. * @description
  4007. *
  4008. * **This is a dangerous API, which you use at your own risk!**
  4009. *
  4010. * Add the specified modules to the current injector.
  4011. *
  4012. * This method will add each of the injectables to the injector and execute all of the config and run
  4013. * blocks for each module passed to the method.
  4014. *
  4015. * If a module has already been loaded into the injector then it will not be loaded again.
  4016. *
  4017. * * The application developer is responsible for loading the code containing the modules; and for
  4018. * ensuring that lazy scripts are not downloaded and executed more often that desired.
  4019. * * Previously compiled HTML will not be affected by newly loaded directives, filters and components.
  4020. * * Modules cannot be unloaded.
  4021. *
  4022. * You can use {@link $injector#modules `$injector.modules`} to check whether a module has been loaded
  4023. * into the injector, which may indicate whether the script has been executed already.
  4024. *
  4025. * @example
  4026. * Here is an example of loading a bundle of modules, with a utility method called `getScript`:
  4027. *
  4028. * ```javascript
  4029. * app.factory('loadModule', function($injector) {
  4030. * return function loadModule(moduleName, bundleUrl) {
  4031. * return getScript(bundleUrl).then(function() { $injector.loadNewModules([moduleName]); });
  4032. * };
  4033. * })
  4034. * ```
  4035. *
  4036. * @param {Array<String|Function|Array>=} mods an array of modules to load into the application.
  4037. * Each item in the array should be the name of a predefined module or a (DI annotated)
  4038. * function that will be invoked by the injector as a `config` block.
  4039. * See: {@link angular.module modules}
  4040. */
  4041. /**
  4042. * @ngdoc service
  4043. * @name $provide
  4044. *
  4045. * @description
  4046. *
  4047. * The {@link auto.$provide $provide} service has a number of methods for registering components
  4048. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  4049. * {@link angular.Module}.
  4050. *
  4051. * An Angular **service** is a singleton object created by a **service factory**. These **service
  4052. * factories** are functions which, in turn, are created by a **service provider**.
  4053. * The **service providers** are constructor functions. When instantiated they must contain a
  4054. * property called `$get`, which holds the **service factory** function.
  4055. *
  4056. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  4057. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  4058. * function to get the instance of the **service**.
  4059. *
  4060. * Often services have no configuration options and there is no need to add methods to the service
  4061. * provider. The provider will be no more than a constructor function with a `$get` property. For
  4062. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  4063. * services without specifying a provider.
  4064. *
  4065. * * {@link auto.$provide#provider provider(name, provider)} - registers a **service provider** with the
  4066. * {@link auto.$injector $injector}
  4067. * * {@link auto.$provide#constant constant(name, obj)} - registers a value/object that can be accessed by
  4068. * providers and services.
  4069. * * {@link auto.$provide#value value(name, obj)} - registers a value/object that can only be accessed by
  4070. * services, not providers.
  4071. * * {@link auto.$provide#factory factory(name, fn)} - registers a service **factory function**
  4072. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  4073. * given factory function.
  4074. * * {@link auto.$provide#service service(name, Fn)} - registers a **constructor function**
  4075. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  4076. * a new object using the given constructor function.
  4077. * * {@link auto.$provide#decorator decorator(name, decorFn)} - registers a **decorator function** that
  4078. * will be able to modify or replace the implementation of another service.
  4079. *
  4080. * See the individual methods for more information and examples.
  4081. */
  4082. /**
  4083. * @ngdoc method
  4084. * @name $provide#provider
  4085. * @description
  4086. *
  4087. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  4088. * are constructor functions, whose instances are responsible for "providing" a factory for a
  4089. * service.
  4090. *
  4091. * Service provider names start with the name of the service they provide followed by `Provider`.
  4092. * For example, the {@link ng.$log $log} service has a provider called
  4093. * {@link ng.$logProvider $logProvider}.
  4094. *
  4095. * Service provider objects can have additional methods which allow configuration of the provider
  4096. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  4097. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  4098. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  4099. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  4100. * console or not.
  4101. *
  4102. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  4103. 'Provider'` key.
  4104. * @param {(Object|function())} provider If the provider is:
  4105. *
  4106. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  4107. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  4108. * - `Constructor`: a new instance of the provider will be created using
  4109. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  4110. *
  4111. * @returns {Object} registered provider instance
  4112. * @example
  4113. *
  4114. * The following example shows how to create a simple event tracking service and register it using
  4115. * {@link auto.$provide#provider $provide.provider()}.
  4116. *
  4117. * ```js
  4118. * // Define the eventTracker provider
  4119. * function EventTrackerProvider() {
  4120. * var trackingUrl = '/track';
  4121. *
  4122. * // A provider method for configuring where the tracked events should been saved
  4123. * this.setTrackingUrl = function(url) {
  4124. * trackingUrl = url;
  4125. * };
  4126. *
  4127. * // The service factory function
  4128. * this.$get = ['$http', function($http) {
  4129. * var trackedEvents = {};
  4130. * return {
  4131. * // Call this to track an event
  4132. * event: function(event) {
  4133. * var count = trackedEvents[event] || 0;
  4134. * count += 1;
  4135. * trackedEvents[event] = count;
  4136. * return count;
  4137. * },
  4138. * // Call this to save the tracked events to the trackingUrl
  4139. * save: function() {
  4140. * $http.post(trackingUrl, trackedEvents);
  4141. * }
  4142. * };
  4143. * }];
  4144. * }
  4145. *
  4146. * describe('eventTracker', function() {
  4147. * var postSpy;
  4148. *
  4149. * beforeEach(module(function($provide) {
  4150. * // Register the eventTracker provider
  4151. * $provide.provider('eventTracker', EventTrackerProvider);
  4152. * }));
  4153. *
  4154. * beforeEach(module(function(eventTrackerProvider) {
  4155. * // Configure eventTracker provider
  4156. * eventTrackerProvider.setTrackingUrl('/custom-track');
  4157. * }));
  4158. *
  4159. * it('tracks events', inject(function(eventTracker) {
  4160. * expect(eventTracker.event('login')).toEqual(1);
  4161. * expect(eventTracker.event('login')).toEqual(2);
  4162. * }));
  4163. *
  4164. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  4165. * postSpy = spyOn($http, 'post');
  4166. * eventTracker.event('login');
  4167. * eventTracker.save();
  4168. * expect(postSpy).toHaveBeenCalled();
  4169. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  4170. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  4171. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  4172. * }));
  4173. * });
  4174. * ```
  4175. */
  4176. /**
  4177. * @ngdoc method
  4178. * @name $provide#factory
  4179. * @description
  4180. *
  4181. * Register a **service factory**, which will be called to return the service instance.
  4182. * This is short for registering a service where its provider consists of only a `$get` property,
  4183. * which is the given service factory function.
  4184. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  4185. * configure your service in a provider.
  4186. *
  4187. * @param {string} name The name of the instance.
  4188. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  4189. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  4190. * @returns {Object} registered provider instance
  4191. *
  4192. * @example
  4193. * Here is an example of registering a service
  4194. * ```js
  4195. * $provide.factory('ping', ['$http', function($http) {
  4196. * return function ping() {
  4197. * return $http.send('/ping');
  4198. * };
  4199. * }]);
  4200. * ```
  4201. * You would then inject and use this service like this:
  4202. * ```js
  4203. * someModule.controller('Ctrl', ['ping', function(ping) {
  4204. * ping();
  4205. * }]);
  4206. * ```
  4207. */
  4208. /**
  4209. * @ngdoc method
  4210. * @name $provide#service
  4211. * @description
  4212. *
  4213. * Register a **service constructor**, which will be invoked with `new` to create the service
  4214. * instance.
  4215. * This is short for registering a service where its provider's `$get` property is a factory
  4216. * function that returns an instance instantiated by the injector from the service constructor
  4217. * function.
  4218. *
  4219. * Internally it looks a bit like this:
  4220. *
  4221. * ```
  4222. * {
  4223. * $get: function() {
  4224. * return $injector.instantiate(constructor);
  4225. * }
  4226. * }
  4227. * ```
  4228. *
  4229. *
  4230. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  4231. * as a type/class.
  4232. *
  4233. * @param {string} name The name of the instance.
  4234. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  4235. * that will be instantiated.
  4236. * @returns {Object} registered provider instance
  4237. *
  4238. * @example
  4239. * Here is an example of registering a service using
  4240. * {@link auto.$provide#service $provide.service(class)}.
  4241. * ```js
  4242. * var Ping = function($http) {
  4243. * this.$http = $http;
  4244. * };
  4245. *
  4246. * Ping.$inject = ['$http'];
  4247. *
  4248. * Ping.prototype.send = function() {
  4249. * return this.$http.get('/ping');
  4250. * };
  4251. * $provide.service('ping', Ping);
  4252. * ```
  4253. * You would then inject and use this service like this:
  4254. * ```js
  4255. * someModule.controller('Ctrl', ['ping', function(ping) {
  4256. * ping.send();
  4257. * }]);
  4258. * ```
  4259. */
  4260. /**
  4261. * @ngdoc method
  4262. * @name $provide#value
  4263. * @description
  4264. *
  4265. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  4266. * number, an array, an object or a function. This is short for registering a service where its
  4267. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  4268. * service**. That also means it is not possible to inject other services into a value service.
  4269. *
  4270. * Value services are similar to constant services, except that they cannot be injected into a
  4271. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  4272. * an Angular {@link auto.$provide#decorator decorator}.
  4273. *
  4274. * @param {string} name The name of the instance.
  4275. * @param {*} value The value.
  4276. * @returns {Object} registered provider instance
  4277. *
  4278. * @example
  4279. * Here are some examples of creating value services.
  4280. * ```js
  4281. * $provide.value('ADMIN_USER', 'admin');
  4282. *
  4283. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  4284. *
  4285. * $provide.value('halfOf', function(value) {
  4286. * return value / 2;
  4287. * });
  4288. * ```
  4289. */
  4290. /**
  4291. * @ngdoc method
  4292. * @name $provide#constant
  4293. * @description
  4294. *
  4295. * Register a **constant service** with the {@link auto.$injector $injector}, such as a string,
  4296. * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not
  4297. * possible to inject other services into a constant.
  4298. *
  4299. * But unlike {@link auto.$provide#value value}, a constant can be
  4300. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  4301. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  4302. *
  4303. * @param {string} name The name of the constant.
  4304. * @param {*} value The constant value.
  4305. * @returns {Object} registered instance
  4306. *
  4307. * @example
  4308. * Here a some examples of creating constants:
  4309. * ```js
  4310. * $provide.constant('SHARD_HEIGHT', 306);
  4311. *
  4312. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  4313. *
  4314. * $provide.constant('double', function(value) {
  4315. * return value * 2;
  4316. * });
  4317. * ```
  4318. */
  4319. /**
  4320. * @ngdoc method
  4321. * @name $provide#decorator
  4322. * @description
  4323. *
  4324. * Register a **decorator function** with the {@link auto.$injector $injector}. A decorator function
  4325. * intercepts the creation of a service, allowing it to override or modify the behavior of the
  4326. * service. The return value of the decorator function may be the original service, or a new service
  4327. * that replaces (or wraps and delegates to) the original service.
  4328. *
  4329. * You can find out more about using decorators in the {@link guide/decorators} guide.
  4330. *
  4331. * @param {string} name The name of the service to decorate.
  4332. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  4333. * provided and should return the decorated service instance. The function is called using
  4334. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  4335. * Local injection arguments:
  4336. *
  4337. * * `$delegate` - The original service instance, which can be replaced, monkey patched, configured,
  4338. * decorated or delegated to.
  4339. *
  4340. * @example
  4341. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  4342. * calls to {@link ng.$log#error $log.warn()}.
  4343. * ```js
  4344. * $provide.decorator('$log', ['$delegate', function($delegate) {
  4345. * $delegate.warn = $delegate.error;
  4346. * return $delegate;
  4347. * }]);
  4348. * ```
  4349. */
  4350. function createInjector(modulesToLoad, strictDi) {
  4351. strictDi = (strictDi === true);
  4352. var INSTANTIATING = {},
  4353. providerSuffix = 'Provider',
  4354. path = [],
  4355. loadedModules = new NgMap(),
  4356. providerCache = {
  4357. $provide: {
  4358. provider: supportObject(provider),
  4359. factory: supportObject(factory),
  4360. service: supportObject(service),
  4361. value: supportObject(value),
  4362. constant: supportObject(constant),
  4363. decorator: decorator
  4364. }
  4365. },
  4366. providerInjector = (providerCache.$injector =
  4367. createInternalInjector(providerCache, function(serviceName, caller) {
  4368. if (angular.isString(caller)) {
  4369. path.push(caller);
  4370. }
  4371. throw $injectorMinErr('unpr', 'Unknown provider: {0}', path.join(' <- '));
  4372. })),
  4373. instanceCache = {},
  4374. protoInstanceInjector =
  4375. createInternalInjector(instanceCache, function(serviceName, caller) {
  4376. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  4377. return instanceInjector.invoke(
  4378. provider.$get, provider, undefined, serviceName);
  4379. }),
  4380. instanceInjector = protoInstanceInjector;
  4381. providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
  4382. instanceInjector.modules = providerInjector.modules = createMap();
  4383. var runBlocks = loadModules(modulesToLoad);
  4384. instanceInjector = protoInstanceInjector.get('$injector');
  4385. instanceInjector.strictDi = strictDi;
  4386. forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
  4387. instanceInjector.loadNewModules = function(mods) {
  4388. forEach(loadModules(mods), function(fn) { if (fn) instanceInjector.invoke(fn); });
  4389. };
  4390. return instanceInjector;
  4391. ////////////////////////////////////
  4392. // $provider
  4393. ////////////////////////////////////
  4394. function supportObject(delegate) {
  4395. return function(key, value) {
  4396. if (isObject(key)) {
  4397. forEach(key, reverseParams(delegate));
  4398. } else {
  4399. return delegate(key, value);
  4400. }
  4401. };
  4402. }
  4403. function provider(name, provider_) {
  4404. assertNotHasOwnProperty(name, 'service');
  4405. if (isFunction(provider_) || isArray(provider_)) {
  4406. provider_ = providerInjector.instantiate(provider_);
  4407. }
  4408. if (!provider_.$get) {
  4409. throw $injectorMinErr('pget', 'Provider \'{0}\' must define $get factory method.', name);
  4410. }
  4411. return (providerCache[name + providerSuffix] = provider_);
  4412. }
  4413. function enforceReturnValue(name, factory) {
  4414. return /** @this */ function enforcedReturnValue() {
  4415. var result = instanceInjector.invoke(factory, this);
  4416. if (isUndefined(result)) {
  4417. throw $injectorMinErr('undef', 'Provider \'{0}\' must return a value from $get factory method.', name);
  4418. }
  4419. return result;
  4420. };
  4421. }
  4422. function factory(name, factoryFn, enforce) {
  4423. return provider(name, {
  4424. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  4425. });
  4426. }
  4427. function service(name, constructor) {
  4428. return factory(name, ['$injector', function($injector) {
  4429. return $injector.instantiate(constructor);
  4430. }]);
  4431. }
  4432. function value(name, val) { return factory(name, valueFn(val), false); }
  4433. function constant(name, value) {
  4434. assertNotHasOwnProperty(name, 'constant');
  4435. providerCache[name] = value;
  4436. instanceCache[name] = value;
  4437. }
  4438. function decorator(serviceName, decorFn) {
  4439. var origProvider = providerInjector.get(serviceName + providerSuffix),
  4440. orig$get = origProvider.$get;
  4441. origProvider.$get = function() {
  4442. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  4443. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  4444. };
  4445. }
  4446. ////////////////////////////////////
  4447. // Module Loading
  4448. ////////////////////////////////////
  4449. function loadModules(modulesToLoad) {
  4450. assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
  4451. var runBlocks = [], moduleFn;
  4452. forEach(modulesToLoad, function(module) {
  4453. if (loadedModules.get(module)) return;
  4454. loadedModules.set(module, true);
  4455. function runInvokeQueue(queue) {
  4456. var i, ii;
  4457. for (i = 0, ii = queue.length; i < ii; i++) {
  4458. var invokeArgs = queue[i],
  4459. provider = providerInjector.get(invokeArgs[0]);
  4460. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  4461. }
  4462. }
  4463. try {
  4464. if (isString(module)) {
  4465. moduleFn = angularModule(module);
  4466. instanceInjector.modules[module] = moduleFn;
  4467. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  4468. runInvokeQueue(moduleFn._invokeQueue);
  4469. runInvokeQueue(moduleFn._configBlocks);
  4470. } else if (isFunction(module)) {
  4471. runBlocks.push(providerInjector.invoke(module));
  4472. } else if (isArray(module)) {
  4473. runBlocks.push(providerInjector.invoke(module));
  4474. } else {
  4475. assertArgFn(module, 'module');
  4476. }
  4477. } catch (e) {
  4478. if (isArray(module)) {
  4479. module = module[module.length - 1];
  4480. }
  4481. if (e.message && e.stack && e.stack.indexOf(e.message) === -1) {
  4482. // Safari & FF's stack traces don't contain error.message content
  4483. // unlike those of Chrome and IE
  4484. // So if stack doesn't contain message, we create a new string that contains both.
  4485. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  4486. // eslint-disable-next-line no-ex-assign
  4487. e = e.message + '\n' + e.stack;
  4488. }
  4489. throw $injectorMinErr('modulerr', 'Failed to instantiate module {0} due to:\n{1}',
  4490. module, e.stack || e.message || e);
  4491. }
  4492. });
  4493. return runBlocks;
  4494. }
  4495. ////////////////////////////////////
  4496. // internal Injector
  4497. ////////////////////////////////////
  4498. function createInternalInjector(cache, factory) {
  4499. function getService(serviceName, caller) {
  4500. if (cache.hasOwnProperty(serviceName)) {
  4501. if (cache[serviceName] === INSTANTIATING) {
  4502. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  4503. serviceName + ' <- ' + path.join(' <- '));
  4504. }
  4505. return cache[serviceName];
  4506. } else {
  4507. try {
  4508. path.unshift(serviceName);
  4509. cache[serviceName] = INSTANTIATING;
  4510. cache[serviceName] = factory(serviceName, caller);
  4511. return cache[serviceName];
  4512. } catch (err) {
  4513. if (cache[serviceName] === INSTANTIATING) {
  4514. delete cache[serviceName];
  4515. }
  4516. throw err;
  4517. } finally {
  4518. path.shift();
  4519. }
  4520. }
  4521. }
  4522. function injectionArgs(fn, locals, serviceName) {
  4523. var args = [],
  4524. $inject = createInjector.$$annotate(fn, strictDi, serviceName);
  4525. for (var i = 0, length = $inject.length; i < length; i++) {
  4526. var key = $inject[i];
  4527. if (typeof key !== 'string') {
  4528. throw $injectorMinErr('itkn',
  4529. 'Incorrect injection token! Expected service name as string, got {0}', key);
  4530. }
  4531. args.push(locals && locals.hasOwnProperty(key) ? locals[key] :
  4532. getService(key, serviceName));
  4533. }
  4534. return args;
  4535. }
  4536. function isClass(func) {
  4537. // Support: IE 9-11 only
  4538. // IE 9-11 do not support classes and IE9 leaks with the code below.
  4539. if (msie || typeof func !== 'function') {
  4540. return false;
  4541. }
  4542. var result = func.$$ngIsClass;
  4543. if (!isBoolean(result)) {
  4544. // Support: Edge 12-13 only
  4545. // See: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/6156135/
  4546. result = func.$$ngIsClass = /^(?:class\b|constructor\()/.test(stringifyFn(func));
  4547. }
  4548. return result;
  4549. }
  4550. function invoke(fn, self, locals, serviceName) {
  4551. if (typeof locals === 'string') {
  4552. serviceName = locals;
  4553. locals = null;
  4554. }
  4555. var args = injectionArgs(fn, locals, serviceName);
  4556. if (isArray(fn)) {
  4557. fn = fn[fn.length - 1];
  4558. }
  4559. if (!isClass(fn)) {
  4560. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  4561. // #5388
  4562. return fn.apply(self, args);
  4563. } else {
  4564. args.unshift(null);
  4565. return new (Function.prototype.bind.apply(fn, args))();
  4566. }
  4567. }
  4568. function instantiate(Type, locals, serviceName) {
  4569. // Check if Type is annotated and use just the given function at n-1 as parameter
  4570. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  4571. var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
  4572. var args = injectionArgs(Type, locals, serviceName);
  4573. // Empty object at position 0 is ignored for invocation with `new`, but required.
  4574. args.unshift(null);
  4575. return new (Function.prototype.bind.apply(ctor, args))();
  4576. }
  4577. return {
  4578. invoke: invoke,
  4579. instantiate: instantiate,
  4580. get: getService,
  4581. annotate: createInjector.$$annotate,
  4582. has: function(name) {
  4583. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  4584. }
  4585. };
  4586. }
  4587. }
  4588. createInjector.$$annotate = annotate;
  4589. /**
  4590. * @ngdoc provider
  4591. * @name $anchorScrollProvider
  4592. * @this
  4593. *
  4594. * @description
  4595. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  4596. * {@link ng.$location#hash $location.hash()} changes.
  4597. */
  4598. function $AnchorScrollProvider() {
  4599. var autoScrollingEnabled = true;
  4600. /**
  4601. * @ngdoc method
  4602. * @name $anchorScrollProvider#disableAutoScrolling
  4603. *
  4604. * @description
  4605. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  4606. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  4607. * Use this method to disable automatic scrolling.
  4608. *
  4609. * If automatic scrolling is disabled, one must explicitly call
  4610. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  4611. * current hash.
  4612. */
  4613. this.disableAutoScrolling = function() {
  4614. autoScrollingEnabled = false;
  4615. };
  4616. /**
  4617. * @ngdoc service
  4618. * @name $anchorScroll
  4619. * @kind function
  4620. * @requires $window
  4621. * @requires $location
  4622. * @requires $rootScope
  4623. *
  4624. * @description
  4625. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  4626. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  4627. * in the
  4628. * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#an-indicated-part-of-the-document).
  4629. *
  4630. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  4631. * match any anchor whenever it changes. This can be disabled by calling
  4632. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  4633. *
  4634. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  4635. * vertical scroll-offset (either fixed or dynamic).
  4636. *
  4637. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  4638. * {@link ng.$location#hash $location.hash()} will be used.
  4639. *
  4640. * @property {(number|function|jqLite)} yOffset
  4641. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  4642. * positioned elements at the top of the page, such as navbars, headers etc.
  4643. *
  4644. * `yOffset` can be specified in various ways:
  4645. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  4646. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  4647. * a number representing the offset (in pixels).<br /><br />
  4648. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  4649. * the top of the page to the element's bottom will be used as offset.<br />
  4650. * **Note**: The element will be taken into account only as long as its `position` is set to
  4651. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  4652. * their height and/or positioning according to the viewport's size.
  4653. *
  4654. * <br />
  4655. * <div class="alert alert-warning">
  4656. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  4657. * not some child element.
  4658. * </div>
  4659. *
  4660. * @example
  4661. <example module="anchorScrollExample" name="anchor-scroll">
  4662. <file name="index.html">
  4663. <div id="scrollArea" ng-controller="ScrollController">
  4664. <a ng-click="gotoBottom()">Go to bottom</a>
  4665. <a id="bottom"></a> You're at the bottom!
  4666. </div>
  4667. </file>
  4668. <file name="script.js">
  4669. angular.module('anchorScrollExample', [])
  4670. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  4671. function($scope, $location, $anchorScroll) {
  4672. $scope.gotoBottom = function() {
  4673. // set the location.hash to the id of
  4674. // the element you wish to scroll to.
  4675. $location.hash('bottom');
  4676. // call $anchorScroll()
  4677. $anchorScroll();
  4678. };
  4679. }]);
  4680. </file>
  4681. <file name="style.css">
  4682. #scrollArea {
  4683. height: 280px;
  4684. overflow: auto;
  4685. }
  4686. #bottom {
  4687. display: block;
  4688. margin-top: 2000px;
  4689. }
  4690. </file>
  4691. </example>
  4692. *
  4693. * <hr />
  4694. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  4695. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  4696. *
  4697. * @example
  4698. <example module="anchorScrollOffsetExample" name="anchor-scroll-offset">
  4699. <file name="index.html">
  4700. <div class="fixed-header" ng-controller="headerCtrl">
  4701. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  4702. Go to anchor {{x}}
  4703. </a>
  4704. </div>
  4705. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  4706. Anchor {{x}} of 5
  4707. </div>
  4708. </file>
  4709. <file name="script.js">
  4710. angular.module('anchorScrollOffsetExample', [])
  4711. .run(['$anchorScroll', function($anchorScroll) {
  4712. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  4713. }])
  4714. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  4715. function($anchorScroll, $location, $scope) {
  4716. $scope.gotoAnchor = function(x) {
  4717. var newHash = 'anchor' + x;
  4718. if ($location.hash() !== newHash) {
  4719. // set the $location.hash to `newHash` and
  4720. // $anchorScroll will automatically scroll to it
  4721. $location.hash('anchor' + x);
  4722. } else {
  4723. // call $anchorScroll() explicitly,
  4724. // since $location.hash hasn't changed
  4725. $anchorScroll();
  4726. }
  4727. };
  4728. }
  4729. ]);
  4730. </file>
  4731. <file name="style.css">
  4732. body {
  4733. padding-top: 50px;
  4734. }
  4735. .anchor {
  4736. border: 2px dashed DarkOrchid;
  4737. padding: 10px 10px 200px 10px;
  4738. }
  4739. .fixed-header {
  4740. background-color: rgba(0, 0, 0, 0.2);
  4741. height: 50px;
  4742. position: fixed;
  4743. top: 0; left: 0; right: 0;
  4744. }
  4745. .fixed-header > a {
  4746. display: inline-block;
  4747. margin: 5px 15px;
  4748. }
  4749. </file>
  4750. </example>
  4751. */
  4752. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  4753. var document = $window.document;
  4754. // Helper function to get first anchor from a NodeList
  4755. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  4756. // and working in all supported browsers.)
  4757. function getFirstAnchor(list) {
  4758. var result = null;
  4759. Array.prototype.some.call(list, function(element) {
  4760. if (nodeName_(element) === 'a') {
  4761. result = element;
  4762. return true;
  4763. }
  4764. });
  4765. return result;
  4766. }
  4767. function getYOffset() {
  4768. var offset = scroll.yOffset;
  4769. if (isFunction(offset)) {
  4770. offset = offset();
  4771. } else if (isElement(offset)) {
  4772. var elem = offset[0];
  4773. var style = $window.getComputedStyle(elem);
  4774. if (style.position !== 'fixed') {
  4775. offset = 0;
  4776. } else {
  4777. offset = elem.getBoundingClientRect().bottom;
  4778. }
  4779. } else if (!isNumber(offset)) {
  4780. offset = 0;
  4781. }
  4782. return offset;
  4783. }
  4784. function scrollTo(elem) {
  4785. if (elem) {
  4786. elem.scrollIntoView();
  4787. var offset = getYOffset();
  4788. if (offset) {
  4789. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  4790. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  4791. // top of the viewport.
  4792. //
  4793. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  4794. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  4795. // way down the page.
  4796. //
  4797. // This is often the case for elements near the bottom of the page.
  4798. //
  4799. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  4800. // the top of the element and the offset, which is enough to align the top of `elem` at the
  4801. // desired position.
  4802. var elemTop = elem.getBoundingClientRect().top;
  4803. $window.scrollBy(0, elemTop - offset);
  4804. }
  4805. } else {
  4806. $window.scrollTo(0, 0);
  4807. }
  4808. }
  4809. function scroll(hash) {
  4810. // Allow numeric hashes
  4811. hash = isString(hash) ? hash : isNumber(hash) ? hash.toString() : $location.hash();
  4812. var elm;
  4813. // empty hash, scroll to the top of the page
  4814. if (!hash) scrollTo(null);
  4815. // element with given id
  4816. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4817. // first anchor with given name :-D
  4818. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4819. // no element and hash === 'top', scroll to the top of the page
  4820. else if (hash === 'top') scrollTo(null);
  4821. }
  4822. // does not scroll when user clicks on anchor link that is currently on
  4823. // (no url change, no $location.hash() change), browser native does scroll
  4824. if (autoScrollingEnabled) {
  4825. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4826. function autoScrollWatchAction(newVal, oldVal) {
  4827. // skip the initial scroll if $location.hash is empty
  4828. if (newVal === oldVal && newVal === '') return;
  4829. jqLiteDocumentLoaded(function() {
  4830. $rootScope.$evalAsync(scroll);
  4831. });
  4832. });
  4833. }
  4834. return scroll;
  4835. }];
  4836. }
  4837. var $animateMinErr = minErr('$animate');
  4838. var ELEMENT_NODE = 1;
  4839. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  4840. function mergeClasses(a,b) {
  4841. if (!a && !b) return '';
  4842. if (!a) return b;
  4843. if (!b) return a;
  4844. if (isArray(a)) a = a.join(' ');
  4845. if (isArray(b)) b = b.join(' ');
  4846. return a + ' ' + b;
  4847. }
  4848. function extractElementNode(element) {
  4849. for (var i = 0; i < element.length; i++) {
  4850. var elm = element[i];
  4851. if (elm.nodeType === ELEMENT_NODE) {
  4852. return elm;
  4853. }
  4854. }
  4855. }
  4856. function splitClasses(classes) {
  4857. if (isString(classes)) {
  4858. classes = classes.split(' ');
  4859. }
  4860. // Use createMap() to prevent class assumptions involving property names in
  4861. // Object.prototype
  4862. var obj = createMap();
  4863. forEach(classes, function(klass) {
  4864. // sometimes the split leaves empty string values
  4865. // incase extra spaces were applied to the options
  4866. if (klass.length) {
  4867. obj[klass] = true;
  4868. }
  4869. });
  4870. return obj;
  4871. }
  4872. // if any other type of options value besides an Object value is
  4873. // passed into the $animate.method() animation then this helper code
  4874. // will be run which will ignore it. While this patch is not the
  4875. // greatest solution to this, a lot of existing plugins depend on
  4876. // $animate to either call the callback (< 1.2) or return a promise
  4877. // that can be changed. This helper function ensures that the options
  4878. // are wiped clean incase a callback function is provided.
  4879. function prepareAnimateOptions(options) {
  4880. return isObject(options)
  4881. ? options
  4882. : {};
  4883. }
  4884. var $$CoreAnimateJsProvider = /** @this */ function() {
  4885. this.$get = noop;
  4886. };
  4887. // this is prefixed with Core since it conflicts with
  4888. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  4889. var $$CoreAnimateQueueProvider = /** @this */ function() {
  4890. var postDigestQueue = new NgMap();
  4891. var postDigestElements = [];
  4892. this.$get = ['$$AnimateRunner', '$rootScope',
  4893. function($$AnimateRunner, $rootScope) {
  4894. return {
  4895. enabled: noop,
  4896. on: noop,
  4897. off: noop,
  4898. pin: noop,
  4899. push: function(element, event, options, domOperation) {
  4900. if (domOperation) {
  4901. domOperation();
  4902. }
  4903. options = options || {};
  4904. if (options.from) {
  4905. element.css(options.from);
  4906. }
  4907. if (options.to) {
  4908. element.css(options.to);
  4909. }
  4910. if (options.addClass || options.removeClass) {
  4911. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  4912. }
  4913. var runner = new $$AnimateRunner();
  4914. // since there are no animations to run the runner needs to be
  4915. // notified that the animation call is complete.
  4916. runner.complete();
  4917. return runner;
  4918. }
  4919. };
  4920. function updateData(data, classes, value) {
  4921. var changed = false;
  4922. if (classes) {
  4923. classes = isString(classes) ? classes.split(' ') :
  4924. isArray(classes) ? classes : [];
  4925. forEach(classes, function(className) {
  4926. if (className) {
  4927. changed = true;
  4928. data[className] = value;
  4929. }
  4930. });
  4931. }
  4932. return changed;
  4933. }
  4934. function handleCSSClassChanges() {
  4935. forEach(postDigestElements, function(element) {
  4936. var data = postDigestQueue.get(element);
  4937. if (data) {
  4938. var existing = splitClasses(element.attr('class'));
  4939. var toAdd = '';
  4940. var toRemove = '';
  4941. forEach(data, function(status, className) {
  4942. var hasClass = !!existing[className];
  4943. if (status !== hasClass) {
  4944. if (status) {
  4945. toAdd += (toAdd.length ? ' ' : '') + className;
  4946. } else {
  4947. toRemove += (toRemove.length ? ' ' : '') + className;
  4948. }
  4949. }
  4950. });
  4951. forEach(element, function(elm) {
  4952. if (toAdd) {
  4953. jqLiteAddClass(elm, toAdd);
  4954. }
  4955. if (toRemove) {
  4956. jqLiteRemoveClass(elm, toRemove);
  4957. }
  4958. });
  4959. postDigestQueue.delete(element);
  4960. }
  4961. });
  4962. postDigestElements.length = 0;
  4963. }
  4964. function addRemoveClassesPostDigest(element, add, remove) {
  4965. var data = postDigestQueue.get(element) || {};
  4966. var classesAdded = updateData(data, add, true);
  4967. var classesRemoved = updateData(data, remove, false);
  4968. if (classesAdded || classesRemoved) {
  4969. postDigestQueue.set(element, data);
  4970. postDigestElements.push(element);
  4971. if (postDigestElements.length === 1) {
  4972. $rootScope.$$postDigest(handleCSSClassChanges);
  4973. }
  4974. }
  4975. }
  4976. }];
  4977. };
  4978. /**
  4979. * @ngdoc provider
  4980. * @name $animateProvider
  4981. *
  4982. * @description
  4983. * Default implementation of $animate that doesn't perform any animations, instead just
  4984. * synchronously performs DOM updates and resolves the returned runner promise.
  4985. *
  4986. * In order to enable animations the `ngAnimate` module has to be loaded.
  4987. *
  4988. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  4989. */
  4990. var $AnimateProvider = ['$provide', /** @this */ function($provide) {
  4991. var provider = this;
  4992. var classNameFilter = null;
  4993. var customFilter = null;
  4994. this.$$registeredAnimations = Object.create(null);
  4995. /**
  4996. * @ngdoc method
  4997. * @name $animateProvider#register
  4998. *
  4999. * @description
  5000. * Registers a new injectable animation factory function. The factory function produces the
  5001. * animation object which contains callback functions for each event that is expected to be
  5002. * animated.
  5003. *
  5004. * * `eventFn`: `function(element, ... , doneFunction, options)`
  5005. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  5006. * on the type of animation additional arguments will be injected into the animation function. The
  5007. * list below explains the function signatures for the different animation methods:
  5008. *
  5009. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  5010. * - addClass: function(element, addedClasses, doneFunction, options)
  5011. * - removeClass: function(element, removedClasses, doneFunction, options)
  5012. * - enter, leave, move: function(element, doneFunction, options)
  5013. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  5014. *
  5015. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  5016. *
  5017. * ```js
  5018. * return {
  5019. * //enter, leave, move signature
  5020. * eventFn : function(element, done, options) {
  5021. * //code to run the animation
  5022. * //once complete, then run done()
  5023. * return function endFunction(wasCancelled) {
  5024. * //code to cancel the animation
  5025. * }
  5026. * }
  5027. * }
  5028. * ```
  5029. *
  5030. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  5031. * @param {Function} factory The factory function that will be executed to return the animation
  5032. * object.
  5033. */
  5034. this.register = function(name, factory) {
  5035. if (name && name.charAt(0) !== '.') {
  5036. throw $animateMinErr('notcsel', 'Expecting class selector starting with \'.\' got \'{0}\'.', name);
  5037. }
  5038. var key = name + '-animation';
  5039. provider.$$registeredAnimations[name.substr(1)] = key;
  5040. $provide.factory(key, factory);
  5041. };
  5042. /**
  5043. * @ngdoc method
  5044. * @name $animateProvider#customFilter
  5045. *
  5046. * @description
  5047. * Sets and/or returns the custom filter function that is used to "filter" animations, i.e.
  5048. * determine if an animation is allowed or not. When no filter is specified (the default), no
  5049. * animation will be blocked. Setting the `customFilter` value will only allow animations for
  5050. * which the filter function's return value is truthy.
  5051. *
  5052. * This allows to easily create arbitrarily complex rules for filtering animations, such as
  5053. * allowing specific events only, or enabling animations on specific subtrees of the DOM, etc.
  5054. * Filtering animations can also boost performance for low-powered devices, as well as
  5055. * applications containing a lot of structural operations.
  5056. *
  5057. * <div class="alert alert-success">
  5058. * **Best Practice:**
  5059. * Keep the filtering function as lean as possible, because it will be called for each DOM
  5060. * action (e.g. insertion, removal, class change) performed by "animation-aware" directives.
  5061. * See {@link guide/animations#which-directives-support-animations- here} for a list of built-in
  5062. * directives that support animations.
  5063. * Performing computationally expensive or time-consuming operations on each call of the
  5064. * filtering function can make your animations sluggish.
  5065. * </div>
  5066. *
  5067. * **Note:** If present, `customFilter` will be checked before
  5068. * {@link $animateProvider#classNameFilter classNameFilter}.
  5069. *
  5070. * @param {Function=} filterFn - The filter function which will be used to filter all animations.
  5071. * If a falsy value is returned, no animation will be performed. The function will be called
  5072. * with the following arguments:
  5073. * - **node** `{DOMElement}` - The DOM element to be animated.
  5074. * - **event** `{String}` - The name of the animation event (e.g. `enter`, `leave`, `addClass`
  5075. * etc).
  5076. * - **options** `{Object}` - A collection of options/styles used for the animation.
  5077. * @return {Function} The current filter function or `null` if there is none set.
  5078. */
  5079. this.customFilter = function(filterFn) {
  5080. if (arguments.length === 1) {
  5081. customFilter = isFunction(filterFn) ? filterFn : null;
  5082. }
  5083. return customFilter;
  5084. };
  5085. /**
  5086. * @ngdoc method
  5087. * @name $animateProvider#classNameFilter
  5088. *
  5089. * @description
  5090. * Sets and/or returns the CSS class regular expression that is checked when performing
  5091. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  5092. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  5093. * When setting the `classNameFilter` value, animations will only be performed on elements
  5094. * that successfully match the filter expression. This in turn can boost performance
  5095. * for low-powered devices as well as applications containing a lot of structural operations.
  5096. *
  5097. * **Note:** If present, `classNameFilter` will be checked after
  5098. * {@link $animateProvider#customFilter customFilter}. If `customFilter` is present and returns
  5099. * false, `classNameFilter` will not be checked.
  5100. *
  5101. * @param {RegExp=} expression The className expression which will be checked against all animations
  5102. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  5103. */
  5104. this.classNameFilter = function(expression) {
  5105. if (arguments.length === 1) {
  5106. classNameFilter = (expression instanceof RegExp) ? expression : null;
  5107. if (classNameFilter) {
  5108. var reservedRegex = new RegExp('[(\\s|\\/)]' + NG_ANIMATE_CLASSNAME + '[(\\s|\\/)]');
  5109. if (reservedRegex.test(classNameFilter.toString())) {
  5110. classNameFilter = null;
  5111. throw $animateMinErr('nongcls', '$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  5112. }
  5113. }
  5114. }
  5115. return classNameFilter;
  5116. };
  5117. this.$get = ['$$animateQueue', function($$animateQueue) {
  5118. function domInsert(element, parentElement, afterElement) {
  5119. // if for some reason the previous element was removed
  5120. // from the dom sometime before this code runs then let's
  5121. // just stick to using the parent element as the anchor
  5122. if (afterElement) {
  5123. var afterNode = extractElementNode(afterElement);
  5124. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  5125. afterElement = null;
  5126. }
  5127. }
  5128. if (afterElement) {
  5129. afterElement.after(element);
  5130. } else {
  5131. parentElement.prepend(element);
  5132. }
  5133. }
  5134. /**
  5135. * @ngdoc service
  5136. * @name $animate
  5137. * @description The $animate service exposes a series of DOM utility methods that provide support
  5138. * for animation hooks. The default behavior is the application of DOM operations, however,
  5139. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  5140. * to ensure that animation runs with the triggered DOM operation.
  5141. *
  5142. * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
  5143. * included and only when it is active then the animation hooks that `$animate` triggers will be
  5144. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  5145. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  5146. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  5147. *
  5148. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  5149. *
  5150. * To learn more about enabling animation support, click here to visit the
  5151. * {@link ngAnimate ngAnimate module page}.
  5152. */
  5153. return {
  5154. // we don't call it directly since non-existant arguments may
  5155. // be interpreted as null within the sub enabled function
  5156. /**
  5157. *
  5158. * @ngdoc method
  5159. * @name $animate#on
  5160. * @kind function
  5161. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  5162. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  5163. * is fired with the following params:
  5164. *
  5165. * ```js
  5166. * $animate.on('enter', container,
  5167. * function callback(element, phase) {
  5168. * // cool we detected an enter animation within the container
  5169. * }
  5170. * );
  5171. * ```
  5172. *
  5173. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  5174. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  5175. * as well as among its children
  5176. * @param {Function} callback the callback function that will be fired when the listener is triggered
  5177. *
  5178. * The arguments present in the callback function are:
  5179. * * `element` - The captured DOM element that the animation was fired on.
  5180. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  5181. */
  5182. on: $$animateQueue.on,
  5183. /**
  5184. *
  5185. * @ngdoc method
  5186. * @name $animate#off
  5187. * @kind function
  5188. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  5189. * can be used in three different ways depending on the arguments:
  5190. *
  5191. * ```js
  5192. * // remove all the animation event listeners listening for `enter`
  5193. * $animate.off('enter');
  5194. *
  5195. * // remove listeners for all animation events from the container element
  5196. * $animate.off(container);
  5197. *
  5198. * // remove all the animation event listeners listening for `enter` on the given element and its children
  5199. * $animate.off('enter', container);
  5200. *
  5201. * // remove the event listener function provided by `callback` that is set
  5202. * // to listen for `enter` on the given `container` as well as its children
  5203. * $animate.off('enter', container, callback);
  5204. * ```
  5205. *
  5206. * @param {string|DOMElement} event|container the animation event (e.g. enter, leave, move,
  5207. * addClass, removeClass, etc...), or the container element. If it is the element, all other
  5208. * arguments are ignored.
  5209. * @param {DOMElement=} container the container element the event listener was placed on
  5210. * @param {Function=} callback the callback function that was registered as the listener
  5211. */
  5212. off: $$animateQueue.off,
  5213. /**
  5214. * @ngdoc method
  5215. * @name $animate#pin
  5216. * @kind function
  5217. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  5218. * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
  5219. * element despite being outside the realm of the application or within another application. Say for example if the application
  5220. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  5221. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  5222. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  5223. *
  5224. * Note that this feature is only active when the `ngAnimate` module is used.
  5225. *
  5226. * @param {DOMElement} element the external element that will be pinned
  5227. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  5228. */
  5229. pin: $$animateQueue.pin,
  5230. /**
  5231. *
  5232. * @ngdoc method
  5233. * @name $animate#enabled
  5234. * @kind function
  5235. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  5236. * function can be called in four ways:
  5237. *
  5238. * ```js
  5239. * // returns true or false
  5240. * $animate.enabled();
  5241. *
  5242. * // changes the enabled state for all animations
  5243. * $animate.enabled(false);
  5244. * $animate.enabled(true);
  5245. *
  5246. * // returns true or false if animations are enabled for an element
  5247. * $animate.enabled(element);
  5248. *
  5249. * // changes the enabled state for an element and its children
  5250. * $animate.enabled(element, true);
  5251. * $animate.enabled(element, false);
  5252. * ```
  5253. *
  5254. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  5255. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  5256. *
  5257. * @return {boolean} whether or not animations are enabled
  5258. */
  5259. enabled: $$animateQueue.enabled,
  5260. /**
  5261. * @ngdoc method
  5262. * @name $animate#cancel
  5263. * @kind function
  5264. * @description Cancels the provided animation.
  5265. *
  5266. * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
  5267. */
  5268. cancel: function(runner) {
  5269. if (runner.end) {
  5270. runner.end();
  5271. }
  5272. },
  5273. /**
  5274. *
  5275. * @ngdoc method
  5276. * @name $animate#enter
  5277. * @kind function
  5278. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  5279. * as the first child within the `parent` element and then triggers an animation.
  5280. * A promise is returned that will be resolved during the next digest once the animation
  5281. * has completed.
  5282. *
  5283. * @param {DOMElement} element the element which will be inserted into the DOM
  5284. * @param {DOMElement} parent the parent element which will append the element as
  5285. * a child (so long as the after element is not present)
  5286. * @param {DOMElement=} after the sibling element after which the element will be appended
  5287. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5288. * The object can have the following properties:
  5289. *
  5290. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5291. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5292. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5293. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5294. *
  5295. * @return {Promise} the animation callback promise
  5296. */
  5297. enter: function(element, parent, after, options) {
  5298. parent = parent && jqLite(parent);
  5299. after = after && jqLite(after);
  5300. parent = parent || after.parent();
  5301. domInsert(element, parent, after);
  5302. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  5303. },
  5304. /**
  5305. *
  5306. * @ngdoc method
  5307. * @name $animate#move
  5308. * @kind function
  5309. * @description Inserts (moves) the element into its new position in the DOM either after
  5310. * the `after` element (if provided) or as the first child within the `parent` element
  5311. * and then triggers an animation. A promise is returned that will be resolved
  5312. * during the next digest once the animation has completed.
  5313. *
  5314. * @param {DOMElement} element the element which will be moved into the new DOM position
  5315. * @param {DOMElement} parent the parent element which will append the element as
  5316. * a child (so long as the after element is not present)
  5317. * @param {DOMElement=} after the sibling element after which the element will be appended
  5318. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5319. * The object can have the following properties:
  5320. *
  5321. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5322. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5323. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5324. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5325. *
  5326. * @return {Promise} the animation callback promise
  5327. */
  5328. move: function(element, parent, after, options) {
  5329. parent = parent && jqLite(parent);
  5330. after = after && jqLite(after);
  5331. parent = parent || after.parent();
  5332. domInsert(element, parent, after);
  5333. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  5334. },
  5335. /**
  5336. * @ngdoc method
  5337. * @name $animate#leave
  5338. * @kind function
  5339. * @description Triggers an animation and then removes the element from the DOM.
  5340. * When the function is called a promise is returned that will be resolved during the next
  5341. * digest once the animation has completed.
  5342. *
  5343. * @param {DOMElement} element the element which will be removed from the DOM
  5344. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5345. * The object can have the following properties:
  5346. *
  5347. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5348. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5349. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5350. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5351. *
  5352. * @return {Promise} the animation callback promise
  5353. */
  5354. leave: function(element, options) {
  5355. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  5356. element.remove();
  5357. });
  5358. },
  5359. /**
  5360. * @ngdoc method
  5361. * @name $animate#addClass
  5362. * @kind function
  5363. *
  5364. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  5365. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  5366. * animation if element already contains the CSS class or if the class is removed at a later step.
  5367. * Note that class-based animations are treated differently compared to structural animations
  5368. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5369. * depending if CSS or JavaScript animations are used.
  5370. *
  5371. * @param {DOMElement} element the element which the CSS classes will be applied to
  5372. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  5373. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5374. * The object can have the following properties:
  5375. *
  5376. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5377. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5378. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5379. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5380. *
  5381. * @return {Promise} the animation callback promise
  5382. */
  5383. addClass: function(element, className, options) {
  5384. options = prepareAnimateOptions(options);
  5385. options.addClass = mergeClasses(options.addclass, className);
  5386. return $$animateQueue.push(element, 'addClass', options);
  5387. },
  5388. /**
  5389. * @ngdoc method
  5390. * @name $animate#removeClass
  5391. * @kind function
  5392. *
  5393. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  5394. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  5395. * animation if element does not contain the CSS class or if the class is added at a later step.
  5396. * Note that class-based animations are treated differently compared to structural animations
  5397. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5398. * depending if CSS or JavaScript animations are used.
  5399. *
  5400. * @param {DOMElement} element the element which the CSS classes will be applied to
  5401. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  5402. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5403. * The object can have the following properties:
  5404. *
  5405. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5406. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5407. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5408. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5409. *
  5410. * @return {Promise} the animation callback promise
  5411. */
  5412. removeClass: function(element, className, options) {
  5413. options = prepareAnimateOptions(options);
  5414. options.removeClass = mergeClasses(options.removeClass, className);
  5415. return $$animateQueue.push(element, 'removeClass', options);
  5416. },
  5417. /**
  5418. * @ngdoc method
  5419. * @name $animate#setClass
  5420. * @kind function
  5421. *
  5422. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  5423. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  5424. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  5425. * passed. Note that class-based animations are treated differently compared to structural animations
  5426. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5427. * depending if CSS or JavaScript animations are used.
  5428. *
  5429. * @param {DOMElement} element the element which the CSS classes will be applied to
  5430. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  5431. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  5432. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5433. * The object can have the following properties:
  5434. *
  5435. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5436. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5437. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5438. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5439. *
  5440. * @return {Promise} the animation callback promise
  5441. */
  5442. setClass: function(element, add, remove, options) {
  5443. options = prepareAnimateOptions(options);
  5444. options.addClass = mergeClasses(options.addClass, add);
  5445. options.removeClass = mergeClasses(options.removeClass, remove);
  5446. return $$animateQueue.push(element, 'setClass', options);
  5447. },
  5448. /**
  5449. * @ngdoc method
  5450. * @name $animate#animate
  5451. * @kind function
  5452. *
  5453. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  5454. * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take
  5455. * on the provided styles. For example, if a transition animation is set for the given className, then the provided `from` and
  5456. * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding
  5457. * style in `to`, the style in `from` is applied immediately, and no animation is run.
  5458. * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`
  5459. * method (or as part of the `options` parameter):
  5460. *
  5461. * ```js
  5462. * ngModule.animation('.my-inline-animation', function() {
  5463. * return {
  5464. * animate : function(element, from, to, done, options) {
  5465. * //animation
  5466. * done();
  5467. * }
  5468. * }
  5469. * });
  5470. * ```
  5471. *
  5472. * @param {DOMElement} element the element which the CSS styles will be applied to
  5473. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  5474. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  5475. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  5476. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  5477. * (Note that if no animation is detected then this value will not be applied to the element.)
  5478. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5479. * The object can have the following properties:
  5480. *
  5481. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5482. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5483. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5484. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5485. *
  5486. * @return {Promise} the animation callback promise
  5487. */
  5488. animate: function(element, from, to, className, options) {
  5489. options = prepareAnimateOptions(options);
  5490. options.from = options.from ? extend(options.from, from) : from;
  5491. options.to = options.to ? extend(options.to, to) : to;
  5492. className = className || 'ng-inline-animate';
  5493. options.tempClasses = mergeClasses(options.tempClasses, className);
  5494. return $$animateQueue.push(element, 'animate', options);
  5495. }
  5496. };
  5497. }];
  5498. }];
  5499. var $$AnimateAsyncRunFactoryProvider = /** @this */ function() {
  5500. this.$get = ['$$rAF', function($$rAF) {
  5501. var waitQueue = [];
  5502. function waitForTick(fn) {
  5503. waitQueue.push(fn);
  5504. if (waitQueue.length > 1) return;
  5505. $$rAF(function() {
  5506. for (var i = 0; i < waitQueue.length; i++) {
  5507. waitQueue[i]();
  5508. }
  5509. waitQueue = [];
  5510. });
  5511. }
  5512. return function() {
  5513. var passed = false;
  5514. waitForTick(function() {
  5515. passed = true;
  5516. });
  5517. return function(callback) {
  5518. if (passed) {
  5519. callback();
  5520. } else {
  5521. waitForTick(callback);
  5522. }
  5523. };
  5524. };
  5525. }];
  5526. };
  5527. var $$AnimateRunnerFactoryProvider = /** @this */ function() {
  5528. this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$$isDocumentHidden', '$timeout',
  5529. function($q, $sniffer, $$animateAsyncRun, $$isDocumentHidden, $timeout) {
  5530. var INITIAL_STATE = 0;
  5531. var DONE_PENDING_STATE = 1;
  5532. var DONE_COMPLETE_STATE = 2;
  5533. AnimateRunner.chain = function(chain, callback) {
  5534. var index = 0;
  5535. next();
  5536. function next() {
  5537. if (index === chain.length) {
  5538. callback(true);
  5539. return;
  5540. }
  5541. chain[index](function(response) {
  5542. if (response === false) {
  5543. callback(false);
  5544. return;
  5545. }
  5546. index++;
  5547. next();
  5548. });
  5549. }
  5550. };
  5551. AnimateRunner.all = function(runners, callback) {
  5552. var count = 0;
  5553. var status = true;
  5554. forEach(runners, function(runner) {
  5555. runner.done(onProgress);
  5556. });
  5557. function onProgress(response) {
  5558. status = status && response;
  5559. if (++count === runners.length) {
  5560. callback(status);
  5561. }
  5562. }
  5563. };
  5564. function AnimateRunner(host) {
  5565. this.setHost(host);
  5566. var rafTick = $$animateAsyncRun();
  5567. var timeoutTick = function(fn) {
  5568. $timeout(fn, 0, false);
  5569. };
  5570. this._doneCallbacks = [];
  5571. this._tick = function(fn) {
  5572. if ($$isDocumentHidden()) {
  5573. timeoutTick(fn);
  5574. } else {
  5575. rafTick(fn);
  5576. }
  5577. };
  5578. this._state = 0;
  5579. }
  5580. AnimateRunner.prototype = {
  5581. setHost: function(host) {
  5582. this.host = host || {};
  5583. },
  5584. done: function(fn) {
  5585. if (this._state === DONE_COMPLETE_STATE) {
  5586. fn();
  5587. } else {
  5588. this._doneCallbacks.push(fn);
  5589. }
  5590. },
  5591. progress: noop,
  5592. getPromise: function() {
  5593. if (!this.promise) {
  5594. var self = this;
  5595. this.promise = $q(function(resolve, reject) {
  5596. self.done(function(status) {
  5597. if (status === false) {
  5598. reject();
  5599. } else {
  5600. resolve();
  5601. }
  5602. });
  5603. });
  5604. }
  5605. return this.promise;
  5606. },
  5607. then: function(resolveHandler, rejectHandler) {
  5608. return this.getPromise().then(resolveHandler, rejectHandler);
  5609. },
  5610. 'catch': function(handler) {
  5611. return this.getPromise()['catch'](handler);
  5612. },
  5613. 'finally': function(handler) {
  5614. return this.getPromise()['finally'](handler);
  5615. },
  5616. pause: function() {
  5617. if (this.host.pause) {
  5618. this.host.pause();
  5619. }
  5620. },
  5621. resume: function() {
  5622. if (this.host.resume) {
  5623. this.host.resume();
  5624. }
  5625. },
  5626. end: function() {
  5627. if (this.host.end) {
  5628. this.host.end();
  5629. }
  5630. this._resolve(true);
  5631. },
  5632. cancel: function() {
  5633. if (this.host.cancel) {
  5634. this.host.cancel();
  5635. }
  5636. this._resolve(false);
  5637. },
  5638. complete: function(response) {
  5639. var self = this;
  5640. if (self._state === INITIAL_STATE) {
  5641. self._state = DONE_PENDING_STATE;
  5642. self._tick(function() {
  5643. self._resolve(response);
  5644. });
  5645. }
  5646. },
  5647. _resolve: function(response) {
  5648. if (this._state !== DONE_COMPLETE_STATE) {
  5649. forEach(this._doneCallbacks, function(fn) {
  5650. fn(response);
  5651. });
  5652. this._doneCallbacks.length = 0;
  5653. this._state = DONE_COMPLETE_STATE;
  5654. }
  5655. }
  5656. };
  5657. return AnimateRunner;
  5658. }];
  5659. };
  5660. /* exported $CoreAnimateCssProvider */
  5661. /**
  5662. * @ngdoc service
  5663. * @name $animateCss
  5664. * @kind object
  5665. * @this
  5666. *
  5667. * @description
  5668. * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
  5669. * then the `$animateCss` service will actually perform animations.
  5670. *
  5671. * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
  5672. */
  5673. var $CoreAnimateCssProvider = function() {
  5674. this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
  5675. return function(element, initialOptions) {
  5676. // all of the animation functions should create
  5677. // a copy of the options data, however, if a
  5678. // parent service has already created a copy then
  5679. // we should stick to using that
  5680. var options = initialOptions || {};
  5681. if (!options.$$prepared) {
  5682. options = copy(options);
  5683. }
  5684. // there is no point in applying the styles since
  5685. // there is no animation that goes on at all in
  5686. // this version of $animateCss.
  5687. if (options.cleanupStyles) {
  5688. options.from = options.to = null;
  5689. }
  5690. if (options.from) {
  5691. element.css(options.from);
  5692. options.from = null;
  5693. }
  5694. var closed, runner = new $$AnimateRunner();
  5695. return {
  5696. start: run,
  5697. end: run
  5698. };
  5699. function run() {
  5700. $$rAF(function() {
  5701. applyAnimationContents();
  5702. if (!closed) {
  5703. runner.complete();
  5704. }
  5705. closed = true;
  5706. });
  5707. return runner;
  5708. }
  5709. function applyAnimationContents() {
  5710. if (options.addClass) {
  5711. element.addClass(options.addClass);
  5712. options.addClass = null;
  5713. }
  5714. if (options.removeClass) {
  5715. element.removeClass(options.removeClass);
  5716. options.removeClass = null;
  5717. }
  5718. if (options.to) {
  5719. element.css(options.to);
  5720. options.to = null;
  5721. }
  5722. }
  5723. };
  5724. }];
  5725. };
  5726. /* global stripHash: true */
  5727. /**
  5728. * ! This is a private undocumented service !
  5729. *
  5730. * @name $browser
  5731. * @requires $log
  5732. * @description
  5733. * This object has two goals:
  5734. *
  5735. * - hide all the global state in the browser caused by the window object
  5736. * - abstract away all the browser specific features and inconsistencies
  5737. *
  5738. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  5739. * service, which can be used for convenient testing of the application without the interaction with
  5740. * the real browser apis.
  5741. */
  5742. /**
  5743. * @param {object} window The global window object.
  5744. * @param {object} document jQuery wrapped document.
  5745. * @param {object} $log window.console or an object with the same interface.
  5746. * @param {object} $sniffer $sniffer service
  5747. */
  5748. function Browser(window, document, $log, $sniffer) {
  5749. var self = this,
  5750. location = window.location,
  5751. history = window.history,
  5752. setTimeout = window.setTimeout,
  5753. clearTimeout = window.clearTimeout,
  5754. pendingDeferIds = {};
  5755. self.isMock = false;
  5756. var outstandingRequestCount = 0;
  5757. var outstandingRequestCallbacks = [];
  5758. // TODO(vojta): remove this temporary api
  5759. self.$$completeOutstandingRequest = completeOutstandingRequest;
  5760. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  5761. /**
  5762. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  5763. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  5764. */
  5765. function completeOutstandingRequest(fn) {
  5766. try {
  5767. fn.apply(null, sliceArgs(arguments, 1));
  5768. } finally {
  5769. outstandingRequestCount--;
  5770. if (outstandingRequestCount === 0) {
  5771. while (outstandingRequestCallbacks.length) {
  5772. try {
  5773. outstandingRequestCallbacks.pop()();
  5774. } catch (e) {
  5775. $log.error(e);
  5776. }
  5777. }
  5778. }
  5779. }
  5780. }
  5781. function getHash(url) {
  5782. var index = url.indexOf('#');
  5783. return index === -1 ? '' : url.substr(index);
  5784. }
  5785. /**
  5786. * @private
  5787. * Note: this method is used only by scenario runner
  5788. * TODO(vojta): prefix this method with $$ ?
  5789. * @param {function()} callback Function that will be called when no outstanding request
  5790. */
  5791. self.notifyWhenNoOutstandingRequests = function(callback) {
  5792. if (outstandingRequestCount === 0) {
  5793. callback();
  5794. } else {
  5795. outstandingRequestCallbacks.push(callback);
  5796. }
  5797. };
  5798. //////////////////////////////////////////////////////////////
  5799. // URL API
  5800. //////////////////////////////////////////////////////////////
  5801. var cachedState, lastHistoryState,
  5802. lastBrowserUrl = location.href,
  5803. baseElement = document.find('base'),
  5804. pendingLocation = null,
  5805. getCurrentState = !$sniffer.history ? noop : function getCurrentState() {
  5806. try {
  5807. return history.state;
  5808. } catch (e) {
  5809. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  5810. }
  5811. };
  5812. cacheState();
  5813. /**
  5814. * @name $browser#url
  5815. *
  5816. * @description
  5817. * GETTER:
  5818. * Without any argument, this method just returns current value of location.href.
  5819. *
  5820. * SETTER:
  5821. * With at least one argument, this method sets url to new value.
  5822. * If html5 history api supported, pushState/replaceState is used, otherwise
  5823. * location.href/location.replace is used.
  5824. * Returns its own instance to allow chaining
  5825. *
  5826. * NOTE: this api is intended for use only by the $location service. Please use the
  5827. * {@link ng.$location $location service} to change url.
  5828. *
  5829. * @param {string} url New url (when used as setter)
  5830. * @param {boolean=} replace Should new url replace current history record?
  5831. * @param {object=} state object to use with pushState/replaceState
  5832. */
  5833. self.url = function(url, replace, state) {
  5834. // In modern browsers `history.state` is `null` by default; treating it separately
  5835. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  5836. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  5837. if (isUndefined(state)) {
  5838. state = null;
  5839. }
  5840. // Android Browser BFCache causes location, history reference to become stale.
  5841. if (location !== window.location) location = window.location;
  5842. if (history !== window.history) history = window.history;
  5843. // setter
  5844. if (url) {
  5845. var sameState = lastHistoryState === state;
  5846. // Don't change anything if previous and current URLs and states match. This also prevents
  5847. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  5848. // See https://github.com/angular/angular.js/commit/ffb2701
  5849. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  5850. return self;
  5851. }
  5852. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  5853. lastBrowserUrl = url;
  5854. lastHistoryState = state;
  5855. // Don't use history API if only the hash changed
  5856. // due to a bug in IE10/IE11 which leads
  5857. // to not firing a `hashchange` nor `popstate` event
  5858. // in some cases (see #9143).
  5859. if ($sniffer.history && (!sameBase || !sameState)) {
  5860. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  5861. cacheState();
  5862. } else {
  5863. if (!sameBase) {
  5864. pendingLocation = url;
  5865. }
  5866. if (replace) {
  5867. location.replace(url);
  5868. } else if (!sameBase) {
  5869. location.href = url;
  5870. } else {
  5871. location.hash = getHash(url);
  5872. }
  5873. if (location.href !== url) {
  5874. pendingLocation = url;
  5875. }
  5876. }
  5877. if (pendingLocation) {
  5878. pendingLocation = url;
  5879. }
  5880. return self;
  5881. // getter
  5882. } else {
  5883. // - pendingLocation is needed as browsers don't allow to read out
  5884. // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
  5885. // https://openradar.appspot.com/22186109).
  5886. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  5887. return pendingLocation || location.href.replace(/%27/g,'\'');
  5888. }
  5889. };
  5890. /**
  5891. * @name $browser#state
  5892. *
  5893. * @description
  5894. * This method is a getter.
  5895. *
  5896. * Return history.state or null if history.state is undefined.
  5897. *
  5898. * @returns {object} state
  5899. */
  5900. self.state = function() {
  5901. return cachedState;
  5902. };
  5903. var urlChangeListeners = [],
  5904. urlChangeInit = false;
  5905. function cacheStateAndFireUrlChange() {
  5906. pendingLocation = null;
  5907. fireStateOrUrlChange();
  5908. }
  5909. // This variable should be used *only* inside the cacheState function.
  5910. var lastCachedState = null;
  5911. function cacheState() {
  5912. // This should be the only place in $browser where `history.state` is read.
  5913. cachedState = getCurrentState();
  5914. cachedState = isUndefined(cachedState) ? null : cachedState;
  5915. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  5916. if (equals(cachedState, lastCachedState)) {
  5917. cachedState = lastCachedState;
  5918. }
  5919. lastCachedState = cachedState;
  5920. lastHistoryState = cachedState;
  5921. }
  5922. function fireStateOrUrlChange() {
  5923. var prevLastHistoryState = lastHistoryState;
  5924. cacheState();
  5925. if (lastBrowserUrl === self.url() && prevLastHistoryState === cachedState) {
  5926. return;
  5927. }
  5928. lastBrowserUrl = self.url();
  5929. lastHistoryState = cachedState;
  5930. forEach(urlChangeListeners, function(listener) {
  5931. listener(self.url(), cachedState);
  5932. });
  5933. }
  5934. /**
  5935. * @name $browser#onUrlChange
  5936. *
  5937. * @description
  5938. * Register callback function that will be called, when url changes.
  5939. *
  5940. * It's only called when the url is changed from outside of angular:
  5941. * - user types different url into address bar
  5942. * - user clicks on history (forward/back) button
  5943. * - user clicks on a link
  5944. *
  5945. * It's not called when url is changed by $browser.url() method
  5946. *
  5947. * The listener gets called with new url as parameter.
  5948. *
  5949. * NOTE: this api is intended for use only by the $location service. Please use the
  5950. * {@link ng.$location $location service} to monitor url changes in angular apps.
  5951. *
  5952. * @param {function(string)} listener Listener function to be called when url changes.
  5953. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  5954. */
  5955. self.onUrlChange = function(callback) {
  5956. // TODO(vojta): refactor to use node's syntax for events
  5957. if (!urlChangeInit) {
  5958. // We listen on both (hashchange/popstate) when available, as some browsers don't
  5959. // fire popstate when user changes the address bar and don't fire hashchange when url
  5960. // changed by push/replaceState
  5961. // html5 history api - popstate event
  5962. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  5963. // hashchange event
  5964. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  5965. urlChangeInit = true;
  5966. }
  5967. urlChangeListeners.push(callback);
  5968. return callback;
  5969. };
  5970. /**
  5971. * @private
  5972. * Remove popstate and hashchange handler from window.
  5973. *
  5974. * NOTE: this api is intended for use only by $rootScope.
  5975. */
  5976. self.$$applicationDestroyed = function() {
  5977. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  5978. };
  5979. /**
  5980. * Checks whether the url has changed outside of Angular.
  5981. * Needs to be exported to be able to check for changes that have been done in sync,
  5982. * as hashchange/popstate events fire in async.
  5983. */
  5984. self.$$checkUrlChange = fireStateOrUrlChange;
  5985. //////////////////////////////////////////////////////////////
  5986. // Misc API
  5987. //////////////////////////////////////////////////////////////
  5988. /**
  5989. * @name $browser#baseHref
  5990. *
  5991. * @description
  5992. * Returns current <base href>
  5993. * (always relative - without domain)
  5994. *
  5995. * @returns {string} The current base href
  5996. */
  5997. self.baseHref = function() {
  5998. var href = baseElement.attr('href');
  5999. return href ? href.replace(/^(https?:)?\/\/[^/]*/, '') : '';
  6000. };
  6001. /**
  6002. * @name $browser#defer
  6003. * @param {function()} fn A function, who's execution should be deferred.
  6004. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  6005. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  6006. *
  6007. * @description
  6008. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  6009. *
  6010. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  6011. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  6012. * via `$browser.defer.flush()`.
  6013. *
  6014. */
  6015. self.defer = function(fn, delay) {
  6016. var timeoutId;
  6017. outstandingRequestCount++;
  6018. timeoutId = setTimeout(function() {
  6019. delete pendingDeferIds[timeoutId];
  6020. completeOutstandingRequest(fn);
  6021. }, delay || 0);
  6022. pendingDeferIds[timeoutId] = true;
  6023. return timeoutId;
  6024. };
  6025. /**
  6026. * @name $browser#defer.cancel
  6027. *
  6028. * @description
  6029. * Cancels a deferred task identified with `deferId`.
  6030. *
  6031. * @param {*} deferId Token returned by the `$browser.defer` function.
  6032. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  6033. * canceled.
  6034. */
  6035. self.defer.cancel = function(deferId) {
  6036. if (pendingDeferIds[deferId]) {
  6037. delete pendingDeferIds[deferId];
  6038. clearTimeout(deferId);
  6039. completeOutstandingRequest(noop);
  6040. return true;
  6041. }
  6042. return false;
  6043. };
  6044. }
  6045. /** @this */
  6046. function $BrowserProvider() {
  6047. this.$get = ['$window', '$log', '$sniffer', '$document',
  6048. function($window, $log, $sniffer, $document) {
  6049. return new Browser($window, $document, $log, $sniffer);
  6050. }];
  6051. }
  6052. /**
  6053. * @ngdoc service
  6054. * @name $cacheFactory
  6055. * @this
  6056. *
  6057. * @description
  6058. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  6059. * them.
  6060. *
  6061. * ```js
  6062. *
  6063. * var cache = $cacheFactory('cacheId');
  6064. * expect($cacheFactory.get('cacheId')).toBe(cache);
  6065. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  6066. *
  6067. * cache.put("key", "value");
  6068. * cache.put("another key", "another value");
  6069. *
  6070. * // We've specified no options on creation
  6071. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  6072. *
  6073. * ```
  6074. *
  6075. *
  6076. * @param {string} cacheId Name or id of the newly created cache.
  6077. * @param {object=} options Options object that specifies the cache behavior. Properties:
  6078. *
  6079. * - `{number=}` `capacity` — turns the cache into LRU cache.
  6080. *
  6081. * @returns {object} Newly created cache object with the following set of methods:
  6082. *
  6083. * - `{object}` `info()` — Returns id, size, and options of cache.
  6084. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  6085. * it.
  6086. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  6087. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  6088. * - `{void}` `removeAll()` — Removes all cached values.
  6089. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  6090. *
  6091. * @example
  6092. <example module="cacheExampleApp" name="cache-factory">
  6093. <file name="index.html">
  6094. <div ng-controller="CacheController">
  6095. <input ng-model="newCacheKey" placeholder="Key">
  6096. <input ng-model="newCacheValue" placeholder="Value">
  6097. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  6098. <p ng-if="keys.length">Cached Values</p>
  6099. <div ng-repeat="key in keys">
  6100. <span ng-bind="key"></span>
  6101. <span>: </span>
  6102. <b ng-bind="cache.get(key)"></b>
  6103. </div>
  6104. <p>Cache Info</p>
  6105. <div ng-repeat="(key, value) in cache.info()">
  6106. <span ng-bind="key"></span>
  6107. <span>: </span>
  6108. <b ng-bind="value"></b>
  6109. </div>
  6110. </div>
  6111. </file>
  6112. <file name="script.js">
  6113. angular.module('cacheExampleApp', []).
  6114. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  6115. $scope.keys = [];
  6116. $scope.cache = $cacheFactory('cacheId');
  6117. $scope.put = function(key, value) {
  6118. if (angular.isUndefined($scope.cache.get(key))) {
  6119. $scope.keys.push(key);
  6120. }
  6121. $scope.cache.put(key, angular.isUndefined(value) ? null : value);
  6122. };
  6123. }]);
  6124. </file>
  6125. <file name="style.css">
  6126. p {
  6127. margin: 10px 0 3px;
  6128. }
  6129. </file>
  6130. </example>
  6131. */
  6132. function $CacheFactoryProvider() {
  6133. this.$get = function() {
  6134. var caches = {};
  6135. function cacheFactory(cacheId, options) {
  6136. if (cacheId in caches) {
  6137. throw minErr('$cacheFactory')('iid', 'CacheId \'{0}\' is already taken!', cacheId);
  6138. }
  6139. var size = 0,
  6140. stats = extend({}, options, {id: cacheId}),
  6141. data = createMap(),
  6142. capacity = (options && options.capacity) || Number.MAX_VALUE,
  6143. lruHash = createMap(),
  6144. freshEnd = null,
  6145. staleEnd = null;
  6146. /**
  6147. * @ngdoc type
  6148. * @name $cacheFactory.Cache
  6149. *
  6150. * @description
  6151. * A cache object used to store and retrieve data, primarily used by
  6152. * {@link $templateRequest $templateRequest} and the {@link ng.directive:script script}
  6153. * directive to cache templates and other data.
  6154. *
  6155. * ```js
  6156. * angular.module('superCache')
  6157. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  6158. * return $cacheFactory('super-cache');
  6159. * }]);
  6160. * ```
  6161. *
  6162. * Example test:
  6163. *
  6164. * ```js
  6165. * it('should behave like a cache', inject(function(superCache) {
  6166. * superCache.put('key', 'value');
  6167. * superCache.put('another key', 'another value');
  6168. *
  6169. * expect(superCache.info()).toEqual({
  6170. * id: 'super-cache',
  6171. * size: 2
  6172. * });
  6173. *
  6174. * superCache.remove('another key');
  6175. * expect(superCache.get('another key')).toBeUndefined();
  6176. *
  6177. * superCache.removeAll();
  6178. * expect(superCache.info()).toEqual({
  6179. * id: 'super-cache',
  6180. * size: 0
  6181. * });
  6182. * }));
  6183. * ```
  6184. */
  6185. return (caches[cacheId] = {
  6186. /**
  6187. * @ngdoc method
  6188. * @name $cacheFactory.Cache#put
  6189. * @kind function
  6190. *
  6191. * @description
  6192. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  6193. * retrieved later, and incrementing the size of the cache if the key was not already
  6194. * present in the cache. If behaving like an LRU cache, it will also remove stale
  6195. * entries from the set.
  6196. *
  6197. * It will not insert undefined values into the cache.
  6198. *
  6199. * @param {string} key the key under which the cached data is stored.
  6200. * @param {*} value the value to store alongside the key. If it is undefined, the key
  6201. * will not be stored.
  6202. * @returns {*} the value stored.
  6203. */
  6204. put: function(key, value) {
  6205. if (isUndefined(value)) return;
  6206. if (capacity < Number.MAX_VALUE) {
  6207. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  6208. refresh(lruEntry);
  6209. }
  6210. if (!(key in data)) size++;
  6211. data[key] = value;
  6212. if (size > capacity) {
  6213. this.remove(staleEnd.key);
  6214. }
  6215. return value;
  6216. },
  6217. /**
  6218. * @ngdoc method
  6219. * @name $cacheFactory.Cache#get
  6220. * @kind function
  6221. *
  6222. * @description
  6223. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  6224. *
  6225. * @param {string} key the key of the data to be retrieved
  6226. * @returns {*} the value stored.
  6227. */
  6228. get: function(key) {
  6229. if (capacity < Number.MAX_VALUE) {
  6230. var lruEntry = lruHash[key];
  6231. if (!lruEntry) return;
  6232. refresh(lruEntry);
  6233. }
  6234. return data[key];
  6235. },
  6236. /**
  6237. * @ngdoc method
  6238. * @name $cacheFactory.Cache#remove
  6239. * @kind function
  6240. *
  6241. * @description
  6242. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  6243. *
  6244. * @param {string} key the key of the entry to be removed
  6245. */
  6246. remove: function(key) {
  6247. if (capacity < Number.MAX_VALUE) {
  6248. var lruEntry = lruHash[key];
  6249. if (!lruEntry) return;
  6250. if (lruEntry === freshEnd) freshEnd = lruEntry.p;
  6251. if (lruEntry === staleEnd) staleEnd = lruEntry.n;
  6252. link(lruEntry.n,lruEntry.p);
  6253. delete lruHash[key];
  6254. }
  6255. if (!(key in data)) return;
  6256. delete data[key];
  6257. size--;
  6258. },
  6259. /**
  6260. * @ngdoc method
  6261. * @name $cacheFactory.Cache#removeAll
  6262. * @kind function
  6263. *
  6264. * @description
  6265. * Clears the cache object of any entries.
  6266. */
  6267. removeAll: function() {
  6268. data = createMap();
  6269. size = 0;
  6270. lruHash = createMap();
  6271. freshEnd = staleEnd = null;
  6272. },
  6273. /**
  6274. * @ngdoc method
  6275. * @name $cacheFactory.Cache#destroy
  6276. * @kind function
  6277. *
  6278. * @description
  6279. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  6280. * removing it from the {@link $cacheFactory $cacheFactory} set.
  6281. */
  6282. destroy: function() {
  6283. data = null;
  6284. stats = null;
  6285. lruHash = null;
  6286. delete caches[cacheId];
  6287. },
  6288. /**
  6289. * @ngdoc method
  6290. * @name $cacheFactory.Cache#info
  6291. * @kind function
  6292. *
  6293. * @description
  6294. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  6295. *
  6296. * @returns {object} an object with the following properties:
  6297. * <ul>
  6298. * <li>**id**: the id of the cache instance</li>
  6299. * <li>**size**: the number of entries kept in the cache instance</li>
  6300. * <li>**...**: any additional properties from the options object when creating the
  6301. * cache.</li>
  6302. * </ul>
  6303. */
  6304. info: function() {
  6305. return extend({}, stats, {size: size});
  6306. }
  6307. });
  6308. /**
  6309. * makes the `entry` the freshEnd of the LRU linked list
  6310. */
  6311. function refresh(entry) {
  6312. if (entry !== freshEnd) {
  6313. if (!staleEnd) {
  6314. staleEnd = entry;
  6315. } else if (staleEnd === entry) {
  6316. staleEnd = entry.n;
  6317. }
  6318. link(entry.n, entry.p);
  6319. link(entry, freshEnd);
  6320. freshEnd = entry;
  6321. freshEnd.n = null;
  6322. }
  6323. }
  6324. /**
  6325. * bidirectionally links two entries of the LRU linked list
  6326. */
  6327. function link(nextEntry, prevEntry) {
  6328. if (nextEntry !== prevEntry) {
  6329. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  6330. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  6331. }
  6332. }
  6333. }
  6334. /**
  6335. * @ngdoc method
  6336. * @name $cacheFactory#info
  6337. *
  6338. * @description
  6339. * Get information about all the caches that have been created
  6340. *
  6341. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  6342. */
  6343. cacheFactory.info = function() {
  6344. var info = {};
  6345. forEach(caches, function(cache, cacheId) {
  6346. info[cacheId] = cache.info();
  6347. });
  6348. return info;
  6349. };
  6350. /**
  6351. * @ngdoc method
  6352. * @name $cacheFactory#get
  6353. *
  6354. * @description
  6355. * Get access to a cache object by the `cacheId` used when it was created.
  6356. *
  6357. * @param {string} cacheId Name or id of a cache to access.
  6358. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  6359. */
  6360. cacheFactory.get = function(cacheId) {
  6361. return caches[cacheId];
  6362. };
  6363. return cacheFactory;
  6364. };
  6365. }
  6366. /**
  6367. * @ngdoc service
  6368. * @name $templateCache
  6369. * @this
  6370. *
  6371. * @description
  6372. * `$templateCache` is a {@link $cacheFactory.Cache Cache object} created by the
  6373. * {@link ng.$cacheFactory $cacheFactory}.
  6374. *
  6375. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  6376. * can load templates directly into the cache in a `script` tag, by using {@link $templateRequest},
  6377. * or by consuming the `$templateCache` service directly.
  6378. *
  6379. * Adding via the `script` tag:
  6380. *
  6381. * ```html
  6382. * <script type="text/ng-template" id="templateId.html">
  6383. * <p>This is the content of the template</p>
  6384. * </script>
  6385. * ```
  6386. *
  6387. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  6388. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (e.g.
  6389. * element with {@link ngApp} attribute), otherwise the template will be ignored.
  6390. *
  6391. * Adding via the `$templateCache` service:
  6392. *
  6393. * ```js
  6394. * var myApp = angular.module('myApp', []);
  6395. * myApp.run(function($templateCache) {
  6396. * $templateCache.put('templateId.html', 'This is the content of the template');
  6397. * });
  6398. * ```
  6399. *
  6400. * To retrieve the template later, simply use it in your component:
  6401. * ```js
  6402. * myApp.component('myComponent', {
  6403. * templateUrl: 'templateId.html'
  6404. * });
  6405. * ```
  6406. *
  6407. * or get it via the `$templateCache` service:
  6408. * ```js
  6409. * $templateCache.get('templateId.html')
  6410. * ```
  6411. *
  6412. */
  6413. function $TemplateCacheProvider() {
  6414. this.$get = ['$cacheFactory', function($cacheFactory) {
  6415. return $cacheFactory('templates');
  6416. }];
  6417. }
  6418. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  6419. * Any commits to this file should be reviewed with security in mind. *
  6420. * Changes to this file can potentially create security vulnerabilities. *
  6421. * An approval from 2 Core members with history of modifying *
  6422. * this file is required. *
  6423. * *
  6424. * Does the change somehow allow for arbitrary javascript to be executed? *
  6425. * Or allows for someone to change the prototype of built-in objects? *
  6426. * Or gives undesired access to variables like document or window? *
  6427. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  6428. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  6429. *
  6430. * DOM-related variables:
  6431. *
  6432. * - "node" - DOM Node
  6433. * - "element" - DOM Element or Node
  6434. * - "$node" or "$element" - jqLite-wrapped node or element
  6435. *
  6436. *
  6437. * Compiler related stuff:
  6438. *
  6439. * - "linkFn" - linking fn of a single directive
  6440. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  6441. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  6442. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  6443. */
  6444. /**
  6445. * @ngdoc service
  6446. * @name $compile
  6447. * @kind function
  6448. *
  6449. * @description
  6450. * Compiles an HTML string or DOM into a template and produces a template function, which
  6451. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  6452. *
  6453. * The compilation is a process of walking the DOM tree and matching DOM elements to
  6454. * {@link ng.$compileProvider#directive directives}.
  6455. *
  6456. * <div class="alert alert-warning">
  6457. * **Note:** This document is an in-depth reference of all directive options.
  6458. * For a gentle introduction to directives with examples of common use cases,
  6459. * see the {@link guide/directive directive guide}.
  6460. * </div>
  6461. *
  6462. * ## Comprehensive Directive API
  6463. *
  6464. * There are many different options for a directive.
  6465. *
  6466. * The difference resides in the return value of the factory function.
  6467. * You can either return a {@link $compile#directive-definition-object Directive Definition Object (see below)}
  6468. * that defines the directive properties, or just the `postLink` function (all other properties will have
  6469. * the default values).
  6470. *
  6471. * <div class="alert alert-success">
  6472. * **Best Practice:** It's recommended to use the "directive definition object" form.
  6473. * </div>
  6474. *
  6475. * Here's an example directive declared with a Directive Definition Object:
  6476. *
  6477. * ```js
  6478. * var myModule = angular.module(...);
  6479. *
  6480. * myModule.directive('directiveName', function factory(injectables) {
  6481. * var directiveDefinitionObject = {
  6482. * {@link $compile#-priority- priority}: 0,
  6483. * {@link $compile#-template- template}: '<div></div>', // or // function(tElement, tAttrs) { ... },
  6484. * // or
  6485. * // {@link $compile#-templateurl- templateUrl}: 'directive.html', // or // function(tElement, tAttrs) { ... },
  6486. * {@link $compile#-transclude- transclude}: false,
  6487. * {@link $compile#-restrict- restrict}: 'A',
  6488. * {@link $compile#-templatenamespace- templateNamespace}: 'html',
  6489. * {@link $compile#-scope- scope}: false,
  6490. * {@link $compile#-controller- controller}: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  6491. * {@link $compile#-controlleras- controllerAs}: 'stringIdentifier',
  6492. * {@link $compile#-bindtocontroller- bindToController}: false,
  6493. * {@link $compile#-require- require}: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  6494. * {@link $compile#-multielement- multiElement}: false,
  6495. * {@link $compile#-compile- compile}: function compile(tElement, tAttrs, transclude) {
  6496. * return {
  6497. * {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
  6498. * {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
  6499. * }
  6500. * // or
  6501. * // return function postLink( ... ) { ... }
  6502. * },
  6503. * // or
  6504. * // {@link $compile#-link- link}: {
  6505. * // {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... },
  6506. * // {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... }
  6507. * // }
  6508. * // or
  6509. * // {@link $compile#-link- link}: function postLink( ... ) { ... }
  6510. * };
  6511. * return directiveDefinitionObject;
  6512. * });
  6513. * ```
  6514. *
  6515. * <div class="alert alert-warning">
  6516. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  6517. * </div>
  6518. *
  6519. * Therefore the above can be simplified as:
  6520. *
  6521. * ```js
  6522. * var myModule = angular.module(...);
  6523. *
  6524. * myModule.directive('directiveName', function factory(injectables) {
  6525. * var directiveDefinitionObject = {
  6526. * link: function postLink(scope, iElement, iAttrs) { ... }
  6527. * };
  6528. * return directiveDefinitionObject;
  6529. * // or
  6530. * // return function postLink(scope, iElement, iAttrs) { ... }
  6531. * });
  6532. * ```
  6533. *
  6534. * ### Life-cycle hooks
  6535. * Directive controllers can provide the following methods that are called by Angular at points in the life-cycle of the
  6536. * directive:
  6537. * * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and
  6538. * had their bindings initialized (and before the pre &amp; post linking functions for the directives on
  6539. * this element). This is a good place to put initialization code for your controller.
  6540. * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The
  6541. * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an
  6542. * object of the form `{ currentValue, previousValue, isFirstChange() }`. Use this hook to trigger updates within a
  6543. * component such as cloning the bound value to prevent accidental mutation of the outer value. Note that this will
  6544. * also be called when your bindings are initialized.
  6545. * * `$doCheck()` - Called on each turn of the digest cycle. Provides an opportunity to detect and act on
  6546. * changes. Any actions that you wish to take in response to the changes that you detect must be
  6547. * invoked from this hook; implementing this has no effect on when `$onChanges` is called. For example, this hook
  6548. * could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not
  6549. * be detected by Angular's change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments;
  6550. * if detecting changes, you must store the previous value(s) for comparison to the current values.
  6551. * * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing
  6552. * external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in
  6553. * the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent
  6554. * components will have their `$onDestroy()` hook called before child components.
  6555. * * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link
  6556. * function this hook can be used to set up DOM event handlers and do direct DOM manipulation.
  6557. * Note that child elements that contain `templateUrl` directives will not have been compiled and linked since
  6558. * they are waiting for their template to load asynchronously and their own compilation and linking has been
  6559. * suspended until that occurs.
  6560. *
  6561. * #### Comparison with Angular 2 life-cycle hooks
  6562. * Angular 2 also uses life-cycle hooks for its components. While the Angular 1 life-cycle hooks are similar there are
  6563. * some differences that you should be aware of, especially when it comes to moving your code from Angular 1 to Angular 2:
  6564. *
  6565. * * Angular 1 hooks are prefixed with `$`, such as `$onInit`. Angular 2 hooks are prefixed with `ng`, such as `ngOnInit`.
  6566. * * Angular 1 hooks can be defined on the controller prototype or added to the controller inside its constructor.
  6567. * In Angular 2 you can only define hooks on the prototype of the Component class.
  6568. * * Due to the differences in change-detection, you may get many more calls to `$doCheck` in Angular 1 than you would to
  6569. * `ngDoCheck` in Angular 2
  6570. * * Changes to the model inside `$doCheck` will trigger new turns of the digest loop, which will cause the changes to be
  6571. * propagated throughout the application.
  6572. * Angular 2 does not allow the `ngDoCheck` hook to trigger a change outside of the component. It will either throw an
  6573. * error or do nothing depending upon the state of `enableProdMode()`.
  6574. *
  6575. * #### Life-cycle hook examples
  6576. *
  6577. * This example shows how you can check for mutations to a Date object even though the identity of the object
  6578. * has not changed.
  6579. *
  6580. * <example name="doCheckDateExample" module="do-check-module">
  6581. * <file name="app.js">
  6582. * angular.module('do-check-module', [])
  6583. * .component('app', {
  6584. * template:
  6585. * 'Month: <input ng-model="$ctrl.month" ng-change="$ctrl.updateDate()">' +
  6586. * 'Date: {{ $ctrl.date }}' +
  6587. * '<test date="$ctrl.date"></test>',
  6588. * controller: function() {
  6589. * this.date = new Date();
  6590. * this.month = this.date.getMonth();
  6591. * this.updateDate = function() {
  6592. * this.date.setMonth(this.month);
  6593. * };
  6594. * }
  6595. * })
  6596. * .component('test', {
  6597. * bindings: { date: '<' },
  6598. * template:
  6599. * '<pre>{{ $ctrl.log | json }}</pre>',
  6600. * controller: function() {
  6601. * var previousValue;
  6602. * this.log = [];
  6603. * this.$doCheck = function() {
  6604. * var currentValue = this.date && this.date.valueOf();
  6605. * if (previousValue !== currentValue) {
  6606. * this.log.push('doCheck: date mutated: ' + this.date);
  6607. * previousValue = currentValue;
  6608. * }
  6609. * };
  6610. * }
  6611. * });
  6612. * </file>
  6613. * <file name="index.html">
  6614. * <app></app>
  6615. * </file>
  6616. * </example>
  6617. *
  6618. * This example show how you might use `$doCheck` to trigger changes in your component's inputs even if the
  6619. * actual identity of the component doesn't change. (Be aware that cloning and deep equality checks on large
  6620. * arrays or objects can have a negative impact on your application performance)
  6621. *
  6622. * <example name="doCheckArrayExample" module="do-check-module">
  6623. * <file name="index.html">
  6624. * <div ng-init="items = []">
  6625. * <button ng-click="items.push(items.length)">Add Item</button>
  6626. * <button ng-click="items = []">Reset Items</button>
  6627. * <pre>{{ items }}</pre>
  6628. * <test items="items"></test>
  6629. * </div>
  6630. * </file>
  6631. * <file name="app.js">
  6632. * angular.module('do-check-module', [])
  6633. * .component('test', {
  6634. * bindings: { items: '<' },
  6635. * template:
  6636. * '<pre>{{ $ctrl.log | json }}</pre>',
  6637. * controller: function() {
  6638. * this.log = [];
  6639. *
  6640. * this.$doCheck = function() {
  6641. * if (this.items_ref !== this.items) {
  6642. * this.log.push('doCheck: items changed');
  6643. * this.items_ref = this.items;
  6644. * }
  6645. * if (!angular.equals(this.items_clone, this.items)) {
  6646. * this.log.push('doCheck: items mutated');
  6647. * this.items_clone = angular.copy(this.items);
  6648. * }
  6649. * };
  6650. * }
  6651. * });
  6652. * </file>
  6653. * </example>
  6654. *
  6655. *
  6656. * ### Directive Definition Object
  6657. *
  6658. * The directive definition object provides instructions to the {@link ng.$compile
  6659. * compiler}. The attributes are:
  6660. *
  6661. * #### `multiElement`
  6662. * When this property is set to true (default is `false`), the HTML compiler will collect DOM nodes between
  6663. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  6664. * together as the directive elements. It is recommended that this feature be used on directives
  6665. * which are not strictly behavioral (such as {@link ngClick}), and which
  6666. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  6667. *
  6668. * #### `priority`
  6669. * When there are multiple directives defined on a single DOM element, sometimes it
  6670. * is necessary to specify the order in which the directives are applied. The `priority` is used
  6671. * to sort the directives before their `compile` functions get called. Priority is defined as a
  6672. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  6673. * are also run in priority order, but post-link functions are run in reverse order. The order
  6674. * of directives with the same priority is undefined. The default priority is `0`.
  6675. *
  6676. * #### `terminal`
  6677. * If set to true then the current `priority` will be the last set of directives
  6678. * which will execute (any directives at the current priority will still execute
  6679. * as the order of execution on same `priority` is undefined). Note that expressions
  6680. * and other directives used in the directive's template will also be excluded from execution.
  6681. *
  6682. * #### `scope`
  6683. * The scope property can be `false`, `true`, or an object:
  6684. *
  6685. * * **`false` (default):** No scope will be created for the directive. The directive will use its
  6686. * parent's scope.
  6687. *
  6688. * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
  6689. * the directive's element. If multiple directives on the same element request a new scope,
  6690. * only one new scope is created.
  6691. *
  6692. * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's template.
  6693. * The 'isolate' scope differs from normal scope in that it does not prototypically
  6694. * inherit from its parent scope. This is useful when creating reusable components, which should not
  6695. * accidentally read or modify data in the parent scope. Note that an isolate scope
  6696. * directive without a `template` or `templateUrl` will not apply the isolate scope
  6697. * to its children elements.
  6698. *
  6699. * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
  6700. * directive's element. These local properties are useful for aliasing values for templates. The keys in
  6701. * the object hash map to the name of the property on the isolate scope; the values define how the property
  6702. * is bound to the parent scope, via matching attributes on the directive's element:
  6703. *
  6704. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  6705. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  6706. * attribute name is assumed to be the same as the local name. Given `<my-component
  6707. * my-attr="hello {{name}}">` and the isolate scope definition `scope: { localName:'@myAttr' }`,
  6708. * the directive's scope property `localName` will reflect the interpolated value of `hello
  6709. * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's
  6710. * scope. The `name` is read from the parent scope (not the directive's scope).
  6711. *
  6712. * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression
  6713. * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.
  6714. * If no `attr` name is specified then the attribute name is assumed to be the same as the local
  6715. * name. Given `<my-component my-attr="parentModel">` and the isolate scope definition `scope: {
  6716. * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the
  6717. * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in
  6718. * `localModel` and vice versa. Optional attributes should be marked as such with a question mark:
  6719. * `=?` or `=?attr`. If the binding expression is non-assignable, or if the attribute isn't
  6720. * optional and doesn't exist, an exception ({@link error/$compile/nonassign `$compile:nonassign`})
  6721. * will be thrown upon discovering changes to the local value, since it will be impossible to sync
  6722. * them back to the parent scope. By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
  6723. * method is used for tracking changes, and the equality check is based on object identity.
  6724. * However, if an object literal or an array literal is passed as the binding expression, the
  6725. * equality check is done by value (using the {@link angular.equals} function). It's also possible
  6726. * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection
  6727. * `$watchCollection`}: use `=*` or `=*attr` (`=*?` or `=*?attr` if the attribute is optional).
  6728. *
  6729. * * `<` or `<attr` - set up a one-way (one-directional) binding between a local scope property and an
  6730. * expression passed via the attribute `attr`. The expression is evaluated in the context of the
  6731. * parent scope. If no `attr` name is specified then the attribute name is assumed to be the same as the
  6732. * local name. You can also make the binding optional by adding `?`: `<?` or `<?attr`.
  6733. *
  6734. * For example, given `<my-component my-attr="parentModel">` and directive definition of
  6735. * `scope: { localModel:'<myAttr' }`, then the isolated scope property `localModel` will reflect the
  6736. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  6737. * in `localModel`, but changes in `localModel` will not reflect in `parentModel`. There are however
  6738. * two caveats:
  6739. * 1. one-way binding does not copy the value from the parent to the isolate scope, it simply
  6740. * sets the same value. That means if your bound value is an object, changes to its properties
  6741. * in the isolated scope will be reflected in the parent scope (because both reference the same object).
  6742. * 2. one-way binding watches changes to the **identity** of the parent value. That means the
  6743. * {@link ng.$rootScope.Scope#$watch `$watch`} on the parent value only fires if the reference
  6744. * to the value has changed. In most cases, this should not be of concern, but can be important
  6745. * to know if you one-way bind to an object, and then replace that object in the isolated scope.
  6746. * If you now change a property of the object in your parent scope, the change will not be
  6747. * propagated to the isolated scope, because the identity of the object on the parent scope
  6748. * has not changed. Instead you must assign a new object.
  6749. *
  6750. * One-way binding is useful if you do not plan to propagate changes to your isolated scope bindings
  6751. * back to the parent. However, it does not make this completely impossible.
  6752. *
  6753. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. If
  6754. * no `attr` name is specified then the attribute name is assumed to be the same as the local name.
  6755. * Given `<my-component my-attr="count = count + value">` and the isolate scope definition `scope: {
  6756. * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for
  6757. * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope
  6758. * via an expression to the parent scope. This can be done by passing a map of local variable names
  6759. * and values into the expression wrapper fn. For example, if the expression is `increment(amount)`
  6760. * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.
  6761. *
  6762. * In general it's possible to apply more than one directive to one element, but there might be limitations
  6763. * depending on the type of scope required by the directives. The following points will help explain these limitations.
  6764. * For simplicity only two directives are taken into account, but it is also applicable for several directives:
  6765. *
  6766. * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
  6767. * * **child scope** + **no scope** => Both directives will share one single child scope
  6768. * * **child scope** + **child scope** => Both directives will share one single child scope
  6769. * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
  6770. * its parent's scope
  6771. * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
  6772. * be applied to the same element.
  6773. * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
  6774. * cannot be applied to the same element.
  6775. *
  6776. *
  6777. * #### `bindToController`
  6778. * This property is used to bind scope properties directly to the controller. It can be either
  6779. * `true` or an object hash with the same format as the `scope` property.
  6780. *
  6781. * When an isolate scope is used for a directive (see above), `bindToController: true` will
  6782. * allow a component to have its properties bound to the controller, rather than to scope.
  6783. *
  6784. * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller
  6785. * properties. You can access these bindings once they have been initialized by providing a controller method called
  6786. * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings
  6787. * initialized.
  6788. *
  6789. * <div class="alert alert-warning">
  6790. * **Deprecation warning:** if `$compileProcvider.preAssignBindingsEnabled(true)` was called, bindings for non-ES6 class
  6791. * controllers are bound to `this` before the controller constructor is called but this use is now deprecated. Please
  6792. * place initialization code that relies upon bindings inside a `$onInit` method on the controller, instead.
  6793. * </div>
  6794. *
  6795. * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.
  6796. * This will set up the scope bindings to the controller directly. Note that `scope` can still be used
  6797. * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate
  6798. * scope (useful for component directives).
  6799. *
  6800. * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.
  6801. *
  6802. *
  6803. * #### `controller`
  6804. * Controller constructor function. The controller is instantiated before the
  6805. * pre-linking phase and can be accessed by other directives (see
  6806. * `require` attribute). This allows the directives to communicate with each other and augment
  6807. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  6808. *
  6809. * * `$scope` - Current scope associated with the element
  6810. * * `$element` - Current element
  6811. * * `$attrs` - Current attributes object for the element
  6812. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  6813. * `function([scope], cloneLinkingFn, futureParentElement, slotName)`:
  6814. * * `scope`: (optional) override the scope.
  6815. * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.
  6816. * * `futureParentElement` (optional):
  6817. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  6818. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  6819. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  6820. * and when the `cloneLinkingFn` is passed,
  6821. * as those elements need to created and cloned in a special way when they are defined outside their
  6822. * usual containers (e.g. like `<svg>`).
  6823. * * See also the `directive.templateNamespace` property.
  6824. * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`)
  6825. * then the default transclusion is provided.
  6826. * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns
  6827. * `true` if the specified slot contains content (i.e. one or more DOM nodes).
  6828. *
  6829. * #### `require`
  6830. * Require another directive and inject its controller as the fourth argument to the linking function. The
  6831. * `require` property can be a string, an array or an object:
  6832. * * a **string** containing the name of the directive to pass to the linking function
  6833. * * an **array** containing the names of directives to pass to the linking function. The argument passed to the
  6834. * linking function will be an array of controllers in the same order as the names in the `require` property
  6835. * * an **object** whose property values are the names of the directives to pass to the linking function. The argument
  6836. * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding
  6837. * controllers.
  6838. *
  6839. * If the `require` property is an object and `bindToController` is truthy, then the required controllers are
  6840. * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers
  6841. * have been constructed but before `$onInit` is called.
  6842. * If the name of the required controller is the same as the local name (the key), the name can be
  6843. * omitted. For example, `{parentDir: '^^'}` is equivalent to `{parentDir: '^^parentDir'}`.
  6844. * See the {@link $compileProvider#component} helper for an example of how this can be used.
  6845. * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is
  6846. * raised (unless no link function is specified and the required controllers are not being bound to the directive
  6847. * controller, in which case error checking is skipped). The name can be prefixed with:
  6848. *
  6849. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  6850. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  6851. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  6852. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  6853. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  6854. * `null` to the `link` fn if not found.
  6855. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  6856. * `null` to the `link` fn if not found.
  6857. *
  6858. *
  6859. * #### `controllerAs`
  6860. * Identifier name for a reference to the controller in the directive's scope.
  6861. * This allows the controller to be referenced from the directive template. This is especially
  6862. * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
  6863. * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
  6864. * `controllerAs` reference might overwrite a property that already exists on the parent scope.
  6865. *
  6866. *
  6867. * #### `restrict`
  6868. * String of subset of `EACM` which restricts the directive to a specific directive
  6869. * declaration style. If omitted, the defaults (elements and attributes) are used.
  6870. *
  6871. * * `E` - Element name (default): `<my-directive></my-directive>`
  6872. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  6873. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  6874. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  6875. *
  6876. *
  6877. * #### `templateNamespace`
  6878. * String representing the document type used by the markup in the template.
  6879. * AngularJS needs this information as those elements need to be created and cloned
  6880. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  6881. *
  6882. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  6883. * top-level elements such as `<svg>` or `<math>`.
  6884. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  6885. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  6886. *
  6887. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  6888. *
  6889. * #### `template`
  6890. * HTML markup that may:
  6891. * * Replace the contents of the directive's element (default).
  6892. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  6893. * * Wrap the contents of the directive's element (if `transclude` is true).
  6894. *
  6895. * Value may be:
  6896. *
  6897. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  6898. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  6899. * function api below) and returns a string value.
  6900. *
  6901. *
  6902. * #### `templateUrl`
  6903. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  6904. *
  6905. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  6906. * for later when the template has been resolved. In the meantime it will continue to compile and link
  6907. * sibling and parent elements as though this element had not contained any directives.
  6908. *
  6909. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  6910. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  6911. * case when only one deeply nested directive has `templateUrl`.
  6912. *
  6913. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  6914. *
  6915. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  6916. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  6917. * a string value representing the url. In either case, the template URL is passed through {@link
  6918. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  6919. *
  6920. *
  6921. * #### `replace` (*DEPRECATED*)
  6922. *
  6923. * `replace` will be removed in next major release - i.e. v2.0).
  6924. *
  6925. * Specifies what the template should replace. Defaults to `false`.
  6926. *
  6927. * * `true` - the template will replace the directive's element.
  6928. * * `false` - the template will replace the contents of the directive's element.
  6929. *
  6930. * The replacement process migrates all of the attributes / classes from the old element to the new
  6931. * one. See the {@link guide/directive#template-expanding-directive
  6932. * Directives Guide} for an example.
  6933. *
  6934. * There are very few scenarios where element replacement is required for the application function,
  6935. * the main one being reusable custom components that are used within SVG contexts
  6936. * (because SVG doesn't work with custom elements in the DOM tree).
  6937. *
  6938. * #### `transclude`
  6939. * Extract the contents of the element where the directive appears and make it available to the directive.
  6940. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  6941. * {@link $compile#transclusion Transclusion} section below.
  6942. *
  6943. *
  6944. * #### `compile`
  6945. *
  6946. * ```js
  6947. * function compile(tElement, tAttrs, transclude) { ... }
  6948. * ```
  6949. *
  6950. * The compile function deals with transforming the template DOM. Since most directives do not do
  6951. * template transformation, it is not used often. The compile function takes the following arguments:
  6952. *
  6953. * * `tElement` - template element - The element where the directive has been declared. It is
  6954. * safe to do template transformation on the element and child elements only.
  6955. *
  6956. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  6957. * between all directive compile functions.
  6958. *
  6959. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  6960. *
  6961. * <div class="alert alert-warning">
  6962. * **Note:** The template instance and the link instance may be different objects if the template has
  6963. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  6964. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  6965. * should be done in a linking function rather than in a compile function.
  6966. * </div>
  6967. * <div class="alert alert-warning">
  6968. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  6969. * own templates or compile functions. Compiling these directives results in an infinite loop and
  6970. * stack overflow errors.
  6971. *
  6972. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  6973. * a directive's template instead of relying on automatic template compilation via `template` or
  6974. * `templateUrl` declaration or manual compilation inside the compile function.
  6975. * </div>
  6976. *
  6977. * <div class="alert alert-danger">
  6978. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  6979. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  6980. * to the link function instead.
  6981. * </div>
  6982. * A compile function can have a return value which can be either a function or an object.
  6983. *
  6984. * * returning a (post-link) function - is equivalent to registering the linking function via the
  6985. * `link` property of the config object when the compile function is empty.
  6986. *
  6987. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  6988. * control when a linking function should be called during the linking phase. See info about
  6989. * pre-linking and post-linking functions below.
  6990. *
  6991. *
  6992. * #### `link`
  6993. * This property is used only if the `compile` property is not defined.
  6994. *
  6995. * ```js
  6996. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  6997. * ```
  6998. *
  6999. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  7000. * executed after the template has been cloned. This is where most of the directive logic will be
  7001. * put.
  7002. *
  7003. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  7004. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  7005. *
  7006. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  7007. * manipulate the children of the element only in `postLink` function since the children have
  7008. * already been linked.
  7009. *
  7010. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  7011. * between all directive linking functions.
  7012. *
  7013. * * `controller` - the directive's required controller instance(s) - Instances are shared
  7014. * among all directives, which allows the directives to use the controllers as a communication
  7015. * channel. The exact value depends on the directive's `require` property:
  7016. * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
  7017. * * `string`: the controller instance
  7018. * * `array`: array of controller instances
  7019. *
  7020. * If a required controller cannot be found, and it is optional, the instance is `null`,
  7021. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  7022. *
  7023. * Note that you can also require the directive's own controller - it will be made available like
  7024. * any other controller.
  7025. *
  7026. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  7027. * This is the same as the `$transclude` parameter of directive controllers,
  7028. * see {@link ng.$compile#-controller- the controller section for details}.
  7029. * `function([scope], cloneLinkingFn, futureParentElement)`.
  7030. *
  7031. * #### Pre-linking function
  7032. *
  7033. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  7034. * compiler linking function will fail to locate the correct elements for linking.
  7035. *
  7036. * #### Post-linking function
  7037. *
  7038. * Executed after the child elements are linked.
  7039. *
  7040. * Note that child elements that contain `templateUrl` directives will not have been compiled
  7041. * and linked since they are waiting for their template to load asynchronously and their own
  7042. * compilation and linking has been suspended until that occurs.
  7043. *
  7044. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  7045. * for their async templates to be resolved.
  7046. *
  7047. *
  7048. * ### Transclusion
  7049. *
  7050. * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
  7051. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  7052. * scope from where they were taken.
  7053. *
  7054. * Transclusion is used (often with {@link ngTransclude}) to insert the
  7055. * original contents of a directive's element into a specified place in the template of the directive.
  7056. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  7057. * content has access to the properties on the scope from which it was taken, even if the directive
  7058. * has isolated scope.
  7059. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  7060. *
  7061. * This makes it possible for the widget to have private state for its template, while the transcluded
  7062. * content has access to its originating scope.
  7063. *
  7064. * <div class="alert alert-warning">
  7065. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  7066. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  7067. * Testing Transclusion Directives}.
  7068. * </div>
  7069. *
  7070. * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the
  7071. * directive's element, the entire element or multiple parts of the element contents:
  7072. *
  7073. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  7074. * * `'element'` - transclude the whole of the directive's element including any directives on this
  7075. * element that defined at a lower priority than this directive. When used, the `template`
  7076. * property is ignored.
  7077. * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template.
  7078. *
  7079. * **Mult-slot transclusion** is declared by providing an object for the `transclude` property.
  7080. *
  7081. * This object is a map where the keys are the name of the slot to fill and the value is an element selector
  7082. * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`)
  7083. * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc).
  7084. *
  7085. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  7086. *
  7087. * If the element selector is prefixed with a `?` then that slot is optional.
  7088. *
  7089. * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `<my-custom-element>` elements to
  7090. * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive.
  7091. *
  7092. * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements
  7093. * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call
  7094. * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and
  7095. * injectable into the directive's controller.
  7096. *
  7097. *
  7098. * #### Transclusion Functions
  7099. *
  7100. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  7101. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  7102. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  7103. *
  7104. * <div class="alert alert-info">
  7105. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  7106. * ngTransclude will deal with it for us.
  7107. * </div>
  7108. *
  7109. * If you want to manually control the insertion and removal of the transcluded content in your directive
  7110. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  7111. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  7112. *
  7113. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  7114. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  7115. * content and the `scope` is the newly created transclusion scope, which the clone will be linked to.
  7116. *
  7117. * <div class="alert alert-info">
  7118. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function
  7119. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  7120. * </div>
  7121. *
  7122. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  7123. * attach function**:
  7124. *
  7125. * ```js
  7126. * var transcludedContent, transclusionScope;
  7127. *
  7128. * $transclude(function(clone, scope) {
  7129. * element.append(clone);
  7130. * transcludedContent = clone;
  7131. * transclusionScope = scope;
  7132. * });
  7133. * ```
  7134. *
  7135. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  7136. * associated transclusion scope:
  7137. *
  7138. * ```js
  7139. * transcludedContent.remove();
  7140. * transclusionScope.$destroy();
  7141. * ```
  7142. *
  7143. * <div class="alert alert-info">
  7144. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  7145. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  7146. * then you are also responsible for calling `$destroy` on the transclusion scope.
  7147. * </div>
  7148. *
  7149. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  7150. * automatically destroy their transcluded clones as necessary so you do not need to worry about this if
  7151. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  7152. *
  7153. *
  7154. * #### Transclusion Scopes
  7155. *
  7156. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  7157. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  7158. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  7159. * was taken.
  7160. *
  7161. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  7162. * like this:
  7163. *
  7164. * ```html
  7165. * <div ng-app>
  7166. * <div isolate>
  7167. * <div transclusion>
  7168. * </div>
  7169. * </div>
  7170. * </div>
  7171. * ```
  7172. *
  7173. * The `$parent` scope hierarchy will look like this:
  7174. *
  7175. ```
  7176. - $rootScope
  7177. - isolate
  7178. - transclusion
  7179. ```
  7180. *
  7181. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  7182. *
  7183. ```
  7184. - $rootScope
  7185. - transclusion
  7186. - isolate
  7187. ```
  7188. *
  7189. *
  7190. * ### Attributes
  7191. *
  7192. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  7193. * `link()` or `compile()` functions. It has a variety of uses.
  7194. *
  7195. * * *Accessing normalized attribute names:* Directives like 'ngBind' can be expressed in many ways:
  7196. * 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. The attributes object allows for normalized access
  7197. * to the attributes.
  7198. *
  7199. * * *Directive inter-communication:* All directives share the same instance of the attributes
  7200. * object which allows the directives to use the attributes object as inter directive
  7201. * communication.
  7202. *
  7203. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  7204. * allowing other directives to read the interpolated value.
  7205. *
  7206. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  7207. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  7208. * the only way to easily get the actual value because during the linking phase the interpolation
  7209. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  7210. *
  7211. * ```js
  7212. * function linkingFn(scope, elm, attrs, ctrl) {
  7213. * // get the attribute value
  7214. * console.log(attrs.ngModel);
  7215. *
  7216. * // change the attribute
  7217. * attrs.$set('ngModel', 'new value');
  7218. *
  7219. * // observe changes to interpolated attribute
  7220. * attrs.$observe('ngModel', function(value) {
  7221. * console.log('ngModel has changed value to ' + value);
  7222. * });
  7223. * }
  7224. * ```
  7225. *
  7226. * ## Example
  7227. *
  7228. * <div class="alert alert-warning">
  7229. * **Note**: Typically directives are registered with `module.directive`. The example below is
  7230. * to illustrate how `$compile` works.
  7231. * </div>
  7232. *
  7233. <example module="compileExample" name="compile">
  7234. <file name="index.html">
  7235. <script>
  7236. angular.module('compileExample', [], function($compileProvider) {
  7237. // configure new 'compile' directive by passing a directive
  7238. // factory function. The factory function injects the '$compile'
  7239. $compileProvider.directive('compile', function($compile) {
  7240. // directive factory creates a link function
  7241. return function(scope, element, attrs) {
  7242. scope.$watch(
  7243. function(scope) {
  7244. // watch the 'compile' expression for changes
  7245. return scope.$eval(attrs.compile);
  7246. },
  7247. function(value) {
  7248. // when the 'compile' expression changes
  7249. // assign it into the current DOM
  7250. element.html(value);
  7251. // compile the new DOM and link it to the current
  7252. // scope.
  7253. // NOTE: we only compile .childNodes so that
  7254. // we don't get into infinite loop compiling ourselves
  7255. $compile(element.contents())(scope);
  7256. }
  7257. );
  7258. };
  7259. });
  7260. })
  7261. .controller('GreeterController', ['$scope', function($scope) {
  7262. $scope.name = 'Angular';
  7263. $scope.html = 'Hello {{name}}';
  7264. }]);
  7265. </script>
  7266. <div ng-controller="GreeterController">
  7267. <input ng-model="name"> <br/>
  7268. <textarea ng-model="html"></textarea> <br/>
  7269. <div compile="html"></div>
  7270. </div>
  7271. </file>
  7272. <file name="protractor.js" type="protractor">
  7273. it('should auto compile', function() {
  7274. var textarea = $('textarea');
  7275. var output = $('div[compile]');
  7276. // The initial state reads 'Hello Angular'.
  7277. expect(output.getText()).toBe('Hello Angular');
  7278. textarea.clear();
  7279. textarea.sendKeys('{{name}}!');
  7280. expect(output.getText()).toBe('Angular!');
  7281. });
  7282. </file>
  7283. </example>
  7284. *
  7285. *
  7286. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  7287. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  7288. *
  7289. * <div class="alert alert-danger">
  7290. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  7291. * e.g. will not use the right outer scope. Please pass the transclude function as a
  7292. * `parentBoundTranscludeFn` to the link function instead.
  7293. * </div>
  7294. *
  7295. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  7296. * root element(s), not their children)
  7297. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  7298. * (a DOM element/tree) to a scope. Where:
  7299. *
  7300. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  7301. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  7302. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  7303. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  7304. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  7305. *
  7306. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  7307. * * `scope` - is the current scope with which the linking function is working with.
  7308. *
  7309. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  7310. * keys may be used to control linking behavior:
  7311. *
  7312. * * `parentBoundTranscludeFn` - the transclude function made available to
  7313. * directives; if given, it will be passed through to the link functions of
  7314. * directives found in `element` during compilation.
  7315. * * `transcludeControllers` - an object hash with keys that map controller names
  7316. * to a hash with the key `instance`, which maps to the controller instance;
  7317. * if given, it will make the controllers available to directives on the compileNode:
  7318. * ```
  7319. * {
  7320. * parent: {
  7321. * instance: parentControllerInstance
  7322. * }
  7323. * }
  7324. * ```
  7325. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  7326. * the cloned elements; only needed for transcludes that are allowed to contain non html
  7327. * elements (e.g. SVG elements). See also the directive.controller property.
  7328. *
  7329. * Calling the linking function returns the element of the template. It is either the original
  7330. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  7331. *
  7332. * After linking the view is not updated until after a call to $digest which typically is done by
  7333. * Angular automatically.
  7334. *
  7335. * If you need access to the bound view, there are two ways to do it:
  7336. *
  7337. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  7338. * before you send them to the compiler and keep this reference around.
  7339. * ```js
  7340. * var element = $compile('<p>{{total}}</p>')(scope);
  7341. * ```
  7342. *
  7343. * - if on the other hand, you need the element to be cloned, the view reference from the original
  7344. * example would not point to the clone, but rather to the original template that was cloned. In
  7345. * this case, you can access the clone via the cloneAttachFn:
  7346. * ```js
  7347. * var templateElement = angular.element('<p>{{total}}</p>'),
  7348. * scope = ....;
  7349. *
  7350. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  7351. * //attach the clone to DOM document at the right place
  7352. * });
  7353. *
  7354. * //now we have reference to the cloned DOM via `clonedElement`
  7355. * ```
  7356. *
  7357. *
  7358. * For information on how the compiler works, see the
  7359. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  7360. *
  7361. * @knownIssue
  7362. *
  7363. * ### Double Compilation
  7364. *
  7365. Double compilation occurs when an already compiled part of the DOM gets
  7366. compiled again. This is an undesired effect and can lead to misbehaving directives, performance issues,
  7367. and memory leaks. Refer to the Compiler Guide {@link guide/compiler#double-compilation-and-how-to-avoid-it
  7368. section on double compilation} for an in-depth explanation and ways to avoid it.
  7369. *
  7370. */
  7371. var $compileMinErr = minErr('$compile');
  7372. function UNINITIALIZED_VALUE() {}
  7373. var _UNINITIALIZED_VALUE = new UNINITIALIZED_VALUE();
  7374. /**
  7375. * @ngdoc provider
  7376. * @name $compileProvider
  7377. *
  7378. * @description
  7379. */
  7380. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  7381. /** @this */
  7382. function $CompileProvider($provide, $$sanitizeUriProvider) {
  7383. var hasDirectives = {},
  7384. Suffix = 'Directive',
  7385. COMMENT_DIRECTIVE_REGEXP = /^\s*directive:\s*([\w-]+)\s+(.*)$/,
  7386. CLASS_DIRECTIVE_REGEXP = /(([\w-]+)(?::([^;]+))?;?)/,
  7387. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  7388. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  7389. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  7390. // The assumption is that future DOM event attribute names will begin with
  7391. // 'on' and be composed of only English letters.
  7392. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  7393. var bindingCache = createMap();
  7394. function parseIsolateBindings(scope, directiveName, isController) {
  7395. var LOCAL_REGEXP = /^\s*([@&<]|=(\*?))(\??)\s*([\w$]*)\s*$/;
  7396. var bindings = createMap();
  7397. forEach(scope, function(definition, scopeName) {
  7398. if (definition in bindingCache) {
  7399. bindings[scopeName] = bindingCache[definition];
  7400. return;
  7401. }
  7402. var match = definition.match(LOCAL_REGEXP);
  7403. if (!match) {
  7404. throw $compileMinErr('iscp',
  7405. 'Invalid {3} for directive \'{0}\'.' +
  7406. ' Definition: {... {1}: \'{2}\' ...}',
  7407. directiveName, scopeName, definition,
  7408. (isController ? 'controller bindings definition' :
  7409. 'isolate scope definition'));
  7410. }
  7411. bindings[scopeName] = {
  7412. mode: match[1][0],
  7413. collection: match[2] === '*',
  7414. optional: match[3] === '?',
  7415. attrName: match[4] || scopeName
  7416. };
  7417. if (match[4]) {
  7418. bindingCache[definition] = bindings[scopeName];
  7419. }
  7420. });
  7421. return bindings;
  7422. }
  7423. function parseDirectiveBindings(directive, directiveName) {
  7424. var bindings = {
  7425. isolateScope: null,
  7426. bindToController: null
  7427. };
  7428. if (isObject(directive.scope)) {
  7429. if (directive.bindToController === true) {
  7430. bindings.bindToController = parseIsolateBindings(directive.scope,
  7431. directiveName, true);
  7432. bindings.isolateScope = {};
  7433. } else {
  7434. bindings.isolateScope = parseIsolateBindings(directive.scope,
  7435. directiveName, false);
  7436. }
  7437. }
  7438. if (isObject(directive.bindToController)) {
  7439. bindings.bindToController =
  7440. parseIsolateBindings(directive.bindToController, directiveName, true);
  7441. }
  7442. if (bindings.bindToController && !directive.controller) {
  7443. // There is no controller
  7444. throw $compileMinErr('noctrl',
  7445. 'Cannot bind to controller without directive \'{0}\'s controller.',
  7446. directiveName);
  7447. }
  7448. return bindings;
  7449. }
  7450. function assertValidDirectiveName(name) {
  7451. var letter = name.charAt(0);
  7452. if (!letter || letter !== lowercase(letter)) {
  7453. throw $compileMinErr('baddir', 'Directive/Component name \'{0}\' is invalid. The first character must be a lowercase letter', name);
  7454. }
  7455. if (name !== name.trim()) {
  7456. throw $compileMinErr('baddir',
  7457. 'Directive/Component name \'{0}\' is invalid. The name should not contain leading or trailing whitespaces',
  7458. name);
  7459. }
  7460. }
  7461. function getDirectiveRequire(directive) {
  7462. var require = directive.require || (directive.controller && directive.name);
  7463. if (!isArray(require) && isObject(require)) {
  7464. forEach(require, function(value, key) {
  7465. var match = value.match(REQUIRE_PREFIX_REGEXP);
  7466. var name = value.substring(match[0].length);
  7467. if (!name) require[key] = match[0] + key;
  7468. });
  7469. }
  7470. return require;
  7471. }
  7472. function getDirectiveRestrict(restrict, name) {
  7473. if (restrict && !(isString(restrict) && /[EACM]/.test(restrict))) {
  7474. throw $compileMinErr('badrestrict',
  7475. 'Restrict property \'{0}\' of directive \'{1}\' is invalid',
  7476. restrict,
  7477. name);
  7478. }
  7479. return restrict || 'EA';
  7480. }
  7481. /**
  7482. * @ngdoc method
  7483. * @name $compileProvider#directive
  7484. * @kind function
  7485. *
  7486. * @description
  7487. * Register a new directive with the compiler.
  7488. *
  7489. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  7490. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  7491. * names and the values are the factories.
  7492. * @param {Function|Array} directiveFactory An injectable directive factory function. See the
  7493. * {@link guide/directive directive guide} and the {@link $compile compile API} for more info.
  7494. * @returns {ng.$compileProvider} Self for chaining.
  7495. */
  7496. this.directive = function registerDirective(name, directiveFactory) {
  7497. assertArg(name, 'name');
  7498. assertNotHasOwnProperty(name, 'directive');
  7499. if (isString(name)) {
  7500. assertValidDirectiveName(name);
  7501. assertArg(directiveFactory, 'directiveFactory');
  7502. if (!hasDirectives.hasOwnProperty(name)) {
  7503. hasDirectives[name] = [];
  7504. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  7505. function($injector, $exceptionHandler) {
  7506. var directives = [];
  7507. forEach(hasDirectives[name], function(directiveFactory, index) {
  7508. try {
  7509. var directive = $injector.invoke(directiveFactory);
  7510. if (isFunction(directive)) {
  7511. directive = { compile: valueFn(directive) };
  7512. } else if (!directive.compile && directive.link) {
  7513. directive.compile = valueFn(directive.link);
  7514. }
  7515. directive.priority = directive.priority || 0;
  7516. directive.index = index;
  7517. directive.name = directive.name || name;
  7518. directive.require = getDirectiveRequire(directive);
  7519. directive.restrict = getDirectiveRestrict(directive.restrict, name);
  7520. directive.$$moduleName = directiveFactory.$$moduleName;
  7521. directives.push(directive);
  7522. } catch (e) {
  7523. $exceptionHandler(e);
  7524. }
  7525. });
  7526. return directives;
  7527. }]);
  7528. }
  7529. hasDirectives[name].push(directiveFactory);
  7530. } else {
  7531. forEach(name, reverseParams(registerDirective));
  7532. }
  7533. return this;
  7534. };
  7535. /**
  7536. * @ngdoc method
  7537. * @name $compileProvider#component
  7538. * @module ng
  7539. * @param {string|Object} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`),
  7540. * or an object map of components where the keys are the names and the values are the component definition objects.
  7541. * @param {Object} options Component definition object (a simplified
  7542. * {@link ng.$compile#directive-definition-object directive definition object}),
  7543. * with the following properties (all optional):
  7544. *
  7545. * - `controller` – `{(string|function()=}` – controller constructor function that should be
  7546. * associated with newly created scope or the name of a {@link ng.$compile#-controller-
  7547. * registered controller} if passed as a string. An empty `noop` function by default.
  7548. * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope.
  7549. * If present, the controller will be published to scope under the `controllerAs` name.
  7550. * If not present, this will default to be `$ctrl`.
  7551. * - `template` – `{string=|function()=}` – html template as a string or a function that
  7552. * returns an html template as a string which should be used as the contents of this component.
  7553. * Empty string by default.
  7554. *
  7555. * If `template` is a function, then it is {@link auto.$injector#invoke injected} with
  7556. * the following locals:
  7557. *
  7558. * - `$element` - Current element
  7559. * - `$attrs` - Current attributes object for the element
  7560. *
  7561. * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
  7562. * template that should be used as the contents of this component.
  7563. *
  7564. * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
  7565. * the following locals:
  7566. *
  7567. * - `$element` - Current element
  7568. * - `$attrs` - Current attributes object for the element
  7569. *
  7570. * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties.
  7571. * Component properties are always bound to the component controller and not to the scope.
  7572. * See {@link ng.$compile#-bindtocontroller- `bindToController`}.
  7573. * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled.
  7574. * Disabled by default.
  7575. * - `require` - `{Object<string, string>=}` - requires the controllers of other directives and binds them to
  7576. * this component's controller. The object keys specify the property names under which the required
  7577. * controllers (object values) will be bound. See {@link ng.$compile#-require- `require`}.
  7578. * - `$...` – additional properties to attach to the directive factory function and the controller
  7579. * constructor function. (This is used by the component router to annotate)
  7580. *
  7581. * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls.
  7582. * @description
  7583. * Register a **component definition** with the compiler. This is a shorthand for registering a special
  7584. * type of directive, which represents a self-contained UI component in your application. Such components
  7585. * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`).
  7586. *
  7587. * Component definitions are very simple and do not require as much configuration as defining general
  7588. * directives. Component definitions usually consist only of a template and a controller backing it.
  7589. *
  7590. * In order to make the definition easier, components enforce best practices like use of `controllerAs`,
  7591. * `bindToController`. They always have **isolate scope** and are restricted to elements.
  7592. *
  7593. * Here are a few examples of how you would usually define components:
  7594. *
  7595. * ```js
  7596. * var myMod = angular.module(...);
  7597. * myMod.component('myComp', {
  7598. * template: '<div>My name is {{$ctrl.name}}</div>',
  7599. * controller: function() {
  7600. * this.name = 'shahar';
  7601. * }
  7602. * });
  7603. *
  7604. * myMod.component('myComp', {
  7605. * template: '<div>My name is {{$ctrl.name}}</div>',
  7606. * bindings: {name: '@'}
  7607. * });
  7608. *
  7609. * myMod.component('myComp', {
  7610. * templateUrl: 'views/my-comp.html',
  7611. * controller: 'MyCtrl',
  7612. * controllerAs: 'ctrl',
  7613. * bindings: {name: '@'}
  7614. * });
  7615. *
  7616. * ```
  7617. * For more examples, and an in-depth guide, see the {@link guide/component component guide}.
  7618. *
  7619. * <br />
  7620. * See also {@link ng.$compileProvider#directive $compileProvider.directive()}.
  7621. */
  7622. this.component = function registerComponent(name, options) {
  7623. if (!isString(name)) {
  7624. forEach(name, reverseParams(bind(this, registerComponent)));
  7625. return this;
  7626. }
  7627. var controller = options.controller || function() {};
  7628. function factory($injector) {
  7629. function makeInjectable(fn) {
  7630. if (isFunction(fn) || isArray(fn)) {
  7631. return /** @this */ function(tElement, tAttrs) {
  7632. return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
  7633. };
  7634. } else {
  7635. return fn;
  7636. }
  7637. }
  7638. var template = (!options.template && !options.templateUrl ? '' : options.template);
  7639. var ddo = {
  7640. controller: controller,
  7641. controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',
  7642. template: makeInjectable(template),
  7643. templateUrl: makeInjectable(options.templateUrl),
  7644. transclude: options.transclude,
  7645. scope: {},
  7646. bindToController: options.bindings || {},
  7647. restrict: 'E',
  7648. require: options.require
  7649. };
  7650. // Copy annotations (starting with $) over to the DDO
  7651. forEach(options, function(val, key) {
  7652. if (key.charAt(0) === '$') ddo[key] = val;
  7653. });
  7654. return ddo;
  7655. }
  7656. // TODO(pete) remove the following `forEach` before we release 1.6.0
  7657. // The component-router@0.2.0 looks for the annotations on the controller constructor
  7658. // Nothing in Angular looks for annotations on the factory function but we can't remove
  7659. // it from 1.5.x yet.
  7660. // Copy any annotation properties (starting with $) over to the factory and controller constructor functions
  7661. // These could be used by libraries such as the new component router
  7662. forEach(options, function(val, key) {
  7663. if (key.charAt(0) === '$') {
  7664. factory[key] = val;
  7665. // Don't try to copy over annotations to named controller
  7666. if (isFunction(controller)) controller[key] = val;
  7667. }
  7668. });
  7669. factory.$inject = ['$injector'];
  7670. return this.directive(name, factory);
  7671. };
  7672. /**
  7673. * @ngdoc method
  7674. * @name $compileProvider#aHrefSanitizationWhitelist
  7675. * @kind function
  7676. *
  7677. * @description
  7678. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  7679. * urls during a[href] sanitization.
  7680. *
  7681. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  7682. *
  7683. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  7684. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  7685. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  7686. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  7687. *
  7688. * @param {RegExp=} regexp New regexp to whitelist urls with.
  7689. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  7690. * chaining otherwise.
  7691. */
  7692. this.aHrefSanitizationWhitelist = function(regexp) {
  7693. if (isDefined(regexp)) {
  7694. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  7695. return this;
  7696. } else {
  7697. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  7698. }
  7699. };
  7700. /**
  7701. * @ngdoc method
  7702. * @name $compileProvider#imgSrcSanitizationWhitelist
  7703. * @kind function
  7704. *
  7705. * @description
  7706. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  7707. * urls during img[src] sanitization.
  7708. *
  7709. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  7710. *
  7711. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  7712. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  7713. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  7714. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  7715. *
  7716. * @param {RegExp=} regexp New regexp to whitelist urls with.
  7717. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  7718. * chaining otherwise.
  7719. */
  7720. this.imgSrcSanitizationWhitelist = function(regexp) {
  7721. if (isDefined(regexp)) {
  7722. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  7723. return this;
  7724. } else {
  7725. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  7726. }
  7727. };
  7728. /**
  7729. * @ngdoc method
  7730. * @name $compileProvider#debugInfoEnabled
  7731. *
  7732. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  7733. * current debugInfoEnabled state
  7734. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  7735. *
  7736. * @kind function
  7737. *
  7738. * @description
  7739. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  7740. * binding information and a reference to the current scope on to DOM elements.
  7741. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  7742. * * `ng-binding` CSS class
  7743. * * `ng-scope` and `ng-isolated-scope` CSS classes
  7744. * * `$binding` data property containing an array of the binding expressions
  7745. * * Data properties used by the {@link angular.element#methods `scope()`/`isolateScope()` methods} to return
  7746. * the element's scope.
  7747. * * Placeholder comments will contain information about what directive and binding caused the placeholder.
  7748. * E.g. `<!-- ngIf: shouldShow() -->`.
  7749. *
  7750. * You may want to disable this in production for a significant performance boost. See
  7751. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  7752. *
  7753. * The default value is true.
  7754. */
  7755. var debugInfoEnabled = true;
  7756. this.debugInfoEnabled = function(enabled) {
  7757. if (isDefined(enabled)) {
  7758. debugInfoEnabled = enabled;
  7759. return this;
  7760. }
  7761. return debugInfoEnabled;
  7762. };
  7763. /**
  7764. * @ngdoc method
  7765. * @name $compileProvider#preAssignBindingsEnabled
  7766. *
  7767. * @param {boolean=} enabled update the preAssignBindingsEnabled state if provided, otherwise just return the
  7768. * current preAssignBindingsEnabled state
  7769. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  7770. *
  7771. * @kind function
  7772. *
  7773. * @description
  7774. * Call this method to enable/disable whether directive controllers are assigned bindings before
  7775. * calling the controller's constructor.
  7776. * If enabled (true), the compiler assigns the value of each of the bindings to the
  7777. * properties of the controller object before the constructor of this object is called.
  7778. *
  7779. * If disabled (false), the compiler calls the constructor first before assigning bindings.
  7780. *
  7781. * The default value is false.
  7782. *
  7783. * @deprecated
  7784. * sinceVersion="1.6.0"
  7785. * removeVersion="1.7.0"
  7786. *
  7787. * This method and the option to assign the bindings before calling the controller's constructor
  7788. * will be removed in v1.7.0.
  7789. */
  7790. var preAssignBindingsEnabled = false;
  7791. this.preAssignBindingsEnabled = function(enabled) {
  7792. if (isDefined(enabled)) {
  7793. preAssignBindingsEnabled = enabled;
  7794. return this;
  7795. }
  7796. return preAssignBindingsEnabled;
  7797. };
  7798. /**
  7799. * @ngdoc method
  7800. * @name $compileProvider#strictComponentBindingsEnabled
  7801. *
  7802. * @param {boolean=} enabled update the strictComponentBindingsEnabled state if provided, otherwise just return the
  7803. * current strictComponentBindingsEnabled state
  7804. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  7805. *
  7806. * @kind function
  7807. *
  7808. * @description
  7809. * Call this method to enable/disable strict component bindings check. If enabled, the compiler will enforce that
  7810. * for all bindings of a component that are not set as optional with `?`, an attribute needs to be provided
  7811. * on the component's HTML tag.
  7812. *
  7813. * The default value is false.
  7814. */
  7815. var strictComponentBindingsEnabled = false;
  7816. this.strictComponentBindingsEnabled = function(enabled) {
  7817. if (isDefined(enabled)) {
  7818. strictComponentBindingsEnabled = enabled;
  7819. return this;
  7820. }
  7821. return strictComponentBindingsEnabled;
  7822. };
  7823. var TTL = 10;
  7824. /**
  7825. * @ngdoc method
  7826. * @name $compileProvider#onChangesTtl
  7827. * @description
  7828. *
  7829. * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and
  7830. * assuming that the model is unstable.
  7831. *
  7832. * The current default is 10 iterations.
  7833. *
  7834. * In complex applications it's possible that dependencies between `$onChanges` hooks and bindings will result
  7835. * in several iterations of calls to these hooks. However if an application needs more than the default 10
  7836. * iterations to stabilize then you should investigate what is causing the model to continuously change during
  7837. * the `$onChanges` hook execution.
  7838. *
  7839. * Increasing the TTL could have performance implications, so you should not change it without proper justification.
  7840. *
  7841. * @param {number} limit The number of `$onChanges` hook iterations.
  7842. * @returns {number|object} the current limit (or `this` if called as a setter for chaining)
  7843. */
  7844. this.onChangesTtl = function(value) {
  7845. if (arguments.length) {
  7846. TTL = value;
  7847. return this;
  7848. }
  7849. return TTL;
  7850. };
  7851. var commentDirectivesEnabledConfig = true;
  7852. /**
  7853. * @ngdoc method
  7854. * @name $compileProvider#commentDirectivesEnabled
  7855. * @description
  7856. *
  7857. * It indicates to the compiler
  7858. * whether or not directives on comments should be compiled.
  7859. * Defaults to `true`.
  7860. *
  7861. * Calling this function with false disables the compilation of directives
  7862. * on comments for the whole application.
  7863. * This results in a compilation performance gain,
  7864. * as the compiler doesn't have to check comments when looking for directives.
  7865. * This should however only be used if you are sure that no comment directives are used in
  7866. * the application (including any 3rd party directives).
  7867. *
  7868. * @param {boolean} enabled `false` if the compiler may ignore directives on comments
  7869. * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
  7870. */
  7871. this.commentDirectivesEnabled = function(value) {
  7872. if (arguments.length) {
  7873. commentDirectivesEnabledConfig = value;
  7874. return this;
  7875. }
  7876. return commentDirectivesEnabledConfig;
  7877. };
  7878. var cssClassDirectivesEnabledConfig = true;
  7879. /**
  7880. * @ngdoc method
  7881. * @name $compileProvider#cssClassDirectivesEnabled
  7882. * @description
  7883. *
  7884. * It indicates to the compiler
  7885. * whether or not directives on element classes should be compiled.
  7886. * Defaults to `true`.
  7887. *
  7888. * Calling this function with false disables the compilation of directives
  7889. * on element classes for the whole application.
  7890. * This results in a compilation performance gain,
  7891. * as the compiler doesn't have to check element classes when looking for directives.
  7892. * This should however only be used if you are sure that no class directives are used in
  7893. * the application (including any 3rd party directives).
  7894. *
  7895. * @param {boolean} enabled `false` if the compiler may ignore directives on element classes
  7896. * @returns {boolean|object} the current value (or `this` if called as a setter for chaining)
  7897. */
  7898. this.cssClassDirectivesEnabled = function(value) {
  7899. if (arguments.length) {
  7900. cssClassDirectivesEnabledConfig = value;
  7901. return this;
  7902. }
  7903. return cssClassDirectivesEnabledConfig;
  7904. };
  7905. this.$get = [
  7906. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  7907. '$controller', '$rootScope', '$sce', '$animate', '$$sanitizeUri',
  7908. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  7909. $controller, $rootScope, $sce, $animate, $$sanitizeUri) {
  7910. var SIMPLE_ATTR_NAME = /^\w/;
  7911. var specialAttrHolder = window.document.createElement('div');
  7912. var commentDirectivesEnabled = commentDirectivesEnabledConfig;
  7913. var cssClassDirectivesEnabled = cssClassDirectivesEnabledConfig;
  7914. var onChangesTtl = TTL;
  7915. // The onChanges hooks should all be run together in a single digest
  7916. // When changes occur, the call to trigger their hooks will be added to this queue
  7917. var onChangesQueue;
  7918. // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest
  7919. function flushOnChangesQueue() {
  7920. try {
  7921. if (!(--onChangesTtl)) {
  7922. // We have hit the TTL limit so reset everything
  7923. onChangesQueue = undefined;
  7924. throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\n', TTL);
  7925. }
  7926. // We must run this hook in an apply since the $$postDigest runs outside apply
  7927. $rootScope.$apply(function() {
  7928. var errors = [];
  7929. for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) {
  7930. try {
  7931. onChangesQueue[i]();
  7932. } catch (e) {
  7933. errors.push(e);
  7934. }
  7935. }
  7936. // Reset the queue to trigger a new schedule next time there is a change
  7937. onChangesQueue = undefined;
  7938. if (errors.length) {
  7939. throw errors;
  7940. }
  7941. });
  7942. } finally {
  7943. onChangesTtl++;
  7944. }
  7945. }
  7946. function Attributes(element, attributesToCopy) {
  7947. if (attributesToCopy) {
  7948. var keys = Object.keys(attributesToCopy);
  7949. var i, l, key;
  7950. for (i = 0, l = keys.length; i < l; i++) {
  7951. key = keys[i];
  7952. this[key] = attributesToCopy[key];
  7953. }
  7954. } else {
  7955. this.$attr = {};
  7956. }
  7957. this.$$element = element;
  7958. }
  7959. Attributes.prototype = {
  7960. /**
  7961. * @ngdoc method
  7962. * @name $compile.directive.Attributes#$normalize
  7963. * @kind function
  7964. *
  7965. * @description
  7966. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  7967. * `data-`) to its normalized, camelCase form.
  7968. *
  7969. * Also there is special case for Moz prefix starting with upper case letter.
  7970. *
  7971. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  7972. *
  7973. * @param {string} name Name to normalize
  7974. */
  7975. $normalize: directiveNormalize,
  7976. /**
  7977. * @ngdoc method
  7978. * @name $compile.directive.Attributes#$addClass
  7979. * @kind function
  7980. *
  7981. * @description
  7982. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  7983. * are enabled then an animation will be triggered for the class addition.
  7984. *
  7985. * @param {string} classVal The className value that will be added to the element
  7986. */
  7987. $addClass: function(classVal) {
  7988. if (classVal && classVal.length > 0) {
  7989. $animate.addClass(this.$$element, classVal);
  7990. }
  7991. },
  7992. /**
  7993. * @ngdoc method
  7994. * @name $compile.directive.Attributes#$removeClass
  7995. * @kind function
  7996. *
  7997. * @description
  7998. * Removes the CSS class value specified by the classVal parameter from the element. If
  7999. * animations are enabled then an animation will be triggered for the class removal.
  8000. *
  8001. * @param {string} classVal The className value that will be removed from the element
  8002. */
  8003. $removeClass: function(classVal) {
  8004. if (classVal && classVal.length > 0) {
  8005. $animate.removeClass(this.$$element, classVal);
  8006. }
  8007. },
  8008. /**
  8009. * @ngdoc method
  8010. * @name $compile.directive.Attributes#$updateClass
  8011. * @kind function
  8012. *
  8013. * @description
  8014. * Adds and removes the appropriate CSS class values to the element based on the difference
  8015. * between the new and old CSS class values (specified as newClasses and oldClasses).
  8016. *
  8017. * @param {string} newClasses The current CSS className value
  8018. * @param {string} oldClasses The former CSS className value
  8019. */
  8020. $updateClass: function(newClasses, oldClasses) {
  8021. var toAdd = tokenDifference(newClasses, oldClasses);
  8022. if (toAdd && toAdd.length) {
  8023. $animate.addClass(this.$$element, toAdd);
  8024. }
  8025. var toRemove = tokenDifference(oldClasses, newClasses);
  8026. if (toRemove && toRemove.length) {
  8027. $animate.removeClass(this.$$element, toRemove);
  8028. }
  8029. },
  8030. /**
  8031. * Set a normalized attribute on the element in a way such that all directives
  8032. * can share the attribute. This function properly handles boolean attributes.
  8033. * @param {string} key Normalized key. (ie ngAttribute)
  8034. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  8035. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  8036. * Defaults to true.
  8037. * @param {string=} attrName Optional none normalized name. Defaults to key.
  8038. */
  8039. $set: function(key, value, writeAttr, attrName) {
  8040. // TODO: decide whether or not to throw an error if "class"
  8041. //is set through this function since it may cause $updateClass to
  8042. //become unstable.
  8043. var node = this.$$element[0],
  8044. booleanKey = getBooleanAttrName(node, key),
  8045. aliasedKey = getAliasedAttrName(key),
  8046. observer = key,
  8047. nodeName;
  8048. if (booleanKey) {
  8049. this.$$element.prop(key, value);
  8050. attrName = booleanKey;
  8051. } else if (aliasedKey) {
  8052. this[aliasedKey] = value;
  8053. observer = aliasedKey;
  8054. }
  8055. this[key] = value;
  8056. // translate normalized key to actual key
  8057. if (attrName) {
  8058. this.$attr[key] = attrName;
  8059. } else {
  8060. attrName = this.$attr[key];
  8061. if (!attrName) {
  8062. this.$attr[key] = attrName = snake_case(key, '-');
  8063. }
  8064. }
  8065. nodeName = nodeName_(this.$$element);
  8066. if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) ||
  8067. (nodeName === 'img' && key === 'src')) {
  8068. // sanitize a[href] and img[src] values
  8069. this[key] = value = $$sanitizeUri(value, key === 'src');
  8070. } else if (nodeName === 'img' && key === 'srcset' && isDefined(value)) {
  8071. // sanitize img[srcset] values
  8072. var result = '';
  8073. // first check if there are spaces because it's not the same pattern
  8074. var trimmedSrcset = trim(value);
  8075. // ( 999x ,| 999w ,| ,|, )
  8076. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  8077. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  8078. // split srcset into tuple of uri and descriptor except for the last item
  8079. var rawUris = trimmedSrcset.split(pattern);
  8080. // for each tuples
  8081. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  8082. for (var i = 0; i < nbrUrisWith2parts; i++) {
  8083. var innerIdx = i * 2;
  8084. // sanitize the uri
  8085. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  8086. // add the descriptor
  8087. result += (' ' + trim(rawUris[innerIdx + 1]));
  8088. }
  8089. // split the last item into uri and descriptor
  8090. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  8091. // sanitize the last uri
  8092. result += $$sanitizeUri(trim(lastTuple[0]), true);
  8093. // and add the last descriptor if any
  8094. if (lastTuple.length === 2) {
  8095. result += (' ' + trim(lastTuple[1]));
  8096. }
  8097. this[key] = value = result;
  8098. }
  8099. if (writeAttr !== false) {
  8100. if (value === null || isUndefined(value)) {
  8101. this.$$element.removeAttr(attrName);
  8102. } else {
  8103. if (SIMPLE_ATTR_NAME.test(attrName)) {
  8104. this.$$element.attr(attrName, value);
  8105. } else {
  8106. setSpecialAttr(this.$$element[0], attrName, value);
  8107. }
  8108. }
  8109. }
  8110. // fire observers
  8111. var $$observers = this.$$observers;
  8112. if ($$observers) {
  8113. forEach($$observers[observer], function(fn) {
  8114. try {
  8115. fn(value);
  8116. } catch (e) {
  8117. $exceptionHandler(e);
  8118. }
  8119. });
  8120. }
  8121. },
  8122. /**
  8123. * @ngdoc method
  8124. * @name $compile.directive.Attributes#$observe
  8125. * @kind function
  8126. *
  8127. * @description
  8128. * Observes an interpolated attribute.
  8129. *
  8130. * The observer function will be invoked once during the next `$digest` following
  8131. * compilation. The observer is then invoked whenever the interpolated value
  8132. * changes.
  8133. *
  8134. * @param {string} key Normalized key. (ie ngAttribute) .
  8135. * @param {function(interpolatedValue)} fn Function that will be called whenever
  8136. the interpolated value of the attribute changes.
  8137. * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation
  8138. * guide} for more info.
  8139. * @returns {function()} Returns a deregistration function for this observer.
  8140. */
  8141. $observe: function(key, fn) {
  8142. var attrs = this,
  8143. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  8144. listeners = ($$observers[key] || ($$observers[key] = []));
  8145. listeners.push(fn);
  8146. $rootScope.$evalAsync(function() {
  8147. if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
  8148. // no one registered attribute interpolation function, so lets call it manually
  8149. fn(attrs[key]);
  8150. }
  8151. });
  8152. return function() {
  8153. arrayRemove(listeners, fn);
  8154. };
  8155. }
  8156. };
  8157. function setSpecialAttr(element, attrName, value) {
  8158. // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute`
  8159. // so we have to jump through some hoops to get such an attribute
  8160. // https://github.com/angular/angular.js/pull/13318
  8161. specialAttrHolder.innerHTML = '<span ' + attrName + '>';
  8162. var attributes = specialAttrHolder.firstChild.attributes;
  8163. var attribute = attributes[0];
  8164. // We have to remove the attribute from its container element before we can add it to the destination element
  8165. attributes.removeNamedItem(attribute.name);
  8166. attribute.value = value;
  8167. element.attributes.setNamedItem(attribute);
  8168. }
  8169. function safeAddClass($element, className) {
  8170. try {
  8171. $element.addClass(className);
  8172. } catch (e) {
  8173. // ignore, since it means that we are trying to set class on
  8174. // SVG element, where class name is read-only.
  8175. }
  8176. }
  8177. var startSymbol = $interpolate.startSymbol(),
  8178. endSymbol = $interpolate.endSymbol(),
  8179. denormalizeTemplate = (startSymbol === '{{' && endSymbol === '}}')
  8180. ? identity
  8181. : function denormalizeTemplate(template) {
  8182. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  8183. },
  8184. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  8185. var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
  8186. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  8187. var bindings = $element.data('$binding') || [];
  8188. if (isArray(binding)) {
  8189. bindings = bindings.concat(binding);
  8190. } else {
  8191. bindings.push(binding);
  8192. }
  8193. $element.data('$binding', bindings);
  8194. } : noop;
  8195. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  8196. safeAddClass($element, 'ng-binding');
  8197. } : noop;
  8198. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  8199. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  8200. $element.data(dataName, scope);
  8201. } : noop;
  8202. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  8203. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  8204. } : noop;
  8205. compile.$$createComment = function(directiveName, comment) {
  8206. var content = '';
  8207. if (debugInfoEnabled) {
  8208. content = ' ' + (directiveName || '') + ': ';
  8209. if (comment) content += comment + ' ';
  8210. }
  8211. return window.document.createComment(content);
  8212. };
  8213. return compile;
  8214. //================================
  8215. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  8216. previousCompileContext) {
  8217. if (!($compileNodes instanceof jqLite)) {
  8218. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  8219. // modify it.
  8220. $compileNodes = jqLite($compileNodes);
  8221. }
  8222. var compositeLinkFn =
  8223. compileNodes($compileNodes, transcludeFn, $compileNodes,
  8224. maxPriority, ignoreDirective, previousCompileContext);
  8225. compile.$$addScopeClass($compileNodes);
  8226. var namespace = null;
  8227. return function publicLinkFn(scope, cloneConnectFn, options) {
  8228. if (!$compileNodes) {
  8229. throw $compileMinErr('multilink', 'This element has already been linked.');
  8230. }
  8231. assertArg(scope, 'scope');
  8232. if (previousCompileContext && previousCompileContext.needsNewScope) {
  8233. // A parent directive did a replace and a directive on this element asked
  8234. // for transclusion, which caused us to lose a layer of element on which
  8235. // we could hold the new transclusion scope, so we will create it manually
  8236. // here.
  8237. scope = scope.$parent.$new();
  8238. }
  8239. options = options || {};
  8240. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  8241. transcludeControllers = options.transcludeControllers,
  8242. futureParentElement = options.futureParentElement;
  8243. // When `parentBoundTranscludeFn` is passed, it is a
  8244. // `controllersBoundTransclude` function (it was previously passed
  8245. // as `transclude` to directive.link) so we must unwrap it to get
  8246. // its `boundTranscludeFn`
  8247. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  8248. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  8249. }
  8250. if (!namespace) {
  8251. namespace = detectNamespaceForChildElements(futureParentElement);
  8252. }
  8253. var $linkNode;
  8254. if (namespace !== 'html') {
  8255. // When using a directive with replace:true and templateUrl the $compileNodes
  8256. // (or a child element inside of them)
  8257. // might change, so we need to recreate the namespace adapted compileNodes
  8258. // for call to the link function.
  8259. // Note: This will already clone the nodes...
  8260. $linkNode = jqLite(
  8261. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  8262. );
  8263. } else if (cloneConnectFn) {
  8264. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  8265. // and sometimes changes the structure of the DOM.
  8266. $linkNode = JQLitePrototype.clone.call($compileNodes);
  8267. } else {
  8268. $linkNode = $compileNodes;
  8269. }
  8270. if (transcludeControllers) {
  8271. for (var controllerName in transcludeControllers) {
  8272. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  8273. }
  8274. }
  8275. compile.$$addScopeInfo($linkNode, scope);
  8276. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  8277. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  8278. if (!cloneConnectFn) {
  8279. $compileNodes = compositeLinkFn = null;
  8280. }
  8281. return $linkNode;
  8282. };
  8283. }
  8284. function detectNamespaceForChildElements(parentElement) {
  8285. // TODO: Make this detect MathML as well...
  8286. var node = parentElement && parentElement[0];
  8287. if (!node) {
  8288. return 'html';
  8289. } else {
  8290. return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html';
  8291. }
  8292. }
  8293. /**
  8294. * Compile function matches each node in nodeList against the directives. Once all directives
  8295. * for a particular node are collected their compile functions are executed. The compile
  8296. * functions return values - the linking functions - are combined into a composite linking
  8297. * function, which is the a linking function for the node.
  8298. *
  8299. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  8300. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  8301. * scope argument is auto-generated to the new child of the transcluded parent scope.
  8302. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  8303. * the rootElement must be set the jqLite collection of the compile root. This is
  8304. * needed so that the jqLite collection items can be replaced with widgets.
  8305. * @param {number=} maxPriority Max directive priority.
  8306. * @returns {Function} A composite linking function of all of the matched directives or null.
  8307. */
  8308. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  8309. previousCompileContext) {
  8310. var linkFns = [],
  8311. // `nodeList` can be either an element's `.childNodes` (live NodeList)
  8312. // or a jqLite/jQuery collection or an array
  8313. notLiveList = isArray(nodeList) || (nodeList instanceof jqLite),
  8314. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  8315. for (var i = 0; i < nodeList.length; i++) {
  8316. attrs = new Attributes();
  8317. // Support: IE 11 only
  8318. // Workaround for #11781 and #14924
  8319. if (msie === 11) {
  8320. mergeConsecutiveTextNodes(nodeList, i, notLiveList);
  8321. }
  8322. // We must always refer to `nodeList[i]` hereafter,
  8323. // since the nodes can be replaced underneath us.
  8324. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  8325. ignoreDirective);
  8326. nodeLinkFn = (directives.length)
  8327. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  8328. null, [], [], previousCompileContext)
  8329. : null;
  8330. if (nodeLinkFn && nodeLinkFn.scope) {
  8331. compile.$$addScopeClass(attrs.$$element);
  8332. }
  8333. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  8334. !(childNodes = nodeList[i].childNodes) ||
  8335. !childNodes.length)
  8336. ? null
  8337. : compileNodes(childNodes,
  8338. nodeLinkFn ? (
  8339. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  8340. && nodeLinkFn.transclude) : transcludeFn);
  8341. if (nodeLinkFn || childLinkFn) {
  8342. linkFns.push(i, nodeLinkFn, childLinkFn);
  8343. linkFnFound = true;
  8344. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  8345. }
  8346. //use the previous context only for the first element in the virtual group
  8347. previousCompileContext = null;
  8348. }
  8349. // return a linking function if we have found anything, null otherwise
  8350. return linkFnFound ? compositeLinkFn : null;
  8351. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  8352. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  8353. var stableNodeList;
  8354. if (nodeLinkFnFound) {
  8355. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  8356. // offsets don't get screwed up
  8357. var nodeListLength = nodeList.length;
  8358. stableNodeList = new Array(nodeListLength);
  8359. // create a sparse array by only copying the elements which have a linkFn
  8360. for (i = 0; i < linkFns.length; i += 3) {
  8361. idx = linkFns[i];
  8362. stableNodeList[idx] = nodeList[idx];
  8363. }
  8364. } else {
  8365. stableNodeList = nodeList;
  8366. }
  8367. for (i = 0, ii = linkFns.length; i < ii;) {
  8368. node = stableNodeList[linkFns[i++]];
  8369. nodeLinkFn = linkFns[i++];
  8370. childLinkFn = linkFns[i++];
  8371. if (nodeLinkFn) {
  8372. if (nodeLinkFn.scope) {
  8373. childScope = scope.$new();
  8374. compile.$$addScopeInfo(jqLite(node), childScope);
  8375. } else {
  8376. childScope = scope;
  8377. }
  8378. if (nodeLinkFn.transcludeOnThisElement) {
  8379. childBoundTranscludeFn = createBoundTranscludeFn(
  8380. scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  8381. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  8382. childBoundTranscludeFn = parentBoundTranscludeFn;
  8383. } else if (!parentBoundTranscludeFn && transcludeFn) {
  8384. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  8385. } else {
  8386. childBoundTranscludeFn = null;
  8387. }
  8388. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  8389. } else if (childLinkFn) {
  8390. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  8391. }
  8392. }
  8393. }
  8394. }
  8395. function mergeConsecutiveTextNodes(nodeList, idx, notLiveList) {
  8396. var node = nodeList[idx];
  8397. var parent = node.parentNode;
  8398. var sibling;
  8399. if (node.nodeType !== NODE_TYPE_TEXT) {
  8400. return;
  8401. }
  8402. while (true) {
  8403. sibling = parent ? node.nextSibling : nodeList[idx + 1];
  8404. if (!sibling || sibling.nodeType !== NODE_TYPE_TEXT) {
  8405. break;
  8406. }
  8407. node.nodeValue = node.nodeValue + sibling.nodeValue;
  8408. if (sibling.parentNode) {
  8409. sibling.parentNode.removeChild(sibling);
  8410. }
  8411. if (notLiveList && sibling === nodeList[idx + 1]) {
  8412. nodeList.splice(idx + 1, 1);
  8413. }
  8414. }
  8415. }
  8416. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  8417. function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  8418. if (!transcludedScope) {
  8419. transcludedScope = scope.$new(false, containingScope);
  8420. transcludedScope.$$transcluded = true;
  8421. }
  8422. return transcludeFn(transcludedScope, cloneFn, {
  8423. parentBoundTranscludeFn: previousBoundTranscludeFn,
  8424. transcludeControllers: controllers,
  8425. futureParentElement: futureParentElement
  8426. });
  8427. }
  8428. // We need to attach the transclusion slots onto the `boundTranscludeFn`
  8429. // so that they are available inside the `controllersBoundTransclude` function
  8430. var boundSlots = boundTranscludeFn.$$slots = createMap();
  8431. for (var slotName in transcludeFn.$$slots) {
  8432. if (transcludeFn.$$slots[slotName]) {
  8433. boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);
  8434. } else {
  8435. boundSlots[slotName] = null;
  8436. }
  8437. }
  8438. return boundTranscludeFn;
  8439. }
  8440. /**
  8441. * Looks for directives on the given node and adds them to the directive collection which is
  8442. * sorted.
  8443. *
  8444. * @param node Node to search.
  8445. * @param directives An array to which the directives are added to. This array is sorted before
  8446. * the function returns.
  8447. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  8448. * @param {number=} maxPriority Max directive priority.
  8449. */
  8450. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  8451. var nodeType = node.nodeType,
  8452. attrsMap = attrs.$attr,
  8453. match,
  8454. nodeName,
  8455. className;
  8456. switch (nodeType) {
  8457. case NODE_TYPE_ELEMENT: /* Element */
  8458. nodeName = nodeName_(node);
  8459. // use the node name: <directive>
  8460. addDirective(directives,
  8461. directiveNormalize(nodeName), 'E', maxPriority, ignoreDirective);
  8462. // iterate over the attributes
  8463. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  8464. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  8465. var attrStartName = false;
  8466. var attrEndName = false;
  8467. attr = nAttrs[j];
  8468. name = attr.name;
  8469. value = attr.value;
  8470. // support ngAttr attribute binding
  8471. ngAttrName = directiveNormalize(name);
  8472. isNgAttr = NG_ATTR_BINDING.test(ngAttrName);
  8473. if (isNgAttr) {
  8474. name = name.replace(PREFIX_REGEXP, '')
  8475. .substr(8).replace(/_(.)/g, function(match, letter) {
  8476. return letter.toUpperCase();
  8477. });
  8478. }
  8479. var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);
  8480. if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {
  8481. attrStartName = name;
  8482. attrEndName = name.substr(0, name.length - 5) + 'end';
  8483. name = name.substr(0, name.length - 6);
  8484. }
  8485. nName = directiveNormalize(name.toLowerCase());
  8486. attrsMap[nName] = name;
  8487. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  8488. attrs[nName] = value;
  8489. if (getBooleanAttrName(node, nName)) {
  8490. attrs[nName] = true; // presence means true
  8491. }
  8492. }
  8493. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  8494. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  8495. attrEndName);
  8496. }
  8497. if (nodeName === 'input' && node.getAttribute('type') === 'hidden') {
  8498. // Hidden input elements can have strange behaviour when navigating back to the page
  8499. // This tells the browser not to try to cache and reinstate previous values
  8500. node.setAttribute('autocomplete', 'off');
  8501. }
  8502. // use class as directive
  8503. if (!cssClassDirectivesEnabled) break;
  8504. className = node.className;
  8505. if (isObject(className)) {
  8506. // Maybe SVGAnimatedString
  8507. className = className.animVal;
  8508. }
  8509. if (isString(className) && className !== '') {
  8510. while ((match = CLASS_DIRECTIVE_REGEXP.exec(className))) {
  8511. nName = directiveNormalize(match[2]);
  8512. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  8513. attrs[nName] = trim(match[3]);
  8514. }
  8515. className = className.substr(match.index + match[0].length);
  8516. }
  8517. }
  8518. break;
  8519. case NODE_TYPE_TEXT: /* Text Node */
  8520. addTextInterpolateDirective(directives, node.nodeValue);
  8521. break;
  8522. case NODE_TYPE_COMMENT: /* Comment */
  8523. if (!commentDirectivesEnabled) break;
  8524. collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective);
  8525. break;
  8526. }
  8527. directives.sort(byPriority);
  8528. return directives;
  8529. }
  8530. function collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  8531. // function created because of performance, try/catch disables
  8532. // the optimization of the whole function #14848
  8533. try {
  8534. var match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  8535. if (match) {
  8536. var nName = directiveNormalize(match[1]);
  8537. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  8538. attrs[nName] = trim(match[2]);
  8539. }
  8540. }
  8541. } catch (e) {
  8542. // turns out that under some circumstances IE9 throws errors when one attempts to read
  8543. // comment's node value.
  8544. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  8545. }
  8546. }
  8547. /**
  8548. * Given a node with a directive-start it collects all of the siblings until it finds
  8549. * directive-end.
  8550. * @param node
  8551. * @param attrStart
  8552. * @param attrEnd
  8553. * @returns {*}
  8554. */
  8555. function groupScan(node, attrStart, attrEnd) {
  8556. var nodes = [];
  8557. var depth = 0;
  8558. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  8559. do {
  8560. if (!node) {
  8561. throw $compileMinErr('uterdir',
  8562. 'Unterminated attribute, found \'{0}\' but no matching \'{1}\' found.',
  8563. attrStart, attrEnd);
  8564. }
  8565. if (node.nodeType === NODE_TYPE_ELEMENT) {
  8566. if (node.hasAttribute(attrStart)) depth++;
  8567. if (node.hasAttribute(attrEnd)) depth--;
  8568. }
  8569. nodes.push(node);
  8570. node = node.nextSibling;
  8571. } while (depth > 0);
  8572. } else {
  8573. nodes.push(node);
  8574. }
  8575. return jqLite(nodes);
  8576. }
  8577. /**
  8578. * Wrapper for linking function which converts normal linking function into a grouped
  8579. * linking function.
  8580. * @param linkFn
  8581. * @param attrStart
  8582. * @param attrEnd
  8583. * @returns {Function}
  8584. */
  8585. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  8586. return function groupedElementsLink(scope, element, attrs, controllers, transcludeFn) {
  8587. element = groupScan(element[0], attrStart, attrEnd);
  8588. return linkFn(scope, element, attrs, controllers, transcludeFn);
  8589. };
  8590. }
  8591. /**
  8592. * A function generator that is used to support both eager and lazy compilation
  8593. * linking function.
  8594. * @param eager
  8595. * @param $compileNodes
  8596. * @param transcludeFn
  8597. * @param maxPriority
  8598. * @param ignoreDirective
  8599. * @param previousCompileContext
  8600. * @returns {Function}
  8601. */
  8602. function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
  8603. var compiled;
  8604. if (eager) {
  8605. return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  8606. }
  8607. return /** @this */ function lazyCompilation() {
  8608. if (!compiled) {
  8609. compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  8610. // Null out all of these references in order to make them eligible for garbage collection
  8611. // since this is a potentially long lived closure
  8612. $compileNodes = transcludeFn = previousCompileContext = null;
  8613. }
  8614. return compiled.apply(this, arguments);
  8615. };
  8616. }
  8617. /**
  8618. * Once the directives have been collected, their compile functions are executed. This method
  8619. * is responsible for inlining directive templates as well as terminating the application
  8620. * of the directives if the terminal directive has been reached.
  8621. *
  8622. * @param {Array} directives Array of collected directives to execute their compile function.
  8623. * this needs to be pre-sorted by priority order.
  8624. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  8625. * @param {Object} templateAttrs The shared attribute function
  8626. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  8627. * scope argument is auto-generated to the new
  8628. * child of the transcluded parent scope.
  8629. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  8630. * argument has the root jqLite array so that we can replace nodes
  8631. * on it.
  8632. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  8633. * compiling the transclusion.
  8634. * @param {Array.<Function>} preLinkFns
  8635. * @param {Array.<Function>} postLinkFns
  8636. * @param {Object} previousCompileContext Context used for previous compilation of the current
  8637. * node
  8638. * @returns {Function} linkFn
  8639. */
  8640. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  8641. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  8642. previousCompileContext) {
  8643. previousCompileContext = previousCompileContext || {};
  8644. var terminalPriority = -Number.MAX_VALUE,
  8645. newScopeDirective = previousCompileContext.newScopeDirective,
  8646. controllerDirectives = previousCompileContext.controllerDirectives,
  8647. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  8648. templateDirective = previousCompileContext.templateDirective,
  8649. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  8650. hasTranscludeDirective = false,
  8651. hasTemplate = false,
  8652. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  8653. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  8654. directive,
  8655. directiveName,
  8656. $template,
  8657. replaceDirective = originalReplaceDirective,
  8658. childTranscludeFn = transcludeFn,
  8659. linkFn,
  8660. didScanForMultipleTransclusion = false,
  8661. mightHaveMultipleTransclusionError = false,
  8662. directiveValue;
  8663. // executes all directives on the current element
  8664. for (var i = 0, ii = directives.length; i < ii; i++) {
  8665. directive = directives[i];
  8666. var attrStart = directive.$$start;
  8667. var attrEnd = directive.$$end;
  8668. // collect multiblock sections
  8669. if (attrStart) {
  8670. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  8671. }
  8672. $template = undefined;
  8673. if (terminalPriority > directive.priority) {
  8674. break; // prevent further processing of directives
  8675. }
  8676. directiveValue = directive.scope;
  8677. if (directiveValue) {
  8678. // skip the check for directives with async templates, we'll check the derived sync
  8679. // directive when the template arrives
  8680. if (!directive.templateUrl) {
  8681. if (isObject(directiveValue)) {
  8682. // This directive is trying to add an isolated scope.
  8683. // Check that there is no scope of any kind already
  8684. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  8685. directive, $compileNode);
  8686. newIsolateScopeDirective = directive;
  8687. } else {
  8688. // This directive is trying to add a child scope.
  8689. // Check that there is no isolated scope already
  8690. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  8691. $compileNode);
  8692. }
  8693. }
  8694. newScopeDirective = newScopeDirective || directive;
  8695. }
  8696. directiveName = directive.name;
  8697. // If we encounter a condition that can result in transclusion on the directive,
  8698. // then scan ahead in the remaining directives for others that may cause a multiple
  8699. // transclusion error to be thrown during the compilation process. If a matching directive
  8700. // is found, then we know that when we encounter a transcluded directive, we need to eagerly
  8701. // compile the `transclude` function rather than doing it lazily in order to throw
  8702. // exceptions at the correct time
  8703. if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))
  8704. || (directive.transclude && !directive.$$tlb))) {
  8705. var candidateDirective;
  8706. for (var scanningIndex = i + 1; (candidateDirective = directives[scanningIndex++]);) {
  8707. if ((candidateDirective.transclude && !candidateDirective.$$tlb)
  8708. || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {
  8709. mightHaveMultipleTransclusionError = true;
  8710. break;
  8711. }
  8712. }
  8713. didScanForMultipleTransclusion = true;
  8714. }
  8715. if (!directive.templateUrl && directive.controller) {
  8716. controllerDirectives = controllerDirectives || createMap();
  8717. assertNoDuplicate('\'' + directiveName + '\' controller',
  8718. controllerDirectives[directiveName], directive, $compileNode);
  8719. controllerDirectives[directiveName] = directive;
  8720. }
  8721. directiveValue = directive.transclude;
  8722. if (directiveValue) {
  8723. hasTranscludeDirective = true;
  8724. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  8725. // This option should only be used by directives that know how to safely handle element transclusion,
  8726. // where the transcluded nodes are added or replaced after linking.
  8727. if (!directive.$$tlb) {
  8728. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  8729. nonTlbTranscludeDirective = directive;
  8730. }
  8731. if (directiveValue === 'element') {
  8732. hasElementTranscludeDirective = true;
  8733. terminalPriority = directive.priority;
  8734. $template = $compileNode;
  8735. $compileNode = templateAttrs.$$element =
  8736. jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName]));
  8737. compileNode = $compileNode[0];
  8738. replaceWith(jqCollection, sliceArgs($template), compileNode);
  8739. // Support: Chrome < 50
  8740. // https://github.com/angular/angular.js/issues/14041
  8741. // In the versions of V8 prior to Chrome 50, the document fragment that is created
  8742. // in the `replaceWith` function is improperly garbage collected despite still
  8743. // being referenced by the `parentNode` property of all of the child nodes. By adding
  8744. // a reference to the fragment via a different property, we can avoid that incorrect
  8745. // behavior.
  8746. // TODO: remove this line after Chrome 50 has been released
  8747. $template[0].$$parentNode = $template[0].parentNode;
  8748. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
  8749. replaceDirective && replaceDirective.name, {
  8750. // Don't pass in:
  8751. // - controllerDirectives - otherwise we'll create duplicates controllers
  8752. // - newIsolateScopeDirective or templateDirective - combining templates with
  8753. // element transclusion doesn't make sense.
  8754. //
  8755. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  8756. // on the same element more than once.
  8757. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  8758. });
  8759. } else {
  8760. var slots = createMap();
  8761. if (!isObject(directiveValue)) {
  8762. $template = jqLite(jqLiteClone(compileNode)).contents();
  8763. } else {
  8764. // We have transclusion slots,
  8765. // collect them up, compile them and store their transclusion functions
  8766. $template = [];
  8767. var slotMap = createMap();
  8768. var filledSlots = createMap();
  8769. // Parse the element selectors
  8770. forEach(directiveValue, function(elementSelector, slotName) {
  8771. // If an element selector starts with a ? then it is optional
  8772. var optional = (elementSelector.charAt(0) === '?');
  8773. elementSelector = optional ? elementSelector.substring(1) : elementSelector;
  8774. slotMap[elementSelector] = slotName;
  8775. // We explicitly assign `null` since this implies that a slot was defined but not filled.
  8776. // Later when calling boundTransclusion functions with a slot name we only error if the
  8777. // slot is `undefined`
  8778. slots[slotName] = null;
  8779. // filledSlots contains `true` for all slots that are either optional or have been
  8780. // filled. This is used to check that we have not missed any required slots
  8781. filledSlots[slotName] = optional;
  8782. });
  8783. // Add the matching elements into their slot
  8784. forEach($compileNode.contents(), function(node) {
  8785. var slotName = slotMap[directiveNormalize(nodeName_(node))];
  8786. if (slotName) {
  8787. filledSlots[slotName] = true;
  8788. slots[slotName] = slots[slotName] || [];
  8789. slots[slotName].push(node);
  8790. } else {
  8791. $template.push(node);
  8792. }
  8793. });
  8794. // Check for required slots that were not filled
  8795. forEach(filledSlots, function(filled, slotName) {
  8796. if (!filled) {
  8797. throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
  8798. }
  8799. });
  8800. for (var slotName in slots) {
  8801. if (slots[slotName]) {
  8802. // Only define a transclusion function if the slot was filled
  8803. slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn);
  8804. }
  8805. }
  8806. }
  8807. $compileNode.empty(); // clear contents
  8808. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
  8809. undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
  8810. childTranscludeFn.$$slots = slots;
  8811. }
  8812. }
  8813. if (directive.template) {
  8814. hasTemplate = true;
  8815. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  8816. templateDirective = directive;
  8817. directiveValue = (isFunction(directive.template))
  8818. ? directive.template($compileNode, templateAttrs)
  8819. : directive.template;
  8820. directiveValue = denormalizeTemplate(directiveValue);
  8821. if (directive.replace) {
  8822. replaceDirective = directive;
  8823. if (jqLiteIsTextNode(directiveValue)) {
  8824. $template = [];
  8825. } else {
  8826. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  8827. }
  8828. compileNode = $template[0];
  8829. if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  8830. throw $compileMinErr('tplrt',
  8831. 'Template for directive \'{0}\' must have exactly one root element. {1}',
  8832. directiveName, '');
  8833. }
  8834. replaceWith(jqCollection, $compileNode, compileNode);
  8835. var newTemplateAttrs = {$attr: {}};
  8836. // combine directives from the original node and from the template:
  8837. // - take the array of directives for this element
  8838. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  8839. // - collect directives from the template and sort them by priority
  8840. // - combine directives as: processed + template + unprocessed
  8841. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  8842. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  8843. if (newIsolateScopeDirective || newScopeDirective) {
  8844. // The original directive caused the current element to be replaced but this element
  8845. // also needs to have a new scope, so we need to tell the template directives
  8846. // that they would need to get their scope from further up, if they require transclusion
  8847. markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
  8848. }
  8849. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  8850. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  8851. ii = directives.length;
  8852. } else {
  8853. $compileNode.html(directiveValue);
  8854. }
  8855. }
  8856. if (directive.templateUrl) {
  8857. hasTemplate = true;
  8858. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  8859. templateDirective = directive;
  8860. if (directive.replace) {
  8861. replaceDirective = directive;
  8862. }
  8863. // eslint-disable-next-line no-func-assign
  8864. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  8865. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  8866. controllerDirectives: controllerDirectives,
  8867. newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
  8868. newIsolateScopeDirective: newIsolateScopeDirective,
  8869. templateDirective: templateDirective,
  8870. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  8871. });
  8872. ii = directives.length;
  8873. } else if (directive.compile) {
  8874. try {
  8875. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  8876. var context = directive.$$originalDirective || directive;
  8877. if (isFunction(linkFn)) {
  8878. addLinkFns(null, bind(context, linkFn), attrStart, attrEnd);
  8879. } else if (linkFn) {
  8880. addLinkFns(bind(context, linkFn.pre), bind(context, linkFn.post), attrStart, attrEnd);
  8881. }
  8882. } catch (e) {
  8883. $exceptionHandler(e, startingTag($compileNode));
  8884. }
  8885. }
  8886. if (directive.terminal) {
  8887. nodeLinkFn.terminal = true;
  8888. terminalPriority = Math.max(terminalPriority, directive.priority);
  8889. }
  8890. }
  8891. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  8892. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  8893. nodeLinkFn.templateOnThisElement = hasTemplate;
  8894. nodeLinkFn.transclude = childTranscludeFn;
  8895. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  8896. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  8897. return nodeLinkFn;
  8898. ////////////////////
  8899. function addLinkFns(pre, post, attrStart, attrEnd) {
  8900. if (pre) {
  8901. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  8902. pre.require = directive.require;
  8903. pre.directiveName = directiveName;
  8904. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  8905. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  8906. }
  8907. preLinkFns.push(pre);
  8908. }
  8909. if (post) {
  8910. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  8911. post.require = directive.require;
  8912. post.directiveName = directiveName;
  8913. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  8914. post = cloneAndAnnotateFn(post, {isolateScope: true});
  8915. }
  8916. postLinkFns.push(post);
  8917. }
  8918. }
  8919. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  8920. var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
  8921. attrs, scopeBindingInfo;
  8922. if (compileNode === linkNode) {
  8923. attrs = templateAttrs;
  8924. $element = templateAttrs.$$element;
  8925. } else {
  8926. $element = jqLite(linkNode);
  8927. attrs = new Attributes($element, templateAttrs);
  8928. }
  8929. controllerScope = scope;
  8930. if (newIsolateScopeDirective) {
  8931. isolateScope = scope.$new(true);
  8932. } else if (newScopeDirective) {
  8933. controllerScope = scope.$parent;
  8934. }
  8935. if (boundTranscludeFn) {
  8936. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  8937. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  8938. transcludeFn = controllersBoundTransclude;
  8939. transcludeFn.$$boundTransclude = boundTranscludeFn;
  8940. // expose the slots on the `$transclude` function
  8941. transcludeFn.isSlotFilled = function(slotName) {
  8942. return !!boundTranscludeFn.$$slots[slotName];
  8943. };
  8944. }
  8945. if (controllerDirectives) {
  8946. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective);
  8947. }
  8948. if (newIsolateScopeDirective) {
  8949. // Initialize isolate scope bindings for new isolate scope directive.
  8950. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  8951. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  8952. compile.$$addScopeClass($element, true);
  8953. isolateScope.$$isolateBindings =
  8954. newIsolateScopeDirective.$$isolateBindings;
  8955. scopeBindingInfo = initializeDirectiveBindings(scope, attrs, isolateScope,
  8956. isolateScope.$$isolateBindings,
  8957. newIsolateScopeDirective);
  8958. if (scopeBindingInfo.removeWatches) {
  8959. isolateScope.$on('$destroy', scopeBindingInfo.removeWatches);
  8960. }
  8961. }
  8962. // Initialize bindToController bindings
  8963. for (var name in elementControllers) {
  8964. var controllerDirective = controllerDirectives[name];
  8965. var controller = elementControllers[name];
  8966. var bindings = controllerDirective.$$bindings.bindToController;
  8967. if (preAssignBindingsEnabled) {
  8968. if (bindings) {
  8969. controller.bindingInfo =
  8970. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8971. } else {
  8972. controller.bindingInfo = {};
  8973. }
  8974. var controllerResult = controller();
  8975. if (controllerResult !== controller.instance) {
  8976. // If the controller constructor has a return value, overwrite the instance
  8977. // from setupControllers
  8978. controller.instance = controllerResult;
  8979. $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
  8980. if (controller.bindingInfo.removeWatches) {
  8981. controller.bindingInfo.removeWatches();
  8982. }
  8983. controller.bindingInfo =
  8984. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8985. }
  8986. } else {
  8987. controller.instance = controller();
  8988. $element.data('$' + controllerDirective.name + 'Controller', controller.instance);
  8989. controller.bindingInfo =
  8990. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8991. }
  8992. }
  8993. // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy
  8994. forEach(controllerDirectives, function(controllerDirective, name) {
  8995. var require = controllerDirective.require;
  8996. if (controllerDirective.bindToController && !isArray(require) && isObject(require)) {
  8997. extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers));
  8998. }
  8999. });
  9000. // Handle the init and destroy lifecycle hooks on all controllers that have them
  9001. forEach(elementControllers, function(controller) {
  9002. var controllerInstance = controller.instance;
  9003. if (isFunction(controllerInstance.$onChanges)) {
  9004. try {
  9005. controllerInstance.$onChanges(controller.bindingInfo.initialChanges);
  9006. } catch (e) {
  9007. $exceptionHandler(e);
  9008. }
  9009. }
  9010. if (isFunction(controllerInstance.$onInit)) {
  9011. try {
  9012. controllerInstance.$onInit();
  9013. } catch (e) {
  9014. $exceptionHandler(e);
  9015. }
  9016. }
  9017. if (isFunction(controllerInstance.$doCheck)) {
  9018. controllerScope.$watch(function() { controllerInstance.$doCheck(); });
  9019. controllerInstance.$doCheck();
  9020. }
  9021. if (isFunction(controllerInstance.$onDestroy)) {
  9022. controllerScope.$on('$destroy', function callOnDestroyHook() {
  9023. controllerInstance.$onDestroy();
  9024. });
  9025. }
  9026. });
  9027. // PRELINKING
  9028. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  9029. linkFn = preLinkFns[i];
  9030. invokeLinkFn(linkFn,
  9031. linkFn.isolateScope ? isolateScope : scope,
  9032. $element,
  9033. attrs,
  9034. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  9035. transcludeFn
  9036. );
  9037. }
  9038. // RECURSION
  9039. // We only pass the isolate scope, if the isolate directive has a template,
  9040. // otherwise the child elements do not belong to the isolate directive.
  9041. var scopeToChild = scope;
  9042. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  9043. scopeToChild = isolateScope;
  9044. }
  9045. if (childLinkFn) {
  9046. childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  9047. }
  9048. // POSTLINKING
  9049. for (i = postLinkFns.length - 1; i >= 0; i--) {
  9050. linkFn = postLinkFns[i];
  9051. invokeLinkFn(linkFn,
  9052. linkFn.isolateScope ? isolateScope : scope,
  9053. $element,
  9054. attrs,
  9055. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  9056. transcludeFn
  9057. );
  9058. }
  9059. // Trigger $postLink lifecycle hooks
  9060. forEach(elementControllers, function(controller) {
  9061. var controllerInstance = controller.instance;
  9062. if (isFunction(controllerInstance.$postLink)) {
  9063. controllerInstance.$postLink();
  9064. }
  9065. });
  9066. // This is the function that is injected as `$transclude`.
  9067. // Note: all arguments are optional!
  9068. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
  9069. var transcludeControllers;
  9070. // No scope passed in:
  9071. if (!isScope(scope)) {
  9072. slotName = futureParentElement;
  9073. futureParentElement = cloneAttachFn;
  9074. cloneAttachFn = scope;
  9075. scope = undefined;
  9076. }
  9077. if (hasElementTranscludeDirective) {
  9078. transcludeControllers = elementControllers;
  9079. }
  9080. if (!futureParentElement) {
  9081. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  9082. }
  9083. if (slotName) {
  9084. // slotTranscludeFn can be one of three things:
  9085. // * a transclude function - a filled slot
  9086. // * `null` - an optional slot that was not filled
  9087. // * `undefined` - a slot that was not declared (i.e. invalid)
  9088. var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];
  9089. if (slotTranscludeFn) {
  9090. return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  9091. } else if (isUndefined(slotTranscludeFn)) {
  9092. throw $compileMinErr('noslot',
  9093. 'No parent directive that requires a transclusion with slot name "{0}". ' +
  9094. 'Element: {1}',
  9095. slotName, startingTag($element));
  9096. }
  9097. } else {
  9098. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  9099. }
  9100. }
  9101. }
  9102. }
  9103. function getControllers(directiveName, require, $element, elementControllers) {
  9104. var value;
  9105. if (isString(require)) {
  9106. var match = require.match(REQUIRE_PREFIX_REGEXP);
  9107. var name = require.substring(match[0].length);
  9108. var inheritType = match[1] || match[3];
  9109. var optional = match[2] === '?';
  9110. //If only parents then start at the parent element
  9111. if (inheritType === '^^') {
  9112. $element = $element.parent();
  9113. //Otherwise attempt getting the controller from elementControllers in case
  9114. //the element is transcluded (and has no data) and to avoid .data if possible
  9115. } else {
  9116. value = elementControllers && elementControllers[name];
  9117. value = value && value.instance;
  9118. }
  9119. if (!value) {
  9120. var dataName = '$' + name + 'Controller';
  9121. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  9122. }
  9123. if (!value && !optional) {
  9124. throw $compileMinErr('ctreq',
  9125. 'Controller \'{0}\', required by directive \'{1}\', can\'t be found!',
  9126. name, directiveName);
  9127. }
  9128. } else if (isArray(require)) {
  9129. value = [];
  9130. for (var i = 0, ii = require.length; i < ii; i++) {
  9131. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  9132. }
  9133. } else if (isObject(require)) {
  9134. value = {};
  9135. forEach(require, function(controller, property) {
  9136. value[property] = getControllers(directiveName, controller, $element, elementControllers);
  9137. });
  9138. }
  9139. return value || null;
  9140. }
  9141. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective) {
  9142. var elementControllers = createMap();
  9143. for (var controllerKey in controllerDirectives) {
  9144. var directive = controllerDirectives[controllerKey];
  9145. var locals = {
  9146. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  9147. $element: $element,
  9148. $attrs: attrs,
  9149. $transclude: transcludeFn
  9150. };
  9151. var controller = directive.controller;
  9152. if (controller === '@') {
  9153. controller = attrs[directive.name];
  9154. }
  9155. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  9156. // For directives with element transclusion the element is a comment.
  9157. // In this case .data will not attach any data.
  9158. // Instead, we save the controllers for the element in a local hash and attach to .data
  9159. // later, once we have the actual element.
  9160. elementControllers[directive.name] = controllerInstance;
  9161. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  9162. }
  9163. return elementControllers;
  9164. }
  9165. // Depending upon the context in which a directive finds itself it might need to have a new isolated
  9166. // or child scope created. For instance:
  9167. // * if the directive has been pulled into a template because another directive with a higher priority
  9168. // asked for element transclusion
  9169. // * if the directive itself asks for transclusion but it is at the root of a template and the original
  9170. // element was replaced. See https://github.com/angular/angular.js/issues/12936
  9171. function markDirectiveScope(directives, isolateScope, newScope) {
  9172. for (var j = 0, jj = directives.length; j < jj; j++) {
  9173. directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
  9174. }
  9175. }
  9176. /**
  9177. * looks up the directive and decorates it with exception handling and proper parameters. We
  9178. * call this the boundDirective.
  9179. *
  9180. * @param {string} name name of the directive to look up.
  9181. * @param {string} location The directive must be found in specific format.
  9182. * String containing any of theses characters:
  9183. *
  9184. * * `E`: element name
  9185. * * `A': attribute
  9186. * * `C`: class
  9187. * * `M`: comment
  9188. * @returns {boolean} true if directive was added.
  9189. */
  9190. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  9191. endAttrName) {
  9192. if (name === ignoreDirective) return null;
  9193. var match = null;
  9194. if (hasDirectives.hasOwnProperty(name)) {
  9195. for (var directive, directives = $injector.get(name + Suffix),
  9196. i = 0, ii = directives.length; i < ii; i++) {
  9197. directive = directives[i];
  9198. if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
  9199. directive.restrict.indexOf(location) !== -1) {
  9200. if (startAttrName) {
  9201. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  9202. }
  9203. if (!directive.$$bindings) {
  9204. var bindings = directive.$$bindings =
  9205. parseDirectiveBindings(directive, directive.name);
  9206. if (isObject(bindings.isolateScope)) {
  9207. directive.$$isolateBindings = bindings.isolateScope;
  9208. }
  9209. }
  9210. tDirectives.push(directive);
  9211. match = directive;
  9212. }
  9213. }
  9214. }
  9215. return match;
  9216. }
  9217. /**
  9218. * looks up the directive and returns true if it is a multi-element directive,
  9219. * and therefore requires DOM nodes between -start and -end markers to be grouped
  9220. * together.
  9221. *
  9222. * @param {string} name name of the directive to look up.
  9223. * @returns true if directive was registered as multi-element.
  9224. */
  9225. function directiveIsMultiElement(name) {
  9226. if (hasDirectives.hasOwnProperty(name)) {
  9227. for (var directive, directives = $injector.get(name + Suffix),
  9228. i = 0, ii = directives.length; i < ii; i++) {
  9229. directive = directives[i];
  9230. if (directive.multiElement) {
  9231. return true;
  9232. }
  9233. }
  9234. }
  9235. return false;
  9236. }
  9237. /**
  9238. * When the element is replaced with HTML template then the new attributes
  9239. * on the template need to be merged with the existing attributes in the DOM.
  9240. * The desired effect is to have both of the attributes present.
  9241. *
  9242. * @param {object} dst destination attributes (original DOM)
  9243. * @param {object} src source attributes (from the directive template)
  9244. */
  9245. function mergeTemplateAttributes(dst, src) {
  9246. var srcAttr = src.$attr,
  9247. dstAttr = dst.$attr;
  9248. // reapply the old attributes to the new element
  9249. forEach(dst, function(value, key) {
  9250. if (key.charAt(0) !== '$') {
  9251. if (src[key] && src[key] !== value) {
  9252. if (value.length) {
  9253. value += (key === 'style' ? ';' : ' ') + src[key];
  9254. } else {
  9255. value = src[key];
  9256. }
  9257. }
  9258. dst.$set(key, value, true, srcAttr[key]);
  9259. }
  9260. });
  9261. // copy the new attributes on the old attrs object
  9262. forEach(src, function(value, key) {
  9263. // Check if we already set this attribute in the loop above.
  9264. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  9265. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  9266. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  9267. if (!dst.hasOwnProperty(key) && key.charAt(0) !== '$') {
  9268. dst[key] = value;
  9269. if (key !== 'class' && key !== 'style') {
  9270. dstAttr[key] = srcAttr[key];
  9271. }
  9272. }
  9273. });
  9274. }
  9275. function compileTemplateUrl(directives, $compileNode, tAttrs,
  9276. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  9277. var linkQueue = [],
  9278. afterTemplateNodeLinkFn,
  9279. afterTemplateChildLinkFn,
  9280. beforeTemplateCompileNode = $compileNode[0],
  9281. origAsyncDirective = directives.shift(),
  9282. derivedSyncDirective = inherit(origAsyncDirective, {
  9283. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  9284. }),
  9285. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  9286. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  9287. : origAsyncDirective.templateUrl,
  9288. templateNamespace = origAsyncDirective.templateNamespace;
  9289. $compileNode.empty();
  9290. $templateRequest(templateUrl)
  9291. .then(function(content) {
  9292. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  9293. content = denormalizeTemplate(content);
  9294. if (origAsyncDirective.replace) {
  9295. if (jqLiteIsTextNode(content)) {
  9296. $template = [];
  9297. } else {
  9298. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  9299. }
  9300. compileNode = $template[0];
  9301. if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  9302. throw $compileMinErr('tplrt',
  9303. 'Template for directive \'{0}\' must have exactly one root element. {1}',
  9304. origAsyncDirective.name, templateUrl);
  9305. }
  9306. tempTemplateAttrs = {$attr: {}};
  9307. replaceWith($rootElement, $compileNode, compileNode);
  9308. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  9309. if (isObject(origAsyncDirective.scope)) {
  9310. // the original directive that caused the template to be loaded async required
  9311. // an isolate scope
  9312. markDirectiveScope(templateDirectives, true);
  9313. }
  9314. directives = templateDirectives.concat(directives);
  9315. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  9316. } else {
  9317. compileNode = beforeTemplateCompileNode;
  9318. $compileNode.html(content);
  9319. }
  9320. directives.unshift(derivedSyncDirective);
  9321. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  9322. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  9323. previousCompileContext);
  9324. forEach($rootElement, function(node, i) {
  9325. if (node === compileNode) {
  9326. $rootElement[i] = $compileNode[0];
  9327. }
  9328. });
  9329. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  9330. while (linkQueue.length) {
  9331. var scope = linkQueue.shift(),
  9332. beforeTemplateLinkNode = linkQueue.shift(),
  9333. linkRootElement = linkQueue.shift(),
  9334. boundTranscludeFn = linkQueue.shift(),
  9335. linkNode = $compileNode[0];
  9336. if (scope.$$destroyed) continue;
  9337. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  9338. var oldClasses = beforeTemplateLinkNode.className;
  9339. if (!(previousCompileContext.hasElementTranscludeDirective &&
  9340. origAsyncDirective.replace)) {
  9341. // it was cloned therefore we have to clone as well.
  9342. linkNode = jqLiteClone(compileNode);
  9343. }
  9344. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  9345. // Copy in CSS classes from original node
  9346. safeAddClass(jqLite(linkNode), oldClasses);
  9347. }
  9348. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  9349. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  9350. } else {
  9351. childBoundTranscludeFn = boundTranscludeFn;
  9352. }
  9353. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  9354. childBoundTranscludeFn);
  9355. }
  9356. linkQueue = null;
  9357. }).catch(function(error) {
  9358. if (isError(error)) {
  9359. $exceptionHandler(error);
  9360. }
  9361. });
  9362. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  9363. var childBoundTranscludeFn = boundTranscludeFn;
  9364. if (scope.$$destroyed) return;
  9365. if (linkQueue) {
  9366. linkQueue.push(scope,
  9367. node,
  9368. rootElement,
  9369. childBoundTranscludeFn);
  9370. } else {
  9371. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  9372. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  9373. }
  9374. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  9375. }
  9376. };
  9377. }
  9378. /**
  9379. * Sorting function for bound directives.
  9380. */
  9381. function byPriority(a, b) {
  9382. var diff = b.priority - a.priority;
  9383. if (diff !== 0) return diff;
  9384. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  9385. return a.index - b.index;
  9386. }
  9387. function assertNoDuplicate(what, previousDirective, directive, element) {
  9388. function wrapModuleNameIfDefined(moduleName) {
  9389. return moduleName ?
  9390. (' (module: ' + moduleName + ')') :
  9391. '';
  9392. }
  9393. if (previousDirective) {
  9394. throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
  9395. previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
  9396. directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
  9397. }
  9398. }
  9399. function addTextInterpolateDirective(directives, text) {
  9400. var interpolateFn = $interpolate(text, true);
  9401. if (interpolateFn) {
  9402. directives.push({
  9403. priority: 0,
  9404. compile: function textInterpolateCompileFn(templateNode) {
  9405. var templateNodeParent = templateNode.parent(),
  9406. hasCompileParent = !!templateNodeParent.length;
  9407. // When transcluding a template that has bindings in the root
  9408. // we don't have a parent and thus need to add the class during linking fn.
  9409. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  9410. return function textInterpolateLinkFn(scope, node) {
  9411. var parent = node.parent();
  9412. if (!hasCompileParent) compile.$$addBindingClass(parent);
  9413. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  9414. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  9415. node[0].nodeValue = value;
  9416. });
  9417. };
  9418. }
  9419. });
  9420. }
  9421. }
  9422. function wrapTemplate(type, template) {
  9423. type = lowercase(type || 'html');
  9424. switch (type) {
  9425. case 'svg':
  9426. case 'math':
  9427. var wrapper = window.document.createElement('div');
  9428. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  9429. return wrapper.childNodes[0].childNodes;
  9430. default:
  9431. return template;
  9432. }
  9433. }
  9434. function getTrustedContext(node, attrNormalizedName) {
  9435. if (attrNormalizedName === 'srcdoc') {
  9436. return $sce.HTML;
  9437. }
  9438. var tag = nodeName_(node);
  9439. // All tags with src attributes require a RESOURCE_URL value, except for
  9440. // img and various html5 media tags.
  9441. if (attrNormalizedName === 'src' || attrNormalizedName === 'ngSrc') {
  9442. if (['img', 'video', 'audio', 'source', 'track'].indexOf(tag) === -1) {
  9443. return $sce.RESOURCE_URL;
  9444. }
  9445. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  9446. } else if (attrNormalizedName === 'xlinkHref' ||
  9447. (tag === 'form' && attrNormalizedName === 'action') ||
  9448. // links can be stylesheets or imports, which can run script in the current origin
  9449. (tag === 'link' && attrNormalizedName === 'href')
  9450. ) {
  9451. return $sce.RESOURCE_URL;
  9452. }
  9453. }
  9454. function addAttrInterpolateDirective(node, directives, value, name, isNgAttr) {
  9455. var trustedContext = getTrustedContext(node, name);
  9456. var mustHaveExpression = !isNgAttr;
  9457. var allOrNothing = ALL_OR_NOTHING_ATTRS[name] || isNgAttr;
  9458. var interpolateFn = $interpolate(value, mustHaveExpression, trustedContext, allOrNothing);
  9459. // no interpolation found -> ignore
  9460. if (!interpolateFn) return;
  9461. if (name === 'multiple' && nodeName_(node) === 'select') {
  9462. throw $compileMinErr('selmulti',
  9463. 'Binding to the \'multiple\' attribute is not supported. Element: {0}',
  9464. startingTag(node));
  9465. }
  9466. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  9467. throw $compileMinErr('nodomevents',
  9468. 'Interpolations for HTML DOM event attributes are disallowed. Please use the ' +
  9469. 'ng- versions (such as ng-click instead of onclick) instead.');
  9470. }
  9471. directives.push({
  9472. priority: 100,
  9473. compile: function() {
  9474. return {
  9475. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  9476. var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
  9477. // If the attribute has changed since last $interpolate()ed
  9478. var newValue = attr[name];
  9479. if (newValue !== value) {
  9480. // we need to interpolate again since the attribute value has been updated
  9481. // (e.g. by another directive's compile function)
  9482. // ensure unset/empty values make interpolateFn falsy
  9483. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  9484. value = newValue;
  9485. }
  9486. // if attribute was updated so that there is no interpolation going on we don't want to
  9487. // register any observers
  9488. if (!interpolateFn) return;
  9489. // initialize attr object so that it's ready in case we need the value for isolate
  9490. // scope initialization, otherwise the value would not be available from isolate
  9491. // directive's linking fn during linking phase
  9492. attr[name] = interpolateFn(scope);
  9493. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  9494. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  9495. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  9496. //special case for class attribute addition + removal
  9497. //so that class changes can tap into the animation
  9498. //hooks provided by the $animate service. Be sure to
  9499. //skip animations when the first digest occurs (when
  9500. //both the new and the old values are the same) since
  9501. //the CSS classes are the non-interpolated values
  9502. if (name === 'class' && newValue !== oldValue) {
  9503. attr.$updateClass(newValue, oldValue);
  9504. } else {
  9505. attr.$set(name, newValue);
  9506. }
  9507. });
  9508. }
  9509. };
  9510. }
  9511. });
  9512. }
  9513. /**
  9514. * This is a special jqLite.replaceWith, which can replace items which
  9515. * have no parents, provided that the containing jqLite collection is provided.
  9516. *
  9517. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  9518. * in the root of the tree.
  9519. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  9520. * the shell, but replace its DOM node reference.
  9521. * @param {Node} newNode The new DOM node.
  9522. */
  9523. function replaceWith($rootElement, elementsToRemove, newNode) {
  9524. var firstElementToRemove = elementsToRemove[0],
  9525. removeCount = elementsToRemove.length,
  9526. parent = firstElementToRemove.parentNode,
  9527. i, ii;
  9528. if ($rootElement) {
  9529. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  9530. if ($rootElement[i] === firstElementToRemove) {
  9531. $rootElement[i++] = newNode;
  9532. for (var j = i, j2 = j + removeCount - 1,
  9533. jj = $rootElement.length;
  9534. j < jj; j++, j2++) {
  9535. if (j2 < jj) {
  9536. $rootElement[j] = $rootElement[j2];
  9537. } else {
  9538. delete $rootElement[j];
  9539. }
  9540. }
  9541. $rootElement.length -= removeCount - 1;
  9542. // If the replaced element is also the jQuery .context then replace it
  9543. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  9544. // http://api.jquery.com/context/
  9545. if ($rootElement.context === firstElementToRemove) {
  9546. $rootElement.context = newNode;
  9547. }
  9548. break;
  9549. }
  9550. }
  9551. }
  9552. if (parent) {
  9553. parent.replaceChild(newNode, firstElementToRemove);
  9554. }
  9555. // Append all the `elementsToRemove` to a fragment. This will...
  9556. // - remove them from the DOM
  9557. // - allow them to still be traversed with .nextSibling
  9558. // - allow a single fragment.qSA to fetch all elements being removed
  9559. var fragment = window.document.createDocumentFragment();
  9560. for (i = 0; i < removeCount; i++) {
  9561. fragment.appendChild(elementsToRemove[i]);
  9562. }
  9563. if (jqLite.hasData(firstElementToRemove)) {
  9564. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  9565. // data here because there's no public interface in jQuery to do that and copying over
  9566. // event listeners (which is the main use of private data) wouldn't work anyway.
  9567. jqLite.data(newNode, jqLite.data(firstElementToRemove));
  9568. // Remove $destroy event listeners from `firstElementToRemove`
  9569. jqLite(firstElementToRemove).off('$destroy');
  9570. }
  9571. // Cleanup any data/listeners on the elements and children.
  9572. // This includes invoking the $destroy event on any elements with listeners.
  9573. jqLite.cleanData(fragment.querySelectorAll('*'));
  9574. // Update the jqLite collection to only contain the `newNode`
  9575. for (i = 1; i < removeCount; i++) {
  9576. delete elementsToRemove[i];
  9577. }
  9578. elementsToRemove[0] = newNode;
  9579. elementsToRemove.length = 1;
  9580. }
  9581. function cloneAndAnnotateFn(fn, annotation) {
  9582. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  9583. }
  9584. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  9585. try {
  9586. linkFn(scope, $element, attrs, controllers, transcludeFn);
  9587. } catch (e) {
  9588. $exceptionHandler(e, startingTag($element));
  9589. }
  9590. }
  9591. function strictBindingsCheck(attrName, directiveName) {
  9592. if (strictComponentBindingsEnabled) {
  9593. throw $compileMinErr('missingattr',
  9594. 'Attribute \'{0}\' of \'{1}\' is non-optional and must be set!',
  9595. attrName, directiveName);
  9596. }
  9597. }
  9598. // Set up $watches for isolate scope and controller bindings.
  9599. function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
  9600. var removeWatchCollection = [];
  9601. var initialChanges = {};
  9602. var changes;
  9603. forEach(bindings, function initializeBinding(definition, scopeName) {
  9604. var attrName = definition.attrName,
  9605. optional = definition.optional,
  9606. mode = definition.mode, // @, =, <, or &
  9607. lastValue,
  9608. parentGet, parentSet, compare, removeWatch;
  9609. switch (mode) {
  9610. case '@':
  9611. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  9612. strictBindingsCheck(attrName, directive.name);
  9613. destination[scopeName] = attrs[attrName] = undefined;
  9614. }
  9615. removeWatch = attrs.$observe(attrName, function(value) {
  9616. if (isString(value) || isBoolean(value)) {
  9617. var oldValue = destination[scopeName];
  9618. recordChanges(scopeName, value, oldValue);
  9619. destination[scopeName] = value;
  9620. }
  9621. });
  9622. attrs.$$observers[attrName].$$scope = scope;
  9623. lastValue = attrs[attrName];
  9624. if (isString(lastValue)) {
  9625. // If the attribute has been provided then we trigger an interpolation to ensure
  9626. // the value is there for use in the link fn
  9627. destination[scopeName] = $interpolate(lastValue)(scope);
  9628. } else if (isBoolean(lastValue)) {
  9629. // If the attributes is one of the BOOLEAN_ATTR then Angular will have converted
  9630. // the value to boolean rather than a string, so we special case this situation
  9631. destination[scopeName] = lastValue;
  9632. }
  9633. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  9634. removeWatchCollection.push(removeWatch);
  9635. break;
  9636. case '=':
  9637. if (!hasOwnProperty.call(attrs, attrName)) {
  9638. if (optional) break;
  9639. strictBindingsCheck(attrName, directive.name);
  9640. attrs[attrName] = undefined;
  9641. }
  9642. if (optional && !attrs[attrName]) break;
  9643. parentGet = $parse(attrs[attrName]);
  9644. if (parentGet.literal) {
  9645. compare = equals;
  9646. } else {
  9647. compare = simpleCompare;
  9648. }
  9649. parentSet = parentGet.assign || function() {
  9650. // reset the change, or we will throw this exception on every $digest
  9651. lastValue = destination[scopeName] = parentGet(scope);
  9652. throw $compileMinErr('nonassign',
  9653. 'Expression \'{0}\' in attribute \'{1}\' used with directive \'{2}\' is non-assignable!',
  9654. attrs[attrName], attrName, directive.name);
  9655. };
  9656. lastValue = destination[scopeName] = parentGet(scope);
  9657. var parentValueWatch = function parentValueWatch(parentValue) {
  9658. if (!compare(parentValue, destination[scopeName])) {
  9659. // we are out of sync and need to copy
  9660. if (!compare(parentValue, lastValue)) {
  9661. // parent changed and it has precedence
  9662. destination[scopeName] = parentValue;
  9663. } else {
  9664. // if the parent can be assigned then do so
  9665. parentSet(scope, parentValue = destination[scopeName]);
  9666. }
  9667. }
  9668. lastValue = parentValue;
  9669. return lastValue;
  9670. };
  9671. parentValueWatch.$stateful = true;
  9672. if (definition.collection) {
  9673. removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  9674. } else {
  9675. removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  9676. }
  9677. removeWatchCollection.push(removeWatch);
  9678. break;
  9679. case '<':
  9680. if (!hasOwnProperty.call(attrs, attrName)) {
  9681. if (optional) break;
  9682. strictBindingsCheck(attrName, directive.name);
  9683. attrs[attrName] = undefined;
  9684. }
  9685. if (optional && !attrs[attrName]) break;
  9686. parentGet = $parse(attrs[attrName]);
  9687. var deepWatch = parentGet.literal;
  9688. var initialValue = destination[scopeName] = parentGet(scope);
  9689. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  9690. removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newValue, oldValue) {
  9691. if (oldValue === newValue) {
  9692. if (oldValue === initialValue || (deepWatch && equals(oldValue, initialValue))) {
  9693. return;
  9694. }
  9695. oldValue = initialValue;
  9696. }
  9697. recordChanges(scopeName, newValue, oldValue);
  9698. destination[scopeName] = newValue;
  9699. }, deepWatch);
  9700. removeWatchCollection.push(removeWatch);
  9701. break;
  9702. case '&':
  9703. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  9704. strictBindingsCheck(attrName, directive.name);
  9705. }
  9706. // Don't assign Object.prototype method to scope
  9707. parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
  9708. // Don't assign noop to destination if expression is not valid
  9709. if (parentGet === noop && optional) break;
  9710. destination[scopeName] = function(locals) {
  9711. return parentGet(scope, locals);
  9712. };
  9713. break;
  9714. }
  9715. });
  9716. function recordChanges(key, currentValue, previousValue) {
  9717. if (isFunction(destination.$onChanges) && !simpleCompare(currentValue, previousValue)) {
  9718. // If we have not already scheduled the top level onChangesQueue handler then do so now
  9719. if (!onChangesQueue) {
  9720. scope.$$postDigest(flushOnChangesQueue);
  9721. onChangesQueue = [];
  9722. }
  9723. // If we have not already queued a trigger of onChanges for this controller then do so now
  9724. if (!changes) {
  9725. changes = {};
  9726. onChangesQueue.push(triggerOnChangesHook);
  9727. }
  9728. // If the has been a change on this property already then we need to reuse the previous value
  9729. if (changes[key]) {
  9730. previousValue = changes[key].previousValue;
  9731. }
  9732. // Store this change
  9733. changes[key] = new SimpleChange(previousValue, currentValue);
  9734. }
  9735. }
  9736. function triggerOnChangesHook() {
  9737. destination.$onChanges(changes);
  9738. // Now clear the changes so that we schedule onChanges when more changes arrive
  9739. changes = undefined;
  9740. }
  9741. return {
  9742. initialChanges: initialChanges,
  9743. removeWatches: removeWatchCollection.length && function removeWatches() {
  9744. for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
  9745. removeWatchCollection[i]();
  9746. }
  9747. }
  9748. };
  9749. }
  9750. }];
  9751. }
  9752. function SimpleChange(previous, current) {
  9753. this.previousValue = previous;
  9754. this.currentValue = current;
  9755. }
  9756. SimpleChange.prototype.isFirstChange = function() { return this.previousValue === _UNINITIALIZED_VALUE; };
  9757. var PREFIX_REGEXP = /^((?:x|data)[:\-_])/i;
  9758. var SPECIAL_CHARS_REGEXP = /[:\-_]+(.)/g;
  9759. /**
  9760. * Converts all accepted directives format into proper directive name.
  9761. * @param name Name to normalize
  9762. */
  9763. function directiveNormalize(name) {
  9764. return name
  9765. .replace(PREFIX_REGEXP, '')
  9766. .replace(SPECIAL_CHARS_REGEXP, function(_, letter, offset) {
  9767. return offset ? letter.toUpperCase() : letter;
  9768. });
  9769. }
  9770. /**
  9771. * @ngdoc type
  9772. * @name $compile.directive.Attributes
  9773. *
  9774. * @description
  9775. * A shared object between directive compile / linking functions which contains normalized DOM
  9776. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  9777. * needed since all of these are treated as equivalent in Angular:
  9778. *
  9779. * ```
  9780. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  9781. * ```
  9782. */
  9783. /**
  9784. * @ngdoc property
  9785. * @name $compile.directive.Attributes#$attr
  9786. *
  9787. * @description
  9788. * A map of DOM element attribute names to the normalized name. This is
  9789. * needed to do reverse lookup from normalized name back to actual name.
  9790. */
  9791. /**
  9792. * @ngdoc method
  9793. * @name $compile.directive.Attributes#$set
  9794. * @kind function
  9795. *
  9796. * @description
  9797. * Set DOM element attribute value.
  9798. *
  9799. *
  9800. * @param {string} name Normalized element attribute name of the property to modify. The name is
  9801. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  9802. * property to the original name.
  9803. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  9804. */
  9805. /**
  9806. * Closure compiler type information
  9807. */
  9808. function nodesetLinkingFn(
  9809. /* angular.Scope */ scope,
  9810. /* NodeList */ nodeList,
  9811. /* Element */ rootElement,
  9812. /* function(Function) */ boundTranscludeFn
  9813. ) {}
  9814. function directiveLinkingFn(
  9815. /* nodesetLinkingFn */ nodesetLinkingFn,
  9816. /* angular.Scope */ scope,
  9817. /* Node */ node,
  9818. /* Element */ rootElement,
  9819. /* function(Function) */ boundTranscludeFn
  9820. ) {}
  9821. function tokenDifference(str1, str2) {
  9822. var values = '',
  9823. tokens1 = str1.split(/\s+/),
  9824. tokens2 = str2.split(/\s+/);
  9825. outer:
  9826. for (var i = 0; i < tokens1.length; i++) {
  9827. var token = tokens1[i];
  9828. for (var j = 0; j < tokens2.length; j++) {
  9829. if (token === tokens2[j]) continue outer;
  9830. }
  9831. values += (values.length > 0 ? ' ' : '') + token;
  9832. }
  9833. return values;
  9834. }
  9835. function removeComments(jqNodes) {
  9836. jqNodes = jqLite(jqNodes);
  9837. var i = jqNodes.length;
  9838. if (i <= 1) {
  9839. return jqNodes;
  9840. }
  9841. while (i--) {
  9842. var node = jqNodes[i];
  9843. if (node.nodeType === NODE_TYPE_COMMENT ||
  9844. (node.nodeType === NODE_TYPE_TEXT && node.nodeValue.trim() === '')) {
  9845. splice.call(jqNodes, i, 1);
  9846. }
  9847. }
  9848. return jqNodes;
  9849. }
  9850. var $controllerMinErr = minErr('$controller');
  9851. var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/;
  9852. function identifierForController(controller, ident) {
  9853. if (ident && isString(ident)) return ident;
  9854. if (isString(controller)) {
  9855. var match = CNTRL_REG.exec(controller);
  9856. if (match) return match[3];
  9857. }
  9858. }
  9859. /**
  9860. * @ngdoc provider
  9861. * @name $controllerProvider
  9862. * @this
  9863. *
  9864. * @description
  9865. * The {@link ng.$controller $controller service} is used by Angular to create new
  9866. * controllers.
  9867. *
  9868. * This provider allows controller registration via the
  9869. * {@link ng.$controllerProvider#register register} method.
  9870. */
  9871. function $ControllerProvider() {
  9872. var controllers = {},
  9873. globals = false;
  9874. /**
  9875. * @ngdoc method
  9876. * @name $controllerProvider#has
  9877. * @param {string} name Controller name to check.
  9878. */
  9879. this.has = function(name) {
  9880. return controllers.hasOwnProperty(name);
  9881. };
  9882. /**
  9883. * @ngdoc method
  9884. * @name $controllerProvider#register
  9885. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  9886. * the names and the values are the constructors.
  9887. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  9888. * annotations in the array notation).
  9889. */
  9890. this.register = function(name, constructor) {
  9891. assertNotHasOwnProperty(name, 'controller');
  9892. if (isObject(name)) {
  9893. extend(controllers, name);
  9894. } else {
  9895. controllers[name] = constructor;
  9896. }
  9897. };
  9898. /**
  9899. * @ngdoc method
  9900. * @name $controllerProvider#allowGlobals
  9901. * @description If called, allows `$controller` to find controller constructors on `window`
  9902. *
  9903. * @deprecated
  9904. * sinceVersion="v1.3.0"
  9905. * removeVersion="v1.7.0"
  9906. * This method of finding controllers has been deprecated.
  9907. */
  9908. this.allowGlobals = function() {
  9909. globals = true;
  9910. };
  9911. this.$get = ['$injector', '$window', function($injector, $window) {
  9912. /**
  9913. * @ngdoc service
  9914. * @name $controller
  9915. * @requires $injector
  9916. *
  9917. * @param {Function|string} constructor If called with a function then it's considered to be the
  9918. * controller constructor function. Otherwise it's considered to be a string which is used
  9919. * to retrieve the controller constructor using the following steps:
  9920. *
  9921. * * check if a controller with given name is registered via `$controllerProvider`
  9922. * * check if evaluating the string on the current scope returns a constructor
  9923. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  9924. * `window` object (deprecated, not recommended)
  9925. *
  9926. * The string can use the `controller as property` syntax, where the controller instance is published
  9927. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  9928. * to work correctly.
  9929. *
  9930. * @param {Object} locals Injection locals for Controller.
  9931. * @return {Object} Instance of given controller.
  9932. *
  9933. * @description
  9934. * `$controller` service is responsible for instantiating controllers.
  9935. *
  9936. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  9937. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  9938. */
  9939. return function $controller(expression, locals, later, ident) {
  9940. // PRIVATE API:
  9941. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  9942. // If true, $controller will allocate the object with the correct
  9943. // prototype chain, but will not invoke the controller until a returned
  9944. // callback is invoked.
  9945. // param `ident` --- An optional label which overrides the label parsed from the controller
  9946. // expression, if any.
  9947. var instance, match, constructor, identifier;
  9948. later = later === true;
  9949. if (ident && isString(ident)) {
  9950. identifier = ident;
  9951. }
  9952. if (isString(expression)) {
  9953. match = expression.match(CNTRL_REG);
  9954. if (!match) {
  9955. throw $controllerMinErr('ctrlfmt',
  9956. 'Badly formed controller string \'{0}\'. ' +
  9957. 'Must match `__name__ as __id__` or `__name__`.', expression);
  9958. }
  9959. constructor = match[1];
  9960. identifier = identifier || match[3];
  9961. expression = controllers.hasOwnProperty(constructor)
  9962. ? controllers[constructor]
  9963. : getter(locals.$scope, constructor, true) ||
  9964. (globals ? getter($window, constructor, true) : undefined);
  9965. if (!expression) {
  9966. throw $controllerMinErr('ctrlreg',
  9967. 'The controller with the name \'{0}\' is not registered.', constructor);
  9968. }
  9969. assertArgFn(expression, constructor, true);
  9970. }
  9971. if (later) {
  9972. // Instantiate controller later:
  9973. // This machinery is used to create an instance of the object before calling the
  9974. // controller's constructor itself.
  9975. //
  9976. // This allows properties to be added to the controller before the constructor is
  9977. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  9978. //
  9979. // This feature is not intended for use by applications, and is thus not documented
  9980. // publicly.
  9981. // Object creation: http://jsperf.com/create-constructor/2
  9982. var controllerPrototype = (isArray(expression) ?
  9983. expression[expression.length - 1] : expression).prototype;
  9984. instance = Object.create(controllerPrototype || null);
  9985. if (identifier) {
  9986. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9987. }
  9988. return extend(function $controllerInit() {
  9989. var result = $injector.invoke(expression, instance, locals, constructor);
  9990. if (result !== instance && (isObject(result) || isFunction(result))) {
  9991. instance = result;
  9992. if (identifier) {
  9993. // If result changed, re-assign controllerAs value to scope.
  9994. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9995. }
  9996. }
  9997. return instance;
  9998. }, {
  9999. instance: instance,
  10000. identifier: identifier
  10001. });
  10002. }
  10003. instance = $injector.instantiate(expression, locals, constructor);
  10004. if (identifier) {
  10005. addIdentifier(locals, identifier, instance, constructor || expression.name);
  10006. }
  10007. return instance;
  10008. };
  10009. function addIdentifier(locals, identifier, instance, name) {
  10010. if (!(locals && isObject(locals.$scope))) {
  10011. throw minErr('$controller')('noscp',
  10012. 'Cannot export controller \'{0}\' as \'{1}\'! No $scope object provided via `locals`.',
  10013. name, identifier);
  10014. }
  10015. locals.$scope[identifier] = instance;
  10016. }
  10017. }];
  10018. }
  10019. /**
  10020. * @ngdoc service
  10021. * @name $document
  10022. * @requires $window
  10023. * @this
  10024. *
  10025. * @description
  10026. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  10027. *
  10028. * @example
  10029. <example module="documentExample" name="document">
  10030. <file name="index.html">
  10031. <div ng-controller="ExampleController">
  10032. <p>$document title: <b ng-bind="title"></b></p>
  10033. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  10034. </div>
  10035. </file>
  10036. <file name="script.js">
  10037. angular.module('documentExample', [])
  10038. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  10039. $scope.title = $document[0].title;
  10040. $scope.windowTitle = angular.element(window.document)[0].title;
  10041. }]);
  10042. </file>
  10043. </example>
  10044. */
  10045. function $DocumentProvider() {
  10046. this.$get = ['$window', function(window) {
  10047. return jqLite(window.document);
  10048. }];
  10049. }
  10050. /**
  10051. * @private
  10052. * @this
  10053. * Listens for document visibility change and makes the current status accessible.
  10054. */
  10055. function $$IsDocumentHiddenProvider() {
  10056. this.$get = ['$document', '$rootScope', function($document, $rootScope) {
  10057. var doc = $document[0];
  10058. var hidden = doc && doc.hidden;
  10059. $document.on('visibilitychange', changeListener);
  10060. $rootScope.$on('$destroy', function() {
  10061. $document.off('visibilitychange', changeListener);
  10062. });
  10063. function changeListener() {
  10064. hidden = doc.hidden;
  10065. }
  10066. return function() {
  10067. return hidden;
  10068. };
  10069. }];
  10070. }
  10071. /**
  10072. * @ngdoc service
  10073. * @name $exceptionHandler
  10074. * @requires ng.$log
  10075. * @this
  10076. *
  10077. * @description
  10078. * Any uncaught exception in angular expressions is delegated to this service.
  10079. * The default implementation simply delegates to `$log.error` which logs it into
  10080. * the browser console.
  10081. *
  10082. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  10083. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  10084. *
  10085. * ## Example:
  10086. *
  10087. * The example below will overwrite the default `$exceptionHandler` in order to (a) log uncaught
  10088. * errors to the backend for later inspection by the developers and (b) to use `$log.warn()` instead
  10089. * of `$log.error()`.
  10090. *
  10091. * ```js
  10092. * angular.
  10093. * module('exceptionOverwrite', []).
  10094. * factory('$exceptionHandler', ['$log', 'logErrorsToBackend', function($log, logErrorsToBackend) {
  10095. * return function myExceptionHandler(exception, cause) {
  10096. * logErrorsToBackend(exception, cause);
  10097. * $log.warn(exception, cause);
  10098. * };
  10099. * }]);
  10100. * ```
  10101. *
  10102. * <hr />
  10103. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  10104. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  10105. * (unless executed during a digest).
  10106. *
  10107. * If you wish, you can manually delegate exceptions, e.g.
  10108. * `try { ... } catch(e) { $exceptionHandler(e); }`
  10109. *
  10110. * @param {Error} exception Exception associated with the error.
  10111. * @param {string=} cause Optional information about the context in which
  10112. * the error was thrown.
  10113. *
  10114. */
  10115. function $ExceptionHandlerProvider() {
  10116. this.$get = ['$log', function($log) {
  10117. return function(exception, cause) {
  10118. $log.error.apply($log, arguments);
  10119. };
  10120. }];
  10121. }
  10122. var $$ForceReflowProvider = /** @this */ function() {
  10123. this.$get = ['$document', function($document) {
  10124. return function(domNode) {
  10125. //the line below will force the browser to perform a repaint so
  10126. //that all the animated elements within the animation frame will
  10127. //be properly updated and drawn on screen. This is required to
  10128. //ensure that the preparation animation is properly flushed so that
  10129. //the active state picks up from there. DO NOT REMOVE THIS LINE.
  10130. //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
  10131. //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
  10132. //WILL TAKE YEARS AWAY FROM YOUR LIFE.
  10133. if (domNode) {
  10134. if (!domNode.nodeType && domNode instanceof jqLite) {
  10135. domNode = domNode[0];
  10136. }
  10137. } else {
  10138. domNode = $document[0].body;
  10139. }
  10140. return domNode.offsetWidth + 1;
  10141. };
  10142. }];
  10143. };
  10144. var APPLICATION_JSON = 'application/json';
  10145. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  10146. var JSON_START = /^\[|^\{(?!\{)/;
  10147. var JSON_ENDS = {
  10148. '[': /]$/,
  10149. '{': /}$/
  10150. };
  10151. var JSON_PROTECTION_PREFIX = /^\)]\}',?\n/;
  10152. var $httpMinErr = minErr('$http');
  10153. function serializeValue(v) {
  10154. if (isObject(v)) {
  10155. return isDate(v) ? v.toISOString() : toJson(v);
  10156. }
  10157. return v;
  10158. }
  10159. /** @this */
  10160. function $HttpParamSerializerProvider() {
  10161. /**
  10162. * @ngdoc service
  10163. * @name $httpParamSerializer
  10164. * @description
  10165. *
  10166. * Default {@link $http `$http`} params serializer that converts objects to strings
  10167. * according to the following rules:
  10168. *
  10169. * * `{'foo': 'bar'}` results in `foo=bar`
  10170. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  10171. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  10172. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D` (stringified and encoded representation of an object)
  10173. *
  10174. * Note that serializer will sort the request parameters alphabetically.
  10175. * */
  10176. this.$get = function() {
  10177. return function ngParamSerializer(params) {
  10178. if (!params) return '';
  10179. var parts = [];
  10180. forEachSorted(params, function(value, key) {
  10181. if (value === null || isUndefined(value) || isFunction(value)) return;
  10182. if (isArray(value)) {
  10183. forEach(value, function(v) {
  10184. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  10185. });
  10186. } else {
  10187. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  10188. }
  10189. });
  10190. return parts.join('&');
  10191. };
  10192. };
  10193. }
  10194. /** @this */
  10195. function $HttpParamSerializerJQLikeProvider() {
  10196. /**
  10197. * @ngdoc service
  10198. * @name $httpParamSerializerJQLike
  10199. *
  10200. * @description
  10201. *
  10202. * Alternative {@link $http `$http`} params serializer that follows
  10203. * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  10204. * The serializer will also sort the params alphabetically.
  10205. *
  10206. * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
  10207. *
  10208. * ```js
  10209. * $http({
  10210. * url: myUrl,
  10211. * method: 'GET',
  10212. * params: myParams,
  10213. * paramSerializer: '$httpParamSerializerJQLike'
  10214. * });
  10215. * ```
  10216. *
  10217. * It is also possible to set it as the default `paramSerializer` in the
  10218. * {@link $httpProvider#defaults `$httpProvider`}.
  10219. *
  10220. * Additionally, you can inject the serializer and use it explicitly, for example to serialize
  10221. * form data for submission:
  10222. *
  10223. * ```js
  10224. * .controller(function($http, $httpParamSerializerJQLike) {
  10225. * //...
  10226. *
  10227. * $http({
  10228. * url: myUrl,
  10229. * method: 'POST',
  10230. * data: $httpParamSerializerJQLike(myData),
  10231. * headers: {
  10232. * 'Content-Type': 'application/x-www-form-urlencoded'
  10233. * }
  10234. * });
  10235. *
  10236. * });
  10237. * ```
  10238. *
  10239. * */
  10240. this.$get = function() {
  10241. return function jQueryLikeParamSerializer(params) {
  10242. if (!params) return '';
  10243. var parts = [];
  10244. serialize(params, '', true);
  10245. return parts.join('&');
  10246. function serialize(toSerialize, prefix, topLevel) {
  10247. if (toSerialize === null || isUndefined(toSerialize)) return;
  10248. if (isArray(toSerialize)) {
  10249. forEach(toSerialize, function(value, index) {
  10250. serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
  10251. });
  10252. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  10253. forEachSorted(toSerialize, function(value, key) {
  10254. serialize(value, prefix +
  10255. (topLevel ? '' : '[') +
  10256. key +
  10257. (topLevel ? '' : ']'));
  10258. });
  10259. } else {
  10260. parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
  10261. }
  10262. }
  10263. };
  10264. };
  10265. }
  10266. function defaultHttpResponseTransform(data, headers) {
  10267. if (isString(data)) {
  10268. // Strip json vulnerability protection prefix and trim whitespace
  10269. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  10270. if (tempData) {
  10271. var contentType = headers('Content-Type');
  10272. var hasJsonContentType = contentType && (contentType.indexOf(APPLICATION_JSON) === 0);
  10273. if (hasJsonContentType || isJsonLike(tempData)) {
  10274. try {
  10275. data = fromJson(tempData);
  10276. } catch (e) {
  10277. if (!hasJsonContentType) {
  10278. return data;
  10279. }
  10280. throw $httpMinErr('baddata', 'Data must be a valid JSON object. Received: "{0}". ' +
  10281. 'Parse error: "{1}"', data, e);
  10282. }
  10283. }
  10284. }
  10285. }
  10286. return data;
  10287. }
  10288. function isJsonLike(str) {
  10289. var jsonStart = str.match(JSON_START);
  10290. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  10291. }
  10292. /**
  10293. * Parse headers into key value object
  10294. *
  10295. * @param {string} headers Raw headers as a string
  10296. * @returns {Object} Parsed headers as key value object
  10297. */
  10298. function parseHeaders(headers) {
  10299. var parsed = createMap(), i;
  10300. function fillInParsed(key, val) {
  10301. if (key) {
  10302. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  10303. }
  10304. }
  10305. if (isString(headers)) {
  10306. forEach(headers.split('\n'), function(line) {
  10307. i = line.indexOf(':');
  10308. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  10309. });
  10310. } else if (isObject(headers)) {
  10311. forEach(headers, function(headerVal, headerKey) {
  10312. fillInParsed(lowercase(headerKey), trim(headerVal));
  10313. });
  10314. }
  10315. return parsed;
  10316. }
  10317. /**
  10318. * Returns a function that provides access to parsed headers.
  10319. *
  10320. * Headers are lazy parsed when first requested.
  10321. * @see parseHeaders
  10322. *
  10323. * @param {(string|Object)} headers Headers to provide access to.
  10324. * @returns {function(string=)} Returns a getter function which if called with:
  10325. *
  10326. * - if called with an argument returns a single header value or null
  10327. * - if called with no arguments returns an object containing all headers.
  10328. */
  10329. function headersGetter(headers) {
  10330. var headersObj;
  10331. return function(name) {
  10332. if (!headersObj) headersObj = parseHeaders(headers);
  10333. if (name) {
  10334. var value = headersObj[lowercase(name)];
  10335. if (value === undefined) {
  10336. value = null;
  10337. }
  10338. return value;
  10339. }
  10340. return headersObj;
  10341. };
  10342. }
  10343. /**
  10344. * Chain all given functions
  10345. *
  10346. * This function is used for both request and response transforming
  10347. *
  10348. * @param {*} data Data to transform.
  10349. * @param {function(string=)} headers HTTP headers getter fn.
  10350. * @param {number} status HTTP status code of the response.
  10351. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  10352. * @returns {*} Transformed data.
  10353. */
  10354. function transformData(data, headers, status, fns) {
  10355. if (isFunction(fns)) {
  10356. return fns(data, headers, status);
  10357. }
  10358. forEach(fns, function(fn) {
  10359. data = fn(data, headers, status);
  10360. });
  10361. return data;
  10362. }
  10363. function isSuccess(status) {
  10364. return 200 <= status && status < 300;
  10365. }
  10366. /**
  10367. * @ngdoc provider
  10368. * @name $httpProvider
  10369. * @this
  10370. *
  10371. * @description
  10372. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  10373. * */
  10374. function $HttpProvider() {
  10375. /**
  10376. * @ngdoc property
  10377. * @name $httpProvider#defaults
  10378. * @description
  10379. *
  10380. * Object containing default values for all {@link ng.$http $http} requests.
  10381. *
  10382. * - **`defaults.cache`** - {boolean|Object} - A boolean value or object created with
  10383. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of HTTP responses
  10384. * by default. See {@link $http#caching $http Caching} for more information.
  10385. *
  10386. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  10387. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  10388. * setting default headers.
  10389. * - **`defaults.headers.common`**
  10390. * - **`defaults.headers.post`**
  10391. * - **`defaults.headers.put`**
  10392. * - **`defaults.headers.patch`**
  10393. *
  10394. * - **`defaults.jsonpCallbackParam`** - `{string}` - the name of the query parameter that passes the name of the
  10395. * callback in a JSONP request. The value of this parameter will be replaced with the expression generated by the
  10396. * {@link $jsonpCallbacks} service. Defaults to `'callback'`.
  10397. *
  10398. * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
  10399. * used to the prepare string representation of request parameters (specified as an object).
  10400. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  10401. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  10402. *
  10403. * - **`defaults.transformRequest`** -
  10404. * `{Array<function(data, headersGetter)>|function(data, headersGetter)}` -
  10405. * An array of functions (or a single function) which are applied to the request data.
  10406. * By default, this is an array with one request transformation function:
  10407. *
  10408. * - If the `data` property of the request configuration object contains an object, serialize it
  10409. * into JSON format.
  10410. *
  10411. * - **`defaults.transformResponse`** -
  10412. * `{Array<function(data, headersGetter, status)>|function(data, headersGetter, status)}` -
  10413. * An array of functions (or a single function) which are applied to the response data. By default,
  10414. * this is an array which applies one response transformation function that does two things:
  10415. *
  10416. * - If XSRF prefix is detected, strip it
  10417. * (see {@link ng.$http#security-considerations Security Considerations in the $http docs}).
  10418. * - If the `Content-Type` is `application/json` or the response looks like JSON,
  10419. * deserialize it using a JSON parser.
  10420. *
  10421. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  10422. * Defaults value is `'XSRF-TOKEN'`.
  10423. *
  10424. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  10425. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  10426. *
  10427. **/
  10428. var defaults = this.defaults = {
  10429. // transform incoming response data
  10430. transformResponse: [defaultHttpResponseTransform],
  10431. // transform outgoing request data
  10432. transformRequest: [function(d) {
  10433. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  10434. }],
  10435. // default headers
  10436. headers: {
  10437. common: {
  10438. 'Accept': 'application/json, text/plain, */*'
  10439. },
  10440. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  10441. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  10442. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  10443. },
  10444. xsrfCookieName: 'XSRF-TOKEN',
  10445. xsrfHeaderName: 'X-XSRF-TOKEN',
  10446. paramSerializer: '$httpParamSerializer',
  10447. jsonpCallbackParam: 'callback'
  10448. };
  10449. var useApplyAsync = false;
  10450. /**
  10451. * @ngdoc method
  10452. * @name $httpProvider#useApplyAsync
  10453. * @description
  10454. *
  10455. * Configure $http service to combine processing of multiple http responses received at around
  10456. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  10457. * significant performance improvement for bigger applications that make many HTTP requests
  10458. * concurrently (common during application bootstrap).
  10459. *
  10460. * Defaults to false. If no value is specified, returns the current configured value.
  10461. *
  10462. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  10463. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  10464. * to load and share the same digest cycle.
  10465. *
  10466. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  10467. * otherwise, returns the current configured value.
  10468. **/
  10469. this.useApplyAsync = function(value) {
  10470. if (isDefined(value)) {
  10471. useApplyAsync = !!value;
  10472. return this;
  10473. }
  10474. return useApplyAsync;
  10475. };
  10476. /**
  10477. * @ngdoc property
  10478. * @name $httpProvider#interceptors
  10479. * @description
  10480. *
  10481. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  10482. * pre-processing of request or postprocessing of responses.
  10483. *
  10484. * These service factories are ordered by request, i.e. they are applied in the same order as the
  10485. * array, on request, but reverse order, on response.
  10486. *
  10487. * {@link ng.$http#interceptors Interceptors detailed info}
  10488. **/
  10489. var interceptorFactories = this.interceptors = [];
  10490. this.$get = ['$browser', '$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector', '$sce',
  10491. function($browser, $httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector, $sce) {
  10492. var defaultCache = $cacheFactory('$http');
  10493. /**
  10494. * Make sure that default param serializer is exposed as a function
  10495. */
  10496. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  10497. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  10498. /**
  10499. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  10500. * The reversal is needed so that we can build up the interception chain around the
  10501. * server request.
  10502. */
  10503. var reversedInterceptors = [];
  10504. forEach(interceptorFactories, function(interceptorFactory) {
  10505. reversedInterceptors.unshift(isString(interceptorFactory)
  10506. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  10507. });
  10508. /**
  10509. * @ngdoc service
  10510. * @kind function
  10511. * @name $http
  10512. * @requires ng.$httpBackend
  10513. * @requires $cacheFactory
  10514. * @requires $rootScope
  10515. * @requires $q
  10516. * @requires $injector
  10517. *
  10518. * @description
  10519. * The `$http` service is a core Angular service that facilitates communication with the remote
  10520. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  10521. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  10522. *
  10523. * For unit testing applications that use `$http` service, see
  10524. * {@link ngMock.$httpBackend $httpBackend mock}.
  10525. *
  10526. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  10527. * $resource} service.
  10528. *
  10529. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  10530. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  10531. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  10532. *
  10533. *
  10534. * ## General usage
  10535. * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
  10536. * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
  10537. *
  10538. * ```js
  10539. * // Simple GET request example:
  10540. * $http({
  10541. * method: 'GET',
  10542. * url: '/someUrl'
  10543. * }).then(function successCallback(response) {
  10544. * // this callback will be called asynchronously
  10545. * // when the response is available
  10546. * }, function errorCallback(response) {
  10547. * // called asynchronously if an error occurs
  10548. * // or server returns response with an error status.
  10549. * });
  10550. * ```
  10551. *
  10552. * The response object has these properties:
  10553. *
  10554. * - **data** – `{string|Object}` – The response body transformed with the transform
  10555. * functions.
  10556. * - **status** – `{number}` – HTTP status code of the response.
  10557. * - **headers** – `{function([headerName])}` – Header getter function.
  10558. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  10559. * - **statusText** – `{string}` – HTTP status text of the response.
  10560. * - **xhrStatus** – `{string}` – Status of the XMLHttpRequest (`complete`, `error`, `timeout` or `abort`).
  10561. *
  10562. * A response status code between 200 and 299 is considered a success status and will result in
  10563. * the success callback being called. Any response status code outside of that range is
  10564. * considered an error status and will result in the error callback being called.
  10565. * Also, status codes less than -1 are normalized to zero. -1 usually means the request was
  10566. * aborted, e.g. using a `config.timeout`.
  10567. * Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning
  10568. * that the outcome (success or error) will be determined by the final response status code.
  10569. *
  10570. *
  10571. * ## Shortcut methods
  10572. *
  10573. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  10574. * request data must be passed in for POST/PUT requests. An optional config can be passed as the
  10575. * last argument.
  10576. *
  10577. * ```js
  10578. * $http.get('/someUrl', config).then(successCallback, errorCallback);
  10579. * $http.post('/someUrl', data, config).then(successCallback, errorCallback);
  10580. * ```
  10581. *
  10582. * Complete list of shortcut methods:
  10583. *
  10584. * - {@link ng.$http#get $http.get}
  10585. * - {@link ng.$http#head $http.head}
  10586. * - {@link ng.$http#post $http.post}
  10587. * - {@link ng.$http#put $http.put}
  10588. * - {@link ng.$http#delete $http.delete}
  10589. * - {@link ng.$http#jsonp $http.jsonp}
  10590. * - {@link ng.$http#patch $http.patch}
  10591. *
  10592. *
  10593. * ## Writing Unit Tests that use $http
  10594. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  10595. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  10596. * request using trained responses.
  10597. *
  10598. * ```
  10599. * $httpBackend.expectGET(...);
  10600. * $http.get(...);
  10601. * $httpBackend.flush();
  10602. * ```
  10603. *
  10604. * ## Setting HTTP Headers
  10605. *
  10606. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  10607. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  10608. * object, which currently contains this default configuration:
  10609. *
  10610. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  10611. * - <code>Accept: application/json, text/plain, \*&#65279;/&#65279;\*</code>
  10612. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  10613. * - `Content-Type: application/json`
  10614. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  10615. * - `Content-Type: application/json`
  10616. *
  10617. * To add or overwrite these defaults, simply add or remove a property from these configuration
  10618. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  10619. * with the lowercased HTTP method name as the key, e.g.
  10620. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  10621. *
  10622. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  10623. * fashion. For example:
  10624. *
  10625. * ```
  10626. * module.run(function($http) {
  10627. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
  10628. * });
  10629. * ```
  10630. *
  10631. * In addition, you can supply a `headers` property in the config object passed when
  10632. * calling `$http(config)`, which overrides the defaults without changing them globally.
  10633. *
  10634. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  10635. * Use the `headers` property, setting the desired header to `undefined`. For example:
  10636. *
  10637. * ```js
  10638. * var req = {
  10639. * method: 'POST',
  10640. * url: 'http://example.com',
  10641. * headers: {
  10642. * 'Content-Type': undefined
  10643. * },
  10644. * data: { test: 'test' }
  10645. * }
  10646. *
  10647. * $http(req).then(function(){...}, function(){...});
  10648. * ```
  10649. *
  10650. * ## Transforming Requests and Responses
  10651. *
  10652. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  10653. * and `transformResponse`. These properties can be a single function that returns
  10654. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  10655. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  10656. *
  10657. * <div class="alert alert-warning">
  10658. * **Note:** Angular does not make a copy of the `data` parameter before it is passed into the `transformRequest` pipeline.
  10659. * That means changes to the properties of `data` are not local to the transform function (since Javascript passes objects by reference).
  10660. * For example, when calling `$http.get(url, $scope.myObject)`, modifications to the object's properties in a transformRequest
  10661. * function will be reflected on the scope and in any templates where the object is data-bound.
  10662. * To prevent this, transform functions should have no side-effects.
  10663. * If you need to modify properties, it is recommended to make a copy of the data, or create new object to return.
  10664. * </div>
  10665. *
  10666. * ### Default Transformations
  10667. *
  10668. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  10669. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  10670. * then these will be applied.
  10671. *
  10672. * You can augment or replace the default transformations by modifying these properties by adding to or
  10673. * replacing the array.
  10674. *
  10675. * Angular provides the following default transformations:
  10676. *
  10677. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`) is
  10678. * an array with one function that does the following:
  10679. *
  10680. * - If the `data` property of the request configuration object contains an object, serialize it
  10681. * into JSON format.
  10682. *
  10683. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`) is
  10684. * an array with one function that does the following:
  10685. *
  10686. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  10687. * - If the `Content-Type` is `application/json` or the response looks like JSON,
  10688. * deserialize it using a JSON parser.
  10689. *
  10690. *
  10691. * ### Overriding the Default Transformations Per Request
  10692. *
  10693. * If you wish to override the request/response transformations only for a single request then provide
  10694. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  10695. * into `$http`.
  10696. *
  10697. * Note that if you provide these properties on the config object the default transformations will be
  10698. * overwritten. If you wish to augment the default transformations then you must include them in your
  10699. * local transformation array.
  10700. *
  10701. * The following code demonstrates adding a new response transformation to be run after the default response
  10702. * transformations have been run.
  10703. *
  10704. * ```js
  10705. * function appendTransform(defaults, transform) {
  10706. *
  10707. * // We can't guarantee that the default transformation is an array
  10708. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  10709. *
  10710. * // Append the new transformation to the defaults
  10711. * return defaults.concat(transform);
  10712. * }
  10713. *
  10714. * $http({
  10715. * url: '...',
  10716. * method: 'GET',
  10717. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  10718. * return doTransform(value);
  10719. * })
  10720. * });
  10721. * ```
  10722. *
  10723. *
  10724. * ## Caching
  10725. *
  10726. * {@link ng.$http `$http`} responses are not cached by default. To enable caching, you must
  10727. * set the config.cache value or the default cache value to TRUE or to a cache object (created
  10728. * with {@link ng.$cacheFactory `$cacheFactory`}). If defined, the value of config.cache takes
  10729. * precedence over the default cache value.
  10730. *
  10731. * In order to:
  10732. * * cache all responses - set the default cache value to TRUE or to a cache object
  10733. * * cache a specific response - set config.cache value to TRUE or to a cache object
  10734. *
  10735. * If caching is enabled, but neither the default cache nor config.cache are set to a cache object,
  10736. * then the default `$cacheFactory("$http")` object is used.
  10737. *
  10738. * The default cache value can be set by updating the
  10739. * {@link ng.$http#defaults `$http.defaults.cache`} property or the
  10740. * {@link $httpProvider#defaults `$httpProvider.defaults.cache`} property.
  10741. *
  10742. * When caching is enabled, {@link ng.$http `$http`} stores the response from the server using
  10743. * the relevant cache object. The next time the same request is made, the response is returned
  10744. * from the cache without sending a request to the server.
  10745. *
  10746. * Take note that:
  10747. *
  10748. * * Only GET and JSONP requests are cached.
  10749. * * The cache key is the request URL including search parameters; headers are not considered.
  10750. * * Cached responses are returned asynchronously, in the same way as responses from the server.
  10751. * * If multiple identical requests are made using the same cache, which is not yet populated,
  10752. * one request will be made to the server and remaining requests will return the same response.
  10753. * * A cache-control header on the response does not affect if or how responses are cached.
  10754. *
  10755. *
  10756. * ## Interceptors
  10757. *
  10758. * Before you start creating interceptors, be sure to understand the
  10759. * {@link ng.$q $q and deferred/promise APIs}.
  10760. *
  10761. * For purposes of global error handling, authentication, or any kind of synchronous or
  10762. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  10763. * able to intercept requests before they are handed to the server and
  10764. * responses before they are handed over to the application code that
  10765. * initiated these requests. The interceptors leverage the {@link ng.$q
  10766. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  10767. *
  10768. * The interceptors are service factories that are registered with the `$httpProvider` by
  10769. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  10770. * injected with dependencies (if specified) and returns the interceptor.
  10771. *
  10772. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  10773. *
  10774. * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
  10775. * modify the `config` object or create a new one. The function needs to return the `config`
  10776. * object directly, or a promise containing the `config` or a new `config` object.
  10777. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  10778. * resolved with a rejection.
  10779. * * `response`: interceptors get called with http `response` object. The function is free to
  10780. * modify the `response` object or create a new one. The function needs to return the `response`
  10781. * object directly, or as a promise containing the `response` or a new `response` object.
  10782. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  10783. * resolved with a rejection.
  10784. *
  10785. *
  10786. * ```js
  10787. * // register the interceptor as a service
  10788. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  10789. * return {
  10790. * // optional method
  10791. * 'request': function(config) {
  10792. * // do something on success
  10793. * return config;
  10794. * },
  10795. *
  10796. * // optional method
  10797. * 'requestError': function(rejection) {
  10798. * // do something on error
  10799. * if (canRecover(rejection)) {
  10800. * return responseOrNewPromise
  10801. * }
  10802. * return $q.reject(rejection);
  10803. * },
  10804. *
  10805. *
  10806. *
  10807. * // optional method
  10808. * 'response': function(response) {
  10809. * // do something on success
  10810. * return response;
  10811. * },
  10812. *
  10813. * // optional method
  10814. * 'responseError': function(rejection) {
  10815. * // do something on error
  10816. * if (canRecover(rejection)) {
  10817. * return responseOrNewPromise
  10818. * }
  10819. * return $q.reject(rejection);
  10820. * }
  10821. * };
  10822. * });
  10823. *
  10824. * $httpProvider.interceptors.push('myHttpInterceptor');
  10825. *
  10826. *
  10827. * // alternatively, register the interceptor via an anonymous factory
  10828. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  10829. * return {
  10830. * 'request': function(config) {
  10831. * // same as above
  10832. * },
  10833. *
  10834. * 'response': function(response) {
  10835. * // same as above
  10836. * }
  10837. * };
  10838. * });
  10839. * ```
  10840. *
  10841. * ## Security Considerations
  10842. *
  10843. * When designing web applications, consider security threats from:
  10844. *
  10845. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  10846. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  10847. *
  10848. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  10849. * pre-configured with strategies that address these issues, but for this to work backend server
  10850. * cooperation is required.
  10851. *
  10852. * ### JSON Vulnerability Protection
  10853. *
  10854. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  10855. * allows third party website to turn your JSON resource URL into
  10856. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  10857. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  10858. * Angular will automatically strip the prefix before processing it as JSON.
  10859. *
  10860. * For example if your server needs to return:
  10861. * ```js
  10862. * ['one','two']
  10863. * ```
  10864. *
  10865. * which is vulnerable to attack, your server can return:
  10866. * ```js
  10867. * )]}',
  10868. * ['one','two']
  10869. * ```
  10870. *
  10871. * Angular will strip the prefix, before processing the JSON.
  10872. *
  10873. *
  10874. * ### Cross Site Request Forgery (XSRF) Protection
  10875. *
  10876. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by
  10877. * which the attacker can trick an authenticated user into unknowingly executing actions on your
  10878. * website. Angular provides a mechanism to counter XSRF. When performing XHR requests, the
  10879. * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP
  10880. * header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the
  10881. * cookie, your server can be assured that the XHR came from JavaScript running on your domain.
  10882. * The header will not be set for cross-domain requests.
  10883. *
  10884. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  10885. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  10886. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  10887. * that only JavaScript running on your domain could have sent the request. The token must be
  10888. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  10889. * making up its own tokens). We recommend that the token is a digest of your site's
  10890. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  10891. * for added security.
  10892. *
  10893. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  10894. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  10895. * or the per-request config object.
  10896. *
  10897. * In order to prevent collisions in environments where multiple Angular apps share the
  10898. * same domain or subdomain, we recommend that each application uses unique cookie name.
  10899. *
  10900. * @param {object} config Object describing the request to be made and how it should be
  10901. * processed. The object has following properties:
  10902. *
  10903. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  10904. * - **url** – `{string|TrustedObject}` – Absolute or relative URL of the resource that is being requested;
  10905. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  10906. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
  10907. * with the `paramSerializer` and appended as GET parameters.
  10908. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  10909. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  10910. * HTTP headers to send to the server. If the return value of a function is null, the
  10911. * header will not be sent. Functions accept a config object as an argument.
  10912. * - **eventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest object.
  10913. * To bind events to the XMLHttpRequest upload object, use `uploadEventHandlers`.
  10914. * The handler will be called in the context of a `$apply` block.
  10915. * - **uploadEventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest upload
  10916. * object. To bind events to the XMLHttpRequest object, use `eventHandlers`.
  10917. * The handler will be called in the context of a `$apply` block.
  10918. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  10919. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  10920. * - **transformRequest** –
  10921. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  10922. * transform function or an array of such functions. The transform function takes the http
  10923. * request body and headers and returns its transformed (typically serialized) version.
  10924. * See {@link ng.$http#overriding-the-default-transformations-per-request
  10925. * Overriding the Default Transformations}
  10926. * - **transformResponse** –
  10927. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  10928. * transform function or an array of such functions. The transform function takes the http
  10929. * response body, headers and status and returns its transformed (typically deserialized) version.
  10930. * See {@link ng.$http#overriding-the-default-transformations-per-request
  10931. * Overriding the Default Transformations}
  10932. * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
  10933. * prepare the string representation of request parameters (specified as an object).
  10934. * If specified as string, it is interpreted as function registered with the
  10935. * {@link $injector $injector}, which means you can create your own serializer
  10936. * by registering it as a {@link auto.$provide#service service}.
  10937. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
  10938. * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
  10939. * - **cache** – `{boolean|Object}` – A boolean value or object created with
  10940. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response.
  10941. * See {@link $http#caching $http Caching} for more information.
  10942. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  10943. * that should abort the request when resolved.
  10944. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  10945. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  10946. * for more information.
  10947. * - **responseType** - `{string}` - see
  10948. * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
  10949. *
  10950. * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
  10951. * when the request succeeds or fails.
  10952. *
  10953. *
  10954. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  10955. * requests. This is primarily meant to be used for debugging purposes.
  10956. *
  10957. *
  10958. * @example
  10959. <example module="httpExample" name="http-service">
  10960. <file name="index.html">
  10961. <div ng-controller="FetchController">
  10962. <select ng-model="method" aria-label="Request method">
  10963. <option>GET</option>
  10964. <option>JSONP</option>
  10965. </select>
  10966. <input type="text" ng-model="url" size="80" aria-label="URL" />
  10967. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  10968. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  10969. <button id="samplejsonpbtn"
  10970. ng-click="updateModel('JSONP',
  10971. 'https://angularjs.org/greet.php?name=Super%20Hero')">
  10972. Sample JSONP
  10973. </button>
  10974. <button id="invalidjsonpbtn"
  10975. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist')">
  10976. Invalid JSONP
  10977. </button>
  10978. <pre>http status code: {{status}}</pre>
  10979. <pre>http response data: {{data}}</pre>
  10980. </div>
  10981. </file>
  10982. <file name="script.js">
  10983. angular.module('httpExample', [])
  10984. .config(['$sceDelegateProvider', function($sceDelegateProvider) {
  10985. // We must whitelist the JSONP endpoint that we are using to show that we trust it
  10986. $sceDelegateProvider.resourceUrlWhitelist([
  10987. 'self',
  10988. 'https://angularjs.org/**'
  10989. ]);
  10990. }])
  10991. .controller('FetchController', ['$scope', '$http', '$templateCache',
  10992. function($scope, $http, $templateCache) {
  10993. $scope.method = 'GET';
  10994. $scope.url = 'http-hello.html';
  10995. $scope.fetch = function() {
  10996. $scope.code = null;
  10997. $scope.response = null;
  10998. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  10999. then(function(response) {
  11000. $scope.status = response.status;
  11001. $scope.data = response.data;
  11002. }, function(response) {
  11003. $scope.data = response.data || 'Request failed';
  11004. $scope.status = response.status;
  11005. });
  11006. };
  11007. $scope.updateModel = function(method, url) {
  11008. $scope.method = method;
  11009. $scope.url = url;
  11010. };
  11011. }]);
  11012. </file>
  11013. <file name="http-hello.html">
  11014. Hello, $http!
  11015. </file>
  11016. <file name="protractor.js" type="protractor">
  11017. var status = element(by.binding('status'));
  11018. var data = element(by.binding('data'));
  11019. var fetchBtn = element(by.id('fetchbtn'));
  11020. var sampleGetBtn = element(by.id('samplegetbtn'));
  11021. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  11022. it('should make an xhr GET request', function() {
  11023. sampleGetBtn.click();
  11024. fetchBtn.click();
  11025. expect(status.getText()).toMatch('200');
  11026. expect(data.getText()).toMatch(/Hello, \$http!/);
  11027. });
  11028. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  11029. // it('should make a JSONP request to angularjs.org', function() {
  11030. // var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  11031. // sampleJsonpBtn.click();
  11032. // fetchBtn.click();
  11033. // expect(status.getText()).toMatch('200');
  11034. // expect(data.getText()).toMatch(/Super Hero!/);
  11035. // });
  11036. it('should make JSONP request to invalid URL and invoke the error handler',
  11037. function() {
  11038. invalidJsonpBtn.click();
  11039. fetchBtn.click();
  11040. expect(status.getText()).toMatch('0');
  11041. expect(data.getText()).toMatch('Request failed');
  11042. });
  11043. </file>
  11044. </example>
  11045. */
  11046. function $http(requestConfig) {
  11047. if (!isObject(requestConfig)) {
  11048. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  11049. }
  11050. if (!isString($sce.valueOf(requestConfig.url))) {
  11051. throw minErr('$http')('badreq', 'Http request configuration url must be a string or a $sce trusted object. Received: {0}', requestConfig.url);
  11052. }
  11053. var config = extend({
  11054. method: 'get',
  11055. transformRequest: defaults.transformRequest,
  11056. transformResponse: defaults.transformResponse,
  11057. paramSerializer: defaults.paramSerializer,
  11058. jsonpCallbackParam: defaults.jsonpCallbackParam
  11059. }, requestConfig);
  11060. config.headers = mergeHeaders(requestConfig);
  11061. config.method = uppercase(config.method);
  11062. config.paramSerializer = isString(config.paramSerializer) ?
  11063. $injector.get(config.paramSerializer) : config.paramSerializer;
  11064. $browser.$$incOutstandingRequestCount();
  11065. var requestInterceptors = [];
  11066. var responseInterceptors = [];
  11067. var promise = $q.resolve(config);
  11068. // apply interceptors
  11069. forEach(reversedInterceptors, function(interceptor) {
  11070. if (interceptor.request || interceptor.requestError) {
  11071. requestInterceptors.unshift(interceptor.request, interceptor.requestError);
  11072. }
  11073. if (interceptor.response || interceptor.responseError) {
  11074. responseInterceptors.push(interceptor.response, interceptor.responseError);
  11075. }
  11076. });
  11077. promise = chainInterceptors(promise, requestInterceptors);
  11078. promise = promise.then(serverRequest);
  11079. promise = chainInterceptors(promise, responseInterceptors);
  11080. promise = promise.finally(completeOutstandingRequest);
  11081. return promise;
  11082. function chainInterceptors(promise, interceptors) {
  11083. for (var i = 0, ii = interceptors.length; i < ii;) {
  11084. var thenFn = interceptors[i++];
  11085. var rejectFn = interceptors[i++];
  11086. promise = promise.then(thenFn, rejectFn);
  11087. }
  11088. interceptors.length = 0;
  11089. return promise;
  11090. }
  11091. function completeOutstandingRequest() {
  11092. $browser.$$completeOutstandingRequest(noop);
  11093. }
  11094. function executeHeaderFns(headers, config) {
  11095. var headerContent, processedHeaders = {};
  11096. forEach(headers, function(headerFn, header) {
  11097. if (isFunction(headerFn)) {
  11098. headerContent = headerFn(config);
  11099. if (headerContent != null) {
  11100. processedHeaders[header] = headerContent;
  11101. }
  11102. } else {
  11103. processedHeaders[header] = headerFn;
  11104. }
  11105. });
  11106. return processedHeaders;
  11107. }
  11108. function mergeHeaders(config) {
  11109. var defHeaders = defaults.headers,
  11110. reqHeaders = extend({}, config.headers),
  11111. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  11112. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  11113. // using for-in instead of forEach to avoid unnecessary iteration after header has been found
  11114. defaultHeadersIteration:
  11115. for (defHeaderName in defHeaders) {
  11116. lowercaseDefHeaderName = lowercase(defHeaderName);
  11117. for (reqHeaderName in reqHeaders) {
  11118. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  11119. continue defaultHeadersIteration;
  11120. }
  11121. }
  11122. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  11123. }
  11124. // execute if header value is a function for merged headers
  11125. return executeHeaderFns(reqHeaders, shallowCopy(config));
  11126. }
  11127. function serverRequest(config) {
  11128. var headers = config.headers;
  11129. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  11130. // strip content-type if data is undefined
  11131. if (isUndefined(reqData)) {
  11132. forEach(headers, function(value, header) {
  11133. if (lowercase(header) === 'content-type') {
  11134. delete headers[header];
  11135. }
  11136. });
  11137. }
  11138. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  11139. config.withCredentials = defaults.withCredentials;
  11140. }
  11141. // send request
  11142. return sendReq(config, reqData).then(transformResponse, transformResponse);
  11143. }
  11144. function transformResponse(response) {
  11145. // make a copy since the response must be cacheable
  11146. var resp = extend({}, response);
  11147. resp.data = transformData(response.data, response.headers, response.status,
  11148. config.transformResponse);
  11149. return (isSuccess(response.status))
  11150. ? resp
  11151. : $q.reject(resp);
  11152. }
  11153. }
  11154. $http.pendingRequests = [];
  11155. /**
  11156. * @ngdoc method
  11157. * @name $http#get
  11158. *
  11159. * @description
  11160. * Shortcut method to perform `GET` request.
  11161. *
  11162. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  11163. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  11164. * @param {Object=} config Optional configuration object. See https://docs.angularjs.org/api/ng/service/$http#usage
  11165. * @returns {HttpPromise} Future object
  11166. */
  11167. /**
  11168. * @ngdoc method
  11169. * @name $http#delete
  11170. *
  11171. * @description
  11172. * Shortcut method to perform `DELETE` request.
  11173. *
  11174. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  11175. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  11176. * @param {Object=} config Optional configuration object. See https://docs.angularjs.org/api/ng/service/$http#usage
  11177. * @returns {HttpPromise} Future object
  11178. */
  11179. /**
  11180. * @ngdoc method
  11181. * @name $http#head
  11182. *
  11183. * @description
  11184. * Shortcut method to perform `HEAD` request.
  11185. *
  11186. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  11187. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  11188. * @param {Object=} config Optional configuration object. See https://docs.angularjs.org/api/ng/service/$http#usage
  11189. * @returns {HttpPromise} Future object
  11190. */
  11191. /**
  11192. * @ngdoc method
  11193. * @name $http#jsonp
  11194. *
  11195. * @description
  11196. * Shortcut method to perform `JSONP` request.
  11197. *
  11198. * Note that, since JSONP requests are sensitive because the response is given full access to the browser,
  11199. * the url must be declared, via {@link $sce} as a trusted resource URL.
  11200. * You can trust a URL by adding it to the whitelist via
  11201. * {@link $sceDelegateProvider#resourceUrlWhitelist `$sceDelegateProvider.resourceUrlWhitelist`} or
  11202. * by explicitly trusting the URL via {@link $sce#trustAsResourceUrl `$sce.trustAsResourceUrl(url)`}.
  11203. *
  11204. * You should avoid generating the URL for the JSONP request from user provided data.
  11205. * Provide additional query parameters via `params` property of the `config` parameter, rather than
  11206. * modifying the URL itself.
  11207. *
  11208. * JSONP requests must specify a callback to be used in the response from the server. This callback
  11209. * is passed as a query parameter in the request. You must specify the name of this parameter by
  11210. * setting the `jsonpCallbackParam` property on the request config object.
  11211. *
  11212. * ```
  11213. * $http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'})
  11214. * ```
  11215. *
  11216. * You can also specify a default callback parameter name in `$http.defaults.jsonpCallbackParam`.
  11217. * Initially this is set to `'callback'`.
  11218. *
  11219. * <div class="alert alert-danger">
  11220. * You can no longer use the `JSON_CALLBACK` string as a placeholder for specifying where the callback
  11221. * parameter value should go.
  11222. * </div>
  11223. *
  11224. * If you would like to customise where and how the callbacks are stored then try overriding
  11225. * or decorating the {@link $jsonpCallbacks} service.
  11226. *
  11227. * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested;
  11228. * or an object created by a call to `$sce.trustAsResourceUrl(url)`.
  11229. * @param {Object=} config Optional configuration object. See https://docs.angularjs.org/api/ng/service/$http#usage
  11230. * @returns {HttpPromise} Future object
  11231. */
  11232. createShortMethods('get', 'delete', 'head', 'jsonp');
  11233. /**
  11234. * @ngdoc method
  11235. * @name $http#post
  11236. *
  11237. * @description
  11238. * Shortcut method to perform `POST` request.
  11239. *
  11240. * @param {string} url Relative or absolute URL specifying the destination of the request
  11241. * @param {*} data Request content
  11242. * @param {Object=} config Optional configuration object. See https://docs.angularjs.org/api/ng/service/$http#usage
  11243. * @returns {HttpPromise} Future object
  11244. */
  11245. /**
  11246. * @ngdoc method
  11247. * @name $http#put
  11248. *
  11249. * @description
  11250. * Shortcut method to perform `PUT` request.
  11251. *
  11252. * @param {string} url Relative or absolute URL specifying the destination of the request
  11253. * @param {*} data Request content
  11254. * @param {Object=} config Optional configuration object. See https://docs.angularjs.org/api/ng/service/$http#usage
  11255. * @returns {HttpPromise} Future object
  11256. */
  11257. /**
  11258. * @ngdoc method
  11259. * @name $http#patch
  11260. *
  11261. * @description
  11262. * Shortcut method to perform `PATCH` request.
  11263. *
  11264. * @param {string} url Relative or absolute URL specifying the destination of the request
  11265. * @param {*} data Request content
  11266. * @param {Object=} config Optional configuration object. See https://docs.angularjs.org/api/ng/service/$http#usage
  11267. * @returns {HttpPromise} Future object
  11268. */
  11269. createShortMethodsWithData('post', 'put', 'patch');
  11270. /**
  11271. * @ngdoc property
  11272. * @name $http#defaults
  11273. *
  11274. * @description
  11275. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  11276. * default headers, withCredentials as well as request and response transformations.
  11277. *
  11278. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  11279. */
  11280. $http.defaults = defaults;
  11281. return $http;
  11282. function createShortMethods(names) {
  11283. forEach(arguments, function(name) {
  11284. $http[name] = function(url, config) {
  11285. return $http(extend({}, config || {}, {
  11286. method: name,
  11287. url: url
  11288. }));
  11289. };
  11290. });
  11291. }
  11292. function createShortMethodsWithData(name) {
  11293. forEach(arguments, function(name) {
  11294. $http[name] = function(url, data, config) {
  11295. return $http(extend({}, config || {}, {
  11296. method: name,
  11297. url: url,
  11298. data: data
  11299. }));
  11300. };
  11301. });
  11302. }
  11303. /**
  11304. * Makes the request.
  11305. *
  11306. * !!! ACCESSES CLOSURE VARS:
  11307. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  11308. */
  11309. function sendReq(config, reqData) {
  11310. var deferred = $q.defer(),
  11311. promise = deferred.promise,
  11312. cache,
  11313. cachedResp,
  11314. reqHeaders = config.headers,
  11315. isJsonp = lowercase(config.method) === 'jsonp',
  11316. url = config.url;
  11317. if (isJsonp) {
  11318. // JSONP is a pretty sensitive operation where we're allowing a script to have full access to
  11319. // our DOM and JS space. So we require that the URL satisfies SCE.RESOURCE_URL.
  11320. url = $sce.getTrustedResourceUrl(url);
  11321. } else if (!isString(url)) {
  11322. // If it is not a string then the URL must be a $sce trusted object
  11323. url = $sce.valueOf(url);
  11324. }
  11325. url = buildUrl(url, config.paramSerializer(config.params));
  11326. if (isJsonp) {
  11327. // Check the url and add the JSONP callback placeholder
  11328. url = sanitizeJsonpCallbackParam(url, config.jsonpCallbackParam);
  11329. }
  11330. $http.pendingRequests.push(config);
  11331. promise.then(removePendingReq, removePendingReq);
  11332. if ((config.cache || defaults.cache) && config.cache !== false &&
  11333. (config.method === 'GET' || config.method === 'JSONP')) {
  11334. cache = isObject(config.cache) ? config.cache
  11335. : isObject(/** @type {?} */ (defaults).cache)
  11336. ? /** @type {?} */ (defaults).cache
  11337. : defaultCache;
  11338. }
  11339. if (cache) {
  11340. cachedResp = cache.get(url);
  11341. if (isDefined(cachedResp)) {
  11342. if (isPromiseLike(cachedResp)) {
  11343. // cached request has already been sent, but there is no response yet
  11344. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  11345. } else {
  11346. // serving from cache
  11347. if (isArray(cachedResp)) {
  11348. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3], cachedResp[4]);
  11349. } else {
  11350. resolvePromise(cachedResp, 200, {}, 'OK', 'complete');
  11351. }
  11352. }
  11353. } else {
  11354. // put the promise for the non-transformed response into cache as a placeholder
  11355. cache.put(url, promise);
  11356. }
  11357. }
  11358. // if we won't have the response in cache, set the xsrf headers and
  11359. // send the request to the backend
  11360. if (isUndefined(cachedResp)) {
  11361. var xsrfValue = urlIsSameOrigin(config.url)
  11362. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  11363. : undefined;
  11364. if (xsrfValue) {
  11365. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  11366. }
  11367. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  11368. config.withCredentials, config.responseType,
  11369. createApplyHandlers(config.eventHandlers),
  11370. createApplyHandlers(config.uploadEventHandlers));
  11371. }
  11372. return promise;
  11373. function createApplyHandlers(eventHandlers) {
  11374. if (eventHandlers) {
  11375. var applyHandlers = {};
  11376. forEach(eventHandlers, function(eventHandler, key) {
  11377. applyHandlers[key] = function(event) {
  11378. if (useApplyAsync) {
  11379. $rootScope.$applyAsync(callEventHandler);
  11380. } else if ($rootScope.$$phase) {
  11381. callEventHandler();
  11382. } else {
  11383. $rootScope.$apply(callEventHandler);
  11384. }
  11385. function callEventHandler() {
  11386. eventHandler(event);
  11387. }
  11388. };
  11389. });
  11390. return applyHandlers;
  11391. }
  11392. }
  11393. /**
  11394. * Callback registered to $httpBackend():
  11395. * - caches the response if desired
  11396. * - resolves the raw $http promise
  11397. * - calls $apply
  11398. */
  11399. function done(status, response, headersString, statusText, xhrStatus) {
  11400. if (cache) {
  11401. if (isSuccess(status)) {
  11402. cache.put(url, [status, response, parseHeaders(headersString), statusText, xhrStatus]);
  11403. } else {
  11404. // remove promise from the cache
  11405. cache.remove(url);
  11406. }
  11407. }
  11408. function resolveHttpPromise() {
  11409. resolvePromise(response, status, headersString, statusText, xhrStatus);
  11410. }
  11411. if (useApplyAsync) {
  11412. $rootScope.$applyAsync(resolveHttpPromise);
  11413. } else {
  11414. resolveHttpPromise();
  11415. if (!$rootScope.$$phase) $rootScope.$apply();
  11416. }
  11417. }
  11418. /**
  11419. * Resolves the raw $http promise.
  11420. */
  11421. function resolvePromise(response, status, headers, statusText, xhrStatus) {
  11422. //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
  11423. status = status >= -1 ? status : 0;
  11424. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  11425. data: response,
  11426. status: status,
  11427. headers: headersGetter(headers),
  11428. config: config,
  11429. statusText: statusText,
  11430. xhrStatus: xhrStatus
  11431. });
  11432. }
  11433. function resolvePromiseWithResult(result) {
  11434. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText, result.xhrStatus);
  11435. }
  11436. function removePendingReq() {
  11437. var idx = $http.pendingRequests.indexOf(config);
  11438. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  11439. }
  11440. }
  11441. function buildUrl(url, serializedParams) {
  11442. if (serializedParams.length > 0) {
  11443. url += ((url.indexOf('?') === -1) ? '?' : '&') + serializedParams;
  11444. }
  11445. return url;
  11446. }
  11447. function sanitizeJsonpCallbackParam(url, cbKey) {
  11448. var parts = url.split('?');
  11449. if (parts.length > 2) {
  11450. // Throw if the url contains more than one `?` query indicator
  11451. throw $httpMinErr('badjsonp', 'Illegal use more than one "?", in url, "{1}"', url);
  11452. }
  11453. var params = parseKeyValue(parts[1]);
  11454. forEach(params, function(value, key) {
  11455. if (value === 'JSON_CALLBACK') {
  11456. // Throw if the url already contains a reference to JSON_CALLBACK
  11457. throw $httpMinErr('badjsonp', 'Illegal use of JSON_CALLBACK in url, "{0}"', url);
  11458. }
  11459. if (key === cbKey) {
  11460. // Throw if the callback param was already provided
  11461. throw $httpMinErr('badjsonp', 'Illegal use of callback param, "{0}", in url, "{1}"', cbKey, url);
  11462. }
  11463. });
  11464. // Add in the JSON_CALLBACK callback param value
  11465. url += ((url.indexOf('?') === -1) ? '?' : '&') + cbKey + '=JSON_CALLBACK';
  11466. return url;
  11467. }
  11468. }];
  11469. }
  11470. /**
  11471. * @ngdoc service
  11472. * @name $xhrFactory
  11473. * @this
  11474. *
  11475. * @description
  11476. * Factory function used to create XMLHttpRequest objects.
  11477. *
  11478. * Replace or decorate this service to create your own custom XMLHttpRequest objects.
  11479. *
  11480. * ```
  11481. * angular.module('myApp', [])
  11482. * .factory('$xhrFactory', function() {
  11483. * return function createXhr(method, url) {
  11484. * return new window.XMLHttpRequest({mozSystem: true});
  11485. * };
  11486. * });
  11487. * ```
  11488. *
  11489. * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
  11490. * @param {string} url URL of the request.
  11491. */
  11492. function $xhrFactoryProvider() {
  11493. this.$get = function() {
  11494. return function createXhr() {
  11495. return new window.XMLHttpRequest();
  11496. };
  11497. };
  11498. }
  11499. /**
  11500. * @ngdoc service
  11501. * @name $httpBackend
  11502. * @requires $jsonpCallbacks
  11503. * @requires $document
  11504. * @requires $xhrFactory
  11505. * @this
  11506. *
  11507. * @description
  11508. * HTTP backend used by the {@link ng.$http service} that delegates to
  11509. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  11510. *
  11511. * You should never need to use this service directly, instead use the higher-level abstractions:
  11512. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  11513. *
  11514. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  11515. * $httpBackend} which can be trained with responses.
  11516. */
  11517. function $HttpBackendProvider() {
  11518. this.$get = ['$browser', '$jsonpCallbacks', '$document', '$xhrFactory', function($browser, $jsonpCallbacks, $document, $xhrFactory) {
  11519. return createHttpBackend($browser, $xhrFactory, $browser.defer, $jsonpCallbacks, $document[0]);
  11520. }];
  11521. }
  11522. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  11523. // TODO(vojta): fix the signature
  11524. return function(method, url, post, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) {
  11525. url = url || $browser.url();
  11526. if (lowercase(method) === 'jsonp') {
  11527. var callbackPath = callbacks.createCallback(url);
  11528. var jsonpDone = jsonpReq(url, callbackPath, function(status, text) {
  11529. // jsonpReq only ever sets status to 200 (OK), 404 (ERROR) or -1 (WAITING)
  11530. var response = (status === 200) && callbacks.getResponse(callbackPath);
  11531. completeRequest(callback, status, response, '', text, 'complete');
  11532. callbacks.removeCallback(callbackPath);
  11533. });
  11534. } else {
  11535. var xhr = createXhr(method, url);
  11536. xhr.open(method, url, true);
  11537. forEach(headers, function(value, key) {
  11538. if (isDefined(value)) {
  11539. xhr.setRequestHeader(key, value);
  11540. }
  11541. });
  11542. xhr.onload = function requestLoaded() {
  11543. var statusText = xhr.statusText || '';
  11544. // responseText is the old-school way of retrieving response (supported by IE9)
  11545. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  11546. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  11547. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  11548. var status = xhr.status === 1223 ? 204 : xhr.status;
  11549. // fix status code when it is 0 (0 status is undocumented).
  11550. // Occurs when accessing file resources or on Android 4.1 stock browser
  11551. // while retrieving files from application cache.
  11552. if (status === 0) {
  11553. status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0;
  11554. }
  11555. completeRequest(callback,
  11556. status,
  11557. response,
  11558. xhr.getAllResponseHeaders(),
  11559. statusText,
  11560. 'complete');
  11561. };
  11562. var requestError = function() {
  11563. // The response is always empty
  11564. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  11565. completeRequest(callback, -1, null, null, '', 'error');
  11566. };
  11567. var requestAborted = function() {
  11568. completeRequest(callback, -1, null, null, '', 'abort');
  11569. };
  11570. var requestTimeout = function() {
  11571. // The response is always empty
  11572. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  11573. completeRequest(callback, -1, null, null, '', 'timeout');
  11574. };
  11575. xhr.onerror = requestError;
  11576. xhr.onabort = requestAborted;
  11577. xhr.ontimeout = requestTimeout;
  11578. forEach(eventHandlers, function(value, key) {
  11579. xhr.addEventListener(key, value);
  11580. });
  11581. forEach(uploadEventHandlers, function(value, key) {
  11582. xhr.upload.addEventListener(key, value);
  11583. });
  11584. if (withCredentials) {
  11585. xhr.withCredentials = true;
  11586. }
  11587. if (responseType) {
  11588. try {
  11589. xhr.responseType = responseType;
  11590. } catch (e) {
  11591. // WebKit added support for the json responseType value on 09/03/2013
  11592. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  11593. // known to throw when setting the value "json" as the response type. Other older
  11594. // browsers implementing the responseType
  11595. //
  11596. // The json response type can be ignored if not supported, because JSON payloads are
  11597. // parsed on the client-side regardless.
  11598. if (responseType !== 'json') {
  11599. throw e;
  11600. }
  11601. }
  11602. }
  11603. xhr.send(isUndefined(post) ? null : post);
  11604. }
  11605. if (timeout > 0) {
  11606. var timeoutId = $browserDefer(timeoutRequest, timeout);
  11607. } else if (isPromiseLike(timeout)) {
  11608. timeout.then(timeoutRequest);
  11609. }
  11610. function timeoutRequest() {
  11611. if (jsonpDone) {
  11612. jsonpDone();
  11613. }
  11614. if (xhr) {
  11615. xhr.abort();
  11616. }
  11617. }
  11618. function completeRequest(callback, status, response, headersString, statusText, xhrStatus) {
  11619. // cancel timeout and subsequent timeout promise resolution
  11620. if (isDefined(timeoutId)) {
  11621. $browserDefer.cancel(timeoutId);
  11622. }
  11623. jsonpDone = xhr = null;
  11624. callback(status, response, headersString, statusText, xhrStatus);
  11625. }
  11626. };
  11627. function jsonpReq(url, callbackPath, done) {
  11628. url = url.replace('JSON_CALLBACK', callbackPath);
  11629. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  11630. // - fetches local scripts via XHR and evals them
  11631. // - adds and immediately removes script elements from the document
  11632. var script = rawDocument.createElement('script'), callback = null;
  11633. script.type = 'text/javascript';
  11634. script.src = url;
  11635. script.async = true;
  11636. callback = function(event) {
  11637. script.removeEventListener('load', callback);
  11638. script.removeEventListener('error', callback);
  11639. rawDocument.body.removeChild(script);
  11640. script = null;
  11641. var status = -1;
  11642. var text = 'unknown';
  11643. if (event) {
  11644. if (event.type === 'load' && !callbacks.wasCalled(callbackPath)) {
  11645. event = { type: 'error' };
  11646. }
  11647. text = event.type;
  11648. status = event.type === 'error' ? 404 : 200;
  11649. }
  11650. if (done) {
  11651. done(status, text);
  11652. }
  11653. };
  11654. script.addEventListener('load', callback);
  11655. script.addEventListener('error', callback);
  11656. rawDocument.body.appendChild(script);
  11657. return callback;
  11658. }
  11659. }
  11660. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  11661. $interpolateMinErr.throwNoconcat = function(text) {
  11662. throw $interpolateMinErr('noconcat',
  11663. 'Error while interpolating: {0}\nStrict Contextual Escaping disallows ' +
  11664. 'interpolations that concatenate multiple expressions when a trusted value is ' +
  11665. 'required. See http://docs.angularjs.org/api/ng.$sce', text);
  11666. };
  11667. $interpolateMinErr.interr = function(text, err) {
  11668. return $interpolateMinErr('interr', 'Can\'t interpolate: {0}\n{1}', text, err.toString());
  11669. };
  11670. /**
  11671. * @ngdoc provider
  11672. * @name $interpolateProvider
  11673. * @this
  11674. *
  11675. * @description
  11676. *
  11677. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  11678. *
  11679. * <div class="alert alert-danger">
  11680. * This feature is sometimes used to mix different markup languages, e.g. to wrap an Angular
  11681. * template within a Python Jinja template (or any other template language). Mixing templating
  11682. * languages is **very dangerous**. The embedding template language will not safely escape Angular
  11683. * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)
  11684. * security bugs!
  11685. * </div>
  11686. *
  11687. * @example
  11688. <example name="custom-interpolation-markup" module="customInterpolationApp">
  11689. <file name="index.html">
  11690. <script>
  11691. var customInterpolationApp = angular.module('customInterpolationApp', []);
  11692. customInterpolationApp.config(function($interpolateProvider) {
  11693. $interpolateProvider.startSymbol('//');
  11694. $interpolateProvider.endSymbol('//');
  11695. });
  11696. customInterpolationApp.controller('DemoController', function() {
  11697. this.label = "This binding is brought you by // interpolation symbols.";
  11698. });
  11699. </script>
  11700. <div ng-controller="DemoController as demo">
  11701. //demo.label//
  11702. </div>
  11703. </file>
  11704. <file name="protractor.js" type="protractor">
  11705. it('should interpolate binding with custom symbols', function() {
  11706. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  11707. });
  11708. </file>
  11709. </example>
  11710. */
  11711. function $InterpolateProvider() {
  11712. var startSymbol = '{{';
  11713. var endSymbol = '}}';
  11714. /**
  11715. * @ngdoc method
  11716. * @name $interpolateProvider#startSymbol
  11717. * @description
  11718. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  11719. *
  11720. * @param {string=} value new value to set the starting symbol to.
  11721. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  11722. */
  11723. this.startSymbol = function(value) {
  11724. if (value) {
  11725. startSymbol = value;
  11726. return this;
  11727. } else {
  11728. return startSymbol;
  11729. }
  11730. };
  11731. /**
  11732. * @ngdoc method
  11733. * @name $interpolateProvider#endSymbol
  11734. * @description
  11735. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  11736. *
  11737. * @param {string=} value new value to set the ending symbol to.
  11738. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  11739. */
  11740. this.endSymbol = function(value) {
  11741. if (value) {
  11742. endSymbol = value;
  11743. return this;
  11744. } else {
  11745. return endSymbol;
  11746. }
  11747. };
  11748. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  11749. var startSymbolLength = startSymbol.length,
  11750. endSymbolLength = endSymbol.length,
  11751. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  11752. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  11753. function escape(ch) {
  11754. return '\\\\\\' + ch;
  11755. }
  11756. function unescapeText(text) {
  11757. return text.replace(escapedStartRegexp, startSymbol).
  11758. replace(escapedEndRegexp, endSymbol);
  11759. }
  11760. // TODO: this is the same as the constantWatchDelegate in parse.js
  11761. function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {
  11762. var unwatch = scope.$watch(function constantInterpolateWatch(scope) {
  11763. unwatch();
  11764. return constantInterp(scope);
  11765. }, listener, objectEquality);
  11766. return unwatch;
  11767. }
  11768. /**
  11769. * @ngdoc service
  11770. * @name $interpolate
  11771. * @kind function
  11772. *
  11773. * @requires $parse
  11774. * @requires $sce
  11775. *
  11776. * @description
  11777. *
  11778. * Compiles a string with markup into an interpolation function. This service is used by the
  11779. * HTML {@link ng.$compile $compile} service for data binding. See
  11780. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  11781. * interpolation markup.
  11782. *
  11783. *
  11784. * ```js
  11785. * var $interpolate = ...; // injected
  11786. * var exp = $interpolate('Hello {{name | uppercase}}!');
  11787. * expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
  11788. * ```
  11789. *
  11790. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  11791. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  11792. * evaluate to a value other than `undefined`.
  11793. *
  11794. * ```js
  11795. * var $interpolate = ...; // injected
  11796. * var context = {greeting: 'Hello', name: undefined };
  11797. *
  11798. * // default "forgiving" mode
  11799. * var exp = $interpolate('{{greeting}} {{name}}!');
  11800. * expect(exp(context)).toEqual('Hello !');
  11801. *
  11802. * // "allOrNothing" mode
  11803. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  11804. * expect(exp(context)).toBeUndefined();
  11805. * context.name = 'Angular';
  11806. * expect(exp(context)).toEqual('Hello Angular!');
  11807. * ```
  11808. *
  11809. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  11810. *
  11811. * #### Escaped Interpolation
  11812. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  11813. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  11814. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  11815. * or binding.
  11816. *
  11817. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  11818. * degree, while also enabling code examples to work without relying on the
  11819. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  11820. *
  11821. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  11822. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  11823. * interpolation start/end markers with their escaped counterparts.**
  11824. *
  11825. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  11826. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  11827. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  11828. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  11829. * this is typically useful only when user-data is used in rendering a template from the server, or
  11830. * when otherwise untrusted data is used by a directive.
  11831. *
  11832. * <example name="interpolation">
  11833. * <file name="index.html">
  11834. * <div ng-init="username='A user'">
  11835. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  11836. * </p>
  11837. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  11838. * application, but fails to accomplish their task, because the server has correctly
  11839. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  11840. * characters.</p>
  11841. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  11842. * from the database by an administrator.</p>
  11843. * </div>
  11844. * </file>
  11845. * </example>
  11846. *
  11847. * @knownIssue
  11848. * It is currently not possible for an interpolated expression to contain the interpolation end
  11849. * symbol. For example, `{{ '}}' }}` will be incorrectly interpreted as `{{ ' }}` + `' }}`, i.e.
  11850. * an interpolated expression consisting of a single-quote (`'`) and the `' }}` string.
  11851. *
  11852. * @knownIssue
  11853. * All directives and components must use the standard `{{` `}}` interpolation symbols
  11854. * in their templates. If you change the application interpolation symbols the {@link $compile}
  11855. * service will attempt to denormalize the standard symbols to the custom symbols.
  11856. * The denormalization process is not clever enough to know not to replace instances of the standard
  11857. * symbols where they would not normally be treated as interpolation symbols. For example in the following
  11858. * code snippet the closing braces of the literal object will get incorrectly denormalized:
  11859. *
  11860. * ```
  11861. * <div data-context='{"context":{"id":3,"type":"page"}}">
  11862. * ```
  11863. *
  11864. * The workaround is to ensure that such instances are separated by whitespace:
  11865. * ```
  11866. * <div data-context='{"context":{"id":3,"type":"page"} }">
  11867. * ```
  11868. *
  11869. * See https://github.com/angular/angular.js/pull/14610#issuecomment-219401099 for more information.
  11870. *
  11871. * @param {string} text The text with markup to interpolate.
  11872. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  11873. * embedded expression in order to return an interpolation function. Strings with no
  11874. * embedded expression will return null for the interpolation function.
  11875. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  11876. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  11877. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  11878. * provides Strict Contextual Escaping for details.
  11879. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  11880. * unless all embedded expressions evaluate to a value other than `undefined`.
  11881. * @returns {function(context)} an interpolation function which is used to compute the
  11882. * interpolated string. The function has these parameters:
  11883. *
  11884. * - `context`: evaluation context for all expressions embedded in the interpolated text
  11885. */
  11886. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  11887. // Provide a quick exit and simplified result function for text with no interpolation
  11888. if (!text.length || text.indexOf(startSymbol) === -1) {
  11889. var constantInterp;
  11890. if (!mustHaveExpression) {
  11891. var unescapedText = unescapeText(text);
  11892. constantInterp = valueFn(unescapedText);
  11893. constantInterp.exp = text;
  11894. constantInterp.expressions = [];
  11895. constantInterp.$$watchDelegate = constantWatchDelegate;
  11896. }
  11897. return constantInterp;
  11898. }
  11899. allOrNothing = !!allOrNothing;
  11900. var startIndex,
  11901. endIndex,
  11902. index = 0,
  11903. expressions = [],
  11904. parseFns = [],
  11905. textLength = text.length,
  11906. exp,
  11907. concat = [],
  11908. expressionPositions = [];
  11909. while (index < textLength) {
  11910. if (((startIndex = text.indexOf(startSymbol, index)) !== -1) &&
  11911. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) !== -1)) {
  11912. if (index !== startIndex) {
  11913. concat.push(unescapeText(text.substring(index, startIndex)));
  11914. }
  11915. exp = text.substring(startIndex + startSymbolLength, endIndex);
  11916. expressions.push(exp);
  11917. parseFns.push($parse(exp, parseStringifyInterceptor));
  11918. index = endIndex + endSymbolLength;
  11919. expressionPositions.push(concat.length);
  11920. concat.push('');
  11921. } else {
  11922. // we did not find an interpolation, so we have to add the remainder to the separators array
  11923. if (index !== textLength) {
  11924. concat.push(unescapeText(text.substring(index)));
  11925. }
  11926. break;
  11927. }
  11928. }
  11929. // Concatenating expressions makes it hard to reason about whether some combination of
  11930. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  11931. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  11932. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  11933. // make it obvious that you bound the value to some user controlled value. This helps reduce
  11934. // the load when auditing for XSS issues.
  11935. if (trustedContext && concat.length > 1) {
  11936. $interpolateMinErr.throwNoconcat(text);
  11937. }
  11938. if (!mustHaveExpression || expressions.length) {
  11939. var compute = function(values) {
  11940. for (var i = 0, ii = expressions.length; i < ii; i++) {
  11941. if (allOrNothing && isUndefined(values[i])) return;
  11942. concat[expressionPositions[i]] = values[i];
  11943. }
  11944. return concat.join('');
  11945. };
  11946. var getValue = function(value) {
  11947. return trustedContext ?
  11948. $sce.getTrusted(trustedContext, value) :
  11949. $sce.valueOf(value);
  11950. };
  11951. return extend(function interpolationFn(context) {
  11952. var i = 0;
  11953. var ii = expressions.length;
  11954. var values = new Array(ii);
  11955. try {
  11956. for (; i < ii; i++) {
  11957. values[i] = parseFns[i](context);
  11958. }
  11959. return compute(values);
  11960. } catch (err) {
  11961. $exceptionHandler($interpolateMinErr.interr(text, err));
  11962. }
  11963. }, {
  11964. // all of these properties are undocumented for now
  11965. exp: text, //just for compatibility with regular watchers created via $watch
  11966. expressions: expressions,
  11967. $$watchDelegate: function(scope, listener) {
  11968. var lastValue;
  11969. return scope.$watchGroup(parseFns, /** @this */ function interpolateFnWatcher(values, oldValues) {
  11970. var currValue = compute(values);
  11971. if (isFunction(listener)) {
  11972. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  11973. }
  11974. lastValue = currValue;
  11975. });
  11976. }
  11977. });
  11978. }
  11979. function parseStringifyInterceptor(value) {
  11980. try {
  11981. value = getValue(value);
  11982. return allOrNothing && !isDefined(value) ? value : stringify(value);
  11983. } catch (err) {
  11984. $exceptionHandler($interpolateMinErr.interr(text, err));
  11985. }
  11986. }
  11987. }
  11988. /**
  11989. * @ngdoc method
  11990. * @name $interpolate#startSymbol
  11991. * @description
  11992. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  11993. *
  11994. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  11995. * the symbol.
  11996. *
  11997. * @returns {string} start symbol.
  11998. */
  11999. $interpolate.startSymbol = function() {
  12000. return startSymbol;
  12001. };
  12002. /**
  12003. * @ngdoc method
  12004. * @name $interpolate#endSymbol
  12005. * @description
  12006. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  12007. *
  12008. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  12009. * the symbol.
  12010. *
  12011. * @returns {string} end symbol.
  12012. */
  12013. $interpolate.endSymbol = function() {
  12014. return endSymbol;
  12015. };
  12016. return $interpolate;
  12017. }];
  12018. }
  12019. /** @this */
  12020. function $IntervalProvider() {
  12021. this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',
  12022. function($rootScope, $window, $q, $$q, $browser) {
  12023. var intervals = {};
  12024. /**
  12025. * @ngdoc service
  12026. * @name $interval
  12027. *
  12028. * @description
  12029. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  12030. * milliseconds.
  12031. *
  12032. * The return value of registering an interval function is a promise. This promise will be
  12033. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  12034. * run indefinitely if `count` is not defined. The value of the notification will be the
  12035. * number of iterations that have run.
  12036. * To cancel an interval, call `$interval.cancel(promise)`.
  12037. *
  12038. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  12039. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  12040. * time.
  12041. *
  12042. * <div class="alert alert-warning">
  12043. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  12044. * with them. In particular they are not automatically destroyed when a controller's scope or a
  12045. * directive's element are destroyed.
  12046. * You should take this into consideration and make sure to always cancel the interval at the
  12047. * appropriate moment. See the example below for more details on how and when to do this.
  12048. * </div>
  12049. *
  12050. * @param {function()} fn A function that should be called repeatedly. If no additional arguments
  12051. * are passed (see below), the function is called with the current iteration count.
  12052. * @param {number} delay Number of milliseconds between each function call.
  12053. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  12054. * indefinitely.
  12055. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  12056. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  12057. * @param {...*=} Pass additional parameters to the executed function.
  12058. * @returns {promise} A promise which will be notified on each iteration. It will resolve once all iterations of the interval complete.
  12059. *
  12060. * @example
  12061. * <example module="intervalExample" name="interval-service">
  12062. * <file name="index.html">
  12063. * <script>
  12064. * angular.module('intervalExample', [])
  12065. * .controller('ExampleController', ['$scope', '$interval',
  12066. * function($scope, $interval) {
  12067. * $scope.format = 'M/d/yy h:mm:ss a';
  12068. * $scope.blood_1 = 100;
  12069. * $scope.blood_2 = 120;
  12070. *
  12071. * var stop;
  12072. * $scope.fight = function() {
  12073. * // Don't start a new fight if we are already fighting
  12074. * if ( angular.isDefined(stop) ) return;
  12075. *
  12076. * stop = $interval(function() {
  12077. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  12078. * $scope.blood_1 = $scope.blood_1 - 3;
  12079. * $scope.blood_2 = $scope.blood_2 - 4;
  12080. * } else {
  12081. * $scope.stopFight();
  12082. * }
  12083. * }, 100);
  12084. * };
  12085. *
  12086. * $scope.stopFight = function() {
  12087. * if (angular.isDefined(stop)) {
  12088. * $interval.cancel(stop);
  12089. * stop = undefined;
  12090. * }
  12091. * };
  12092. *
  12093. * $scope.resetFight = function() {
  12094. * $scope.blood_1 = 100;
  12095. * $scope.blood_2 = 120;
  12096. * };
  12097. *
  12098. * $scope.$on('$destroy', function() {
  12099. * // Make sure that the interval is destroyed too
  12100. * $scope.stopFight();
  12101. * });
  12102. * }])
  12103. * // Register the 'myCurrentTime' directive factory method.
  12104. * // We inject $interval and dateFilter service since the factory method is DI.
  12105. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  12106. * function($interval, dateFilter) {
  12107. * // return the directive link function. (compile function not needed)
  12108. * return function(scope, element, attrs) {
  12109. * var format, // date format
  12110. * stopTime; // so that we can cancel the time updates
  12111. *
  12112. * // used to update the UI
  12113. * function updateTime() {
  12114. * element.text(dateFilter(new Date(), format));
  12115. * }
  12116. *
  12117. * // watch the expression, and update the UI on change.
  12118. * scope.$watch(attrs.myCurrentTime, function(value) {
  12119. * format = value;
  12120. * updateTime();
  12121. * });
  12122. *
  12123. * stopTime = $interval(updateTime, 1000);
  12124. *
  12125. * // listen on DOM destroy (removal) event, and cancel the next UI update
  12126. * // to prevent updating time after the DOM element was removed.
  12127. * element.on('$destroy', function() {
  12128. * $interval.cancel(stopTime);
  12129. * });
  12130. * }
  12131. * }]);
  12132. * </script>
  12133. *
  12134. * <div>
  12135. * <div ng-controller="ExampleController">
  12136. * <label>Date format: <input ng-model="format"></label> <hr/>
  12137. * Current time is: <span my-current-time="format"></span>
  12138. * <hr/>
  12139. * Blood 1 : <font color='red'>{{blood_1}}</font>
  12140. * Blood 2 : <font color='red'>{{blood_2}}</font>
  12141. * <button type="button" data-ng-click="fight()">Fight</button>
  12142. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  12143. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  12144. * </div>
  12145. * </div>
  12146. *
  12147. * </file>
  12148. * </example>
  12149. */
  12150. function interval(fn, delay, count, invokeApply) {
  12151. var hasParams = arguments.length > 4,
  12152. args = hasParams ? sliceArgs(arguments, 4) : [],
  12153. setInterval = $window.setInterval,
  12154. clearInterval = $window.clearInterval,
  12155. iteration = 0,
  12156. skipApply = (isDefined(invokeApply) && !invokeApply),
  12157. deferred = (skipApply ? $$q : $q).defer(),
  12158. promise = deferred.promise;
  12159. count = isDefined(count) ? count : 0;
  12160. promise.$$intervalId = setInterval(function tick() {
  12161. if (skipApply) {
  12162. $browser.defer(callback);
  12163. } else {
  12164. $rootScope.$evalAsync(callback);
  12165. }
  12166. deferred.notify(iteration++);
  12167. if (count > 0 && iteration >= count) {
  12168. deferred.resolve(iteration);
  12169. clearInterval(promise.$$intervalId);
  12170. delete intervals[promise.$$intervalId];
  12171. }
  12172. if (!skipApply) $rootScope.$apply();
  12173. }, delay);
  12174. intervals[promise.$$intervalId] = deferred;
  12175. return promise;
  12176. function callback() {
  12177. if (!hasParams) {
  12178. fn(iteration);
  12179. } else {
  12180. fn.apply(null, args);
  12181. }
  12182. }
  12183. }
  12184. /**
  12185. * @ngdoc method
  12186. * @name $interval#cancel
  12187. *
  12188. * @description
  12189. * Cancels a task associated with the `promise`.
  12190. *
  12191. * @param {Promise=} promise returned by the `$interval` function.
  12192. * @returns {boolean} Returns `true` if the task was successfully canceled.
  12193. */
  12194. interval.cancel = function(promise) {
  12195. if (promise && promise.$$intervalId in intervals) {
  12196. // Interval cancels should not report as unhandled promise.
  12197. markQExceptionHandled(intervals[promise.$$intervalId].promise);
  12198. intervals[promise.$$intervalId].reject('canceled');
  12199. $window.clearInterval(promise.$$intervalId);
  12200. delete intervals[promise.$$intervalId];
  12201. return true;
  12202. }
  12203. return false;
  12204. };
  12205. return interval;
  12206. }];
  12207. }
  12208. /**
  12209. * @ngdoc service
  12210. * @name $jsonpCallbacks
  12211. * @requires $window
  12212. * @description
  12213. * This service handles the lifecycle of callbacks to handle JSONP requests.
  12214. * Override this service if you wish to customise where the callbacks are stored and
  12215. * how they vary compared to the requested url.
  12216. */
  12217. var $jsonpCallbacksProvider = /** @this */ function() {
  12218. this.$get = function() {
  12219. var callbacks = angular.callbacks;
  12220. var callbackMap = {};
  12221. function createCallback(callbackId) {
  12222. var callback = function(data) {
  12223. callback.data = data;
  12224. callback.called = true;
  12225. };
  12226. callback.id = callbackId;
  12227. return callback;
  12228. }
  12229. return {
  12230. /**
  12231. * @ngdoc method
  12232. * @name $jsonpCallbacks#createCallback
  12233. * @param {string} url the url of the JSONP request
  12234. * @returns {string} the callback path to send to the server as part of the JSONP request
  12235. * @description
  12236. * {@link $httpBackend} calls this method to create a callback and get hold of the path to the callback
  12237. * to pass to the server, which will be used to call the callback with its payload in the JSONP response.
  12238. */
  12239. createCallback: function(url) {
  12240. var callbackId = '_' + (callbacks.$$counter++).toString(36);
  12241. var callbackPath = 'angular.callbacks.' + callbackId;
  12242. var callback = createCallback(callbackId);
  12243. callbackMap[callbackPath] = callbacks[callbackId] = callback;
  12244. return callbackPath;
  12245. },
  12246. /**
  12247. * @ngdoc method
  12248. * @name $jsonpCallbacks#wasCalled
  12249. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  12250. * @returns {boolean} whether the callback has been called, as a result of the JSONP response
  12251. * @description
  12252. * {@link $httpBackend} calls this method to find out whether the JSONP response actually called the
  12253. * callback that was passed in the request.
  12254. */
  12255. wasCalled: function(callbackPath) {
  12256. return callbackMap[callbackPath].called;
  12257. },
  12258. /**
  12259. * @ngdoc method
  12260. * @name $jsonpCallbacks#getResponse
  12261. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  12262. * @returns {*} the data received from the response via the registered callback
  12263. * @description
  12264. * {@link $httpBackend} calls this method to get hold of the data that was provided to the callback
  12265. * in the JSONP response.
  12266. */
  12267. getResponse: function(callbackPath) {
  12268. return callbackMap[callbackPath].data;
  12269. },
  12270. /**
  12271. * @ngdoc method
  12272. * @name $jsonpCallbacks#removeCallback
  12273. * @param {string} callbackPath the path to the callback that was sent in the JSONP request
  12274. * @description
  12275. * {@link $httpBackend} calls this method to remove the callback after the JSONP request has
  12276. * completed or timed-out.
  12277. */
  12278. removeCallback: function(callbackPath) {
  12279. var callback = callbackMap[callbackPath];
  12280. delete callbacks[callback.id];
  12281. delete callbackMap[callbackPath];
  12282. }
  12283. };
  12284. };
  12285. };
  12286. /**
  12287. * @ngdoc service
  12288. * @name $locale
  12289. *
  12290. * @description
  12291. * $locale service provides localization rules for various Angular components. As of right now the
  12292. * only public api is:
  12293. *
  12294. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  12295. */
  12296. var PATH_MATCH = /^([^?#]*)(\?([^#]*))?(#(.*))?$/,
  12297. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  12298. var $locationMinErr = minErr('$location');
  12299. /**
  12300. * Encode path using encodeUriSegment, ignoring forward slashes
  12301. *
  12302. * @param {string} path Path to encode
  12303. * @returns {string}
  12304. */
  12305. function encodePath(path) {
  12306. var segments = path.split('/'),
  12307. i = segments.length;
  12308. while (i--) {
  12309. // decode forward slashes to prevent them from being double encoded
  12310. segments[i] = encodeUriSegment(segments[i].replace(/%2F/g, '/'));
  12311. }
  12312. return segments.join('/');
  12313. }
  12314. function decodePath(path, html5Mode) {
  12315. var segments = path.split('/'),
  12316. i = segments.length;
  12317. while (i--) {
  12318. segments[i] = decodeURIComponent(segments[i]);
  12319. if (html5Mode) {
  12320. // encode forward slashes to prevent them from being mistaken for path separators
  12321. segments[i] = segments[i].replace(/\//g, '%2F');
  12322. }
  12323. }
  12324. return segments.join('/');
  12325. }
  12326. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  12327. var parsedUrl = urlResolve(absoluteUrl);
  12328. locationObj.$$protocol = parsedUrl.protocol;
  12329. locationObj.$$host = parsedUrl.hostname;
  12330. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  12331. }
  12332. var DOUBLE_SLASH_REGEX = /^\s*[\\/]{2,}/;
  12333. function parseAppUrl(url, locationObj, html5Mode) {
  12334. if (DOUBLE_SLASH_REGEX.test(url)) {
  12335. throw $locationMinErr('badpath', 'Invalid url "{0}".', url);
  12336. }
  12337. var prefixed = (url.charAt(0) !== '/');
  12338. if (prefixed) {
  12339. url = '/' + url;
  12340. }
  12341. var match = urlResolve(url);
  12342. var path = prefixed && match.pathname.charAt(0) === '/' ? match.pathname.substring(1) : match.pathname;
  12343. locationObj.$$path = decodePath(path, html5Mode);
  12344. locationObj.$$search = parseKeyValue(match.search);
  12345. locationObj.$$hash = decodeURIComponent(match.hash);
  12346. // make sure path starts with '/';
  12347. if (locationObj.$$path && locationObj.$$path.charAt(0) !== '/') {
  12348. locationObj.$$path = '/' + locationObj.$$path;
  12349. }
  12350. }
  12351. function startsWith(str, search) {
  12352. return str.slice(0, search.length) === search;
  12353. }
  12354. /**
  12355. *
  12356. * @param {string} base
  12357. * @param {string} url
  12358. * @returns {string} returns text from `url` after `base` or `undefined` if it does not begin with
  12359. * the expected string.
  12360. */
  12361. function stripBaseUrl(base, url) {
  12362. if (startsWith(url, base)) {
  12363. return url.substr(base.length);
  12364. }
  12365. }
  12366. function stripHash(url) {
  12367. var index = url.indexOf('#');
  12368. return index === -1 ? url : url.substr(0, index);
  12369. }
  12370. function trimEmptyHash(url) {
  12371. return url.replace(/(#.+)|#$/, '$1');
  12372. }
  12373. function stripFile(url) {
  12374. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  12375. }
  12376. /* return the server only (scheme://host:port) */
  12377. function serverBase(url) {
  12378. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  12379. }
  12380. /**
  12381. * LocationHtml5Url represents a URL
  12382. * This object is exposed as $location service when HTML5 mode is enabled and supported
  12383. *
  12384. * @constructor
  12385. * @param {string} appBase application base URL
  12386. * @param {string} appBaseNoFile application base URL stripped of any filename
  12387. * @param {string} basePrefix URL path prefix
  12388. */
  12389. function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
  12390. this.$$html5 = true;
  12391. basePrefix = basePrefix || '';
  12392. parseAbsoluteUrl(appBase, this);
  12393. /**
  12394. * Parse given HTML5 (regular) URL string into properties
  12395. * @param {string} url HTML5 URL
  12396. * @private
  12397. */
  12398. this.$$parse = function(url) {
  12399. var pathUrl = stripBaseUrl(appBaseNoFile, url);
  12400. if (!isString(pathUrl)) {
  12401. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  12402. appBaseNoFile);
  12403. }
  12404. parseAppUrl(pathUrl, this, true);
  12405. if (!this.$$path) {
  12406. this.$$path = '/';
  12407. }
  12408. this.$$compose();
  12409. };
  12410. /**
  12411. * Compose url and update `absUrl` property
  12412. * @private
  12413. */
  12414. this.$$compose = function() {
  12415. var search = toKeyValue(this.$$search),
  12416. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  12417. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  12418. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  12419. this.$$urlUpdatedByLocation = true;
  12420. };
  12421. this.$$parseLinkUrl = function(url, relHref) {
  12422. if (relHref && relHref[0] === '#') {
  12423. // special case for links to hash fragments:
  12424. // keep the old url and only replace the hash fragment
  12425. this.hash(relHref.slice(1));
  12426. return true;
  12427. }
  12428. var appUrl, prevAppUrl;
  12429. var rewrittenUrl;
  12430. if (isDefined(appUrl = stripBaseUrl(appBase, url))) {
  12431. prevAppUrl = appUrl;
  12432. if (basePrefix && isDefined(appUrl = stripBaseUrl(basePrefix, appUrl))) {
  12433. rewrittenUrl = appBaseNoFile + (stripBaseUrl('/', appUrl) || appUrl);
  12434. } else {
  12435. rewrittenUrl = appBase + prevAppUrl;
  12436. }
  12437. } else if (isDefined(appUrl = stripBaseUrl(appBaseNoFile, url))) {
  12438. rewrittenUrl = appBaseNoFile + appUrl;
  12439. } else if (appBaseNoFile === url + '/') {
  12440. rewrittenUrl = appBaseNoFile;
  12441. }
  12442. if (rewrittenUrl) {
  12443. this.$$parse(rewrittenUrl);
  12444. }
  12445. return !!rewrittenUrl;
  12446. };
  12447. }
  12448. /**
  12449. * LocationHashbangUrl represents URL
  12450. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  12451. * It also serves as the base class for html5 mode fallback on legacy browsers.
  12452. *
  12453. * @constructor
  12454. * @param {string} appBase application base URL
  12455. * @param {string} appBaseNoFile application base URL stripped of any filename
  12456. * @param {string} hashPrefix hashbang prefix
  12457. */
  12458. function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
  12459. parseAbsoluteUrl(appBase, this);
  12460. /**
  12461. * Parse given hashbang URL into properties
  12462. * @param {string} url Hashbang URL
  12463. * @private
  12464. */
  12465. this.$$parse = function(url) {
  12466. var withoutBaseUrl = stripBaseUrl(appBase, url) || stripBaseUrl(appBaseNoFile, url);
  12467. var withoutHashUrl;
  12468. if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
  12469. // The rest of the URL starts with a hash so we have
  12470. // got either a hashbang path or a plain hash fragment
  12471. withoutHashUrl = stripBaseUrl(hashPrefix, withoutBaseUrl);
  12472. if (isUndefined(withoutHashUrl)) {
  12473. // There was no hashbang prefix so we just have a hash fragment
  12474. withoutHashUrl = withoutBaseUrl;
  12475. }
  12476. } else {
  12477. // There was no hashbang path nor hash fragment:
  12478. // If we are in HTML5 mode we use what is left as the path;
  12479. // Otherwise we ignore what is left
  12480. if (this.$$html5) {
  12481. withoutHashUrl = withoutBaseUrl;
  12482. } else {
  12483. withoutHashUrl = '';
  12484. if (isUndefined(withoutBaseUrl)) {
  12485. appBase = url;
  12486. /** @type {?} */ (this).replace();
  12487. }
  12488. }
  12489. }
  12490. parseAppUrl(withoutHashUrl, this, false);
  12491. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  12492. this.$$compose();
  12493. /*
  12494. * In Windows, on an anchor node on documents loaded from
  12495. * the filesystem, the browser will return a pathname
  12496. * prefixed with the drive name ('/C:/path') when a
  12497. * pathname without a drive is set:
  12498. * * a.setAttribute('href', '/foo')
  12499. * * a.pathname === '/C:/foo' //true
  12500. *
  12501. * Inside of Angular, we're always using pathnames that
  12502. * do not include drive names for routing.
  12503. */
  12504. function removeWindowsDriveName(path, url, base) {
  12505. /*
  12506. Matches paths for file protocol on windows,
  12507. such as /C:/foo/bar, and captures only /foo/bar.
  12508. */
  12509. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  12510. var firstPathSegmentMatch;
  12511. //Get the relative path from the input URL.
  12512. if (startsWith(url, base)) {
  12513. url = url.replace(base, '');
  12514. }
  12515. // The input URL intentionally contains a first path segment that ends with a colon.
  12516. if (windowsFilePathExp.exec(url)) {
  12517. return path;
  12518. }
  12519. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  12520. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  12521. }
  12522. };
  12523. /**
  12524. * Compose hashbang URL and update `absUrl` property
  12525. * @private
  12526. */
  12527. this.$$compose = function() {
  12528. var search = toKeyValue(this.$$search),
  12529. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  12530. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  12531. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  12532. this.$$urlUpdatedByLocation = true;
  12533. };
  12534. this.$$parseLinkUrl = function(url, relHref) {
  12535. if (stripHash(appBase) === stripHash(url)) {
  12536. this.$$parse(url);
  12537. return true;
  12538. }
  12539. return false;
  12540. };
  12541. }
  12542. /**
  12543. * LocationHashbangUrl represents URL
  12544. * This object is exposed as $location service when html5 history api is enabled but the browser
  12545. * does not support it.
  12546. *
  12547. * @constructor
  12548. * @param {string} appBase application base URL
  12549. * @param {string} appBaseNoFile application base URL stripped of any filename
  12550. * @param {string} hashPrefix hashbang prefix
  12551. */
  12552. function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
  12553. this.$$html5 = true;
  12554. LocationHashbangUrl.apply(this, arguments);
  12555. this.$$parseLinkUrl = function(url, relHref) {
  12556. if (relHref && relHref[0] === '#') {
  12557. // special case for links to hash fragments:
  12558. // keep the old url and only replace the hash fragment
  12559. this.hash(relHref.slice(1));
  12560. return true;
  12561. }
  12562. var rewrittenUrl;
  12563. var appUrl;
  12564. if (appBase === stripHash(url)) {
  12565. rewrittenUrl = url;
  12566. } else if ((appUrl = stripBaseUrl(appBaseNoFile, url))) {
  12567. rewrittenUrl = appBase + hashPrefix + appUrl;
  12568. } else if (appBaseNoFile === url + '/') {
  12569. rewrittenUrl = appBaseNoFile;
  12570. }
  12571. if (rewrittenUrl) {
  12572. this.$$parse(rewrittenUrl);
  12573. }
  12574. return !!rewrittenUrl;
  12575. };
  12576. this.$$compose = function() {
  12577. var search = toKeyValue(this.$$search),
  12578. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  12579. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  12580. // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
  12581. this.$$absUrl = appBase + hashPrefix + this.$$url;
  12582. this.$$urlUpdatedByLocation = true;
  12583. };
  12584. }
  12585. var locationPrototype = {
  12586. /**
  12587. * Ensure absolute URL is initialized.
  12588. * @private
  12589. */
  12590. $$absUrl:'',
  12591. /**
  12592. * Are we in html5 mode?
  12593. * @private
  12594. */
  12595. $$html5: false,
  12596. /**
  12597. * Has any change been replacing?
  12598. * @private
  12599. */
  12600. $$replace: false,
  12601. /**
  12602. * @ngdoc method
  12603. * @name $location#absUrl
  12604. *
  12605. * @description
  12606. * This method is getter only.
  12607. *
  12608. * Return full URL representation with all segments encoded according to rules specified in
  12609. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  12610. *
  12611. *
  12612. * ```js
  12613. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12614. * var absUrl = $location.absUrl();
  12615. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  12616. * ```
  12617. *
  12618. * @return {string} full URL
  12619. */
  12620. absUrl: locationGetter('$$absUrl'),
  12621. /**
  12622. * @ngdoc method
  12623. * @name $location#url
  12624. *
  12625. * @description
  12626. * This method is getter / setter.
  12627. *
  12628. * Return URL (e.g. `/path?a=b#hash`) when called without any parameter.
  12629. *
  12630. * Change path, search and hash, when called with parameter and return `$location`.
  12631. *
  12632. *
  12633. * ```js
  12634. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12635. * var url = $location.url();
  12636. * // => "/some/path?foo=bar&baz=xoxo"
  12637. * ```
  12638. *
  12639. * @param {string=} url New URL without base prefix (e.g. `/path?a=b#hash`)
  12640. * @return {string} url
  12641. */
  12642. url: function(url) {
  12643. if (isUndefined(url)) {
  12644. return this.$$url;
  12645. }
  12646. var match = PATH_MATCH.exec(url);
  12647. if (match[1] || url === '') this.path(decodeURI(match[1]));
  12648. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  12649. this.hash(match[5] || '');
  12650. return this;
  12651. },
  12652. /**
  12653. * @ngdoc method
  12654. * @name $location#protocol
  12655. *
  12656. * @description
  12657. * This method is getter only.
  12658. *
  12659. * Return protocol of current URL.
  12660. *
  12661. *
  12662. * ```js
  12663. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12664. * var protocol = $location.protocol();
  12665. * // => "http"
  12666. * ```
  12667. *
  12668. * @return {string} protocol of current URL
  12669. */
  12670. protocol: locationGetter('$$protocol'),
  12671. /**
  12672. * @ngdoc method
  12673. * @name $location#host
  12674. *
  12675. * @description
  12676. * This method is getter only.
  12677. *
  12678. * Return host of current URL.
  12679. *
  12680. * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  12681. *
  12682. *
  12683. * ```js
  12684. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12685. * var host = $location.host();
  12686. * // => "example.com"
  12687. *
  12688. * // given URL http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  12689. * host = $location.host();
  12690. * // => "example.com"
  12691. * host = location.host;
  12692. * // => "example.com:8080"
  12693. * ```
  12694. *
  12695. * @return {string} host of current URL.
  12696. */
  12697. host: locationGetter('$$host'),
  12698. /**
  12699. * @ngdoc method
  12700. * @name $location#port
  12701. *
  12702. * @description
  12703. * This method is getter only.
  12704. *
  12705. * Return port of current URL.
  12706. *
  12707. *
  12708. * ```js
  12709. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12710. * var port = $location.port();
  12711. * // => 80
  12712. * ```
  12713. *
  12714. * @return {Number} port
  12715. */
  12716. port: locationGetter('$$port'),
  12717. /**
  12718. * @ngdoc method
  12719. * @name $location#path
  12720. *
  12721. * @description
  12722. * This method is getter / setter.
  12723. *
  12724. * Return path of current URL when called without any parameter.
  12725. *
  12726. * Change path when called with parameter and return `$location`.
  12727. *
  12728. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  12729. * if it is missing.
  12730. *
  12731. *
  12732. * ```js
  12733. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12734. * var path = $location.path();
  12735. * // => "/some/path"
  12736. * ```
  12737. *
  12738. * @param {(string|number)=} path New path
  12739. * @return {(string|object)} path if called with no parameters, or `$location` if called with a parameter
  12740. */
  12741. path: locationGetterSetter('$$path', function(path) {
  12742. path = path !== null ? path.toString() : '';
  12743. return path.charAt(0) === '/' ? path : '/' + path;
  12744. }),
  12745. /**
  12746. * @ngdoc method
  12747. * @name $location#search
  12748. *
  12749. * @description
  12750. * This method is getter / setter.
  12751. *
  12752. * Return search part (as object) of current URL when called without any parameter.
  12753. *
  12754. * Change search part when called with parameter and return `$location`.
  12755. *
  12756. *
  12757. * ```js
  12758. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo
  12759. * var searchObject = $location.search();
  12760. * // => {foo: 'bar', baz: 'xoxo'}
  12761. *
  12762. * // set foo to 'yipee'
  12763. * $location.search('foo', 'yipee');
  12764. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  12765. * ```
  12766. *
  12767. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  12768. * hash object.
  12769. *
  12770. * When called with a single argument the method acts as a setter, setting the `search` component
  12771. * of `$location` to the specified value.
  12772. *
  12773. * If the argument is a hash object containing an array of values, these values will be encoded
  12774. * as duplicate search parameters in the URL.
  12775. *
  12776. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  12777. * will override only a single search property.
  12778. *
  12779. * If `paramValue` is an array, it will override the property of the `search` component of
  12780. * `$location` specified via the first argument.
  12781. *
  12782. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  12783. *
  12784. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  12785. * value nor trailing equal sign.
  12786. *
  12787. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  12788. * one or more arguments returns `$location` object itself.
  12789. */
  12790. search: function(search, paramValue) {
  12791. switch (arguments.length) {
  12792. case 0:
  12793. return this.$$search;
  12794. case 1:
  12795. if (isString(search) || isNumber(search)) {
  12796. search = search.toString();
  12797. this.$$search = parseKeyValue(search);
  12798. } else if (isObject(search)) {
  12799. search = copy(search, {});
  12800. // remove object undefined or null properties
  12801. forEach(search, function(value, key) {
  12802. if (value == null) delete search[key];
  12803. });
  12804. this.$$search = search;
  12805. } else {
  12806. throw $locationMinErr('isrcharg',
  12807. 'The first argument of the `$location#search()` call must be a string or an object.');
  12808. }
  12809. break;
  12810. default:
  12811. if (isUndefined(paramValue) || paramValue === null) {
  12812. delete this.$$search[search];
  12813. } else {
  12814. this.$$search[search] = paramValue;
  12815. }
  12816. }
  12817. this.$$compose();
  12818. return this;
  12819. },
  12820. /**
  12821. * @ngdoc method
  12822. * @name $location#hash
  12823. *
  12824. * @description
  12825. * This method is getter / setter.
  12826. *
  12827. * Returns the hash fragment when called without any parameters.
  12828. *
  12829. * Changes the hash fragment when called with a parameter and returns `$location`.
  12830. *
  12831. *
  12832. * ```js
  12833. * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  12834. * var hash = $location.hash();
  12835. * // => "hashValue"
  12836. * ```
  12837. *
  12838. * @param {(string|number)=} hash New hash fragment
  12839. * @return {string} hash
  12840. */
  12841. hash: locationGetterSetter('$$hash', function(hash) {
  12842. return hash !== null ? hash.toString() : '';
  12843. }),
  12844. /**
  12845. * @ngdoc method
  12846. * @name $location#replace
  12847. *
  12848. * @description
  12849. * If called, all changes to $location during the current `$digest` will replace the current history
  12850. * record, instead of adding a new one.
  12851. */
  12852. replace: function() {
  12853. this.$$replace = true;
  12854. return this;
  12855. }
  12856. };
  12857. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  12858. Location.prototype = Object.create(locationPrototype);
  12859. /**
  12860. * @ngdoc method
  12861. * @name $location#state
  12862. *
  12863. * @description
  12864. * This method is getter / setter.
  12865. *
  12866. * Return the history state object when called without any parameter.
  12867. *
  12868. * Change the history state object when called with one parameter and return `$location`.
  12869. * The state object is later passed to `pushState` or `replaceState`.
  12870. *
  12871. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  12872. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  12873. * older browsers (like IE9 or Android < 4.0), don't use this method.
  12874. *
  12875. * @param {object=} state State object for pushState or replaceState
  12876. * @return {object} state
  12877. */
  12878. Location.prototype.state = function(state) {
  12879. if (!arguments.length) {
  12880. return this.$$state;
  12881. }
  12882. if (Location !== LocationHtml5Url || !this.$$html5) {
  12883. throw $locationMinErr('nostate', 'History API state support is available only ' +
  12884. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  12885. }
  12886. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  12887. // but we're changing the $$state reference to $browser.state() during the $digest
  12888. // so the modification window is narrow.
  12889. this.$$state = isUndefined(state) ? null : state;
  12890. this.$$urlUpdatedByLocation = true;
  12891. return this;
  12892. };
  12893. });
  12894. function locationGetter(property) {
  12895. return /** @this */ function() {
  12896. return this[property];
  12897. };
  12898. }
  12899. function locationGetterSetter(property, preprocess) {
  12900. return /** @this */ function(value) {
  12901. if (isUndefined(value)) {
  12902. return this[property];
  12903. }
  12904. this[property] = preprocess(value);
  12905. this.$$compose();
  12906. return this;
  12907. };
  12908. }
  12909. /**
  12910. * @ngdoc service
  12911. * @name $location
  12912. *
  12913. * @requires $rootElement
  12914. *
  12915. * @description
  12916. * The $location service parses the URL in the browser address bar (based on the
  12917. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  12918. * available to your application. Changes to the URL in the address bar are reflected into
  12919. * $location service and changes to $location are reflected into the browser address bar.
  12920. *
  12921. * **The $location service:**
  12922. *
  12923. * - Exposes the current URL in the browser address bar, so you can
  12924. * - Watch and observe the URL.
  12925. * - Change the URL.
  12926. * - Synchronizes the URL with the browser when the user
  12927. * - Changes the address bar.
  12928. * - Clicks the back or forward button (or clicks a History link).
  12929. * - Clicks on a link.
  12930. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  12931. *
  12932. * For more information see {@link guide/$location Developer Guide: Using $location}
  12933. */
  12934. /**
  12935. * @ngdoc provider
  12936. * @name $locationProvider
  12937. * @this
  12938. *
  12939. * @description
  12940. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  12941. */
  12942. function $LocationProvider() {
  12943. var hashPrefix = '!',
  12944. html5Mode = {
  12945. enabled: false,
  12946. requireBase: true,
  12947. rewriteLinks: true
  12948. };
  12949. /**
  12950. * @ngdoc method
  12951. * @name $locationProvider#hashPrefix
  12952. * @description
  12953. * The default value for the prefix is `'!'`.
  12954. * @param {string=} prefix Prefix for hash part (containing path and search)
  12955. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  12956. */
  12957. this.hashPrefix = function(prefix) {
  12958. if (isDefined(prefix)) {
  12959. hashPrefix = prefix;
  12960. return this;
  12961. } else {
  12962. return hashPrefix;
  12963. }
  12964. };
  12965. /**
  12966. * @ngdoc method
  12967. * @name $locationProvider#html5Mode
  12968. * @description
  12969. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  12970. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  12971. * properties:
  12972. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  12973. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  12974. * support `pushState`.
  12975. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  12976. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  12977. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  12978. * See the {@link guide/$location $location guide for more information}
  12979. * - **rewriteLinks** - `{boolean|string}` - (default: `true`) When html5Mode is enabled,
  12980. * enables/disables URL rewriting for relative links. If set to a string, URL rewriting will
  12981. * only happen on links with an attribute that matches the given string. For example, if set
  12982. * to `'internal-link'`, then the URL will only be rewritten for `<a internal-link>` links.
  12983. * Note that [attribute name normalization](guide/directive#normalization) does not apply
  12984. * here, so `'internalLink'` will **not** match `'internal-link'`.
  12985. *
  12986. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  12987. */
  12988. this.html5Mode = function(mode) {
  12989. if (isBoolean(mode)) {
  12990. html5Mode.enabled = mode;
  12991. return this;
  12992. } else if (isObject(mode)) {
  12993. if (isBoolean(mode.enabled)) {
  12994. html5Mode.enabled = mode.enabled;
  12995. }
  12996. if (isBoolean(mode.requireBase)) {
  12997. html5Mode.requireBase = mode.requireBase;
  12998. }
  12999. if (isBoolean(mode.rewriteLinks) || isString(mode.rewriteLinks)) {
  13000. html5Mode.rewriteLinks = mode.rewriteLinks;
  13001. }
  13002. return this;
  13003. } else {
  13004. return html5Mode;
  13005. }
  13006. };
  13007. /**
  13008. * @ngdoc event
  13009. * @name $location#$locationChangeStart
  13010. * @eventType broadcast on root scope
  13011. * @description
  13012. * Broadcasted before a URL will change.
  13013. *
  13014. * This change can be prevented by calling
  13015. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  13016. * details about event object. Upon successful change
  13017. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  13018. *
  13019. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  13020. * the browser supports the HTML5 History API.
  13021. *
  13022. * @param {Object} angularEvent Synthetic event object.
  13023. * @param {string} newUrl New URL
  13024. * @param {string=} oldUrl URL that was before it was changed.
  13025. * @param {string=} newState New history state object
  13026. * @param {string=} oldState History state object that was before it was changed.
  13027. */
  13028. /**
  13029. * @ngdoc event
  13030. * @name $location#$locationChangeSuccess
  13031. * @eventType broadcast on root scope
  13032. * @description
  13033. * Broadcasted after a URL was changed.
  13034. *
  13035. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  13036. * the browser supports the HTML5 History API.
  13037. *
  13038. * @param {Object} angularEvent Synthetic event object.
  13039. * @param {string} newUrl New URL
  13040. * @param {string=} oldUrl URL that was before it was changed.
  13041. * @param {string=} newState New history state object
  13042. * @param {string=} oldState History state object that was before it was changed.
  13043. */
  13044. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  13045. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  13046. var $location,
  13047. LocationMode,
  13048. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  13049. initialUrl = $browser.url(),
  13050. appBase;
  13051. if (html5Mode.enabled) {
  13052. if (!baseHref && html5Mode.requireBase) {
  13053. throw $locationMinErr('nobase',
  13054. '$location in HTML5 mode requires a <base> tag to be present!');
  13055. }
  13056. appBase = serverBase(initialUrl) + (baseHref || '/');
  13057. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  13058. } else {
  13059. appBase = stripHash(initialUrl);
  13060. LocationMode = LocationHashbangUrl;
  13061. }
  13062. var appBaseNoFile = stripFile(appBase);
  13063. $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
  13064. $location.$$parseLinkUrl(initialUrl, initialUrl);
  13065. $location.$$state = $browser.state();
  13066. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  13067. function setBrowserUrlWithFallback(url, replace, state) {
  13068. var oldUrl = $location.url();
  13069. var oldState = $location.$$state;
  13070. try {
  13071. $browser.url(url, replace, state);
  13072. // Make sure $location.state() returns referentially identical (not just deeply equal)
  13073. // state object; this makes possible quick checking if the state changed in the digest
  13074. // loop. Checking deep equality would be too expensive.
  13075. $location.$$state = $browser.state();
  13076. } catch (e) {
  13077. // Restore old values if pushState fails
  13078. $location.url(oldUrl);
  13079. $location.$$state = oldState;
  13080. throw e;
  13081. }
  13082. }
  13083. $rootElement.on('click', function(event) {
  13084. var rewriteLinks = html5Mode.rewriteLinks;
  13085. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  13086. // currently we open nice url link and redirect then
  13087. if (!rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which === 2 || event.button === 2) return;
  13088. var elm = jqLite(event.target);
  13089. // traverse the DOM up to find first A tag
  13090. while (nodeName_(elm[0]) !== 'a') {
  13091. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  13092. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  13093. }
  13094. if (isString(rewriteLinks) && isUndefined(elm.attr(rewriteLinks))) return;
  13095. var absHref = elm.prop('href');
  13096. // get the actual href attribute - see
  13097. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  13098. var relHref = elm.attr('href') || elm.attr('xlink:href');
  13099. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  13100. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  13101. // an animation.
  13102. absHref = urlResolve(absHref.animVal).href;
  13103. }
  13104. // Ignore when url is started with javascript: or mailto:
  13105. if (IGNORE_URI_REGEXP.test(absHref)) return;
  13106. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  13107. if ($location.$$parseLinkUrl(absHref, relHref)) {
  13108. // We do a preventDefault for all urls that are part of the angular application,
  13109. // in html5mode and also without, so that we are able to abort navigation without
  13110. // getting double entries in the location history.
  13111. event.preventDefault();
  13112. // update location manually
  13113. if ($location.absUrl() !== $browser.url()) {
  13114. $rootScope.$apply();
  13115. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  13116. $window.angular['ff-684208-preventDefault'] = true;
  13117. }
  13118. }
  13119. }
  13120. });
  13121. // rewrite hashbang url <> html5 url
  13122. if (trimEmptyHash($location.absUrl()) !== trimEmptyHash(initialUrl)) {
  13123. $browser.url($location.absUrl(), true);
  13124. }
  13125. var initializing = true;
  13126. // update $location when $browser url changes
  13127. $browser.onUrlChange(function(newUrl, newState) {
  13128. if (!startsWith(newUrl, appBaseNoFile)) {
  13129. // If we are navigating outside of the app then force a reload
  13130. $window.location.href = newUrl;
  13131. return;
  13132. }
  13133. $rootScope.$evalAsync(function() {
  13134. var oldUrl = $location.absUrl();
  13135. var oldState = $location.$$state;
  13136. var defaultPrevented;
  13137. newUrl = trimEmptyHash(newUrl);
  13138. $location.$$parse(newUrl);
  13139. $location.$$state = newState;
  13140. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  13141. newState, oldState).defaultPrevented;
  13142. // if the location was changed by a `$locationChangeStart` handler then stop
  13143. // processing this location change
  13144. if ($location.absUrl() !== newUrl) return;
  13145. if (defaultPrevented) {
  13146. $location.$$parse(oldUrl);
  13147. $location.$$state = oldState;
  13148. setBrowserUrlWithFallback(oldUrl, false, oldState);
  13149. } else {
  13150. initializing = false;
  13151. afterLocationChange(oldUrl, oldState);
  13152. }
  13153. });
  13154. if (!$rootScope.$$phase) $rootScope.$digest();
  13155. });
  13156. // update browser
  13157. $rootScope.$watch(function $locationWatch() {
  13158. if (initializing || $location.$$urlUpdatedByLocation) {
  13159. $location.$$urlUpdatedByLocation = false;
  13160. var oldUrl = trimEmptyHash($browser.url());
  13161. var newUrl = trimEmptyHash($location.absUrl());
  13162. var oldState = $browser.state();
  13163. var currentReplace = $location.$$replace;
  13164. var urlOrStateChanged = oldUrl !== newUrl ||
  13165. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  13166. if (initializing || urlOrStateChanged) {
  13167. initializing = false;
  13168. $rootScope.$evalAsync(function() {
  13169. var newUrl = $location.absUrl();
  13170. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  13171. $location.$$state, oldState).defaultPrevented;
  13172. // if the location was changed by a `$locationChangeStart` handler then stop
  13173. // processing this location change
  13174. if ($location.absUrl() !== newUrl) return;
  13175. if (defaultPrevented) {
  13176. $location.$$parse(oldUrl);
  13177. $location.$$state = oldState;
  13178. } else {
  13179. if (urlOrStateChanged) {
  13180. setBrowserUrlWithFallback(newUrl, currentReplace,
  13181. oldState === $location.$$state ? null : $location.$$state);
  13182. }
  13183. afterLocationChange(oldUrl, oldState);
  13184. }
  13185. });
  13186. }
  13187. }
  13188. $location.$$replace = false;
  13189. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  13190. // there is a change
  13191. });
  13192. return $location;
  13193. function afterLocationChange(oldUrl, oldState) {
  13194. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  13195. $location.$$state, oldState);
  13196. }
  13197. }];
  13198. }
  13199. /**
  13200. * @ngdoc service
  13201. * @name $log
  13202. * @requires $window
  13203. *
  13204. * @description
  13205. * Simple service for logging. Default implementation safely writes the message
  13206. * into the browser's console (if present).
  13207. *
  13208. * The main purpose of this service is to simplify debugging and troubleshooting.
  13209. *
  13210. * To reveal the location of the calls to `$log` in the JavaScript console,
  13211. * you can "blackbox" the AngularJS source in your browser:
  13212. *
  13213. * [Mozilla description of blackboxing](https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Black_box_a_source).
  13214. * [Chrome description of blackboxing](https://developer.chrome.com/devtools/docs/blackboxing).
  13215. *
  13216. * Note: Not all browsers support blackboxing.
  13217. *
  13218. * The default is to log `debug` messages. You can use
  13219. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  13220. *
  13221. * @example
  13222. <example module="logExample" name="log-service">
  13223. <file name="script.js">
  13224. angular.module('logExample', [])
  13225. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  13226. $scope.$log = $log;
  13227. $scope.message = 'Hello World!';
  13228. }]);
  13229. </file>
  13230. <file name="index.html">
  13231. <div ng-controller="LogController">
  13232. <p>Reload this page with open console, enter text and hit the log button...</p>
  13233. <label>Message:
  13234. <input type="text" ng-model="message" /></label>
  13235. <button ng-click="$log.log(message)">log</button>
  13236. <button ng-click="$log.warn(message)">warn</button>
  13237. <button ng-click="$log.info(message)">info</button>
  13238. <button ng-click="$log.error(message)">error</button>
  13239. <button ng-click="$log.debug(message)">debug</button>
  13240. </div>
  13241. </file>
  13242. </example>
  13243. */
  13244. /**
  13245. * @ngdoc provider
  13246. * @name $logProvider
  13247. * @this
  13248. *
  13249. * @description
  13250. * Use the `$logProvider` to configure how the application logs messages
  13251. */
  13252. function $LogProvider() {
  13253. var debug = true,
  13254. self = this;
  13255. /**
  13256. * @ngdoc method
  13257. * @name $logProvider#debugEnabled
  13258. * @description
  13259. * @param {boolean=} flag enable or disable debug level messages
  13260. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  13261. */
  13262. this.debugEnabled = function(flag) {
  13263. if (isDefined(flag)) {
  13264. debug = flag;
  13265. return this;
  13266. } else {
  13267. return debug;
  13268. }
  13269. };
  13270. this.$get = ['$window', function($window) {
  13271. // Support: IE 9-11, Edge 12-14+
  13272. // IE/Edge display errors in such a way that it requires the user to click in 4 places
  13273. // to see the stack trace. There is no way to feature-detect it so there's a chance
  13274. // of the user agent sniffing to go wrong but since it's only about logging, this shouldn't
  13275. // break apps. Other browsers display errors in a sensible way and some of them map stack
  13276. // traces along source maps if available so it makes sense to let browsers display it
  13277. // as they want.
  13278. var formatStackTrace = msie || /\bEdge\//.test($window.navigator && $window.navigator.userAgent);
  13279. return {
  13280. /**
  13281. * @ngdoc method
  13282. * @name $log#log
  13283. *
  13284. * @description
  13285. * Write a log message
  13286. */
  13287. log: consoleLog('log'),
  13288. /**
  13289. * @ngdoc method
  13290. * @name $log#info
  13291. *
  13292. * @description
  13293. * Write an information message
  13294. */
  13295. info: consoleLog('info'),
  13296. /**
  13297. * @ngdoc method
  13298. * @name $log#warn
  13299. *
  13300. * @description
  13301. * Write a warning message
  13302. */
  13303. warn: consoleLog('warn'),
  13304. /**
  13305. * @ngdoc method
  13306. * @name $log#error
  13307. *
  13308. * @description
  13309. * Write an error message
  13310. */
  13311. error: consoleLog('error'),
  13312. /**
  13313. * @ngdoc method
  13314. * @name $log#debug
  13315. *
  13316. * @description
  13317. * Write a debug message
  13318. */
  13319. debug: (function() {
  13320. var fn = consoleLog('debug');
  13321. return function() {
  13322. if (debug) {
  13323. fn.apply(self, arguments);
  13324. }
  13325. };
  13326. })()
  13327. };
  13328. function formatError(arg) {
  13329. if (isError(arg)) {
  13330. if (arg.stack && formatStackTrace) {
  13331. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  13332. ? 'Error: ' + arg.message + '\n' + arg.stack
  13333. : arg.stack;
  13334. } else if (arg.sourceURL) {
  13335. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  13336. }
  13337. }
  13338. return arg;
  13339. }
  13340. function consoleLog(type) {
  13341. var console = $window.console || {},
  13342. logFn = console[type] || console.log || noop;
  13343. return function() {
  13344. var args = [];
  13345. forEach(arguments, function(arg) {
  13346. args.push(formatError(arg));
  13347. });
  13348. // Support: IE 9 only
  13349. // console methods don't inherit from Function.prototype in IE 9 so we can't
  13350. // call `logFn.apply(console, args)` directly.
  13351. return Function.prototype.apply.call(logFn, console, args);
  13352. };
  13353. }
  13354. }];
  13355. }
  13356. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  13357. * Any commits to this file should be reviewed with security in mind. *
  13358. * Changes to this file can potentially create security vulnerabilities. *
  13359. * An approval from 2 Core members with history of modifying *
  13360. * this file is required. *
  13361. * *
  13362. * Does the change somehow allow for arbitrary javascript to be executed? *
  13363. * Or allows for someone to change the prototype of built-in objects? *
  13364. * Or gives undesired access to variables likes document or window? *
  13365. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  13366. var $parseMinErr = minErr('$parse');
  13367. var objectValueOf = {}.constructor.prototype.valueOf;
  13368. // Sandboxing Angular Expressions
  13369. // ------------------------------
  13370. // Angular expressions are no longer sandboxed. So it is now even easier to access arbitrary JS code by
  13371. // various means such as obtaining a reference to native JS functions like the Function constructor.
  13372. //
  13373. // As an example, consider the following Angular expression:
  13374. //
  13375. // {}.toString.constructor('alert("evil JS code")')
  13376. //
  13377. // It is important to realize that if you create an expression from a string that contains user provided
  13378. // content then it is possible that your application contains a security vulnerability to an XSS style attack.
  13379. //
  13380. // See https://docs.angularjs.org/guide/security
  13381. function getStringValue(name) {
  13382. // Property names must be strings. This means that non-string objects cannot be used
  13383. // as keys in an object. Any non-string object, including a number, is typecasted
  13384. // into a string via the toString method.
  13385. // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names
  13386. //
  13387. // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it
  13388. // to a string. It's not always possible. If `name` is an object and its `toString` method is
  13389. // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:
  13390. //
  13391. // TypeError: Cannot convert object to primitive value
  13392. //
  13393. // For performance reasons, we don't catch this error here and allow it to propagate up the call
  13394. // stack. Note that you'll get the same error in JavaScript if you try to access a property using
  13395. // such a 'broken' object as a key.
  13396. return name + '';
  13397. }
  13398. var OPERATORS = createMap();
  13399. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  13400. var ESCAPE = {'n':'\n', 'f':'\f', 'r':'\r', 't':'\t', 'v':'\v', '\'':'\'', '"':'"'};
  13401. /////////////////////////////////////////
  13402. /**
  13403. * @constructor
  13404. */
  13405. var Lexer = function Lexer(options) {
  13406. this.options = options;
  13407. };
  13408. Lexer.prototype = {
  13409. constructor: Lexer,
  13410. lex: function(text) {
  13411. this.text = text;
  13412. this.index = 0;
  13413. this.tokens = [];
  13414. while (this.index < this.text.length) {
  13415. var ch = this.text.charAt(this.index);
  13416. if (ch === '"' || ch === '\'') {
  13417. this.readString(ch);
  13418. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  13419. this.readNumber();
  13420. } else if (this.isIdentifierStart(this.peekMultichar())) {
  13421. this.readIdent();
  13422. } else if (this.is(ch, '(){}[].,;:?')) {
  13423. this.tokens.push({index: this.index, text: ch});
  13424. this.index++;
  13425. } else if (this.isWhitespace(ch)) {
  13426. this.index++;
  13427. } else {
  13428. var ch2 = ch + this.peek();
  13429. var ch3 = ch2 + this.peek(2);
  13430. var op1 = OPERATORS[ch];
  13431. var op2 = OPERATORS[ch2];
  13432. var op3 = OPERATORS[ch3];
  13433. if (op1 || op2 || op3) {
  13434. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  13435. this.tokens.push({index: this.index, text: token, operator: true});
  13436. this.index += token.length;
  13437. } else {
  13438. this.throwError('Unexpected next character ', this.index, this.index + 1);
  13439. }
  13440. }
  13441. }
  13442. return this.tokens;
  13443. },
  13444. is: function(ch, chars) {
  13445. return chars.indexOf(ch) !== -1;
  13446. },
  13447. peek: function(i) {
  13448. var num = i || 1;
  13449. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  13450. },
  13451. isNumber: function(ch) {
  13452. return ('0' <= ch && ch <= '9') && typeof ch === 'string';
  13453. },
  13454. isWhitespace: function(ch) {
  13455. // IE treats non-breaking space as \u00A0
  13456. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  13457. ch === '\n' || ch === '\v' || ch === '\u00A0');
  13458. },
  13459. isIdentifierStart: function(ch) {
  13460. return this.options.isIdentifierStart ?
  13461. this.options.isIdentifierStart(ch, this.codePointAt(ch)) :
  13462. this.isValidIdentifierStart(ch);
  13463. },
  13464. isValidIdentifierStart: function(ch) {
  13465. return ('a' <= ch && ch <= 'z' ||
  13466. 'A' <= ch && ch <= 'Z' ||
  13467. '_' === ch || ch === '$');
  13468. },
  13469. isIdentifierContinue: function(ch) {
  13470. return this.options.isIdentifierContinue ?
  13471. this.options.isIdentifierContinue(ch, this.codePointAt(ch)) :
  13472. this.isValidIdentifierContinue(ch);
  13473. },
  13474. isValidIdentifierContinue: function(ch, cp) {
  13475. return this.isValidIdentifierStart(ch, cp) || this.isNumber(ch);
  13476. },
  13477. codePointAt: function(ch) {
  13478. if (ch.length === 1) return ch.charCodeAt(0);
  13479. // eslint-disable-next-line no-bitwise
  13480. return (ch.charCodeAt(0) << 10) + ch.charCodeAt(1) - 0x35FDC00;
  13481. },
  13482. peekMultichar: function() {
  13483. var ch = this.text.charAt(this.index);
  13484. var peek = this.peek();
  13485. if (!peek) {
  13486. return ch;
  13487. }
  13488. var cp1 = ch.charCodeAt(0);
  13489. var cp2 = peek.charCodeAt(0);
  13490. if (cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF) {
  13491. return ch + peek;
  13492. }
  13493. return ch;
  13494. },
  13495. isExpOperator: function(ch) {
  13496. return (ch === '-' || ch === '+' || this.isNumber(ch));
  13497. },
  13498. throwError: function(error, start, end) {
  13499. end = end || this.index;
  13500. var colStr = (isDefined(start)
  13501. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  13502. : ' ' + end);
  13503. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  13504. error, colStr, this.text);
  13505. },
  13506. readNumber: function() {
  13507. var number = '';
  13508. var start = this.index;
  13509. while (this.index < this.text.length) {
  13510. var ch = lowercase(this.text.charAt(this.index));
  13511. if (ch === '.' || this.isNumber(ch)) {
  13512. number += ch;
  13513. } else {
  13514. var peekCh = this.peek();
  13515. if (ch === 'e' && this.isExpOperator(peekCh)) {
  13516. number += ch;
  13517. } else if (this.isExpOperator(ch) &&
  13518. peekCh && this.isNumber(peekCh) &&
  13519. number.charAt(number.length - 1) === 'e') {
  13520. number += ch;
  13521. } else if (this.isExpOperator(ch) &&
  13522. (!peekCh || !this.isNumber(peekCh)) &&
  13523. number.charAt(number.length - 1) === 'e') {
  13524. this.throwError('Invalid exponent');
  13525. } else {
  13526. break;
  13527. }
  13528. }
  13529. this.index++;
  13530. }
  13531. this.tokens.push({
  13532. index: start,
  13533. text: number,
  13534. constant: true,
  13535. value: Number(number)
  13536. });
  13537. },
  13538. readIdent: function() {
  13539. var start = this.index;
  13540. this.index += this.peekMultichar().length;
  13541. while (this.index < this.text.length) {
  13542. var ch = this.peekMultichar();
  13543. if (!this.isIdentifierContinue(ch)) {
  13544. break;
  13545. }
  13546. this.index += ch.length;
  13547. }
  13548. this.tokens.push({
  13549. index: start,
  13550. text: this.text.slice(start, this.index),
  13551. identifier: true
  13552. });
  13553. },
  13554. readString: function(quote) {
  13555. var start = this.index;
  13556. this.index++;
  13557. var string = '';
  13558. var rawString = quote;
  13559. var escape = false;
  13560. while (this.index < this.text.length) {
  13561. var ch = this.text.charAt(this.index);
  13562. rawString += ch;
  13563. if (escape) {
  13564. if (ch === 'u') {
  13565. var hex = this.text.substring(this.index + 1, this.index + 5);
  13566. if (!hex.match(/[\da-f]{4}/i)) {
  13567. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  13568. }
  13569. this.index += 4;
  13570. string += String.fromCharCode(parseInt(hex, 16));
  13571. } else {
  13572. var rep = ESCAPE[ch];
  13573. string = string + (rep || ch);
  13574. }
  13575. escape = false;
  13576. } else if (ch === '\\') {
  13577. escape = true;
  13578. } else if (ch === quote) {
  13579. this.index++;
  13580. this.tokens.push({
  13581. index: start,
  13582. text: rawString,
  13583. constant: true,
  13584. value: string
  13585. });
  13586. return;
  13587. } else {
  13588. string += ch;
  13589. }
  13590. this.index++;
  13591. }
  13592. this.throwError('Unterminated quote', start);
  13593. }
  13594. };
  13595. var AST = function AST(lexer, options) {
  13596. this.lexer = lexer;
  13597. this.options = options;
  13598. };
  13599. AST.Program = 'Program';
  13600. AST.ExpressionStatement = 'ExpressionStatement';
  13601. AST.AssignmentExpression = 'AssignmentExpression';
  13602. AST.ConditionalExpression = 'ConditionalExpression';
  13603. AST.LogicalExpression = 'LogicalExpression';
  13604. AST.BinaryExpression = 'BinaryExpression';
  13605. AST.UnaryExpression = 'UnaryExpression';
  13606. AST.CallExpression = 'CallExpression';
  13607. AST.MemberExpression = 'MemberExpression';
  13608. AST.Identifier = 'Identifier';
  13609. AST.Literal = 'Literal';
  13610. AST.ArrayExpression = 'ArrayExpression';
  13611. AST.Property = 'Property';
  13612. AST.ObjectExpression = 'ObjectExpression';
  13613. AST.ThisExpression = 'ThisExpression';
  13614. AST.LocalsExpression = 'LocalsExpression';
  13615. // Internal use only
  13616. AST.NGValueParameter = 'NGValueParameter';
  13617. AST.prototype = {
  13618. ast: function(text) {
  13619. this.text = text;
  13620. this.tokens = this.lexer.lex(text);
  13621. var value = this.program();
  13622. if (this.tokens.length !== 0) {
  13623. this.throwError('is an unexpected token', this.tokens[0]);
  13624. }
  13625. return value;
  13626. },
  13627. program: function() {
  13628. var body = [];
  13629. while (true) {
  13630. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  13631. body.push(this.expressionStatement());
  13632. if (!this.expect(';')) {
  13633. return { type: AST.Program, body: body};
  13634. }
  13635. }
  13636. },
  13637. expressionStatement: function() {
  13638. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  13639. },
  13640. filterChain: function() {
  13641. var left = this.expression();
  13642. while (this.expect('|')) {
  13643. left = this.filter(left);
  13644. }
  13645. return left;
  13646. },
  13647. expression: function() {
  13648. return this.assignment();
  13649. },
  13650. assignment: function() {
  13651. var result = this.ternary();
  13652. if (this.expect('=')) {
  13653. if (!isAssignable(result)) {
  13654. throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
  13655. }
  13656. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  13657. }
  13658. return result;
  13659. },
  13660. ternary: function() {
  13661. var test = this.logicalOR();
  13662. var alternate;
  13663. var consequent;
  13664. if (this.expect('?')) {
  13665. alternate = this.expression();
  13666. if (this.consume(':')) {
  13667. consequent = this.expression();
  13668. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  13669. }
  13670. }
  13671. return test;
  13672. },
  13673. logicalOR: function() {
  13674. var left = this.logicalAND();
  13675. while (this.expect('||')) {
  13676. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  13677. }
  13678. return left;
  13679. },
  13680. logicalAND: function() {
  13681. var left = this.equality();
  13682. while (this.expect('&&')) {
  13683. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  13684. }
  13685. return left;
  13686. },
  13687. equality: function() {
  13688. var left = this.relational();
  13689. var token;
  13690. while ((token = this.expect('==','!=','===','!=='))) {
  13691. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  13692. }
  13693. return left;
  13694. },
  13695. relational: function() {
  13696. var left = this.additive();
  13697. var token;
  13698. while ((token = this.expect('<', '>', '<=', '>='))) {
  13699. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  13700. }
  13701. return left;
  13702. },
  13703. additive: function() {
  13704. var left = this.multiplicative();
  13705. var token;
  13706. while ((token = this.expect('+','-'))) {
  13707. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  13708. }
  13709. return left;
  13710. },
  13711. multiplicative: function() {
  13712. var left = this.unary();
  13713. var token;
  13714. while ((token = this.expect('*','/','%'))) {
  13715. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  13716. }
  13717. return left;
  13718. },
  13719. unary: function() {
  13720. var token;
  13721. if ((token = this.expect('+', '-', '!'))) {
  13722. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  13723. } else {
  13724. return this.primary();
  13725. }
  13726. },
  13727. primary: function() {
  13728. var primary;
  13729. if (this.expect('(')) {
  13730. primary = this.filterChain();
  13731. this.consume(')');
  13732. } else if (this.expect('[')) {
  13733. primary = this.arrayDeclaration();
  13734. } else if (this.expect('{')) {
  13735. primary = this.object();
  13736. } else if (this.selfReferential.hasOwnProperty(this.peek().text)) {
  13737. primary = copy(this.selfReferential[this.consume().text]);
  13738. } else if (this.options.literals.hasOwnProperty(this.peek().text)) {
  13739. primary = { type: AST.Literal, value: this.options.literals[this.consume().text]};
  13740. } else if (this.peek().identifier) {
  13741. primary = this.identifier();
  13742. } else if (this.peek().constant) {
  13743. primary = this.constant();
  13744. } else {
  13745. this.throwError('not a primary expression', this.peek());
  13746. }
  13747. var next;
  13748. while ((next = this.expect('(', '[', '.'))) {
  13749. if (next.text === '(') {
  13750. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  13751. this.consume(')');
  13752. } else if (next.text === '[') {
  13753. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  13754. this.consume(']');
  13755. } else if (next.text === '.') {
  13756. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  13757. } else {
  13758. this.throwError('IMPOSSIBLE');
  13759. }
  13760. }
  13761. return primary;
  13762. },
  13763. filter: function(baseExpression) {
  13764. var args = [baseExpression];
  13765. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  13766. while (this.expect(':')) {
  13767. args.push(this.expression());
  13768. }
  13769. return result;
  13770. },
  13771. parseArguments: function() {
  13772. var args = [];
  13773. if (this.peekToken().text !== ')') {
  13774. do {
  13775. args.push(this.filterChain());
  13776. } while (this.expect(','));
  13777. }
  13778. return args;
  13779. },
  13780. identifier: function() {
  13781. var token = this.consume();
  13782. if (!token.identifier) {
  13783. this.throwError('is not a valid identifier', token);
  13784. }
  13785. return { type: AST.Identifier, name: token.text };
  13786. },
  13787. constant: function() {
  13788. // TODO check that it is a constant
  13789. return { type: AST.Literal, value: this.consume().value };
  13790. },
  13791. arrayDeclaration: function() {
  13792. var elements = [];
  13793. if (this.peekToken().text !== ']') {
  13794. do {
  13795. if (this.peek(']')) {
  13796. // Support trailing commas per ES5.1.
  13797. break;
  13798. }
  13799. elements.push(this.expression());
  13800. } while (this.expect(','));
  13801. }
  13802. this.consume(']');
  13803. return { type: AST.ArrayExpression, elements: elements };
  13804. },
  13805. object: function() {
  13806. var properties = [], property;
  13807. if (this.peekToken().text !== '}') {
  13808. do {
  13809. if (this.peek('}')) {
  13810. // Support trailing commas per ES5.1.
  13811. break;
  13812. }
  13813. property = {type: AST.Property, kind: 'init'};
  13814. if (this.peek().constant) {
  13815. property.key = this.constant();
  13816. property.computed = false;
  13817. this.consume(':');
  13818. property.value = this.expression();
  13819. } else if (this.peek().identifier) {
  13820. property.key = this.identifier();
  13821. property.computed = false;
  13822. if (this.peek(':')) {
  13823. this.consume(':');
  13824. property.value = this.expression();
  13825. } else {
  13826. property.value = property.key;
  13827. }
  13828. } else if (this.peek('[')) {
  13829. this.consume('[');
  13830. property.key = this.expression();
  13831. this.consume(']');
  13832. property.computed = true;
  13833. this.consume(':');
  13834. property.value = this.expression();
  13835. } else {
  13836. this.throwError('invalid key', this.peek());
  13837. }
  13838. properties.push(property);
  13839. } while (this.expect(','));
  13840. }
  13841. this.consume('}');
  13842. return {type: AST.ObjectExpression, properties: properties };
  13843. },
  13844. throwError: function(msg, token) {
  13845. throw $parseMinErr('syntax',
  13846. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  13847. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  13848. },
  13849. consume: function(e1) {
  13850. if (this.tokens.length === 0) {
  13851. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  13852. }
  13853. var token = this.expect(e1);
  13854. if (!token) {
  13855. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  13856. }
  13857. return token;
  13858. },
  13859. peekToken: function() {
  13860. if (this.tokens.length === 0) {
  13861. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  13862. }
  13863. return this.tokens[0];
  13864. },
  13865. peek: function(e1, e2, e3, e4) {
  13866. return this.peekAhead(0, e1, e2, e3, e4);
  13867. },
  13868. peekAhead: function(i, e1, e2, e3, e4) {
  13869. if (this.tokens.length > i) {
  13870. var token = this.tokens[i];
  13871. var t = token.text;
  13872. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  13873. (!e1 && !e2 && !e3 && !e4)) {
  13874. return token;
  13875. }
  13876. }
  13877. return false;
  13878. },
  13879. expect: function(e1, e2, e3, e4) {
  13880. var token = this.peek(e1, e2, e3, e4);
  13881. if (token) {
  13882. this.tokens.shift();
  13883. return token;
  13884. }
  13885. return false;
  13886. },
  13887. selfReferential: {
  13888. 'this': {type: AST.ThisExpression },
  13889. '$locals': {type: AST.LocalsExpression }
  13890. }
  13891. };
  13892. function ifDefined(v, d) {
  13893. return typeof v !== 'undefined' ? v : d;
  13894. }
  13895. function plusFn(l, r) {
  13896. if (typeof l === 'undefined') return r;
  13897. if (typeof r === 'undefined') return l;
  13898. return l + r;
  13899. }
  13900. function isStateless($filter, filterName) {
  13901. var fn = $filter(filterName);
  13902. return !fn.$stateful;
  13903. }
  13904. var PURITY_ABSOLUTE = 1;
  13905. var PURITY_RELATIVE = 2;
  13906. // Detect nodes which could depend on non-shallow state of objects
  13907. function isPure(node, parentIsPure) {
  13908. switch (node.type) {
  13909. // Computed members might invoke a stateful toString()
  13910. case AST.MemberExpression:
  13911. if (node.computed) {
  13912. return false;
  13913. }
  13914. break;
  13915. // Unary always convert to primative
  13916. case AST.UnaryExpression:
  13917. return PURITY_ABSOLUTE;
  13918. // The binary + operator can invoke a stateful toString().
  13919. case AST.BinaryExpression:
  13920. return node.operator !== '+' ? PURITY_ABSOLUTE : false;
  13921. // Functions / filters probably read state from within objects
  13922. case AST.CallExpression:
  13923. return false;
  13924. }
  13925. return (undefined === parentIsPure) ? PURITY_RELATIVE : parentIsPure;
  13926. }
  13927. function findConstantAndWatchExpressions(ast, $filter, parentIsPure) {
  13928. var allConstants;
  13929. var argsToWatch;
  13930. var isStatelessFilter;
  13931. var astIsPure = ast.isPure = isPure(ast, parentIsPure);
  13932. switch (ast.type) {
  13933. case AST.Program:
  13934. allConstants = true;
  13935. forEach(ast.body, function(expr) {
  13936. findConstantAndWatchExpressions(expr.expression, $filter, astIsPure);
  13937. allConstants = allConstants && expr.expression.constant;
  13938. });
  13939. ast.constant = allConstants;
  13940. break;
  13941. case AST.Literal:
  13942. ast.constant = true;
  13943. ast.toWatch = [];
  13944. break;
  13945. case AST.UnaryExpression:
  13946. findConstantAndWatchExpressions(ast.argument, $filter, astIsPure);
  13947. ast.constant = ast.argument.constant;
  13948. ast.toWatch = ast.argument.toWatch;
  13949. break;
  13950. case AST.BinaryExpression:
  13951. findConstantAndWatchExpressions(ast.left, $filter, astIsPure);
  13952. findConstantAndWatchExpressions(ast.right, $filter, astIsPure);
  13953. ast.constant = ast.left.constant && ast.right.constant;
  13954. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  13955. break;
  13956. case AST.LogicalExpression:
  13957. findConstantAndWatchExpressions(ast.left, $filter, astIsPure);
  13958. findConstantAndWatchExpressions(ast.right, $filter, astIsPure);
  13959. ast.constant = ast.left.constant && ast.right.constant;
  13960. ast.toWatch = ast.constant ? [] : [ast];
  13961. break;
  13962. case AST.ConditionalExpression:
  13963. findConstantAndWatchExpressions(ast.test, $filter, astIsPure);
  13964. findConstantAndWatchExpressions(ast.alternate, $filter, astIsPure);
  13965. findConstantAndWatchExpressions(ast.consequent, $filter, astIsPure);
  13966. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  13967. ast.toWatch = ast.constant ? [] : [ast];
  13968. break;
  13969. case AST.Identifier:
  13970. ast.constant = false;
  13971. ast.toWatch = [ast];
  13972. break;
  13973. case AST.MemberExpression:
  13974. findConstantAndWatchExpressions(ast.object, $filter, astIsPure);
  13975. if (ast.computed) {
  13976. findConstantAndWatchExpressions(ast.property, $filter, astIsPure);
  13977. }
  13978. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  13979. ast.toWatch = ast.constant ? [] : [ast];
  13980. break;
  13981. case AST.CallExpression:
  13982. isStatelessFilter = ast.filter ? isStateless($filter, ast.callee.name) : false;
  13983. allConstants = isStatelessFilter;
  13984. argsToWatch = [];
  13985. forEach(ast.arguments, function(expr) {
  13986. findConstantAndWatchExpressions(expr, $filter, astIsPure);
  13987. allConstants = allConstants && expr.constant;
  13988. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  13989. });
  13990. ast.constant = allConstants;
  13991. ast.toWatch = isStatelessFilter ? argsToWatch : [ast];
  13992. break;
  13993. case AST.AssignmentExpression:
  13994. findConstantAndWatchExpressions(ast.left, $filter, astIsPure);
  13995. findConstantAndWatchExpressions(ast.right, $filter, astIsPure);
  13996. ast.constant = ast.left.constant && ast.right.constant;
  13997. ast.toWatch = [ast];
  13998. break;
  13999. case AST.ArrayExpression:
  14000. allConstants = true;
  14001. argsToWatch = [];
  14002. forEach(ast.elements, function(expr) {
  14003. findConstantAndWatchExpressions(expr, $filter, astIsPure);
  14004. allConstants = allConstants && expr.constant;
  14005. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  14006. });
  14007. ast.constant = allConstants;
  14008. ast.toWatch = argsToWatch;
  14009. break;
  14010. case AST.ObjectExpression:
  14011. allConstants = true;
  14012. argsToWatch = [];
  14013. forEach(ast.properties, function(property) {
  14014. findConstantAndWatchExpressions(property.value, $filter, astIsPure);
  14015. allConstants = allConstants && property.value.constant;
  14016. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  14017. if (property.computed) {
  14018. //`{[key]: value}` implicitly does `key.toString()` which may be non-pure
  14019. findConstantAndWatchExpressions(property.key, $filter, /*parentIsPure=*/false);
  14020. allConstants = allConstants && property.key.constant;
  14021. argsToWatch.push.apply(argsToWatch, property.key.toWatch);
  14022. }
  14023. });
  14024. ast.constant = allConstants;
  14025. ast.toWatch = argsToWatch;
  14026. break;
  14027. case AST.ThisExpression:
  14028. ast.constant = false;
  14029. ast.toWatch = [];
  14030. break;
  14031. case AST.LocalsExpression:
  14032. ast.constant = false;
  14033. ast.toWatch = [];
  14034. break;
  14035. }
  14036. }
  14037. function getInputs(body) {
  14038. if (body.length !== 1) return;
  14039. var lastExpression = body[0].expression;
  14040. var candidate = lastExpression.toWatch;
  14041. if (candidate.length !== 1) return candidate;
  14042. return candidate[0] !== lastExpression ? candidate : undefined;
  14043. }
  14044. function isAssignable(ast) {
  14045. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  14046. }
  14047. function assignableAST(ast) {
  14048. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  14049. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  14050. }
  14051. }
  14052. function isLiteral(ast) {
  14053. return ast.body.length === 0 ||
  14054. ast.body.length === 1 && (
  14055. ast.body[0].expression.type === AST.Literal ||
  14056. ast.body[0].expression.type === AST.ArrayExpression ||
  14057. ast.body[0].expression.type === AST.ObjectExpression);
  14058. }
  14059. function isConstant(ast) {
  14060. return ast.constant;
  14061. }
  14062. function ASTCompiler($filter) {
  14063. this.$filter = $filter;
  14064. }
  14065. ASTCompiler.prototype = {
  14066. compile: function(ast) {
  14067. var self = this;
  14068. this.state = {
  14069. nextId: 0,
  14070. filters: {},
  14071. fn: {vars: [], body: [], own: {}},
  14072. assign: {vars: [], body: [], own: {}},
  14073. inputs: []
  14074. };
  14075. findConstantAndWatchExpressions(ast, self.$filter);
  14076. var extra = '';
  14077. var assignable;
  14078. this.stage = 'assign';
  14079. if ((assignable = assignableAST(ast))) {
  14080. this.state.computing = 'assign';
  14081. var result = this.nextId();
  14082. this.recurse(assignable, result);
  14083. this.return_(result);
  14084. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  14085. }
  14086. var toWatch = getInputs(ast.body);
  14087. self.stage = 'inputs';
  14088. forEach(toWatch, function(watch, key) {
  14089. var fnKey = 'fn' + key;
  14090. self.state[fnKey] = {vars: [], body: [], own: {}};
  14091. self.state.computing = fnKey;
  14092. var intoId = self.nextId();
  14093. self.recurse(watch, intoId);
  14094. self.return_(intoId);
  14095. self.state.inputs.push({name: fnKey, isPure: watch.isPure});
  14096. watch.watchId = key;
  14097. });
  14098. this.state.computing = 'fn';
  14099. this.stage = 'main';
  14100. this.recurse(ast);
  14101. var fnString =
  14102. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  14103. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  14104. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  14105. this.filterPrefix() +
  14106. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  14107. extra +
  14108. this.watchFns() +
  14109. 'return fn;';
  14110. // eslint-disable-next-line no-new-func
  14111. var fn = (new Function('$filter',
  14112. 'getStringValue',
  14113. 'ifDefined',
  14114. 'plus',
  14115. fnString))(
  14116. this.$filter,
  14117. getStringValue,
  14118. ifDefined,
  14119. plusFn);
  14120. this.state = this.stage = undefined;
  14121. return fn;
  14122. },
  14123. USE: 'use',
  14124. STRICT: 'strict',
  14125. watchFns: function() {
  14126. var result = [];
  14127. var inputs = this.state.inputs;
  14128. var self = this;
  14129. forEach(inputs, function(input) {
  14130. result.push('var ' + input.name + '=' + self.generateFunction(input.name, 's'));
  14131. if (input.isPure) {
  14132. result.push(input.name, '.isPure=' + JSON.stringify(input.isPure) + ';');
  14133. }
  14134. });
  14135. if (inputs.length) {
  14136. result.push('fn.inputs=[' + inputs.map(function(i) { return i.name; }).join(',') + '];');
  14137. }
  14138. return result.join('');
  14139. },
  14140. generateFunction: function(name, params) {
  14141. return 'function(' + params + '){' +
  14142. this.varsPrefix(name) +
  14143. this.body(name) +
  14144. '};';
  14145. },
  14146. filterPrefix: function() {
  14147. var parts = [];
  14148. var self = this;
  14149. forEach(this.state.filters, function(id, filter) {
  14150. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  14151. });
  14152. if (parts.length) return 'var ' + parts.join(',') + ';';
  14153. return '';
  14154. },
  14155. varsPrefix: function(section) {
  14156. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  14157. },
  14158. body: function(section) {
  14159. return this.state[section].body.join('');
  14160. },
  14161. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  14162. var left, right, self = this, args, expression, computed;
  14163. recursionFn = recursionFn || noop;
  14164. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  14165. intoId = intoId || this.nextId();
  14166. this.if_('i',
  14167. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  14168. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  14169. );
  14170. return;
  14171. }
  14172. switch (ast.type) {
  14173. case AST.Program:
  14174. forEach(ast.body, function(expression, pos) {
  14175. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  14176. if (pos !== ast.body.length - 1) {
  14177. self.current().body.push(right, ';');
  14178. } else {
  14179. self.return_(right);
  14180. }
  14181. });
  14182. break;
  14183. case AST.Literal:
  14184. expression = this.escape(ast.value);
  14185. this.assign(intoId, expression);
  14186. recursionFn(intoId || expression);
  14187. break;
  14188. case AST.UnaryExpression:
  14189. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  14190. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  14191. this.assign(intoId, expression);
  14192. recursionFn(expression);
  14193. break;
  14194. case AST.BinaryExpression:
  14195. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  14196. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  14197. if (ast.operator === '+') {
  14198. expression = this.plus(left, right);
  14199. } else if (ast.operator === '-') {
  14200. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  14201. } else {
  14202. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  14203. }
  14204. this.assign(intoId, expression);
  14205. recursionFn(expression);
  14206. break;
  14207. case AST.LogicalExpression:
  14208. intoId = intoId || this.nextId();
  14209. self.recurse(ast.left, intoId);
  14210. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  14211. recursionFn(intoId);
  14212. break;
  14213. case AST.ConditionalExpression:
  14214. intoId = intoId || this.nextId();
  14215. self.recurse(ast.test, intoId);
  14216. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  14217. recursionFn(intoId);
  14218. break;
  14219. case AST.Identifier:
  14220. intoId = intoId || this.nextId();
  14221. if (nameId) {
  14222. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  14223. nameId.computed = false;
  14224. nameId.name = ast.name;
  14225. }
  14226. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  14227. function() {
  14228. self.if_(self.stage === 'inputs' || 's', function() {
  14229. if (create && create !== 1) {
  14230. self.if_(
  14231. self.isNull(self.nonComputedMember('s', ast.name)),
  14232. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  14233. }
  14234. self.assign(intoId, self.nonComputedMember('s', ast.name));
  14235. });
  14236. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  14237. );
  14238. recursionFn(intoId);
  14239. break;
  14240. case AST.MemberExpression:
  14241. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  14242. intoId = intoId || this.nextId();
  14243. self.recurse(ast.object, left, undefined, function() {
  14244. self.if_(self.notNull(left), function() {
  14245. if (ast.computed) {
  14246. right = self.nextId();
  14247. self.recurse(ast.property, right);
  14248. self.getStringValue(right);
  14249. if (create && create !== 1) {
  14250. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  14251. }
  14252. expression = self.computedMember(left, right);
  14253. self.assign(intoId, expression);
  14254. if (nameId) {
  14255. nameId.computed = true;
  14256. nameId.name = right;
  14257. }
  14258. } else {
  14259. if (create && create !== 1) {
  14260. self.if_(self.isNull(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  14261. }
  14262. expression = self.nonComputedMember(left, ast.property.name);
  14263. self.assign(intoId, expression);
  14264. if (nameId) {
  14265. nameId.computed = false;
  14266. nameId.name = ast.property.name;
  14267. }
  14268. }
  14269. }, function() {
  14270. self.assign(intoId, 'undefined');
  14271. });
  14272. recursionFn(intoId);
  14273. }, !!create);
  14274. break;
  14275. case AST.CallExpression:
  14276. intoId = intoId || this.nextId();
  14277. if (ast.filter) {
  14278. right = self.filter(ast.callee.name);
  14279. args = [];
  14280. forEach(ast.arguments, function(expr) {
  14281. var argument = self.nextId();
  14282. self.recurse(expr, argument);
  14283. args.push(argument);
  14284. });
  14285. expression = right + '(' + args.join(',') + ')';
  14286. self.assign(intoId, expression);
  14287. recursionFn(intoId);
  14288. } else {
  14289. right = self.nextId();
  14290. left = {};
  14291. args = [];
  14292. self.recurse(ast.callee, right, left, function() {
  14293. self.if_(self.notNull(right), function() {
  14294. forEach(ast.arguments, function(expr) {
  14295. self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
  14296. args.push(argument);
  14297. });
  14298. });
  14299. if (left.name) {
  14300. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  14301. } else {
  14302. expression = right + '(' + args.join(',') + ')';
  14303. }
  14304. self.assign(intoId, expression);
  14305. }, function() {
  14306. self.assign(intoId, 'undefined');
  14307. });
  14308. recursionFn(intoId);
  14309. });
  14310. }
  14311. break;
  14312. case AST.AssignmentExpression:
  14313. right = this.nextId();
  14314. left = {};
  14315. this.recurse(ast.left, undefined, left, function() {
  14316. self.if_(self.notNull(left.context), function() {
  14317. self.recurse(ast.right, right);
  14318. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  14319. self.assign(intoId, expression);
  14320. recursionFn(intoId || expression);
  14321. });
  14322. }, 1);
  14323. break;
  14324. case AST.ArrayExpression:
  14325. args = [];
  14326. forEach(ast.elements, function(expr) {
  14327. self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
  14328. args.push(argument);
  14329. });
  14330. });
  14331. expression = '[' + args.join(',') + ']';
  14332. this.assign(intoId, expression);
  14333. recursionFn(intoId || expression);
  14334. break;
  14335. case AST.ObjectExpression:
  14336. args = [];
  14337. computed = false;
  14338. forEach(ast.properties, function(property) {
  14339. if (property.computed) {
  14340. computed = true;
  14341. }
  14342. });
  14343. if (computed) {
  14344. intoId = intoId || this.nextId();
  14345. this.assign(intoId, '{}');
  14346. forEach(ast.properties, function(property) {
  14347. if (property.computed) {
  14348. left = self.nextId();
  14349. self.recurse(property.key, left);
  14350. } else {
  14351. left = property.key.type === AST.Identifier ?
  14352. property.key.name :
  14353. ('' + property.key.value);
  14354. }
  14355. right = self.nextId();
  14356. self.recurse(property.value, right);
  14357. self.assign(self.member(intoId, left, property.computed), right);
  14358. });
  14359. } else {
  14360. forEach(ast.properties, function(property) {
  14361. self.recurse(property.value, ast.constant ? undefined : self.nextId(), undefined, function(expr) {
  14362. args.push(self.escape(
  14363. property.key.type === AST.Identifier ? property.key.name :
  14364. ('' + property.key.value)) +
  14365. ':' + expr);
  14366. });
  14367. });
  14368. expression = '{' + args.join(',') + '}';
  14369. this.assign(intoId, expression);
  14370. }
  14371. recursionFn(intoId || expression);
  14372. break;
  14373. case AST.ThisExpression:
  14374. this.assign(intoId, 's');
  14375. recursionFn(intoId || 's');
  14376. break;
  14377. case AST.LocalsExpression:
  14378. this.assign(intoId, 'l');
  14379. recursionFn(intoId || 'l');
  14380. break;
  14381. case AST.NGValueParameter:
  14382. this.assign(intoId, 'v');
  14383. recursionFn(intoId || 'v');
  14384. break;
  14385. }
  14386. },
  14387. getHasOwnProperty: function(element, property) {
  14388. var key = element + '.' + property;
  14389. var own = this.current().own;
  14390. if (!own.hasOwnProperty(key)) {
  14391. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  14392. }
  14393. return own[key];
  14394. },
  14395. assign: function(id, value) {
  14396. if (!id) return;
  14397. this.current().body.push(id, '=', value, ';');
  14398. return id;
  14399. },
  14400. filter: function(filterName) {
  14401. if (!this.state.filters.hasOwnProperty(filterName)) {
  14402. this.state.filters[filterName] = this.nextId(true);
  14403. }
  14404. return this.state.filters[filterName];
  14405. },
  14406. ifDefined: function(id, defaultValue) {
  14407. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  14408. },
  14409. plus: function(left, right) {
  14410. return 'plus(' + left + ',' + right + ')';
  14411. },
  14412. return_: function(id) {
  14413. this.current().body.push('return ', id, ';');
  14414. },
  14415. if_: function(test, alternate, consequent) {
  14416. if (test === true) {
  14417. alternate();
  14418. } else {
  14419. var body = this.current().body;
  14420. body.push('if(', test, '){');
  14421. alternate();
  14422. body.push('}');
  14423. if (consequent) {
  14424. body.push('else{');
  14425. consequent();
  14426. body.push('}');
  14427. }
  14428. }
  14429. },
  14430. not: function(expression) {
  14431. return '!(' + expression + ')';
  14432. },
  14433. isNull: function(expression) {
  14434. return expression + '==null';
  14435. },
  14436. notNull: function(expression) {
  14437. return expression + '!=null';
  14438. },
  14439. nonComputedMember: function(left, right) {
  14440. var SAFE_IDENTIFIER = /^[$_a-zA-Z][$_a-zA-Z0-9]*$/;
  14441. var UNSAFE_CHARACTERS = /[^$_a-zA-Z0-9]/g;
  14442. if (SAFE_IDENTIFIER.test(right)) {
  14443. return left + '.' + right;
  14444. } else {
  14445. return left + '["' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '"]';
  14446. }
  14447. },
  14448. computedMember: function(left, right) {
  14449. return left + '[' + right + ']';
  14450. },
  14451. member: function(left, right, computed) {
  14452. if (computed) return this.computedMember(left, right);
  14453. return this.nonComputedMember(left, right);
  14454. },
  14455. getStringValue: function(item) {
  14456. this.assign(item, 'getStringValue(' + item + ')');
  14457. },
  14458. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  14459. var self = this;
  14460. return function() {
  14461. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  14462. };
  14463. },
  14464. lazyAssign: function(id, value) {
  14465. var self = this;
  14466. return function() {
  14467. self.assign(id, value);
  14468. };
  14469. },
  14470. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  14471. stringEscapeFn: function(c) {
  14472. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  14473. },
  14474. escape: function(value) {
  14475. if (isString(value)) return '\'' + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + '\'';
  14476. if (isNumber(value)) return value.toString();
  14477. if (value === true) return 'true';
  14478. if (value === false) return 'false';
  14479. if (value === null) return 'null';
  14480. if (typeof value === 'undefined') return 'undefined';
  14481. throw $parseMinErr('esc', 'IMPOSSIBLE');
  14482. },
  14483. nextId: function(skip, init) {
  14484. var id = 'v' + (this.state.nextId++);
  14485. if (!skip) {
  14486. this.current().vars.push(id + (init ? '=' + init : ''));
  14487. }
  14488. return id;
  14489. },
  14490. current: function() {
  14491. return this.state[this.state.computing];
  14492. }
  14493. };
  14494. function ASTInterpreter($filter) {
  14495. this.$filter = $filter;
  14496. }
  14497. ASTInterpreter.prototype = {
  14498. compile: function(ast) {
  14499. var self = this;
  14500. findConstantAndWatchExpressions(ast, self.$filter);
  14501. var assignable;
  14502. var assign;
  14503. if ((assignable = assignableAST(ast))) {
  14504. assign = this.recurse(assignable);
  14505. }
  14506. var toWatch = getInputs(ast.body);
  14507. var inputs;
  14508. if (toWatch) {
  14509. inputs = [];
  14510. forEach(toWatch, function(watch, key) {
  14511. var input = self.recurse(watch);
  14512. input.isPure = watch.isPure;
  14513. watch.input = input;
  14514. inputs.push(input);
  14515. watch.watchId = key;
  14516. });
  14517. }
  14518. var expressions = [];
  14519. forEach(ast.body, function(expression) {
  14520. expressions.push(self.recurse(expression.expression));
  14521. });
  14522. var fn = ast.body.length === 0 ? noop :
  14523. ast.body.length === 1 ? expressions[0] :
  14524. function(scope, locals) {
  14525. var lastValue;
  14526. forEach(expressions, function(exp) {
  14527. lastValue = exp(scope, locals);
  14528. });
  14529. return lastValue;
  14530. };
  14531. if (assign) {
  14532. fn.assign = function(scope, value, locals) {
  14533. return assign(scope, locals, value);
  14534. };
  14535. }
  14536. if (inputs) {
  14537. fn.inputs = inputs;
  14538. }
  14539. return fn;
  14540. },
  14541. recurse: function(ast, context, create) {
  14542. var left, right, self = this, args;
  14543. if (ast.input) {
  14544. return this.inputs(ast.input, ast.watchId);
  14545. }
  14546. switch (ast.type) {
  14547. case AST.Literal:
  14548. return this.value(ast.value, context);
  14549. case AST.UnaryExpression:
  14550. right = this.recurse(ast.argument);
  14551. return this['unary' + ast.operator](right, context);
  14552. case AST.BinaryExpression:
  14553. left = this.recurse(ast.left);
  14554. right = this.recurse(ast.right);
  14555. return this['binary' + ast.operator](left, right, context);
  14556. case AST.LogicalExpression:
  14557. left = this.recurse(ast.left);
  14558. right = this.recurse(ast.right);
  14559. return this['binary' + ast.operator](left, right, context);
  14560. case AST.ConditionalExpression:
  14561. return this['ternary?:'](
  14562. this.recurse(ast.test),
  14563. this.recurse(ast.alternate),
  14564. this.recurse(ast.consequent),
  14565. context
  14566. );
  14567. case AST.Identifier:
  14568. return self.identifier(ast.name, context, create);
  14569. case AST.MemberExpression:
  14570. left = this.recurse(ast.object, false, !!create);
  14571. if (!ast.computed) {
  14572. right = ast.property.name;
  14573. }
  14574. if (ast.computed) right = this.recurse(ast.property);
  14575. return ast.computed ?
  14576. this.computedMember(left, right, context, create) :
  14577. this.nonComputedMember(left, right, context, create);
  14578. case AST.CallExpression:
  14579. args = [];
  14580. forEach(ast.arguments, function(expr) {
  14581. args.push(self.recurse(expr));
  14582. });
  14583. if (ast.filter) right = this.$filter(ast.callee.name);
  14584. if (!ast.filter) right = this.recurse(ast.callee, true);
  14585. return ast.filter ?
  14586. function(scope, locals, assign, inputs) {
  14587. var values = [];
  14588. for (var i = 0; i < args.length; ++i) {
  14589. values.push(args[i](scope, locals, assign, inputs));
  14590. }
  14591. var value = right.apply(undefined, values, inputs);
  14592. return context ? {context: undefined, name: undefined, value: value} : value;
  14593. } :
  14594. function(scope, locals, assign, inputs) {
  14595. var rhs = right(scope, locals, assign, inputs);
  14596. var value;
  14597. if (rhs.value != null) {
  14598. var values = [];
  14599. for (var i = 0; i < args.length; ++i) {
  14600. values.push(args[i](scope, locals, assign, inputs));
  14601. }
  14602. value = rhs.value.apply(rhs.context, values);
  14603. }
  14604. return context ? {value: value} : value;
  14605. };
  14606. case AST.AssignmentExpression:
  14607. left = this.recurse(ast.left, true, 1);
  14608. right = this.recurse(ast.right);
  14609. return function(scope, locals, assign, inputs) {
  14610. var lhs = left(scope, locals, assign, inputs);
  14611. var rhs = right(scope, locals, assign, inputs);
  14612. lhs.context[lhs.name] = rhs;
  14613. return context ? {value: rhs} : rhs;
  14614. };
  14615. case AST.ArrayExpression:
  14616. args = [];
  14617. forEach(ast.elements, function(expr) {
  14618. args.push(self.recurse(expr));
  14619. });
  14620. return function(scope, locals, assign, inputs) {
  14621. var value = [];
  14622. for (var i = 0; i < args.length; ++i) {
  14623. value.push(args[i](scope, locals, assign, inputs));
  14624. }
  14625. return context ? {value: value} : value;
  14626. };
  14627. case AST.ObjectExpression:
  14628. args = [];
  14629. forEach(ast.properties, function(property) {
  14630. if (property.computed) {
  14631. args.push({key: self.recurse(property.key),
  14632. computed: true,
  14633. value: self.recurse(property.value)
  14634. });
  14635. } else {
  14636. args.push({key: property.key.type === AST.Identifier ?
  14637. property.key.name :
  14638. ('' + property.key.value),
  14639. computed: false,
  14640. value: self.recurse(property.value)
  14641. });
  14642. }
  14643. });
  14644. return function(scope, locals, assign, inputs) {
  14645. var value = {};
  14646. for (var i = 0; i < args.length; ++i) {
  14647. if (args[i].computed) {
  14648. value[args[i].key(scope, locals, assign, inputs)] = args[i].value(scope, locals, assign, inputs);
  14649. } else {
  14650. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  14651. }
  14652. }
  14653. return context ? {value: value} : value;
  14654. };
  14655. case AST.ThisExpression:
  14656. return function(scope) {
  14657. return context ? {value: scope} : scope;
  14658. };
  14659. case AST.LocalsExpression:
  14660. return function(scope, locals) {
  14661. return context ? {value: locals} : locals;
  14662. };
  14663. case AST.NGValueParameter:
  14664. return function(scope, locals, assign) {
  14665. return context ? {value: assign} : assign;
  14666. };
  14667. }
  14668. },
  14669. 'unary+': function(argument, context) {
  14670. return function(scope, locals, assign, inputs) {
  14671. var arg = argument(scope, locals, assign, inputs);
  14672. if (isDefined(arg)) {
  14673. arg = +arg;
  14674. } else {
  14675. arg = 0;
  14676. }
  14677. return context ? {value: arg} : arg;
  14678. };
  14679. },
  14680. 'unary-': function(argument, context) {
  14681. return function(scope, locals, assign, inputs) {
  14682. var arg = argument(scope, locals, assign, inputs);
  14683. if (isDefined(arg)) {
  14684. arg = -arg;
  14685. } else {
  14686. arg = -0;
  14687. }
  14688. return context ? {value: arg} : arg;
  14689. };
  14690. },
  14691. 'unary!': function(argument, context) {
  14692. return function(scope, locals, assign, inputs) {
  14693. var arg = !argument(scope, locals, assign, inputs);
  14694. return context ? {value: arg} : arg;
  14695. };
  14696. },
  14697. 'binary+': function(left, right, context) {
  14698. return function(scope, locals, assign, inputs) {
  14699. var lhs = left(scope, locals, assign, inputs);
  14700. var rhs = right(scope, locals, assign, inputs);
  14701. var arg = plusFn(lhs, rhs);
  14702. return context ? {value: arg} : arg;
  14703. };
  14704. },
  14705. 'binary-': function(left, right, context) {
  14706. return function(scope, locals, assign, inputs) {
  14707. var lhs = left(scope, locals, assign, inputs);
  14708. var rhs = right(scope, locals, assign, inputs);
  14709. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  14710. return context ? {value: arg} : arg;
  14711. };
  14712. },
  14713. 'binary*': function(left, right, context) {
  14714. return function(scope, locals, assign, inputs) {
  14715. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  14716. return context ? {value: arg} : arg;
  14717. };
  14718. },
  14719. 'binary/': function(left, right, context) {
  14720. return function(scope, locals, assign, inputs) {
  14721. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  14722. return context ? {value: arg} : arg;
  14723. };
  14724. },
  14725. 'binary%': function(left, right, context) {
  14726. return function(scope, locals, assign, inputs) {
  14727. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  14728. return context ? {value: arg} : arg;
  14729. };
  14730. },
  14731. 'binary===': function(left, right, context) {
  14732. return function(scope, locals, assign, inputs) {
  14733. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  14734. return context ? {value: arg} : arg;
  14735. };
  14736. },
  14737. 'binary!==': function(left, right, context) {
  14738. return function(scope, locals, assign, inputs) {
  14739. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  14740. return context ? {value: arg} : arg;
  14741. };
  14742. },
  14743. 'binary==': function(left, right, context) {
  14744. return function(scope, locals, assign, inputs) {
  14745. // eslint-disable-next-line eqeqeq
  14746. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  14747. return context ? {value: arg} : arg;
  14748. };
  14749. },
  14750. 'binary!=': function(left, right, context) {
  14751. return function(scope, locals, assign, inputs) {
  14752. // eslint-disable-next-line eqeqeq
  14753. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  14754. return context ? {value: arg} : arg;
  14755. };
  14756. },
  14757. 'binary<': function(left, right, context) {
  14758. return function(scope, locals, assign, inputs) {
  14759. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  14760. return context ? {value: arg} : arg;
  14761. };
  14762. },
  14763. 'binary>': function(left, right, context) {
  14764. return function(scope, locals, assign, inputs) {
  14765. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  14766. return context ? {value: arg} : arg;
  14767. };
  14768. },
  14769. 'binary<=': function(left, right, context) {
  14770. return function(scope, locals, assign, inputs) {
  14771. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  14772. return context ? {value: arg} : arg;
  14773. };
  14774. },
  14775. 'binary>=': function(left, right, context) {
  14776. return function(scope, locals, assign, inputs) {
  14777. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  14778. return context ? {value: arg} : arg;
  14779. };
  14780. },
  14781. 'binary&&': function(left, right, context) {
  14782. return function(scope, locals, assign, inputs) {
  14783. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  14784. return context ? {value: arg} : arg;
  14785. };
  14786. },
  14787. 'binary||': function(left, right, context) {
  14788. return function(scope, locals, assign, inputs) {
  14789. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  14790. return context ? {value: arg} : arg;
  14791. };
  14792. },
  14793. 'ternary?:': function(test, alternate, consequent, context) {
  14794. return function(scope, locals, assign, inputs) {
  14795. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  14796. return context ? {value: arg} : arg;
  14797. };
  14798. },
  14799. value: function(value, context) {
  14800. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  14801. },
  14802. identifier: function(name, context, create) {
  14803. return function(scope, locals, assign, inputs) {
  14804. var base = locals && (name in locals) ? locals : scope;
  14805. if (create && create !== 1 && base && base[name] == null) {
  14806. base[name] = {};
  14807. }
  14808. var value = base ? base[name] : undefined;
  14809. if (context) {
  14810. return {context: base, name: name, value: value};
  14811. } else {
  14812. return value;
  14813. }
  14814. };
  14815. },
  14816. computedMember: function(left, right, context, create) {
  14817. return function(scope, locals, assign, inputs) {
  14818. var lhs = left(scope, locals, assign, inputs);
  14819. var rhs;
  14820. var value;
  14821. if (lhs != null) {
  14822. rhs = right(scope, locals, assign, inputs);
  14823. rhs = getStringValue(rhs);
  14824. if (create && create !== 1) {
  14825. if (lhs && !(lhs[rhs])) {
  14826. lhs[rhs] = {};
  14827. }
  14828. }
  14829. value = lhs[rhs];
  14830. }
  14831. if (context) {
  14832. return {context: lhs, name: rhs, value: value};
  14833. } else {
  14834. return value;
  14835. }
  14836. };
  14837. },
  14838. nonComputedMember: function(left, right, context, create) {
  14839. return function(scope, locals, assign, inputs) {
  14840. var lhs = left(scope, locals, assign, inputs);
  14841. if (create && create !== 1) {
  14842. if (lhs && lhs[right] == null) {
  14843. lhs[right] = {};
  14844. }
  14845. }
  14846. var value = lhs != null ? lhs[right] : undefined;
  14847. if (context) {
  14848. return {context: lhs, name: right, value: value};
  14849. } else {
  14850. return value;
  14851. }
  14852. };
  14853. },
  14854. inputs: function(input, watchId) {
  14855. return function(scope, value, locals, inputs) {
  14856. if (inputs) return inputs[watchId];
  14857. return input(scope, value, locals);
  14858. };
  14859. }
  14860. };
  14861. /**
  14862. * @constructor
  14863. */
  14864. function Parser(lexer, $filter, options) {
  14865. this.ast = new AST(lexer, options);
  14866. this.astCompiler = options.csp ? new ASTInterpreter($filter) :
  14867. new ASTCompiler($filter);
  14868. }
  14869. Parser.prototype = {
  14870. constructor: Parser,
  14871. parse: function(text) {
  14872. var ast = this.ast.ast(text);
  14873. var fn = this.astCompiler.compile(ast);
  14874. fn.literal = isLiteral(ast);
  14875. fn.constant = isConstant(ast);
  14876. return fn;
  14877. }
  14878. };
  14879. function getValueOf(value) {
  14880. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  14881. }
  14882. ///////////////////////////////////
  14883. /**
  14884. * @ngdoc service
  14885. * @name $parse
  14886. * @kind function
  14887. *
  14888. * @description
  14889. *
  14890. * Converts Angular {@link guide/expression expression} into a function.
  14891. *
  14892. * ```js
  14893. * var getter = $parse('user.name');
  14894. * var setter = getter.assign;
  14895. * var context = {user:{name:'angular'}};
  14896. * var locals = {user:{name:'local'}};
  14897. *
  14898. * expect(getter(context)).toEqual('angular');
  14899. * setter(context, 'newValue');
  14900. * expect(context.user.name).toEqual('newValue');
  14901. * expect(getter(context, locals)).toEqual('local');
  14902. * ```
  14903. *
  14904. *
  14905. * @param {string} expression String expression to compile.
  14906. * @returns {function(context, locals)} a function which represents the compiled expression:
  14907. *
  14908. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14909. * are evaluated against (typically a scope object).
  14910. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14911. * `context`.
  14912. *
  14913. * The returned function also has the following properties:
  14914. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  14915. * literal.
  14916. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  14917. * constant literals.
  14918. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  14919. * set to a function to change its value on the given context.
  14920. *
  14921. */
  14922. /**
  14923. * @ngdoc provider
  14924. * @name $parseProvider
  14925. * @this
  14926. *
  14927. * @description
  14928. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  14929. * service.
  14930. */
  14931. function $ParseProvider() {
  14932. var cache = createMap();
  14933. var literals = {
  14934. 'true': true,
  14935. 'false': false,
  14936. 'null': null,
  14937. 'undefined': undefined
  14938. };
  14939. var identStart, identContinue;
  14940. /**
  14941. * @ngdoc method
  14942. * @name $parseProvider#addLiteral
  14943. * @description
  14944. *
  14945. * Configure $parse service to add literal values that will be present as literal at expressions.
  14946. *
  14947. * @param {string} literalName Token for the literal value. The literal name value must be a valid literal name.
  14948. * @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`.
  14949. *
  14950. **/
  14951. this.addLiteral = function(literalName, literalValue) {
  14952. literals[literalName] = literalValue;
  14953. };
  14954. /**
  14955. * @ngdoc method
  14956. * @name $parseProvider#setIdentifierFns
  14957. *
  14958. * @description
  14959. *
  14960. * Allows defining the set of characters that are allowed in Angular expressions. The function
  14961. * `identifierStart` will get called to know if a given character is a valid character to be the
  14962. * first character for an identifier. The function `identifierContinue` will get called to know if
  14963. * a given character is a valid character to be a follow-up identifier character. The functions
  14964. * `identifierStart` and `identifierContinue` will receive as arguments the single character to be
  14965. * identifier and the character code point. These arguments will be `string` and `numeric`. Keep in
  14966. * mind that the `string` parameter can be two characters long depending on the character
  14967. * representation. It is expected for the function to return `true` or `false`, whether that
  14968. * character is allowed or not.
  14969. *
  14970. * Since this function will be called extensively, keep the implementation of these functions fast,
  14971. * as the performance of these functions have a direct impact on the expressions parsing speed.
  14972. *
  14973. * @param {function=} identifierStart The function that will decide whether the given character is
  14974. * a valid identifier start character.
  14975. * @param {function=} identifierContinue The function that will decide whether the given character is
  14976. * a valid identifier continue character.
  14977. */
  14978. this.setIdentifierFns = function(identifierStart, identifierContinue) {
  14979. identStart = identifierStart;
  14980. identContinue = identifierContinue;
  14981. return this;
  14982. };
  14983. this.$get = ['$filter', function($filter) {
  14984. var noUnsafeEval = csp().noUnsafeEval;
  14985. var $parseOptions = {
  14986. csp: noUnsafeEval,
  14987. literals: copy(literals),
  14988. isIdentifierStart: isFunction(identStart) && identStart,
  14989. isIdentifierContinue: isFunction(identContinue) && identContinue
  14990. };
  14991. return $parse;
  14992. function $parse(exp, interceptorFn) {
  14993. var parsedExpression, oneTime, cacheKey;
  14994. switch (typeof exp) {
  14995. case 'string':
  14996. exp = exp.trim();
  14997. cacheKey = exp;
  14998. parsedExpression = cache[cacheKey];
  14999. if (!parsedExpression) {
  15000. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  15001. oneTime = true;
  15002. exp = exp.substring(2);
  15003. }
  15004. var lexer = new Lexer($parseOptions);
  15005. var parser = new Parser(lexer, $filter, $parseOptions);
  15006. parsedExpression = parser.parse(exp);
  15007. if (parsedExpression.constant) {
  15008. parsedExpression.$$watchDelegate = constantWatchDelegate;
  15009. } else if (oneTime) {
  15010. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  15011. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  15012. } else if (parsedExpression.inputs) {
  15013. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  15014. }
  15015. cache[cacheKey] = parsedExpression;
  15016. }
  15017. return addInterceptor(parsedExpression, interceptorFn);
  15018. case 'function':
  15019. return addInterceptor(exp, interceptorFn);
  15020. default:
  15021. return addInterceptor(noop, interceptorFn);
  15022. }
  15023. }
  15024. function expressionInputDirtyCheck(newValue, oldValueOfValue, compareObjectIdentity) {
  15025. if (newValue == null || oldValueOfValue == null) { // null/undefined
  15026. return newValue === oldValueOfValue;
  15027. }
  15028. if (typeof newValue === 'object') {
  15029. // attempt to convert the value to a primitive type
  15030. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  15031. // be cheaply dirty-checked
  15032. newValue = getValueOf(newValue);
  15033. if (typeof newValue === 'object' && !compareObjectIdentity) {
  15034. // objects/arrays are not supported - deep-watching them would be too expensive
  15035. return false;
  15036. }
  15037. // fall-through to the primitive equality check
  15038. }
  15039. //Primitive or NaN
  15040. // eslint-disable-next-line no-self-compare
  15041. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  15042. }
  15043. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  15044. var inputExpressions = parsedExpression.inputs;
  15045. var lastResult;
  15046. if (inputExpressions.length === 1) {
  15047. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  15048. inputExpressions = inputExpressions[0];
  15049. return scope.$watch(function expressionInputWatch(scope) {
  15050. var newInputValue = inputExpressions(scope);
  15051. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf, inputExpressions.isPure)) {
  15052. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  15053. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  15054. }
  15055. return lastResult;
  15056. }, listener, objectEquality, prettyPrintExpression);
  15057. }
  15058. var oldInputValueOfValues = [];
  15059. var oldInputValues = [];
  15060. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  15061. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  15062. oldInputValues[i] = null;
  15063. }
  15064. return scope.$watch(function expressionInputsWatch(scope) {
  15065. var changed = false;
  15066. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  15067. var newInputValue = inputExpressions[i](scope);
  15068. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i], inputExpressions[i].isPure))) {
  15069. oldInputValues[i] = newInputValue;
  15070. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  15071. }
  15072. }
  15073. if (changed) {
  15074. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  15075. }
  15076. return lastResult;
  15077. }, listener, objectEquality, prettyPrintExpression);
  15078. }
  15079. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  15080. var unwatch, lastValue;
  15081. if (parsedExpression.inputs) {
  15082. unwatch = inputsWatchDelegate(scope, oneTimeListener, objectEquality, parsedExpression, prettyPrintExpression);
  15083. } else {
  15084. unwatch = scope.$watch(oneTimeWatch, oneTimeListener, objectEquality);
  15085. }
  15086. return unwatch;
  15087. function oneTimeWatch(scope) {
  15088. return parsedExpression(scope);
  15089. }
  15090. function oneTimeListener(value, old, scope) {
  15091. lastValue = value;
  15092. if (isFunction(listener)) {
  15093. listener(value, old, scope);
  15094. }
  15095. if (isDefined(value)) {
  15096. scope.$$postDigest(function() {
  15097. if (isDefined(lastValue)) {
  15098. unwatch();
  15099. }
  15100. });
  15101. }
  15102. }
  15103. }
  15104. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  15105. var unwatch, lastValue;
  15106. unwatch = scope.$watch(function oneTimeWatch(scope) {
  15107. return parsedExpression(scope);
  15108. }, function oneTimeListener(value, old, scope) {
  15109. lastValue = value;
  15110. if (isFunction(listener)) {
  15111. listener(value, old, scope);
  15112. }
  15113. if (isAllDefined(value)) {
  15114. scope.$$postDigest(function() {
  15115. if (isAllDefined(lastValue)) unwatch();
  15116. });
  15117. }
  15118. }, objectEquality);
  15119. return unwatch;
  15120. function isAllDefined(value) {
  15121. var allDefined = true;
  15122. forEach(value, function(val) {
  15123. if (!isDefined(val)) allDefined = false;
  15124. });
  15125. return allDefined;
  15126. }
  15127. }
  15128. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  15129. var unwatch = scope.$watch(function constantWatch(scope) {
  15130. unwatch();
  15131. return parsedExpression(scope);
  15132. }, listener, objectEquality);
  15133. return unwatch;
  15134. }
  15135. function addInterceptor(parsedExpression, interceptorFn) {
  15136. if (!interceptorFn) return parsedExpression;
  15137. var watchDelegate = parsedExpression.$$watchDelegate;
  15138. var useInputs = false;
  15139. var regularWatch =
  15140. watchDelegate !== oneTimeLiteralWatchDelegate &&
  15141. watchDelegate !== oneTimeWatchDelegate;
  15142. var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
  15143. var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
  15144. return interceptorFn(value, scope, locals);
  15145. } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
  15146. var value = parsedExpression(scope, locals, assign, inputs);
  15147. var result = interceptorFn(value, scope, locals);
  15148. // we only return the interceptor's result if the
  15149. // initial value is defined (for bind-once)
  15150. return isDefined(value) ? result : value;
  15151. };
  15152. // Propagate $$watchDelegates other then inputsWatchDelegate
  15153. useInputs = !parsedExpression.inputs;
  15154. if (watchDelegate && watchDelegate !== inputsWatchDelegate) {
  15155. fn.$$watchDelegate = watchDelegate;
  15156. fn.inputs = parsedExpression.inputs;
  15157. } else if (!interceptorFn.$stateful) {
  15158. // Treat interceptor like filters - assume non-stateful by default and use the inputsWatchDelegate
  15159. fn.$$watchDelegate = inputsWatchDelegate;
  15160. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  15161. }
  15162. if (fn.inputs) {
  15163. fn.inputs = fn.inputs.map(function(e) {
  15164. // Remove the isPure flag of inputs when it is not absolute because they are now wrapped in a
  15165. // potentially non-pure interceptor function.
  15166. if (e.isPure === PURITY_RELATIVE) {
  15167. return function depurifier(s) { return e(s); };
  15168. }
  15169. return e;
  15170. });
  15171. }
  15172. return fn;
  15173. }
  15174. }];
  15175. }
  15176. /**
  15177. * @ngdoc service
  15178. * @name $q
  15179. * @requires $rootScope
  15180. *
  15181. * @description
  15182. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  15183. * when they are done processing.
  15184. *
  15185. * This is a [Promises/A+](https://promisesaplus.com/)-compliant implementation of promises/deferred
  15186. * objects inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
  15187. *
  15188. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  15189. * implementations, and the other which resembles ES6 (ES2015) promises to some degree.
  15190. *
  15191. * ## $q constructor
  15192. *
  15193. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  15194. * function as the first argument. This is similar to the native Promise implementation from ES6,
  15195. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  15196. *
  15197. * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are
  15198. * available yet.
  15199. *
  15200. * It can be used like so:
  15201. *
  15202. * ```js
  15203. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  15204. * // are available in the current lexical scope (they could have been injected or passed in).
  15205. *
  15206. * function asyncGreet(name) {
  15207. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  15208. * return $q(function(resolve, reject) {
  15209. * setTimeout(function() {
  15210. * if (okToGreet(name)) {
  15211. * resolve('Hello, ' + name + '!');
  15212. * } else {
  15213. * reject('Greeting ' + name + ' is not allowed.');
  15214. * }
  15215. * }, 1000);
  15216. * });
  15217. * }
  15218. *
  15219. * var promise = asyncGreet('Robin Hood');
  15220. * promise.then(function(greeting) {
  15221. * alert('Success: ' + greeting);
  15222. * }, function(reason) {
  15223. * alert('Failed: ' + reason);
  15224. * });
  15225. * ```
  15226. *
  15227. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  15228. *
  15229. * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.
  15230. *
  15231. * However, the more traditional CommonJS-style usage is still available, and documented below.
  15232. *
  15233. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  15234. * interface for interacting with an object that represents the result of an action that is
  15235. * performed asynchronously, and may or may not be finished at any given point in time.
  15236. *
  15237. * From the perspective of dealing with error handling, deferred and promise APIs are to
  15238. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  15239. *
  15240. * ```js
  15241. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  15242. * // are available in the current lexical scope (they could have been injected or passed in).
  15243. *
  15244. * function asyncGreet(name) {
  15245. * var deferred = $q.defer();
  15246. *
  15247. * setTimeout(function() {
  15248. * deferred.notify('About to greet ' + name + '.');
  15249. *
  15250. * if (okToGreet(name)) {
  15251. * deferred.resolve('Hello, ' + name + '!');
  15252. * } else {
  15253. * deferred.reject('Greeting ' + name + ' is not allowed.');
  15254. * }
  15255. * }, 1000);
  15256. *
  15257. * return deferred.promise;
  15258. * }
  15259. *
  15260. * var promise = asyncGreet('Robin Hood');
  15261. * promise.then(function(greeting) {
  15262. * alert('Success: ' + greeting);
  15263. * }, function(reason) {
  15264. * alert('Failed: ' + reason);
  15265. * }, function(update) {
  15266. * alert('Got notification: ' + update);
  15267. * });
  15268. * ```
  15269. *
  15270. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  15271. * comes in the way of guarantees that promise and deferred APIs make, see
  15272. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  15273. *
  15274. * Additionally the promise api allows for composition that is very hard to do with the
  15275. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  15276. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  15277. * section on serial or parallel joining of promises.
  15278. *
  15279. * ## The Deferred API
  15280. *
  15281. * A new instance of deferred is constructed by calling `$q.defer()`.
  15282. *
  15283. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  15284. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  15285. * of the task.
  15286. *
  15287. * **Methods**
  15288. *
  15289. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  15290. * constructed via `$q.reject`, the promise will be rejected instead.
  15291. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  15292. * resolving it with a rejection constructed via `$q.reject`.
  15293. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  15294. * multiple times before the promise is either resolved or rejected.
  15295. *
  15296. * **Properties**
  15297. *
  15298. * - promise – `{Promise}` – promise object associated with this deferred.
  15299. *
  15300. *
  15301. * ## The Promise API
  15302. *
  15303. * A new promise instance is created when a deferred instance is created and can be retrieved by
  15304. * calling `deferred.promise`.
  15305. *
  15306. * The purpose of the promise object is to allow for interested parties to get access to the result
  15307. * of the deferred task when it completes.
  15308. *
  15309. * **Methods**
  15310. *
  15311. * - `then(successCallback, [errorCallback], [notifyCallback])` – regardless of when the promise was or
  15312. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  15313. * as soon as the result is available. The callbacks are called with a single argument: the result
  15314. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  15315. * provide a progress indication, before the promise is resolved or rejected.
  15316. *
  15317. * This method *returns a new promise* which is resolved or rejected via the return value of the
  15318. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  15319. * with the value which is resolved in that promise using
  15320. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  15321. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  15322. * resolved or rejected from the notifyCallback method. The errorCallback and notifyCallback
  15323. * arguments are optional.
  15324. *
  15325. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  15326. *
  15327. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  15328. * but to do so without modifying the final value. This is useful to release resources or do some
  15329. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  15330. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  15331. * more information.
  15332. *
  15333. * ## Chaining promises
  15334. *
  15335. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  15336. * possible to create a chain of promises:
  15337. *
  15338. * ```js
  15339. * promiseB = promiseA.then(function(result) {
  15340. * return result + 1;
  15341. * });
  15342. *
  15343. * // promiseB will be resolved immediately after promiseA is resolved and its value
  15344. * // will be the result of promiseA incremented by 1
  15345. * ```
  15346. *
  15347. * It is possible to create chains of any length and since a promise can be resolved with another
  15348. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  15349. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  15350. * $http's response interceptors.
  15351. *
  15352. *
  15353. * ## Differences between Kris Kowal's Q and $q
  15354. *
  15355. * There are two main differences:
  15356. *
  15357. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  15358. * mechanism in angular, which means faster propagation of resolution or rejection into your
  15359. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  15360. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  15361. * all the important functionality needed for common async tasks.
  15362. *
  15363. * ## Testing
  15364. *
  15365. * ```js
  15366. * it('should simulate promise', inject(function($q, $rootScope) {
  15367. * var deferred = $q.defer();
  15368. * var promise = deferred.promise;
  15369. * var resolvedValue;
  15370. *
  15371. * promise.then(function(value) { resolvedValue = value; });
  15372. * expect(resolvedValue).toBeUndefined();
  15373. *
  15374. * // Simulate resolving of promise
  15375. * deferred.resolve(123);
  15376. * // Note that the 'then' function does not get called synchronously.
  15377. * // This is because we want the promise API to always be async, whether or not
  15378. * // it got called synchronously or asynchronously.
  15379. * expect(resolvedValue).toBeUndefined();
  15380. *
  15381. * // Propagate promise resolution to 'then' functions using $apply().
  15382. * $rootScope.$apply();
  15383. * expect(resolvedValue).toEqual(123);
  15384. * }));
  15385. * ```
  15386. *
  15387. * @param {function(function, function)} resolver Function which is responsible for resolving or
  15388. * rejecting the newly created promise. The first parameter is a function which resolves the
  15389. * promise, the second parameter is a function which rejects the promise.
  15390. *
  15391. * @returns {Promise} The newly created promise.
  15392. */
  15393. /**
  15394. * @ngdoc provider
  15395. * @name $qProvider
  15396. * @this
  15397. *
  15398. * @description
  15399. */
  15400. function $QProvider() {
  15401. var errorOnUnhandledRejections = true;
  15402. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  15403. return qFactory(function(callback) {
  15404. $rootScope.$evalAsync(callback);
  15405. }, $exceptionHandler, errorOnUnhandledRejections);
  15406. }];
  15407. /**
  15408. * @ngdoc method
  15409. * @name $qProvider#errorOnUnhandledRejections
  15410. * @kind function
  15411. *
  15412. * @description
  15413. * Retrieves or overrides whether to generate an error when a rejected promise is not handled.
  15414. * This feature is enabled by default.
  15415. *
  15416. * @param {boolean=} value Whether to generate an error when a rejected promise is not handled.
  15417. * @returns {boolean|ng.$qProvider} Current value when called without a new value or self for
  15418. * chaining otherwise.
  15419. */
  15420. this.errorOnUnhandledRejections = function(value) {
  15421. if (isDefined(value)) {
  15422. errorOnUnhandledRejections = value;
  15423. return this;
  15424. } else {
  15425. return errorOnUnhandledRejections;
  15426. }
  15427. };
  15428. }
  15429. /** @this */
  15430. function $$QProvider() {
  15431. var errorOnUnhandledRejections = true;
  15432. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  15433. return qFactory(function(callback) {
  15434. $browser.defer(callback);
  15435. }, $exceptionHandler, errorOnUnhandledRejections);
  15436. }];
  15437. this.errorOnUnhandledRejections = function(value) {
  15438. if (isDefined(value)) {
  15439. errorOnUnhandledRejections = value;
  15440. return this;
  15441. } else {
  15442. return errorOnUnhandledRejections;
  15443. }
  15444. };
  15445. }
  15446. /**
  15447. * Constructs a promise manager.
  15448. *
  15449. * @param {function(function)} nextTick Function for executing functions in the next turn.
  15450. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  15451. * debugging purposes.
  15452. * @param {boolean=} errorOnUnhandledRejections Whether an error should be generated on unhandled
  15453. * promises rejections.
  15454. * @returns {object} Promise manager.
  15455. */
  15456. function qFactory(nextTick, exceptionHandler, errorOnUnhandledRejections) {
  15457. var $qMinErr = minErr('$q', TypeError);
  15458. var queueSize = 0;
  15459. var checkQueue = [];
  15460. /**
  15461. * @ngdoc method
  15462. * @name ng.$q#defer
  15463. * @kind function
  15464. *
  15465. * @description
  15466. * Creates a `Deferred` object which represents a task which will finish in the future.
  15467. *
  15468. * @returns {Deferred} Returns a new instance of deferred.
  15469. */
  15470. function defer() {
  15471. return new Deferred();
  15472. }
  15473. function Deferred() {
  15474. var promise = this.promise = new Promise();
  15475. //Non prototype methods necessary to support unbound execution :/
  15476. this.resolve = function(val) { resolvePromise(promise, val); };
  15477. this.reject = function(reason) { rejectPromise(promise, reason); };
  15478. this.notify = function(progress) { notifyPromise(promise, progress); };
  15479. }
  15480. function Promise() {
  15481. this.$$state = { status: 0 };
  15482. }
  15483. extend(Promise.prototype, {
  15484. then: function(onFulfilled, onRejected, progressBack) {
  15485. if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
  15486. return this;
  15487. }
  15488. var result = new Promise();
  15489. this.$$state.pending = this.$$state.pending || [];
  15490. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  15491. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  15492. return result;
  15493. },
  15494. 'catch': function(callback) {
  15495. return this.then(null, callback);
  15496. },
  15497. 'finally': function(callback, progressBack) {
  15498. return this.then(function(value) {
  15499. return handleCallback(value, resolve, callback);
  15500. }, function(error) {
  15501. return handleCallback(error, reject, callback);
  15502. }, progressBack);
  15503. }
  15504. });
  15505. function processQueue(state) {
  15506. var fn, promise, pending;
  15507. pending = state.pending;
  15508. state.processScheduled = false;
  15509. state.pending = undefined;
  15510. try {
  15511. for (var i = 0, ii = pending.length; i < ii; ++i) {
  15512. markQStateExceptionHandled(state);
  15513. promise = pending[i][0];
  15514. fn = pending[i][state.status];
  15515. try {
  15516. if (isFunction(fn)) {
  15517. resolvePromise(promise, fn(state.value));
  15518. } else if (state.status === 1) {
  15519. resolvePromise(promise, state.value);
  15520. } else {
  15521. rejectPromise(promise, state.value);
  15522. }
  15523. } catch (e) {
  15524. rejectPromise(promise, e);
  15525. // This error is explicitly marked for being passed to the $exceptionHandler
  15526. if (e && e.$$passToExceptionHandler === true) {
  15527. exceptionHandler(e);
  15528. }
  15529. }
  15530. }
  15531. } finally {
  15532. --queueSize;
  15533. if (errorOnUnhandledRejections && queueSize === 0) {
  15534. nextTick(processChecks);
  15535. }
  15536. }
  15537. }
  15538. function processChecks() {
  15539. // eslint-disable-next-line no-unmodified-loop-condition
  15540. while (!queueSize && checkQueue.length) {
  15541. var toCheck = checkQueue.shift();
  15542. if (!isStateExceptionHandled(toCheck)) {
  15543. markQStateExceptionHandled(toCheck);
  15544. var errorMessage = 'Possibly unhandled rejection: ' + toDebugString(toCheck.value);
  15545. if (isError(toCheck.value)) {
  15546. exceptionHandler(toCheck.value, errorMessage);
  15547. } else {
  15548. exceptionHandler(errorMessage);
  15549. }
  15550. }
  15551. }
  15552. }
  15553. function scheduleProcessQueue(state) {
  15554. if (errorOnUnhandledRejections && !state.pending && state.status === 2 && !isStateExceptionHandled(state)) {
  15555. if (queueSize === 0 && checkQueue.length === 0) {
  15556. nextTick(processChecks);
  15557. }
  15558. checkQueue.push(state);
  15559. }
  15560. if (state.processScheduled || !state.pending) return;
  15561. state.processScheduled = true;
  15562. ++queueSize;
  15563. nextTick(function() { processQueue(state); });
  15564. }
  15565. function resolvePromise(promise, val) {
  15566. if (promise.$$state.status) return;
  15567. if (val === promise) {
  15568. $$reject(promise, $qMinErr(
  15569. 'qcycle',
  15570. 'Expected promise to be resolved with value other than itself \'{0}\'',
  15571. val));
  15572. } else {
  15573. $$resolve(promise, val);
  15574. }
  15575. }
  15576. function $$resolve(promise, val) {
  15577. var then;
  15578. var done = false;
  15579. try {
  15580. if (isObject(val) || isFunction(val)) then = val.then;
  15581. if (isFunction(then)) {
  15582. promise.$$state.status = -1;
  15583. then.call(val, doResolve, doReject, doNotify);
  15584. } else {
  15585. promise.$$state.value = val;
  15586. promise.$$state.status = 1;
  15587. scheduleProcessQueue(promise.$$state);
  15588. }
  15589. } catch (e) {
  15590. doReject(e);
  15591. }
  15592. function doResolve(val) {
  15593. if (done) return;
  15594. done = true;
  15595. $$resolve(promise, val);
  15596. }
  15597. function doReject(val) {
  15598. if (done) return;
  15599. done = true;
  15600. $$reject(promise, val);
  15601. }
  15602. function doNotify(progress) {
  15603. notifyPromise(promise, progress);
  15604. }
  15605. }
  15606. function rejectPromise(promise, reason) {
  15607. if (promise.$$state.status) return;
  15608. $$reject(promise, reason);
  15609. }
  15610. function $$reject(promise, reason) {
  15611. promise.$$state.value = reason;
  15612. promise.$$state.status = 2;
  15613. scheduleProcessQueue(promise.$$state);
  15614. }
  15615. function notifyPromise(promise, progress) {
  15616. var callbacks = promise.$$state.pending;
  15617. if ((promise.$$state.status <= 0) && callbacks && callbacks.length) {
  15618. nextTick(function() {
  15619. var callback, result;
  15620. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  15621. result = callbacks[i][0];
  15622. callback = callbacks[i][3];
  15623. try {
  15624. notifyPromise(result, isFunction(callback) ? callback(progress) : progress);
  15625. } catch (e) {
  15626. exceptionHandler(e);
  15627. }
  15628. }
  15629. });
  15630. }
  15631. }
  15632. /**
  15633. * @ngdoc method
  15634. * @name $q#reject
  15635. * @kind function
  15636. *
  15637. * @description
  15638. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  15639. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  15640. * a promise chain, you don't need to worry about it.
  15641. *
  15642. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  15643. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  15644. * a promise error callback and you want to forward the error to the promise derived from the
  15645. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  15646. * `reject`.
  15647. *
  15648. * ```js
  15649. * promiseB = promiseA.then(function(result) {
  15650. * // success: do something and resolve promiseB
  15651. * // with the old or a new result
  15652. * return result;
  15653. * }, function(reason) {
  15654. * // error: handle the error if possible and
  15655. * // resolve promiseB with newPromiseOrValue,
  15656. * // otherwise forward the rejection to promiseB
  15657. * if (canHandle(reason)) {
  15658. * // handle the error and recover
  15659. * return newPromiseOrValue;
  15660. * }
  15661. * return $q.reject(reason);
  15662. * });
  15663. * ```
  15664. *
  15665. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  15666. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  15667. */
  15668. function reject(reason) {
  15669. var result = new Promise();
  15670. rejectPromise(result, reason);
  15671. return result;
  15672. }
  15673. function handleCallback(value, resolver, callback) {
  15674. var callbackOutput = null;
  15675. try {
  15676. if (isFunction(callback)) callbackOutput = callback();
  15677. } catch (e) {
  15678. return reject(e);
  15679. }
  15680. if (isPromiseLike(callbackOutput)) {
  15681. return callbackOutput.then(function() {
  15682. return resolver(value);
  15683. }, reject);
  15684. } else {
  15685. return resolver(value);
  15686. }
  15687. }
  15688. /**
  15689. * @ngdoc method
  15690. * @name $q#when
  15691. * @kind function
  15692. *
  15693. * @description
  15694. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  15695. * This is useful when you are dealing with an object that might or might not be a promise, or if
  15696. * the promise comes from a source that can't be trusted.
  15697. *
  15698. * @param {*} value Value or a promise
  15699. * @param {Function=} successCallback
  15700. * @param {Function=} errorCallback
  15701. * @param {Function=} progressCallback
  15702. * @returns {Promise} Returns a promise of the passed value or promise
  15703. */
  15704. function when(value, callback, errback, progressBack) {
  15705. var result = new Promise();
  15706. resolvePromise(result, value);
  15707. return result.then(callback, errback, progressBack);
  15708. }
  15709. /**
  15710. * @ngdoc method
  15711. * @name $q#resolve
  15712. * @kind function
  15713. *
  15714. * @description
  15715. * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
  15716. *
  15717. * @param {*} value Value or a promise
  15718. * @param {Function=} successCallback
  15719. * @param {Function=} errorCallback
  15720. * @param {Function=} progressCallback
  15721. * @returns {Promise} Returns a promise of the passed value or promise
  15722. */
  15723. var resolve = when;
  15724. /**
  15725. * @ngdoc method
  15726. * @name $q#all
  15727. * @kind function
  15728. *
  15729. * @description
  15730. * Combines multiple promises into a single promise that is resolved when all of the input
  15731. * promises are resolved.
  15732. *
  15733. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  15734. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  15735. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  15736. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  15737. * with the same rejection value.
  15738. */
  15739. function all(promises) {
  15740. var result = new Promise(),
  15741. counter = 0,
  15742. results = isArray(promises) ? [] : {};
  15743. forEach(promises, function(promise, key) {
  15744. counter++;
  15745. when(promise).then(function(value) {
  15746. results[key] = value;
  15747. if (!(--counter)) resolvePromise(result, results);
  15748. }, function(reason) {
  15749. rejectPromise(result, reason);
  15750. });
  15751. });
  15752. if (counter === 0) {
  15753. resolvePromise(result, results);
  15754. }
  15755. return result;
  15756. }
  15757. /**
  15758. * @ngdoc method
  15759. * @name $q#race
  15760. * @kind function
  15761. *
  15762. * @description
  15763. * Returns a promise that resolves or rejects as soon as one of those promises
  15764. * resolves or rejects, with the value or reason from that promise.
  15765. *
  15766. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  15767. * @returns {Promise} a promise that resolves or rejects as soon as one of the `promises`
  15768. * resolves or rejects, with the value or reason from that promise.
  15769. */
  15770. function race(promises) {
  15771. var deferred = defer();
  15772. forEach(promises, function(promise) {
  15773. when(promise).then(deferred.resolve, deferred.reject);
  15774. });
  15775. return deferred.promise;
  15776. }
  15777. function $Q(resolver) {
  15778. if (!isFunction(resolver)) {
  15779. throw $qMinErr('norslvr', 'Expected resolverFn, got \'{0}\'', resolver);
  15780. }
  15781. var promise = new Promise();
  15782. function resolveFn(value) {
  15783. resolvePromise(promise, value);
  15784. }
  15785. function rejectFn(reason) {
  15786. rejectPromise(promise, reason);
  15787. }
  15788. resolver(resolveFn, rejectFn);
  15789. return promise;
  15790. }
  15791. // Let's make the instanceof operator work for promises, so that
  15792. // `new $q(fn) instanceof $q` would evaluate to true.
  15793. $Q.prototype = Promise.prototype;
  15794. $Q.defer = defer;
  15795. $Q.reject = reject;
  15796. $Q.when = when;
  15797. $Q.resolve = resolve;
  15798. $Q.all = all;
  15799. $Q.race = race;
  15800. return $Q;
  15801. }
  15802. function isStateExceptionHandled(state) {
  15803. return !!state.pur;
  15804. }
  15805. function markQStateExceptionHandled(state) {
  15806. state.pur = true;
  15807. }
  15808. function markQExceptionHandled(q) {
  15809. markQStateExceptionHandled(q.$$state);
  15810. }
  15811. /** @this */
  15812. function $$RAFProvider() { //rAF
  15813. this.$get = ['$window', '$timeout', function($window, $timeout) {
  15814. var requestAnimationFrame = $window.requestAnimationFrame ||
  15815. $window.webkitRequestAnimationFrame;
  15816. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  15817. $window.webkitCancelAnimationFrame ||
  15818. $window.webkitCancelRequestAnimationFrame;
  15819. var rafSupported = !!requestAnimationFrame;
  15820. var raf = rafSupported
  15821. ? function(fn) {
  15822. var id = requestAnimationFrame(fn);
  15823. return function() {
  15824. cancelAnimationFrame(id);
  15825. };
  15826. }
  15827. : function(fn) {
  15828. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  15829. return function() {
  15830. $timeout.cancel(timer);
  15831. };
  15832. };
  15833. raf.supported = rafSupported;
  15834. return raf;
  15835. }];
  15836. }
  15837. /**
  15838. * DESIGN NOTES
  15839. *
  15840. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  15841. *
  15842. * The typical use of scope is to watch the expressions, which most of the time return the same
  15843. * value as last time so we optimize the operation.
  15844. *
  15845. * Closures construction is expensive in terms of speed as well as memory:
  15846. * - No closures, instead use prototypical inheritance for API
  15847. * - Internal state needs to be stored on scope directly, which means that private state is
  15848. * exposed as $$____ properties
  15849. *
  15850. * Loop operations are optimized by using while(count--) { ... }
  15851. * - This means that in order to keep the same order of execution as addition we have to add
  15852. * items to the array at the beginning (unshift) instead of at the end (push)
  15853. *
  15854. * Child scopes are created and removed often
  15855. * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
  15856. *
  15857. * There are fewer watches than observers. This is why you don't want the observer to be implemented
  15858. * in the same way as watch. Watch requires return of the initialization function which is expensive
  15859. * to construct.
  15860. */
  15861. /**
  15862. * @ngdoc provider
  15863. * @name $rootScopeProvider
  15864. * @description
  15865. *
  15866. * Provider for the $rootScope service.
  15867. */
  15868. /**
  15869. * @ngdoc method
  15870. * @name $rootScopeProvider#digestTtl
  15871. * @description
  15872. *
  15873. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  15874. * assuming that the model is unstable.
  15875. *
  15876. * The current default is 10 iterations.
  15877. *
  15878. * In complex applications it's possible that the dependencies between `$watch`s will result in
  15879. * several digest iterations. However if an application needs more than the default 10 digest
  15880. * iterations for its model to stabilize then you should investigate what is causing the model to
  15881. * continuously change during the digest.
  15882. *
  15883. * Increasing the TTL could have performance implications, so you should not change it without
  15884. * proper justification.
  15885. *
  15886. * @param {number} limit The number of digest iterations.
  15887. */
  15888. /**
  15889. * @ngdoc service
  15890. * @name $rootScope
  15891. * @this
  15892. *
  15893. * @description
  15894. *
  15895. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  15896. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  15897. * between the model and the view, via a mechanism for watching the model for changes.
  15898. * They also provide event emission/broadcast and subscription facility. See the
  15899. * {@link guide/scope developer guide on scopes}.
  15900. */
  15901. function $RootScopeProvider() {
  15902. var TTL = 10;
  15903. var $rootScopeMinErr = minErr('$rootScope');
  15904. var lastDirtyWatch = null;
  15905. var applyAsyncId = null;
  15906. this.digestTtl = function(value) {
  15907. if (arguments.length) {
  15908. TTL = value;
  15909. }
  15910. return TTL;
  15911. };
  15912. function createChildScopeClass(parent) {
  15913. function ChildScope() {
  15914. this.$$watchers = this.$$nextSibling =
  15915. this.$$childHead = this.$$childTail = null;
  15916. this.$$listeners = {};
  15917. this.$$listenerCount = {};
  15918. this.$$watchersCount = 0;
  15919. this.$id = nextUid();
  15920. this.$$ChildScope = null;
  15921. }
  15922. ChildScope.prototype = parent;
  15923. return ChildScope;
  15924. }
  15925. this.$get = ['$exceptionHandler', '$parse', '$browser',
  15926. function($exceptionHandler, $parse, $browser) {
  15927. function destroyChildScope($event) {
  15928. $event.currentScope.$$destroyed = true;
  15929. }
  15930. function cleanUpScope($scope) {
  15931. // Support: IE 9 only
  15932. if (msie === 9) {
  15933. // There is a memory leak in IE9 if all child scopes are not disconnected
  15934. // completely when a scope is destroyed. So this code will recurse up through
  15935. // all this scopes children
  15936. //
  15937. // See issue https://github.com/angular/angular.js/issues/10706
  15938. if ($scope.$$childHead) {
  15939. cleanUpScope($scope.$$childHead);
  15940. }
  15941. if ($scope.$$nextSibling) {
  15942. cleanUpScope($scope.$$nextSibling);
  15943. }
  15944. }
  15945. // The code below works around IE9 and V8's memory leaks
  15946. //
  15947. // See:
  15948. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  15949. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  15950. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  15951. $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
  15952. $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
  15953. }
  15954. /**
  15955. * @ngdoc type
  15956. * @name $rootScope.Scope
  15957. *
  15958. * @description
  15959. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  15960. * {@link auto.$injector $injector}. Child scopes are created using the
  15961. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  15962. * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
  15963. * an in-depth introduction and usage examples.
  15964. *
  15965. *
  15966. * ## Inheritance
  15967. * A scope can inherit from a parent scope, as in this example:
  15968. * ```js
  15969. var parent = $rootScope;
  15970. var child = parent.$new();
  15971. parent.salutation = "Hello";
  15972. expect(child.salutation).toEqual('Hello');
  15973. child.salutation = "Welcome";
  15974. expect(child.salutation).toEqual('Welcome');
  15975. expect(parent.salutation).toEqual('Hello');
  15976. * ```
  15977. *
  15978. * When interacting with `Scope` in tests, additional helper methods are available on the
  15979. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  15980. * details.
  15981. *
  15982. *
  15983. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  15984. * provided for the current scope. Defaults to {@link ng}.
  15985. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  15986. * append/override services provided by `providers`. This is handy
  15987. * when unit-testing and having the need to override a default
  15988. * service.
  15989. * @returns {Object} Newly created scope.
  15990. *
  15991. */
  15992. function Scope() {
  15993. this.$id = nextUid();
  15994. this.$$phase = this.$parent = this.$$watchers =
  15995. this.$$nextSibling = this.$$prevSibling =
  15996. this.$$childHead = this.$$childTail = null;
  15997. this.$root = this;
  15998. this.$$destroyed = false;
  15999. this.$$listeners = {};
  16000. this.$$listenerCount = {};
  16001. this.$$watchersCount = 0;
  16002. this.$$isolateBindings = null;
  16003. }
  16004. /**
  16005. * @ngdoc property
  16006. * @name $rootScope.Scope#$id
  16007. *
  16008. * @description
  16009. * Unique scope ID (monotonically increasing) useful for debugging.
  16010. */
  16011. /**
  16012. * @ngdoc property
  16013. * @name $rootScope.Scope#$parent
  16014. *
  16015. * @description
  16016. * Reference to the parent scope.
  16017. */
  16018. /**
  16019. * @ngdoc property
  16020. * @name $rootScope.Scope#$root
  16021. *
  16022. * @description
  16023. * Reference to the root scope.
  16024. */
  16025. Scope.prototype = {
  16026. constructor: Scope,
  16027. /**
  16028. * @ngdoc method
  16029. * @name $rootScope.Scope#$new
  16030. * @kind function
  16031. *
  16032. * @description
  16033. * Creates a new child {@link ng.$rootScope.Scope scope}.
  16034. *
  16035. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  16036. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  16037. *
  16038. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  16039. * desired for the scope and its child scopes to be permanently detached from the parent and
  16040. * thus stop participating in model change detection and listener notification by invoking.
  16041. *
  16042. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  16043. * parent scope. The scope is isolated, as it can not see parent scope properties.
  16044. * When creating widgets, it is useful for the widget to not accidentally read parent
  16045. * state.
  16046. *
  16047. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  16048. * of the newly created scope. Defaults to `this` scope if not provided.
  16049. * This is used when creating a transclude scope to correctly place it
  16050. * in the scope hierarchy while maintaining the correct prototypical
  16051. * inheritance.
  16052. *
  16053. * @returns {Object} The newly created child scope.
  16054. *
  16055. */
  16056. $new: function(isolate, parent) {
  16057. var child;
  16058. parent = parent || this;
  16059. if (isolate) {
  16060. child = new Scope();
  16061. child.$root = this.$root;
  16062. } else {
  16063. // Only create a child scope class if somebody asks for one,
  16064. // but cache it to allow the VM to optimize lookups.
  16065. if (!this.$$ChildScope) {
  16066. this.$$ChildScope = createChildScopeClass(this);
  16067. }
  16068. child = new this.$$ChildScope();
  16069. }
  16070. child.$parent = parent;
  16071. child.$$prevSibling = parent.$$childTail;
  16072. if (parent.$$childHead) {
  16073. parent.$$childTail.$$nextSibling = child;
  16074. parent.$$childTail = child;
  16075. } else {
  16076. parent.$$childHead = parent.$$childTail = child;
  16077. }
  16078. // When the new scope is not isolated or we inherit from `this`, and
  16079. // the parent scope is destroyed, the property `$$destroyed` is inherited
  16080. // prototypically. In all other cases, this property needs to be set
  16081. // when the parent scope is destroyed.
  16082. // The listener needs to be added after the parent is set
  16083. if (isolate || parent !== this) child.$on('$destroy', destroyChildScope);
  16084. return child;
  16085. },
  16086. /**
  16087. * @ngdoc method
  16088. * @name $rootScope.Scope#$watch
  16089. * @kind function
  16090. *
  16091. * @description
  16092. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  16093. *
  16094. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  16095. * $digest()} and should return the value that will be watched. (`watchExpression` should not change
  16096. * its value when executed multiple times with the same input because it may be executed multiple
  16097. * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
  16098. * [idempotent](http://en.wikipedia.org/wiki/Idempotence).)
  16099. * - The `listener` is called only when the value from the current `watchExpression` and the
  16100. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  16101. * see below). Inequality is determined according to reference inequality,
  16102. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  16103. * via the `!==` Javascript operator, unless `objectEquality == true`
  16104. * (see next point)
  16105. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  16106. * according to the {@link angular.equals} function. To save the value of the object for
  16107. * later comparison, the {@link angular.copy} function is used. This therefore means that
  16108. * watching complex objects will have adverse memory and performance implications.
  16109. * - This should not be used to watch for changes in objects that are
  16110. * or contain [File](https://developer.mozilla.org/docs/Web/API/File) objects due to limitations with {@link angular.copy `angular.copy`}.
  16111. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  16112. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  16113. * iteration limit is 10 to prevent an infinite loop deadlock.
  16114. *
  16115. *
  16116. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  16117. * you can register a `watchExpression` function with no `listener`. (Be prepared for
  16118. * multiple calls to your `watchExpression` because it will execute multiple times in a
  16119. * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
  16120. *
  16121. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  16122. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  16123. * watcher. In rare cases, this is undesirable because the listener is called when the result
  16124. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  16125. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  16126. * listener was called due to initialization.
  16127. *
  16128. *
  16129. *
  16130. * @example
  16131. * ```js
  16132. // let's assume that scope was dependency injected as the $rootScope
  16133. var scope = $rootScope;
  16134. scope.name = 'misko';
  16135. scope.counter = 0;
  16136. expect(scope.counter).toEqual(0);
  16137. scope.$watch('name', function(newValue, oldValue) {
  16138. scope.counter = scope.counter + 1;
  16139. });
  16140. expect(scope.counter).toEqual(0);
  16141. scope.$digest();
  16142. // the listener is always called during the first $digest loop after it was registered
  16143. expect(scope.counter).toEqual(1);
  16144. scope.$digest();
  16145. // but now it will not be called unless the value changes
  16146. expect(scope.counter).toEqual(1);
  16147. scope.name = 'adam';
  16148. scope.$digest();
  16149. expect(scope.counter).toEqual(2);
  16150. // Using a function as a watchExpression
  16151. var food;
  16152. scope.foodCounter = 0;
  16153. expect(scope.foodCounter).toEqual(0);
  16154. scope.$watch(
  16155. // This function returns the value being watched. It is called for each turn of the $digest loop
  16156. function() { return food; },
  16157. // This is the change listener, called when the value returned from the above function changes
  16158. function(newValue, oldValue) {
  16159. if ( newValue !== oldValue ) {
  16160. // Only increment the counter if the value changed
  16161. scope.foodCounter = scope.foodCounter + 1;
  16162. }
  16163. }
  16164. );
  16165. // No digest has been run so the counter will be zero
  16166. expect(scope.foodCounter).toEqual(0);
  16167. // Run the digest but since food has not changed count will still be zero
  16168. scope.$digest();
  16169. expect(scope.foodCounter).toEqual(0);
  16170. // Update food and run digest. Now the counter will increment
  16171. food = 'cheeseburger';
  16172. scope.$digest();
  16173. expect(scope.foodCounter).toEqual(1);
  16174. * ```
  16175. *
  16176. *
  16177. *
  16178. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  16179. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  16180. * a call to the `listener`.
  16181. *
  16182. * - `string`: Evaluated as {@link guide/expression expression}
  16183. * - `function(scope)`: called with current `scope` as a parameter.
  16184. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  16185. * of `watchExpression` changes.
  16186. *
  16187. * - `newVal` contains the current value of the `watchExpression`
  16188. * - `oldVal` contains the previous value of the `watchExpression`
  16189. * - `scope` refers to the current scope
  16190. * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of
  16191. * comparing for reference equality.
  16192. * @returns {function()} Returns a deregistration function for this listener.
  16193. */
  16194. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  16195. var get = $parse(watchExp);
  16196. if (get.$$watchDelegate) {
  16197. return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
  16198. }
  16199. var scope = this,
  16200. array = scope.$$watchers,
  16201. watcher = {
  16202. fn: listener,
  16203. last: initWatchVal,
  16204. get: get,
  16205. exp: prettyPrintExpression || watchExp,
  16206. eq: !!objectEquality
  16207. };
  16208. lastDirtyWatch = null;
  16209. if (!isFunction(listener)) {
  16210. watcher.fn = noop;
  16211. }
  16212. if (!array) {
  16213. array = scope.$$watchers = [];
  16214. array.$$digestWatchIndex = -1;
  16215. }
  16216. // we use unshift since we use a while loop in $digest for speed.
  16217. // the while loop reads in reverse order.
  16218. array.unshift(watcher);
  16219. array.$$digestWatchIndex++;
  16220. incrementWatchersCount(this, 1);
  16221. return function deregisterWatch() {
  16222. var index = arrayRemove(array, watcher);
  16223. if (index >= 0) {
  16224. incrementWatchersCount(scope, -1);
  16225. if (index < array.$$digestWatchIndex) {
  16226. array.$$digestWatchIndex--;
  16227. }
  16228. }
  16229. lastDirtyWatch = null;
  16230. };
  16231. },
  16232. /**
  16233. * @ngdoc method
  16234. * @name $rootScope.Scope#$watchGroup
  16235. * @kind function
  16236. *
  16237. * @description
  16238. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  16239. * If any one expression in the collection changes the `listener` is executed.
  16240. *
  16241. * - The items in the `watchExpressions` array are observed via the standard `$watch` operation. Their return
  16242. * values are examined for changes on every call to `$digest`.
  16243. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  16244. *
  16245. * `$watchGroup` is more performant than watching each expression individually, and should be
  16246. * used when the listener does not need to know which expression has changed.
  16247. * If the listener needs to know which expression has changed,
  16248. * {@link ng.$rootScope.Scope#$watch $watch()} or
  16249. * {@link ng.$rootScope.Scope#$watchCollection $watchCollection()} should be used.
  16250. *
  16251. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  16252. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  16253. *
  16254. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  16255. * expression in `watchExpressions` changes
  16256. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  16257. * those of `watchExpression`
  16258. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  16259. * those of `watchExpression`.
  16260. *
  16261. * Note that `newValues` and `oldValues` reflect the differences in each **individual**
  16262. * expression, and not the difference of the values between each call of the listener.
  16263. * That means the difference between `newValues` and `oldValues` cannot be used to determine
  16264. * which expression has changed / remained stable:
  16265. *
  16266. * ```js
  16267. *
  16268. * $scope.$watchGroup(['v1', 'v2'], function(newValues, oldValues) {
  16269. * console.log(newValues, oldValues);
  16270. * });
  16271. *
  16272. * // newValues, oldValues initially
  16273. * // [undefined, undefined], [undefined, undefined]
  16274. *
  16275. * $scope.v1 = 'a';
  16276. * $scope.v2 = 'a';
  16277. *
  16278. * // ['a', 'a'], [undefined, undefined]
  16279. *
  16280. * $scope.v2 = 'b'
  16281. *
  16282. * // v1 hasn't changed since it became `'a'`, therefore its oldValue is still `undefined`
  16283. * // ['a', 'b'], [undefined, 'a']
  16284. *
  16285. * ```
  16286. *
  16287. * The `scope` refers to the current scope.
  16288. * @returns {function()} Returns a de-registration function for all listeners.
  16289. */
  16290. $watchGroup: function(watchExpressions, listener) {
  16291. var oldValues = new Array(watchExpressions.length);
  16292. var newValues = new Array(watchExpressions.length);
  16293. var deregisterFns = [];
  16294. var self = this;
  16295. var changeReactionScheduled = false;
  16296. var firstRun = true;
  16297. if (!watchExpressions.length) {
  16298. // No expressions means we call the listener ASAP
  16299. var shouldCall = true;
  16300. self.$evalAsync(function() {
  16301. if (shouldCall) listener(newValues, newValues, self);
  16302. });
  16303. return function deregisterWatchGroup() {
  16304. shouldCall = false;
  16305. };
  16306. }
  16307. if (watchExpressions.length === 1) {
  16308. // Special case size of one
  16309. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  16310. newValues[0] = value;
  16311. oldValues[0] = oldValue;
  16312. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  16313. });
  16314. }
  16315. forEach(watchExpressions, function(expr, i) {
  16316. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  16317. newValues[i] = value;
  16318. oldValues[i] = oldValue;
  16319. if (!changeReactionScheduled) {
  16320. changeReactionScheduled = true;
  16321. self.$evalAsync(watchGroupAction);
  16322. }
  16323. });
  16324. deregisterFns.push(unwatchFn);
  16325. });
  16326. function watchGroupAction() {
  16327. changeReactionScheduled = false;
  16328. if (firstRun) {
  16329. firstRun = false;
  16330. listener(newValues, newValues, self);
  16331. } else {
  16332. listener(newValues, oldValues, self);
  16333. }
  16334. }
  16335. return function deregisterWatchGroup() {
  16336. while (deregisterFns.length) {
  16337. deregisterFns.shift()();
  16338. }
  16339. };
  16340. },
  16341. /**
  16342. * @ngdoc method
  16343. * @name $rootScope.Scope#$watchCollection
  16344. * @kind function
  16345. *
  16346. * @description
  16347. * Shallow watches the properties of an object and fires whenever any of the properties change
  16348. * (for arrays, this implies watching the array items; for object maps, this implies watching
  16349. * the properties). If a change is detected, the `listener` callback is fired.
  16350. *
  16351. * - The `obj` collection is observed via standard $watch operation and is examined on every
  16352. * call to $digest() to see if any items have been added, removed, or moved.
  16353. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  16354. * adding, removing, and moving items belonging to an object or array.
  16355. *
  16356. *
  16357. * @example
  16358. * ```js
  16359. $scope.names = ['igor', 'matias', 'misko', 'james'];
  16360. $scope.dataCount = 4;
  16361. $scope.$watchCollection('names', function(newNames, oldNames) {
  16362. $scope.dataCount = newNames.length;
  16363. });
  16364. expect($scope.dataCount).toEqual(4);
  16365. $scope.$digest();
  16366. //still at 4 ... no changes
  16367. expect($scope.dataCount).toEqual(4);
  16368. $scope.names.pop();
  16369. $scope.$digest();
  16370. //now there's been a change
  16371. expect($scope.dataCount).toEqual(3);
  16372. * ```
  16373. *
  16374. *
  16375. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  16376. * expression value should evaluate to an object or an array which is observed on each
  16377. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  16378. * collection will trigger a call to the `listener`.
  16379. *
  16380. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  16381. * when a change is detected.
  16382. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  16383. * - The `oldCollection` object is a copy of the former collection data.
  16384. * Due to performance considerations, the`oldCollection` value is computed only if the
  16385. * `listener` function declares two or more arguments.
  16386. * - The `scope` argument refers to the current scope.
  16387. *
  16388. * @returns {function()} Returns a de-registration function for this listener. When the
  16389. * de-registration function is executed, the internal watch operation is terminated.
  16390. */
  16391. $watchCollection: function(obj, listener) {
  16392. $watchCollectionInterceptor.$stateful = true;
  16393. var self = this;
  16394. // the current value, updated on each dirty-check run
  16395. var newValue;
  16396. // a shallow copy of the newValue from the last dirty-check run,
  16397. // updated to match newValue during dirty-check run
  16398. var oldValue;
  16399. // a shallow copy of the newValue from when the last change happened
  16400. var veryOldValue;
  16401. // only track veryOldValue if the listener is asking for it
  16402. var trackVeryOldValue = (listener.length > 1);
  16403. var changeDetected = 0;
  16404. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  16405. var internalArray = [];
  16406. var internalObject = {};
  16407. var initRun = true;
  16408. var oldLength = 0;
  16409. function $watchCollectionInterceptor(_value) {
  16410. newValue = _value;
  16411. var newLength, key, bothNaN, newItem, oldItem;
  16412. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  16413. if (isUndefined(newValue)) return;
  16414. if (!isObject(newValue)) { // if primitive
  16415. if (oldValue !== newValue) {
  16416. oldValue = newValue;
  16417. changeDetected++;
  16418. }
  16419. } else if (isArrayLike(newValue)) {
  16420. if (oldValue !== internalArray) {
  16421. // we are transitioning from something which was not an array into array.
  16422. oldValue = internalArray;
  16423. oldLength = oldValue.length = 0;
  16424. changeDetected++;
  16425. }
  16426. newLength = newValue.length;
  16427. if (oldLength !== newLength) {
  16428. // if lengths do not match we need to trigger change notification
  16429. changeDetected++;
  16430. oldValue.length = oldLength = newLength;
  16431. }
  16432. // copy the items to oldValue and look for changes.
  16433. for (var i = 0; i < newLength; i++) {
  16434. oldItem = oldValue[i];
  16435. newItem = newValue[i];
  16436. // eslint-disable-next-line no-self-compare
  16437. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  16438. if (!bothNaN && (oldItem !== newItem)) {
  16439. changeDetected++;
  16440. oldValue[i] = newItem;
  16441. }
  16442. }
  16443. } else {
  16444. if (oldValue !== internalObject) {
  16445. // we are transitioning from something which was not an object into object.
  16446. oldValue = internalObject = {};
  16447. oldLength = 0;
  16448. changeDetected++;
  16449. }
  16450. // copy the items to oldValue and look for changes.
  16451. newLength = 0;
  16452. for (key in newValue) {
  16453. if (hasOwnProperty.call(newValue, key)) {
  16454. newLength++;
  16455. newItem = newValue[key];
  16456. oldItem = oldValue[key];
  16457. if (key in oldValue) {
  16458. // eslint-disable-next-line no-self-compare
  16459. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  16460. if (!bothNaN && (oldItem !== newItem)) {
  16461. changeDetected++;
  16462. oldValue[key] = newItem;
  16463. }
  16464. } else {
  16465. oldLength++;
  16466. oldValue[key] = newItem;
  16467. changeDetected++;
  16468. }
  16469. }
  16470. }
  16471. if (oldLength > newLength) {
  16472. // we used to have more keys, need to find them and destroy them.
  16473. changeDetected++;
  16474. for (key in oldValue) {
  16475. if (!hasOwnProperty.call(newValue, key)) {
  16476. oldLength--;
  16477. delete oldValue[key];
  16478. }
  16479. }
  16480. }
  16481. }
  16482. return changeDetected;
  16483. }
  16484. function $watchCollectionAction() {
  16485. if (initRun) {
  16486. initRun = false;
  16487. listener(newValue, newValue, self);
  16488. } else {
  16489. listener(newValue, veryOldValue, self);
  16490. }
  16491. // make a copy for the next time a collection is changed
  16492. if (trackVeryOldValue) {
  16493. if (!isObject(newValue)) {
  16494. //primitive
  16495. veryOldValue = newValue;
  16496. } else if (isArrayLike(newValue)) {
  16497. veryOldValue = new Array(newValue.length);
  16498. for (var i = 0; i < newValue.length; i++) {
  16499. veryOldValue[i] = newValue[i];
  16500. }
  16501. } else { // if object
  16502. veryOldValue = {};
  16503. for (var key in newValue) {
  16504. if (hasOwnProperty.call(newValue, key)) {
  16505. veryOldValue[key] = newValue[key];
  16506. }
  16507. }
  16508. }
  16509. }
  16510. }
  16511. return this.$watch(changeDetector, $watchCollectionAction);
  16512. },
  16513. /**
  16514. * @ngdoc method
  16515. * @name $rootScope.Scope#$digest
  16516. * @kind function
  16517. *
  16518. * @description
  16519. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  16520. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  16521. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  16522. * until no more listeners are firing. This means that it is possible to get into an infinite
  16523. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  16524. * iterations exceeds 10.
  16525. *
  16526. * Usually, you don't call `$digest()` directly in
  16527. * {@link ng.directive:ngController controllers} or in
  16528. * {@link ng.$compileProvider#directive directives}.
  16529. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  16530. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  16531. *
  16532. * If you want to be notified whenever `$digest()` is called,
  16533. * you can register a `watchExpression` function with
  16534. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  16535. *
  16536. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  16537. *
  16538. * @example
  16539. * ```js
  16540. var scope = ...;
  16541. scope.name = 'misko';
  16542. scope.counter = 0;
  16543. expect(scope.counter).toEqual(0);
  16544. scope.$watch('name', function(newValue, oldValue) {
  16545. scope.counter = scope.counter + 1;
  16546. });
  16547. expect(scope.counter).toEqual(0);
  16548. scope.$digest();
  16549. // the listener is always called during the first $digest loop after it was registered
  16550. expect(scope.counter).toEqual(1);
  16551. scope.$digest();
  16552. // but now it will not be called unless the value changes
  16553. expect(scope.counter).toEqual(1);
  16554. scope.name = 'adam';
  16555. scope.$digest();
  16556. expect(scope.counter).toEqual(2);
  16557. * ```
  16558. *
  16559. */
  16560. $digest: function() {
  16561. var watch, value, last, fn, get,
  16562. watchers,
  16563. dirty, ttl = TTL,
  16564. next, current, target = this,
  16565. watchLog = [],
  16566. logIdx, asyncTask;
  16567. beginPhase('$digest');
  16568. // Check for changes to browser url that happened in sync before the call to $digest
  16569. $browser.$$checkUrlChange();
  16570. if (this === $rootScope && applyAsyncId !== null) {
  16571. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  16572. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  16573. $browser.defer.cancel(applyAsyncId);
  16574. flushApplyAsync();
  16575. }
  16576. lastDirtyWatch = null;
  16577. do { // "while dirty" loop
  16578. dirty = false;
  16579. current = target;
  16580. // It's safe for asyncQueuePosition to be a local variable here because this loop can't
  16581. // be reentered recursively. Calling $digest from a function passed to $evalAsync would
  16582. // lead to a '$digest already in progress' error.
  16583. for (var asyncQueuePosition = 0; asyncQueuePosition < asyncQueue.length; asyncQueuePosition++) {
  16584. try {
  16585. asyncTask = asyncQueue[asyncQueuePosition];
  16586. fn = asyncTask.fn;
  16587. fn(asyncTask.scope, asyncTask.locals);
  16588. } catch (e) {
  16589. $exceptionHandler(e);
  16590. }
  16591. lastDirtyWatch = null;
  16592. }
  16593. asyncQueue.length = 0;
  16594. traverseScopesLoop:
  16595. do { // "traverse the scopes" loop
  16596. if ((watchers = current.$$watchers)) {
  16597. // process our watches
  16598. watchers.$$digestWatchIndex = watchers.length;
  16599. while (watchers.$$digestWatchIndex--) {
  16600. try {
  16601. watch = watchers[watchers.$$digestWatchIndex];
  16602. // Most common watches are on primitives, in which case we can short
  16603. // circuit it with === operator, only when === fails do we use .equals
  16604. if (watch) {
  16605. get = watch.get;
  16606. if ((value = get(current)) !== (last = watch.last) &&
  16607. !(watch.eq
  16608. ? equals(value, last)
  16609. : (isNumberNaN(value) && isNumberNaN(last)))) {
  16610. dirty = true;
  16611. lastDirtyWatch = watch;
  16612. watch.last = watch.eq ? copy(value, null) : value;
  16613. fn = watch.fn;
  16614. fn(value, ((last === initWatchVal) ? value : last), current);
  16615. if (ttl < 5) {
  16616. logIdx = 4 - ttl;
  16617. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  16618. watchLog[logIdx].push({
  16619. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  16620. newVal: value,
  16621. oldVal: last
  16622. });
  16623. }
  16624. } else if (watch === lastDirtyWatch) {
  16625. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  16626. // have already been tested.
  16627. dirty = false;
  16628. break traverseScopesLoop;
  16629. }
  16630. }
  16631. } catch (e) {
  16632. $exceptionHandler(e);
  16633. }
  16634. }
  16635. }
  16636. // Insanity Warning: scope depth-first traversal
  16637. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  16638. // this piece should be kept in sync with the traversal in $broadcast
  16639. if (!(next = ((current.$$watchersCount && current.$$childHead) ||
  16640. (current !== target && current.$$nextSibling)))) {
  16641. while (current !== target && !(next = current.$$nextSibling)) {
  16642. current = current.$parent;
  16643. }
  16644. }
  16645. } while ((current = next));
  16646. // `break traverseScopesLoop;` takes us to here
  16647. if ((dirty || asyncQueue.length) && !(ttl--)) {
  16648. clearPhase();
  16649. throw $rootScopeMinErr('infdig',
  16650. '{0} $digest() iterations reached. Aborting!\n' +
  16651. 'Watchers fired in the last 5 iterations: {1}',
  16652. TTL, watchLog);
  16653. }
  16654. } while (dirty || asyncQueue.length);
  16655. clearPhase();
  16656. // postDigestQueuePosition isn't local here because this loop can be reentered recursively.
  16657. while (postDigestQueuePosition < postDigestQueue.length) {
  16658. try {
  16659. postDigestQueue[postDigestQueuePosition++]();
  16660. } catch (e) {
  16661. $exceptionHandler(e);
  16662. }
  16663. }
  16664. postDigestQueue.length = postDigestQueuePosition = 0;
  16665. // Check for changes to browser url that happened during the $digest
  16666. // (for which no event is fired; e.g. via `history.pushState()`)
  16667. $browser.$$checkUrlChange();
  16668. },
  16669. /**
  16670. * @ngdoc event
  16671. * @name $rootScope.Scope#$destroy
  16672. * @eventType broadcast on scope being destroyed
  16673. *
  16674. * @description
  16675. * Broadcasted when a scope and its children are being destroyed.
  16676. *
  16677. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  16678. * clean up DOM bindings before an element is removed from the DOM.
  16679. */
  16680. /**
  16681. * @ngdoc method
  16682. * @name $rootScope.Scope#$destroy
  16683. * @kind function
  16684. *
  16685. * @description
  16686. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  16687. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  16688. * propagate to the current scope and its children. Removal also implies that the current
  16689. * scope is eligible for garbage collection.
  16690. *
  16691. * The `$destroy()` is usually used by directives such as
  16692. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  16693. * unrolling of the loop.
  16694. *
  16695. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  16696. * Application code can register a `$destroy` event handler that will give it a chance to
  16697. * perform any necessary cleanup.
  16698. *
  16699. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  16700. * clean up DOM bindings before an element is removed from the DOM.
  16701. */
  16702. $destroy: function() {
  16703. // We can't destroy a scope that has been already destroyed.
  16704. if (this.$$destroyed) return;
  16705. var parent = this.$parent;
  16706. this.$broadcast('$destroy');
  16707. this.$$destroyed = true;
  16708. if (this === $rootScope) {
  16709. //Remove handlers attached to window when $rootScope is removed
  16710. $browser.$$applicationDestroyed();
  16711. }
  16712. incrementWatchersCount(this, -this.$$watchersCount);
  16713. for (var eventName in this.$$listenerCount) {
  16714. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  16715. }
  16716. // sever all the references to parent scopes (after this cleanup, the current scope should
  16717. // not be retained by any of our references and should be eligible for garbage collection)
  16718. if (parent && parent.$$childHead === this) parent.$$childHead = this.$$nextSibling;
  16719. if (parent && parent.$$childTail === this) parent.$$childTail = this.$$prevSibling;
  16720. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  16721. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  16722. // Disable listeners, watchers and apply/digest methods
  16723. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  16724. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  16725. this.$$listeners = {};
  16726. // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
  16727. this.$$nextSibling = null;
  16728. cleanUpScope(this);
  16729. },
  16730. /**
  16731. * @ngdoc method
  16732. * @name $rootScope.Scope#$eval
  16733. * @kind function
  16734. *
  16735. * @description
  16736. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  16737. * the expression are propagated (uncaught). This is useful when evaluating Angular
  16738. * expressions.
  16739. *
  16740. * @example
  16741. * ```js
  16742. var scope = ng.$rootScope.Scope();
  16743. scope.a = 1;
  16744. scope.b = 2;
  16745. expect(scope.$eval('a+b')).toEqual(3);
  16746. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  16747. * ```
  16748. *
  16749. * @param {(string|function())=} expression An angular expression to be executed.
  16750. *
  16751. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16752. * - `function(scope)`: execute the function with the current `scope` parameter.
  16753. *
  16754. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  16755. * @returns {*} The result of evaluating the expression.
  16756. */
  16757. $eval: function(expr, locals) {
  16758. return $parse(expr)(this, locals);
  16759. },
  16760. /**
  16761. * @ngdoc method
  16762. * @name $rootScope.Scope#$evalAsync
  16763. * @kind function
  16764. *
  16765. * @description
  16766. * Executes the expression on the current scope at a later point in time.
  16767. *
  16768. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  16769. * that:
  16770. *
  16771. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  16772. * rendering).
  16773. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  16774. * `expression` execution.
  16775. *
  16776. * Any exceptions from the execution of the expression are forwarded to the
  16777. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16778. *
  16779. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  16780. * will be scheduled. However, it is encouraged to always call code that changes the model
  16781. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  16782. *
  16783. * @param {(string|function())=} expression An angular expression to be executed.
  16784. *
  16785. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16786. * - `function(scope)`: execute the function with the current `scope` parameter.
  16787. *
  16788. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  16789. */
  16790. $evalAsync: function(expr, locals) {
  16791. // if we are outside of an $digest loop and this is the first time we are scheduling async
  16792. // task also schedule async auto-flush
  16793. if (!$rootScope.$$phase && !asyncQueue.length) {
  16794. $browser.defer(function() {
  16795. if (asyncQueue.length) {
  16796. $rootScope.$digest();
  16797. }
  16798. });
  16799. }
  16800. asyncQueue.push({scope: this, fn: $parse(expr), locals: locals});
  16801. },
  16802. $$postDigest: function(fn) {
  16803. postDigestQueue.push(fn);
  16804. },
  16805. /**
  16806. * @ngdoc method
  16807. * @name $rootScope.Scope#$apply
  16808. * @kind function
  16809. *
  16810. * @description
  16811. * `$apply()` is used to execute an expression in angular from outside of the angular
  16812. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  16813. * Because we are calling into the angular framework we need to perform proper scope life
  16814. * cycle of {@link ng.$exceptionHandler exception handling},
  16815. * {@link ng.$rootScope.Scope#$digest executing watches}.
  16816. *
  16817. * **Life cycle: Pseudo-Code of `$apply()`**
  16818. *
  16819. * ```js
  16820. function $apply(expr) {
  16821. try {
  16822. return $eval(expr);
  16823. } catch (e) {
  16824. $exceptionHandler(e);
  16825. } finally {
  16826. $root.$digest();
  16827. }
  16828. }
  16829. * ```
  16830. *
  16831. *
  16832. * Scope's `$apply()` method transitions through the following stages:
  16833. *
  16834. * 1. The {@link guide/expression expression} is executed using the
  16835. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  16836. * 2. Any exceptions from the execution of the expression are forwarded to the
  16837. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16838. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  16839. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  16840. *
  16841. *
  16842. * @param {(string|function())=} exp An angular expression to be executed.
  16843. *
  16844. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16845. * - `function(scope)`: execute the function with current `scope` parameter.
  16846. *
  16847. * @returns {*} The result of evaluating the expression.
  16848. */
  16849. $apply: function(expr) {
  16850. try {
  16851. beginPhase('$apply');
  16852. try {
  16853. return this.$eval(expr);
  16854. } finally {
  16855. clearPhase();
  16856. }
  16857. } catch (e) {
  16858. $exceptionHandler(e);
  16859. } finally {
  16860. try {
  16861. $rootScope.$digest();
  16862. } catch (e) {
  16863. $exceptionHandler(e);
  16864. // eslint-disable-next-line no-unsafe-finally
  16865. throw e;
  16866. }
  16867. }
  16868. },
  16869. /**
  16870. * @ngdoc method
  16871. * @name $rootScope.Scope#$applyAsync
  16872. * @kind function
  16873. *
  16874. * @description
  16875. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  16876. * varies across browsers, but is typically around ~10 milliseconds.
  16877. *
  16878. * This can be used to queue up multiple expressions which need to be evaluated in the same
  16879. * digest.
  16880. *
  16881. * @param {(string|function())=} exp An angular expression to be executed.
  16882. *
  16883. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  16884. * - `function(scope)`: execute the function with current `scope` parameter.
  16885. */
  16886. $applyAsync: function(expr) {
  16887. var scope = this;
  16888. if (expr) {
  16889. applyAsyncQueue.push($applyAsyncExpression);
  16890. }
  16891. expr = $parse(expr);
  16892. scheduleApplyAsync();
  16893. function $applyAsyncExpression() {
  16894. scope.$eval(expr);
  16895. }
  16896. },
  16897. /**
  16898. * @ngdoc method
  16899. * @name $rootScope.Scope#$on
  16900. * @kind function
  16901. *
  16902. * @description
  16903. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  16904. * discussion of event life cycle.
  16905. *
  16906. * The event listener function format is: `function(event, args...)`. The `event` object
  16907. * passed into the listener has the following attributes:
  16908. *
  16909. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  16910. * `$broadcast`-ed.
  16911. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  16912. * event propagates through the scope hierarchy, this property is set to null.
  16913. * - `name` - `{string}`: name of the event.
  16914. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  16915. * further event propagation (available only for events that were `$emit`-ed).
  16916. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  16917. * to true.
  16918. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  16919. *
  16920. * @param {string} name Event name to listen on.
  16921. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  16922. * @returns {function()} Returns a deregistration function for this listener.
  16923. */
  16924. $on: function(name, listener) {
  16925. var namedListeners = this.$$listeners[name];
  16926. if (!namedListeners) {
  16927. this.$$listeners[name] = namedListeners = [];
  16928. }
  16929. namedListeners.push(listener);
  16930. var current = this;
  16931. do {
  16932. if (!current.$$listenerCount[name]) {
  16933. current.$$listenerCount[name] = 0;
  16934. }
  16935. current.$$listenerCount[name]++;
  16936. } while ((current = current.$parent));
  16937. var self = this;
  16938. return function() {
  16939. var indexOfListener = namedListeners.indexOf(listener);
  16940. if (indexOfListener !== -1) {
  16941. // Use delete in the hope of the browser deallocating the memory for the array entry,
  16942. // while not shifting the array indexes of other listeners.
  16943. // See issue https://github.com/angular/angular.js/issues/16135
  16944. delete namedListeners[indexOfListener];
  16945. decrementListenerCount(self, 1, name);
  16946. }
  16947. };
  16948. },
  16949. /**
  16950. * @ngdoc method
  16951. * @name $rootScope.Scope#$emit
  16952. * @kind function
  16953. *
  16954. * @description
  16955. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  16956. * registered {@link ng.$rootScope.Scope#$on} listeners.
  16957. *
  16958. * The event life cycle starts at the scope on which `$emit` was called. All
  16959. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  16960. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  16961. * registered listeners along the way. The event will stop propagating if one of the listeners
  16962. * cancels it.
  16963. *
  16964. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  16965. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  16966. *
  16967. * @param {string} name Event name to emit.
  16968. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  16969. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  16970. */
  16971. $emit: function(name, args) {
  16972. var empty = [],
  16973. namedListeners,
  16974. scope = this,
  16975. stopPropagation = false,
  16976. event = {
  16977. name: name,
  16978. targetScope: scope,
  16979. stopPropagation: function() {stopPropagation = true;},
  16980. preventDefault: function() {
  16981. event.defaultPrevented = true;
  16982. },
  16983. defaultPrevented: false
  16984. },
  16985. listenerArgs = concat([event], arguments, 1),
  16986. i, length;
  16987. do {
  16988. namedListeners = scope.$$listeners[name] || empty;
  16989. event.currentScope = scope;
  16990. for (i = 0, length = namedListeners.length; i < length; i++) {
  16991. // if listeners were deregistered, defragment the array
  16992. if (!namedListeners[i]) {
  16993. namedListeners.splice(i, 1);
  16994. i--;
  16995. length--;
  16996. continue;
  16997. }
  16998. try {
  16999. //allow all listeners attached to the current scope to run
  17000. namedListeners[i].apply(null, listenerArgs);
  17001. } catch (e) {
  17002. $exceptionHandler(e);
  17003. }
  17004. }
  17005. //if any listener on the current scope stops propagation, prevent bubbling
  17006. if (stopPropagation) {
  17007. break;
  17008. }
  17009. //traverse upwards
  17010. scope = scope.$parent;
  17011. } while (scope);
  17012. event.currentScope = null;
  17013. return event;
  17014. },
  17015. /**
  17016. * @ngdoc method
  17017. * @name $rootScope.Scope#$broadcast
  17018. * @kind function
  17019. *
  17020. * @description
  17021. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  17022. * registered {@link ng.$rootScope.Scope#$on} listeners.
  17023. *
  17024. * The event life cycle starts at the scope on which `$broadcast` was called. All
  17025. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  17026. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  17027. * scope and calls all registered listeners along the way. The event cannot be canceled.
  17028. *
  17029. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  17030. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  17031. *
  17032. * @param {string} name Event name to broadcast.
  17033. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  17034. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  17035. */
  17036. $broadcast: function(name, args) {
  17037. var target = this,
  17038. current = target,
  17039. next = target,
  17040. event = {
  17041. name: name,
  17042. targetScope: target,
  17043. preventDefault: function() {
  17044. event.defaultPrevented = true;
  17045. },
  17046. defaultPrevented: false
  17047. };
  17048. if (!target.$$listenerCount[name]) return event;
  17049. var listenerArgs = concat([event], arguments, 1),
  17050. listeners, i, length;
  17051. //down while you can, then up and next sibling or up and next sibling until back at root
  17052. while ((current = next)) {
  17053. event.currentScope = current;
  17054. listeners = current.$$listeners[name] || [];
  17055. for (i = 0, length = listeners.length; i < length; i++) {
  17056. // if listeners were deregistered, defragment the array
  17057. if (!listeners[i]) {
  17058. listeners.splice(i, 1);
  17059. i--;
  17060. length--;
  17061. continue;
  17062. }
  17063. try {
  17064. listeners[i].apply(null, listenerArgs);
  17065. } catch (e) {
  17066. $exceptionHandler(e);
  17067. }
  17068. }
  17069. // Insanity Warning: scope depth-first traversal
  17070. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  17071. // this piece should be kept in sync with the traversal in $digest
  17072. // (though it differs due to having the extra check for $$listenerCount)
  17073. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  17074. (current !== target && current.$$nextSibling)))) {
  17075. while (current !== target && !(next = current.$$nextSibling)) {
  17076. current = current.$parent;
  17077. }
  17078. }
  17079. }
  17080. event.currentScope = null;
  17081. return event;
  17082. }
  17083. };
  17084. var $rootScope = new Scope();
  17085. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  17086. var asyncQueue = $rootScope.$$asyncQueue = [];
  17087. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  17088. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  17089. var postDigestQueuePosition = 0;
  17090. return $rootScope;
  17091. function beginPhase(phase) {
  17092. if ($rootScope.$$phase) {
  17093. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  17094. }
  17095. $rootScope.$$phase = phase;
  17096. }
  17097. function clearPhase() {
  17098. $rootScope.$$phase = null;
  17099. }
  17100. function incrementWatchersCount(current, count) {
  17101. do {
  17102. current.$$watchersCount += count;
  17103. } while ((current = current.$parent));
  17104. }
  17105. function decrementListenerCount(current, count, name) {
  17106. do {
  17107. current.$$listenerCount[name] -= count;
  17108. if (current.$$listenerCount[name] === 0) {
  17109. delete current.$$listenerCount[name];
  17110. }
  17111. } while ((current = current.$parent));
  17112. }
  17113. /**
  17114. * function used as an initial value for watchers.
  17115. * because it's unique we can easily tell it apart from other values
  17116. */
  17117. function initWatchVal() {}
  17118. function flushApplyAsync() {
  17119. while (applyAsyncQueue.length) {
  17120. try {
  17121. applyAsyncQueue.shift()();
  17122. } catch (e) {
  17123. $exceptionHandler(e);
  17124. }
  17125. }
  17126. applyAsyncId = null;
  17127. }
  17128. function scheduleApplyAsync() {
  17129. if (applyAsyncId === null) {
  17130. applyAsyncId = $browser.defer(function() {
  17131. $rootScope.$apply(flushApplyAsync);
  17132. });
  17133. }
  17134. }
  17135. }];
  17136. }
  17137. /**
  17138. * @ngdoc service
  17139. * @name $rootElement
  17140. *
  17141. * @description
  17142. * The root element of Angular application. This is either the element where {@link
  17143. * ng.directive:ngApp ngApp} was declared or the element passed into
  17144. * {@link angular.bootstrap}. The element represents the root element of application. It is also the
  17145. * location where the application's {@link auto.$injector $injector} service gets
  17146. * published, and can be retrieved using `$rootElement.injector()`.
  17147. */
  17148. // the implementation is in angular.bootstrap
  17149. /**
  17150. * @this
  17151. * @description
  17152. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  17153. */
  17154. function $$SanitizeUriProvider() {
  17155. var aHrefSanitizationWhitelist = /^\s*(https?|s?ftp|mailto|tel|file):/,
  17156. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  17157. /**
  17158. * @description
  17159. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  17160. * urls during a[href] sanitization.
  17161. *
  17162. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  17163. *
  17164. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  17165. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  17166. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  17167. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  17168. *
  17169. * @param {RegExp=} regexp New regexp to whitelist urls with.
  17170. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  17171. * chaining otherwise.
  17172. */
  17173. this.aHrefSanitizationWhitelist = function(regexp) {
  17174. if (isDefined(regexp)) {
  17175. aHrefSanitizationWhitelist = regexp;
  17176. return this;
  17177. }
  17178. return aHrefSanitizationWhitelist;
  17179. };
  17180. /**
  17181. * @description
  17182. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  17183. * urls during img[src] sanitization.
  17184. *
  17185. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  17186. *
  17187. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  17188. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  17189. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  17190. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  17191. *
  17192. * @param {RegExp=} regexp New regexp to whitelist urls with.
  17193. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  17194. * chaining otherwise.
  17195. */
  17196. this.imgSrcSanitizationWhitelist = function(regexp) {
  17197. if (isDefined(regexp)) {
  17198. imgSrcSanitizationWhitelist = regexp;
  17199. return this;
  17200. }
  17201. return imgSrcSanitizationWhitelist;
  17202. };
  17203. this.$get = function() {
  17204. return function sanitizeUri(uri, isImage) {
  17205. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  17206. var normalizedVal;
  17207. normalizedVal = urlResolve(uri && uri.trim()).href;
  17208. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  17209. return 'unsafe:' + normalizedVal;
  17210. }
  17211. return uri;
  17212. };
  17213. };
  17214. }
  17215. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  17216. * Any commits to this file should be reviewed with security in mind. *
  17217. * Changes to this file can potentially create security vulnerabilities. *
  17218. * An approval from 2 Core members with history of modifying *
  17219. * this file is required. *
  17220. * *
  17221. * Does the change somehow allow for arbitrary javascript to be executed? *
  17222. * Or allows for someone to change the prototype of built-in objects? *
  17223. * Or gives undesired access to variables likes document or window? *
  17224. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  17225. /* exported $SceProvider, $SceDelegateProvider */
  17226. var $sceMinErr = minErr('$sce');
  17227. var SCE_CONTEXTS = {
  17228. // HTML is used when there's HTML rendered (e.g. ng-bind-html, iframe srcdoc binding).
  17229. HTML: 'html',
  17230. // Style statements or stylesheets. Currently unused in AngularJS.
  17231. CSS: 'css',
  17232. // An URL used in a context where it does not refer to a resource that loads code. Currently
  17233. // unused in AngularJS.
  17234. URL: 'url',
  17235. // RESOURCE_URL is a subtype of URL used where the referred-to resource could be interpreted as
  17236. // code. (e.g. ng-include, script src binding, templateUrl)
  17237. RESOURCE_URL: 'resourceUrl',
  17238. // Script. Currently unused in AngularJS.
  17239. JS: 'js'
  17240. };
  17241. // Helper functions follow.
  17242. var UNDERSCORE_LOWERCASE_REGEXP = /_([a-z])/g;
  17243. function snakeToCamel(name) {
  17244. return name
  17245. .replace(UNDERSCORE_LOWERCASE_REGEXP, fnCamelCaseReplace);
  17246. }
  17247. function adjustMatcher(matcher) {
  17248. if (matcher === 'self') {
  17249. return matcher;
  17250. } else if (isString(matcher)) {
  17251. // Strings match exactly except for 2 wildcards - '*' and '**'.
  17252. // '*' matches any character except those from the set ':/.?&'.
  17253. // '**' matches any character (like .* in a RegExp).
  17254. // More than 2 *'s raises an error as it's ill defined.
  17255. if (matcher.indexOf('***') > -1) {
  17256. throw $sceMinErr('iwcard',
  17257. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  17258. }
  17259. matcher = escapeForRegexp(matcher).
  17260. replace(/\\\*\\\*/g, '.*').
  17261. replace(/\\\*/g, '[^:/.?&;]*');
  17262. return new RegExp('^' + matcher + '$');
  17263. } else if (isRegExp(matcher)) {
  17264. // The only other type of matcher allowed is a Regexp.
  17265. // Match entire URL / disallow partial matches.
  17266. // Flags are reset (i.e. no global, ignoreCase or multiline)
  17267. return new RegExp('^' + matcher.source + '$');
  17268. } else {
  17269. throw $sceMinErr('imatcher',
  17270. 'Matchers may only be "self", string patterns or RegExp objects');
  17271. }
  17272. }
  17273. function adjustMatchers(matchers) {
  17274. var adjustedMatchers = [];
  17275. if (isDefined(matchers)) {
  17276. forEach(matchers, function(matcher) {
  17277. adjustedMatchers.push(adjustMatcher(matcher));
  17278. });
  17279. }
  17280. return adjustedMatchers;
  17281. }
  17282. /**
  17283. * @ngdoc service
  17284. * @name $sceDelegate
  17285. * @kind function
  17286. *
  17287. * @description
  17288. *
  17289. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  17290. * Contextual Escaping (SCE)} services to AngularJS.
  17291. *
  17292. * For an overview of this service and the functionnality it provides in AngularJS, see the main
  17293. * page for {@link ng.$sce SCE}. The current page is targeted for developers who need to alter how
  17294. * SCE works in their application, which shouldn't be needed in most cases.
  17295. *
  17296. * <div class="alert alert-danger">
  17297. * AngularJS strongly relies on contextual escaping for the security of bindings: disabling or
  17298. * modifying this might cause cross site scripting (XSS) vulnerabilities. For libraries owners,
  17299. * changes to this service will also influence users, so be extra careful and document your changes.
  17300. * </div>
  17301. *
  17302. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  17303. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  17304. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  17305. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  17306. * work because `$sce` delegates to `$sceDelegate` for these operations.
  17307. *
  17308. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  17309. *
  17310. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  17311. * can override it completely to change the behavior of `$sce`, the common case would
  17312. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  17313. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  17314. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  17315. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  17316. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  17317. */
  17318. /**
  17319. * @ngdoc provider
  17320. * @name $sceDelegateProvider
  17321. * @this
  17322. *
  17323. * @description
  17324. *
  17325. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  17326. * $sceDelegate service}, used as a delegate for {@link ng.$sce Strict Contextual Escaping (SCE)}.
  17327. *
  17328. * The `$sceDelegateProvider` allows one to get/set the whitelists and blacklists used to ensure
  17329. * that the URLs used for sourcing AngularJS templates and other script-running URLs are safe (all
  17330. * places that use the `$sce.RESOURCE_URL` context). See
  17331. * {@link ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist}
  17332. * and
  17333. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist},
  17334. *
  17335. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  17336. * Strict Contextual Escaping (SCE)}.
  17337. *
  17338. * **Example**: Consider the following case. <a name="example"></a>
  17339. *
  17340. * - your app is hosted at url `http://myapp.example.com/`
  17341. * - but some of your templates are hosted on other domains you control such as
  17342. * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
  17343. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  17344. *
  17345. * Here is what a secure configuration for this scenario might look like:
  17346. *
  17347. * ```
  17348. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  17349. * $sceDelegateProvider.resourceUrlWhitelist([
  17350. * // Allow same origin resource loads.
  17351. * 'self',
  17352. * // Allow loading from our assets domain. Notice the difference between * and **.
  17353. * 'http://srv*.assets.example.com/**'
  17354. * ]);
  17355. *
  17356. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  17357. * $sceDelegateProvider.resourceUrlBlacklist([
  17358. * 'http://myapp.example.com/clickThru**'
  17359. * ]);
  17360. * });
  17361. * ```
  17362. * Note that an empty whitelist will block every resource URL from being loaded, and will require
  17363. * you to manually mark each one as trusted with `$sce.trustAsResourceUrl`. However, templates
  17364. * requested by {@link ng.$templateRequest $templateRequest} that are present in
  17365. * {@link ng.$templateCache $templateCache} will not go through this check. If you have a mechanism
  17366. * to populate your templates in that cache at config time, then it is a good idea to remove 'self'
  17367. * from that whitelist. This helps to mitigate the security impact of certain types of issues, like
  17368. * for instance attacker-controlled `ng-includes`.
  17369. */
  17370. function $SceDelegateProvider() {
  17371. this.SCE_CONTEXTS = SCE_CONTEXTS;
  17372. // Resource URLs can also be trusted by policy.
  17373. var resourceUrlWhitelist = ['self'],
  17374. resourceUrlBlacklist = [];
  17375. /**
  17376. * @ngdoc method
  17377. * @name $sceDelegateProvider#resourceUrlWhitelist
  17378. * @kind function
  17379. *
  17380. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  17381. * provided. This must be an array or null. A snapshot of this array is used so further
  17382. * changes to the array are ignored.
  17383. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  17384. * allowed in this array.
  17385. *
  17386. * @return {Array} The currently set whitelist array.
  17387. *
  17388. * @description
  17389. * Sets/Gets the whitelist of trusted resource URLs.
  17390. *
  17391. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  17392. * same origin resource requests.
  17393. *
  17394. * <div class="alert alert-warning">
  17395. * **Note:** the default whitelist of 'self' is not recommended if your app shares its origin
  17396. * with other apps! It is a good idea to limit it to only your application's directory.
  17397. * </div>
  17398. */
  17399. this.resourceUrlWhitelist = function(value) {
  17400. if (arguments.length) {
  17401. resourceUrlWhitelist = adjustMatchers(value);
  17402. }
  17403. return resourceUrlWhitelist;
  17404. };
  17405. /**
  17406. * @ngdoc method
  17407. * @name $sceDelegateProvider#resourceUrlBlacklist
  17408. * @kind function
  17409. *
  17410. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  17411. * provided. This must be an array or null. A snapshot of this array is used so further
  17412. * changes to the array are ignored.</p><p>
  17413. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  17414. * allowed in this array.</p><p>
  17415. * The typical usage for the blacklist is to **block
  17416. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  17417. * these would otherwise be trusted but actually return content from the redirected domain.
  17418. * </p><p>
  17419. * Finally, **the blacklist overrides the whitelist** and has the final say.
  17420. *
  17421. * @return {Array} The currently set blacklist array.
  17422. *
  17423. * @description
  17424. * Sets/Gets the blacklist of trusted resource URLs.
  17425. *
  17426. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  17427. * is no blacklist.)
  17428. */
  17429. this.resourceUrlBlacklist = function(value) {
  17430. if (arguments.length) {
  17431. resourceUrlBlacklist = adjustMatchers(value);
  17432. }
  17433. return resourceUrlBlacklist;
  17434. };
  17435. this.$get = ['$injector', function($injector) {
  17436. var htmlSanitizer = function htmlSanitizer(html) {
  17437. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  17438. };
  17439. if ($injector.has('$sanitize')) {
  17440. htmlSanitizer = $injector.get('$sanitize');
  17441. }
  17442. function matchUrl(matcher, parsedUrl) {
  17443. if (matcher === 'self') {
  17444. return urlIsSameOrigin(parsedUrl);
  17445. } else {
  17446. // definitely a regex. See adjustMatchers()
  17447. return !!matcher.exec(parsedUrl.href);
  17448. }
  17449. }
  17450. function isResourceUrlAllowedByPolicy(url) {
  17451. var parsedUrl = urlResolve(url.toString());
  17452. var i, n, allowed = false;
  17453. // Ensure that at least one item from the whitelist allows this url.
  17454. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  17455. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  17456. allowed = true;
  17457. break;
  17458. }
  17459. }
  17460. if (allowed) {
  17461. // Ensure that no item from the blacklist blocked this url.
  17462. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  17463. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  17464. allowed = false;
  17465. break;
  17466. }
  17467. }
  17468. }
  17469. return allowed;
  17470. }
  17471. function generateHolderType(Base) {
  17472. var holderType = function TrustedValueHolderType(trustedValue) {
  17473. this.$$unwrapTrustedValue = function() {
  17474. return trustedValue;
  17475. };
  17476. };
  17477. if (Base) {
  17478. holderType.prototype = new Base();
  17479. }
  17480. holderType.prototype.valueOf = function sceValueOf() {
  17481. return this.$$unwrapTrustedValue();
  17482. };
  17483. holderType.prototype.toString = function sceToString() {
  17484. return this.$$unwrapTrustedValue().toString();
  17485. };
  17486. return holderType;
  17487. }
  17488. var trustedValueHolderBase = generateHolderType(),
  17489. byType = {};
  17490. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  17491. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  17492. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  17493. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  17494. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  17495. /**
  17496. * @ngdoc method
  17497. * @name $sceDelegate#trustAs
  17498. *
  17499. * @description
  17500. * Returns a trusted representation of the parameter for the specified context. This trusted
  17501. * object will later on be used as-is, without any security check, by bindings or directives
  17502. * that require this security context.
  17503. * For instance, marking a string as trusted for the `$sce.HTML` context will entirely bypass
  17504. * the potential `$sanitize` call in corresponding `$sce.HTML` bindings or directives, such as
  17505. * `ng-bind-html`. Note that in most cases you won't need to call this function: if you have the
  17506. * sanitizer loaded, passing the value itself will render all the HTML that does not pose a
  17507. * security risk.
  17508. *
  17509. * See {@link ng.$sceDelegate#getTrusted getTrusted} for the function that will consume those
  17510. * trusted values, and {@link ng.$sce $sce} for general documentation about strict contextual
  17511. * escaping.
  17512. *
  17513. * @param {string} type The context in which this value is safe for use, e.g. `$sce.URL`,
  17514. * `$sce.RESOURCE_URL`, `$sce.HTML`, `$sce.JS` or `$sce.CSS`.
  17515. *
  17516. * @param {*} value The value that should be considered trusted.
  17517. * @return {*} A trusted representation of value, that can be used in the given context.
  17518. */
  17519. function trustAs(type, trustedValue) {
  17520. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  17521. if (!Constructor) {
  17522. throw $sceMinErr('icontext',
  17523. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  17524. type, trustedValue);
  17525. }
  17526. if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
  17527. return trustedValue;
  17528. }
  17529. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  17530. // mutable objects, we ensure here that the value passed in is actually a string.
  17531. if (typeof trustedValue !== 'string') {
  17532. throw $sceMinErr('itype',
  17533. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  17534. type);
  17535. }
  17536. return new Constructor(trustedValue);
  17537. }
  17538. /**
  17539. * @ngdoc method
  17540. * @name $sceDelegate#valueOf
  17541. *
  17542. * @description
  17543. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  17544. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  17545. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  17546. *
  17547. * If the passed parameter is not a value that had been returned by {@link
  17548. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, it must be returned as-is.
  17549. *
  17550. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  17551. * call or anything else.
  17552. * @return {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  17553. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  17554. * `value` unchanged.
  17555. */
  17556. function valueOf(maybeTrusted) {
  17557. if (maybeTrusted instanceof trustedValueHolderBase) {
  17558. return maybeTrusted.$$unwrapTrustedValue();
  17559. } else {
  17560. return maybeTrusted;
  17561. }
  17562. }
  17563. /**
  17564. * @ngdoc method
  17565. * @name $sceDelegate#getTrusted
  17566. *
  17567. * @description
  17568. * Takes any input, and either returns a value that's safe to use in the specified context, or
  17569. * throws an exception.
  17570. *
  17571. * In practice, there are several cases. When given a string, this function runs checks
  17572. * and sanitization to make it safe without prior assumptions. When given the result of a {@link
  17573. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call, it returns the originally supplied
  17574. * value if that value's context is valid for this call's context. Finally, this function can
  17575. * also throw when there is no way to turn `maybeTrusted` in a safe value (e.g., no sanitization
  17576. * is available or possible.)
  17577. *
  17578. * @param {string} type The context in which this value is to be used (such as `$sce.HTML`).
  17579. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  17580. * `$sceDelegate.trustAs`} call, or anything else (which will not be considered trusted.)
  17581. * @return {*} A version of the value that's safe to use in the given context, or throws an
  17582. * exception if this is impossible.
  17583. */
  17584. function getTrusted(type, maybeTrusted) {
  17585. if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
  17586. return maybeTrusted;
  17587. }
  17588. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  17589. // If maybeTrusted is a trusted class instance or subclass instance, then unwrap and return
  17590. // as-is.
  17591. if (constructor && maybeTrusted instanceof constructor) {
  17592. return maybeTrusted.$$unwrapTrustedValue();
  17593. }
  17594. // Otherwise, if we get here, then we may either make it safe, or throw an exception. This
  17595. // depends on the context: some are sanitizatible (HTML), some use whitelists (RESOURCE_URL),
  17596. // some are impossible to do (JS). This step isn't implemented for CSS and URL, as AngularJS
  17597. // has no corresponding sinks.
  17598. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  17599. // RESOURCE_URL uses a whitelist.
  17600. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  17601. return maybeTrusted;
  17602. } else {
  17603. throw $sceMinErr('insecurl',
  17604. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  17605. maybeTrusted.toString());
  17606. }
  17607. } else if (type === SCE_CONTEXTS.HTML) {
  17608. // htmlSanitizer throws its own error when no sanitizer is available.
  17609. return htmlSanitizer(maybeTrusted);
  17610. }
  17611. // Default error when the $sce service has no way to make the input safe.
  17612. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  17613. }
  17614. return { trustAs: trustAs,
  17615. getTrusted: getTrusted,
  17616. valueOf: valueOf };
  17617. }];
  17618. }
  17619. /**
  17620. * @ngdoc provider
  17621. * @name $sceProvider
  17622. * @this
  17623. *
  17624. * @description
  17625. *
  17626. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  17627. * - enable/disable Strict Contextual Escaping (SCE) in a module
  17628. * - override the default implementation with a custom delegate
  17629. *
  17630. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  17631. */
  17632. /**
  17633. * @ngdoc service
  17634. * @name $sce
  17635. * @kind function
  17636. *
  17637. * @description
  17638. *
  17639. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  17640. *
  17641. * ## Strict Contextual Escaping
  17642. *
  17643. * Strict Contextual Escaping (SCE) is a mode in which AngularJS constrains bindings to only render
  17644. * trusted values. Its goal is to assist in writing code in a way that (a) is secure by default, and
  17645. * (b) makes auditing for security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  17646. *
  17647. * ### Overview
  17648. *
  17649. * To systematically block XSS security bugs, AngularJS treats all values as untrusted by default in
  17650. * HTML or sensitive URL bindings. When binding untrusted values, AngularJS will automatically
  17651. * run security checks on them (sanitizations, whitelists, depending on context), or throw when it
  17652. * cannot guarantee the security of the result. That behavior depends strongly on contexts: HTML
  17653. * can be sanitized, but template URLs cannot, for instance.
  17654. *
  17655. * To illustrate this, consider the `ng-bind-html` directive. It renders its value directly as HTML:
  17656. * we call that the *context*. When given an untrusted input, AngularJS will attempt to sanitize it
  17657. * before rendering if a sanitizer is available, and throw otherwise. To bypass sanitization and
  17658. * render the input as-is, you will need to mark it as trusted for that context before attempting
  17659. * to bind it.
  17660. *
  17661. * As of version 1.2, AngularJS ships with SCE enabled by default.
  17662. *
  17663. * ### In practice
  17664. *
  17665. * Here's an example of a binding in a privileged context:
  17666. *
  17667. * ```
  17668. * <input ng-model="userHtml" aria-label="User input">
  17669. * <div ng-bind-html="userHtml"></div>
  17670. * ```
  17671. *
  17672. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  17673. * disabled, this application allows the user to render arbitrary HTML into the DIV, which would
  17674. * be an XSS security bug. In a more realistic example, one may be rendering user comments, blog
  17675. * articles, etc. via bindings. (HTML is just one example of a context where rendering user
  17676. * controlled input creates security vulnerabilities.)
  17677. *
  17678. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  17679. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  17680. *
  17681. * How would you ensure that every place that used these types of bindings was bound to a value that
  17682. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  17683. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  17684. * properties/fields and forgot to update the binding to the sanitized value?
  17685. *
  17686. * To be secure by default, AngularJS makes sure bindings go through that sanitization, or
  17687. * any similar validation process, unless there's a good reason to trust the given value in this
  17688. * context. That trust is formalized with a function call. This means that as a developer, you
  17689. * can assume all untrusted bindings are safe. Then, to audit your code for binding security issues,
  17690. * you just need to ensure the values you mark as trusted indeed are safe - because they were
  17691. * received from your server, sanitized by your library, etc. You can organize your codebase to
  17692. * help with this - perhaps allowing only the files in a specific directory to do this.
  17693. * Ensuring that the internal API exposed by that code doesn't markup arbitrary values as safe then
  17694. * becomes a more manageable task.
  17695. *
  17696. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  17697. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  17698. * build the trusted versions of your values.
  17699. *
  17700. * ### How does it work?
  17701. *
  17702. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  17703. * $sce.getTrusted(context, value)} rather than to the value directly. Think of this function as
  17704. * a way to enforce the required security context in your data sink. Directives use {@link
  17705. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs
  17706. * the {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals. Also,
  17707. * when binding without directives, AngularJS will understand the context of your bindings
  17708. * automatically.
  17709. *
  17710. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  17711. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  17712. * simplified):
  17713. *
  17714. * ```
  17715. * var ngBindHtmlDirective = ['$sce', function($sce) {
  17716. * return function(scope, element, attr) {
  17717. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  17718. * element.html(value || '');
  17719. * });
  17720. * };
  17721. * }];
  17722. * ```
  17723. *
  17724. * ### Impact on loading templates
  17725. *
  17726. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  17727. * `templateUrl`'s specified by {@link guide/directive directives}.
  17728. *
  17729. * By default, Angular only loads templates from the same domain and protocol as the application
  17730. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  17731. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  17732. * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  17733. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  17734. *
  17735. * *Please note*:
  17736. * The browser's
  17737. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  17738. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  17739. * policy apply in addition to this and may further restrict whether the template is successfully
  17740. * loaded. This means that without the right CORS policy, loading templates from a different domain
  17741. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  17742. * browsers.
  17743. *
  17744. * ### This feels like too much overhead
  17745. *
  17746. * It's important to remember that SCE only applies to interpolation expressions.
  17747. *
  17748. * If your expressions are constant literals, they're automatically trusted and you don't need to
  17749. * call `$sce.trustAs` on them (e.g.
  17750. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works. The `$sceDelegate` will
  17751. * also use the `$sanitize` service if it is available when binding untrusted values to
  17752. * `$sce.HTML` context. AngularJS provides an implementation in `angular-sanitize.js`, and if you
  17753. * wish to use it, you will also need to depend on the {@link ngSanitize `ngSanitize`} module in
  17754. * your application.
  17755. *
  17756. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  17757. * templates in `ng-include` from your application's domain without having to even know about SCE.
  17758. * It blocks loading templates from other domains or loading templates over http from an https
  17759. * served document. You can change these by setting your own custom {@link
  17760. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  17761. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  17762. *
  17763. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  17764. * application that's secure and can be audited to verify that with much more ease than bolting
  17765. * security onto an application later.
  17766. *
  17767. * <a name="contexts"></a>
  17768. * ### What trusted context types are supported?
  17769. *
  17770. * | Context | Notes |
  17771. * |---------------------|----------------|
  17772. * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered, and the {@link ngSanitize.$sanitize $sanitize} service is available (implemented by the {@link ngSanitize ngSanitize} module) this will sanitize the value instead of throwing an error. |
  17773. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently, no bindings require this context. Feel free to use it in your own directives. |
  17774. * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=`, `<img src=`, and some others sanitize their urls and don't constitute an SCE context.) |
  17775. * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG`, `VIDEO`, `AUDIO`, `SOURCE`, and `TRACK` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does (it's not just the URL that matters, but also what is at the end of it), and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
  17776. * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently, no bindings require this context. Feel free to use it in your own directives. |
  17777. *
  17778. *
  17779. * Be aware that `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  17780. * through {@link ng.$sce#getTrusted $sce.getTrusted}. There's no CSS-, URL-, or JS-context bindings
  17781. * in AngularJS currently, so their corresponding `$sce.trustAs` functions aren't useful yet. This
  17782. * might evolve.
  17783. *
  17784. * ### Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  17785. *
  17786. * Each element in these arrays must be one of the following:
  17787. *
  17788. * - **'self'**
  17789. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  17790. * domain** as the application document using the **same protocol**.
  17791. * - **String** (except the special value `'self'`)
  17792. * - The string is matched against the full *normalized / absolute URL* of the resource
  17793. * being tested (substring matches are not good enough.)
  17794. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  17795. * match themselves.
  17796. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  17797. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
  17798. * in a whitelist.
  17799. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  17800. * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
  17801. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  17802. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  17803. * http://foo.example.com/templates/**).
  17804. * - **RegExp** (*see caveat below*)
  17805. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  17806. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  17807. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  17808. * have good test coverage). For instance, the use of `.` in the regex is correct only in a
  17809. * small number of cases. A `.` character in the regex used when matching the scheme or a
  17810. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  17811. * is highly recommended to use the string patterns and only fall back to regular expressions
  17812. * as a last resort.
  17813. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  17814. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  17815. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  17816. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  17817. * - If you are generating your JavaScript from some other templating engine (not
  17818. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  17819. * remember to escape your regular expression (and be aware that you might need more than
  17820. * one level of escaping depending on your templating engine and the way you interpolated
  17821. * the value.) Do make use of your platform's escaping mechanism as it might be good
  17822. * enough before coding your own. E.g. Ruby has
  17823. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  17824. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  17825. * Javascript lacks a similar built in function for escaping. Take a look at Google
  17826. * Closure library's [goog.string.regExpEscape(s)](
  17827. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  17828. *
  17829. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  17830. *
  17831. * ### Show me an example using SCE.
  17832. *
  17833. * <example module="mySceApp" deps="angular-sanitize.js" name="sce-service">
  17834. * <file name="index.html">
  17835. * <div ng-controller="AppController as myCtrl">
  17836. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  17837. * <b>User comments</b><br>
  17838. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  17839. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  17840. * exploit.
  17841. * <div class="well">
  17842. * <div ng-repeat="userComment in myCtrl.userComments">
  17843. * <b>{{userComment.name}}</b>:
  17844. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  17845. * <br>
  17846. * </div>
  17847. * </div>
  17848. * </div>
  17849. * </file>
  17850. *
  17851. * <file name="script.js">
  17852. * angular.module('mySceApp', ['ngSanitize'])
  17853. * .controller('AppController', ['$http', '$templateCache', '$sce',
  17854. * function AppController($http, $templateCache, $sce) {
  17855. * var self = this;
  17856. * $http.get('test_data.json', {cache: $templateCache}).then(function(response) {
  17857. * self.userComments = response.data;
  17858. * });
  17859. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  17860. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  17861. * 'sanitization.&quot;">Hover over this text.</span>');
  17862. * }]);
  17863. * </file>
  17864. *
  17865. * <file name="test_data.json">
  17866. * [
  17867. * { "name": "Alice",
  17868. * "htmlComment":
  17869. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  17870. * },
  17871. * { "name": "Bob",
  17872. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  17873. * }
  17874. * ]
  17875. * </file>
  17876. *
  17877. * <file name="protractor.js" type="protractor">
  17878. * describe('SCE doc demo', function() {
  17879. * it('should sanitize untrusted values', function() {
  17880. * expect(element.all(by.css('.htmlComment')).first().getAttribute('innerHTML'))
  17881. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  17882. * });
  17883. *
  17884. * it('should NOT sanitize explicitly trusted values', function() {
  17885. * expect(element(by.id('explicitlyTrustedHtml')).getAttribute('innerHTML')).toBe(
  17886. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  17887. * 'sanitization.&quot;">Hover over this text.</span>');
  17888. * });
  17889. * });
  17890. * </file>
  17891. * </example>
  17892. *
  17893. *
  17894. *
  17895. * ## Can I disable SCE completely?
  17896. *
  17897. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  17898. * for little coding overhead. It will be much harder to take an SCE disabled application and
  17899. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  17900. * for cases where you have a lot of existing code that was written before SCE was introduced and
  17901. * you're migrating them a module at a time. Also do note that this is an app-wide setting, so if
  17902. * you are writing a library, you will cause security bugs applications using it.
  17903. *
  17904. * That said, here's how you can completely disable SCE:
  17905. *
  17906. * ```
  17907. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  17908. * // Completely disable SCE. For demonstration purposes only!
  17909. * // Do not use in new projects or libraries.
  17910. * $sceProvider.enabled(false);
  17911. * });
  17912. * ```
  17913. *
  17914. */
  17915. function $SceProvider() {
  17916. var enabled = true;
  17917. /**
  17918. * @ngdoc method
  17919. * @name $sceProvider#enabled
  17920. * @kind function
  17921. *
  17922. * @param {boolean=} value If provided, then enables/disables SCE application-wide.
  17923. * @return {boolean} True if SCE is enabled, false otherwise.
  17924. *
  17925. * @description
  17926. * Enables/disables SCE and returns the current value.
  17927. */
  17928. this.enabled = function(value) {
  17929. if (arguments.length) {
  17930. enabled = !!value;
  17931. }
  17932. return enabled;
  17933. };
  17934. /* Design notes on the default implementation for SCE.
  17935. *
  17936. * The API contract for the SCE delegate
  17937. * -------------------------------------
  17938. * The SCE delegate object must provide the following 3 methods:
  17939. *
  17940. * - trustAs(contextEnum, value)
  17941. * This method is used to tell the SCE service that the provided value is OK to use in the
  17942. * contexts specified by contextEnum. It must return an object that will be accepted by
  17943. * getTrusted() for a compatible contextEnum and return this value.
  17944. *
  17945. * - valueOf(value)
  17946. * For values that were not produced by trustAs(), return them as is. For values that were
  17947. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  17948. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  17949. * such a value.
  17950. *
  17951. * - getTrusted(contextEnum, value)
  17952. * This function should return the a value that is safe to use in the context specified by
  17953. * contextEnum or throw and exception otherwise.
  17954. *
  17955. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  17956. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  17957. * instance, an implementation could maintain a registry of all trusted objects by context. In
  17958. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  17959. * return the same object passed in if it was found in the registry under a compatible context or
  17960. * throw an exception otherwise. An implementation might only wrap values some of the time based
  17961. * on some criteria. getTrusted() might return a value and not throw an exception for special
  17962. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  17963. *
  17964. *
  17965. * A note on the inheritance model for SCE contexts
  17966. * ------------------------------------------------
  17967. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  17968. * is purely an implementation details.
  17969. *
  17970. * The contract is simply this:
  17971. *
  17972. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  17973. * will also succeed.
  17974. *
  17975. * Inheritance happens to capture this in a natural way. In some future, we may not use
  17976. * inheritance anymore. That is OK because no code outside of sce.js and sceSpecs.js would need to
  17977. * be aware of this detail.
  17978. */
  17979. this.$get = ['$parse', '$sceDelegate', function(
  17980. $parse, $sceDelegate) {
  17981. // Support: IE 9-11 only
  17982. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  17983. // the "expression(javascript expression)" syntax which is insecure.
  17984. if (enabled && msie < 8) {
  17985. throw $sceMinErr('iequirks',
  17986. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  17987. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  17988. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  17989. }
  17990. var sce = shallowCopy(SCE_CONTEXTS);
  17991. /**
  17992. * @ngdoc method
  17993. * @name $sce#isEnabled
  17994. * @kind function
  17995. *
  17996. * @return {Boolean} True if SCE is enabled, false otherwise. If you want to set the value, you
  17997. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  17998. *
  17999. * @description
  18000. * Returns a boolean indicating if SCE is enabled.
  18001. */
  18002. sce.isEnabled = function() {
  18003. return enabled;
  18004. };
  18005. sce.trustAs = $sceDelegate.trustAs;
  18006. sce.getTrusted = $sceDelegate.getTrusted;
  18007. sce.valueOf = $sceDelegate.valueOf;
  18008. if (!enabled) {
  18009. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  18010. sce.valueOf = identity;
  18011. }
  18012. /**
  18013. * @ngdoc method
  18014. * @name $sce#parseAs
  18015. *
  18016. * @description
  18017. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  18018. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  18019. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  18020. * *result*)}
  18021. *
  18022. * @param {string} type The SCE context in which this result will be used.
  18023. * @param {string} expression String expression to compile.
  18024. * @return {function(context, locals)} A function which represents the compiled expression:
  18025. *
  18026. * * `context` – `{object}` – an object against which any expressions embedded in the
  18027. * strings are evaluated against (typically a scope object).
  18028. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  18029. * in `context`.
  18030. */
  18031. sce.parseAs = function sceParseAs(type, expr) {
  18032. var parsed = $parse(expr);
  18033. if (parsed.literal && parsed.constant) {
  18034. return parsed;
  18035. } else {
  18036. return $parse(expr, function(value) {
  18037. return sce.getTrusted(type, value);
  18038. });
  18039. }
  18040. };
  18041. /**
  18042. * @ngdoc method
  18043. * @name $sce#trustAs
  18044. *
  18045. * @description
  18046. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such, returns a
  18047. * wrapped object that represents your value, and the trust you have in its safety for the given
  18048. * context. AngularJS can then use that value as-is in bindings of the specified secure context.
  18049. * This is used in bindings for `ng-bind-html`, `ng-include`, and most `src` attribute
  18050. * interpolations. See {@link ng.$sce $sce} for strict contextual escaping.
  18051. *
  18052. * @param {string} type The context in which this value is safe for use, e.g. `$sce.URL`,
  18053. * `$sce.RESOURCE_URL`, `$sce.HTML`, `$sce.JS` or `$sce.CSS`.
  18054. *
  18055. * @param {*} value The value that that should be considered trusted.
  18056. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  18057. * in the context you specified.
  18058. */
  18059. /**
  18060. * @ngdoc method
  18061. * @name $sce#trustAsHtml
  18062. *
  18063. * @description
  18064. * Shorthand method. `$sce.trustAsHtml(value)` →
  18065. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  18066. *
  18067. * @param {*} value The value to mark as trusted for `$sce.HTML` context.
  18068. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  18069. * in `$sce.HTML` context (like `ng-bind-html`).
  18070. */
  18071. /**
  18072. * @ngdoc method
  18073. * @name $sce#trustAsCss
  18074. *
  18075. * @description
  18076. * Shorthand method. `$sce.trustAsCss(value)` →
  18077. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.CSS, value)`}
  18078. *
  18079. * @param {*} value The value to mark as trusted for `$sce.CSS` context.
  18080. * @return {*} A wrapped version of value that can be used as a trusted variant
  18081. * of your `value` in `$sce.CSS` context. This context is currently unused, so there are
  18082. * almost no reasons to use this function so far.
  18083. */
  18084. /**
  18085. * @ngdoc method
  18086. * @name $sce#trustAsUrl
  18087. *
  18088. * @description
  18089. * Shorthand method. `$sce.trustAsUrl(value)` →
  18090. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  18091. *
  18092. * @param {*} value The value to mark as trusted for `$sce.URL` context.
  18093. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  18094. * in `$sce.URL` context. That context is currently unused, so there are almost no reasons
  18095. * to use this function so far.
  18096. */
  18097. /**
  18098. * @ngdoc method
  18099. * @name $sce#trustAsResourceUrl
  18100. *
  18101. * @description
  18102. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  18103. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  18104. *
  18105. * @param {*} value The value to mark as trusted for `$sce.RESOURCE_URL` context.
  18106. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  18107. * in `$sce.RESOURCE_URL` context (template URLs in `ng-include`, most `src` attribute
  18108. * bindings, ...)
  18109. */
  18110. /**
  18111. * @ngdoc method
  18112. * @name $sce#trustAsJs
  18113. *
  18114. * @description
  18115. * Shorthand method. `$sce.trustAsJs(value)` →
  18116. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  18117. *
  18118. * @param {*} value The value to mark as trusted for `$sce.JS` context.
  18119. * @return {*} A wrapped version of value that can be used as a trusted variant of your `value`
  18120. * in `$sce.JS` context. That context is currently unused, so there are almost no reasons to
  18121. * use this function so far.
  18122. */
  18123. /**
  18124. * @ngdoc method
  18125. * @name $sce#getTrusted
  18126. *
  18127. * @description
  18128. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  18129. * takes any input, and either returns a value that's safe to use in the specified context,
  18130. * or throws an exception. This function is aware of trusted values created by the `trustAs`
  18131. * function and its shorthands, and when contexts are appropriate, returns the unwrapped value
  18132. * as-is. Finally, this function can also throw when there is no way to turn `maybeTrusted` in a
  18133. * safe value (e.g., no sanitization is available or possible.)
  18134. *
  18135. * @param {string} type The context in which this value is to be used.
  18136. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs
  18137. * `$sce.trustAs`} call, or anything else (which will not be considered trusted.)
  18138. * @return {*} A version of the value that's safe to use in the given context, or throws an
  18139. * exception if this is impossible.
  18140. */
  18141. /**
  18142. * @ngdoc method
  18143. * @name $sce#getTrustedHtml
  18144. *
  18145. * @description
  18146. * Shorthand method. `$sce.getTrustedHtml(value)` →
  18147. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  18148. *
  18149. * @param {*} value The value to pass to `$sce.getTrusted`.
  18150. * @return {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  18151. */
  18152. /**
  18153. * @ngdoc method
  18154. * @name $sce#getTrustedCss
  18155. *
  18156. * @description
  18157. * Shorthand method. `$sce.getTrustedCss(value)` →
  18158. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  18159. *
  18160. * @param {*} value The value to pass to `$sce.getTrusted`.
  18161. * @return {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  18162. */
  18163. /**
  18164. * @ngdoc method
  18165. * @name $sce#getTrustedUrl
  18166. *
  18167. * @description
  18168. * Shorthand method. `$sce.getTrustedUrl(value)` →
  18169. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  18170. *
  18171. * @param {*} value The value to pass to `$sce.getTrusted`.
  18172. * @return {*} The return value of `$sce.getTrusted($sce.URL, value)`
  18173. */
  18174. /**
  18175. * @ngdoc method
  18176. * @name $sce#getTrustedResourceUrl
  18177. *
  18178. * @description
  18179. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  18180. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  18181. *
  18182. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  18183. * @return {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  18184. */
  18185. /**
  18186. * @ngdoc method
  18187. * @name $sce#getTrustedJs
  18188. *
  18189. * @description
  18190. * Shorthand method. `$sce.getTrustedJs(value)` →
  18191. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  18192. *
  18193. * @param {*} value The value to pass to `$sce.getTrusted`.
  18194. * @return {*} The return value of `$sce.getTrusted($sce.JS, value)`
  18195. */
  18196. /**
  18197. * @ngdoc method
  18198. * @name $sce#parseAsHtml
  18199. *
  18200. * @description
  18201. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  18202. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  18203. *
  18204. * @param {string} expression String expression to compile.
  18205. * @return {function(context, locals)} A function which represents the compiled expression:
  18206. *
  18207. * * `context` – `{object}` – an object against which any expressions embedded in the
  18208. * strings are evaluated against (typically a scope object).
  18209. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  18210. * in `context`.
  18211. */
  18212. /**
  18213. * @ngdoc method
  18214. * @name $sce#parseAsCss
  18215. *
  18216. * @description
  18217. * Shorthand method. `$sce.parseAsCss(value)` →
  18218. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  18219. *
  18220. * @param {string} expression String expression to compile.
  18221. * @return {function(context, locals)} A function which represents the compiled expression:
  18222. *
  18223. * * `context` – `{object}` – an object against which any expressions embedded in the
  18224. * strings are evaluated against (typically a scope object).
  18225. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  18226. * in `context`.
  18227. */
  18228. /**
  18229. * @ngdoc method
  18230. * @name $sce#parseAsUrl
  18231. *
  18232. * @description
  18233. * Shorthand method. `$sce.parseAsUrl(value)` →
  18234. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  18235. *
  18236. * @param {string} expression String expression to compile.
  18237. * @return {function(context, locals)} A function which represents the compiled expression:
  18238. *
  18239. * * `context` – `{object}` – an object against which any expressions embedded in the
  18240. * strings are evaluated against (typically a scope object).
  18241. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  18242. * in `context`.
  18243. */
  18244. /**
  18245. * @ngdoc method
  18246. * @name $sce#parseAsResourceUrl
  18247. *
  18248. * @description
  18249. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  18250. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  18251. *
  18252. * @param {string} expression String expression to compile.
  18253. * @return {function(context, locals)} A function which represents the compiled expression:
  18254. *
  18255. * * `context` – `{object}` – an object against which any expressions embedded in the
  18256. * strings are evaluated against (typically a scope object).
  18257. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  18258. * in `context`.
  18259. */
  18260. /**
  18261. * @ngdoc method
  18262. * @name $sce#parseAsJs
  18263. *
  18264. * @description
  18265. * Shorthand method. `$sce.parseAsJs(value)` →
  18266. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  18267. *
  18268. * @param {string} expression String expression to compile.
  18269. * @return {function(context, locals)} A function which represents the compiled expression:
  18270. *
  18271. * * `context` – `{object}` – an object against which any expressions embedded in the
  18272. * strings are evaluated against (typically a scope object).
  18273. * * `locals` – `{object=}` – local variables context object, useful for overriding values
  18274. * in `context`.
  18275. */
  18276. // Shorthand delegations.
  18277. var parse = sce.parseAs,
  18278. getTrusted = sce.getTrusted,
  18279. trustAs = sce.trustAs;
  18280. forEach(SCE_CONTEXTS, function(enumValue, name) {
  18281. var lName = lowercase(name);
  18282. sce[snakeToCamel('parse_as_' + lName)] = function(expr) {
  18283. return parse(enumValue, expr);
  18284. };
  18285. sce[snakeToCamel('get_trusted_' + lName)] = function(value) {
  18286. return getTrusted(enumValue, value);
  18287. };
  18288. sce[snakeToCamel('trust_as_' + lName)] = function(value) {
  18289. return trustAs(enumValue, value);
  18290. };
  18291. });
  18292. return sce;
  18293. }];
  18294. }
  18295. /* exported $SnifferProvider */
  18296. /**
  18297. * !!! This is an undocumented "private" service !!!
  18298. *
  18299. * @name $sniffer
  18300. * @requires $window
  18301. * @requires $document
  18302. * @this
  18303. *
  18304. * @property {boolean} history Does the browser support html5 history api ?
  18305. * @property {boolean} transitions Does the browser support CSS transition events ?
  18306. * @property {boolean} animations Does the browser support CSS animation events ?
  18307. *
  18308. * @description
  18309. * This is very simple implementation of testing browser's features.
  18310. */
  18311. function $SnifferProvider() {
  18312. this.$get = ['$window', '$document', function($window, $document) {
  18313. var eventSupport = {},
  18314. // Chrome Packaged Apps are not allowed to access `history.pushState`.
  18315. // If not sandboxed, they can be detected by the presence of `chrome.app.runtime`
  18316. // (see https://developer.chrome.com/apps/api_index). If sandboxed, they can be detected by
  18317. // the presence of an extension runtime ID and the absence of other Chrome runtime APIs
  18318. // (see https://developer.chrome.com/apps/manifest/sandbox).
  18319. // (NW.js apps have access to Chrome APIs, but do support `history`.)
  18320. isNw = $window.nw && $window.nw.process,
  18321. isChromePackagedApp =
  18322. !isNw &&
  18323. $window.chrome &&
  18324. ($window.chrome.app && $window.chrome.app.runtime ||
  18325. !$window.chrome.app && $window.chrome.runtime && $window.chrome.runtime.id),
  18326. hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState,
  18327. android =
  18328. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  18329. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  18330. document = $document[0] || {},
  18331. bodyStyle = document.body && document.body.style,
  18332. transitions = false,
  18333. animations = false;
  18334. if (bodyStyle) {
  18335. // Support: Android <5, Blackberry Browser 10, default Chrome in Android 4.4.x
  18336. // Mentioned browsers need a -webkit- prefix for transitions & animations.
  18337. transitions = !!('transition' in bodyStyle || 'webkitTransition' in bodyStyle);
  18338. animations = !!('animation' in bodyStyle || 'webkitAnimation' in bodyStyle);
  18339. }
  18340. return {
  18341. // Android has history.pushState, but it does not update location correctly
  18342. // so let's not use the history API at all.
  18343. // http://code.google.com/p/android/issues/detail?id=17471
  18344. // https://github.com/angular/angular.js/issues/904
  18345. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  18346. // so let's not use the history API also
  18347. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  18348. history: !!(hasHistoryPushState && !(android < 4) && !boxee),
  18349. hasEvent: function(event) {
  18350. // Support: IE 9-11 only
  18351. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  18352. // it. In particular the event is not fired when backspace or delete key are pressed or
  18353. // when cut operation is performed.
  18354. // IE10+ implements 'input' event but it erroneously fires under various situations,
  18355. // e.g. when placeholder changes, or a form is focused.
  18356. if (event === 'input' && msie) return false;
  18357. if (isUndefined(eventSupport[event])) {
  18358. var divElm = document.createElement('div');
  18359. eventSupport[event] = 'on' + event in divElm;
  18360. }
  18361. return eventSupport[event];
  18362. },
  18363. csp: csp(),
  18364. transitions: transitions,
  18365. animations: animations,
  18366. android: android
  18367. };
  18368. }];
  18369. }
  18370. var $templateRequestMinErr = minErr('$compile');
  18371. /**
  18372. * @ngdoc provider
  18373. * @name $templateRequestProvider
  18374. * @this
  18375. *
  18376. * @description
  18377. * Used to configure the options passed to the {@link $http} service when making a template request.
  18378. *
  18379. * For example, it can be used for specifying the "Accept" header that is sent to the server, when
  18380. * requesting a template.
  18381. */
  18382. function $TemplateRequestProvider() {
  18383. var httpOptions;
  18384. /**
  18385. * @ngdoc method
  18386. * @name $templateRequestProvider#httpOptions
  18387. * @description
  18388. * The options to be passed to the {@link $http} service when making the request.
  18389. * You can use this to override options such as the "Accept" header for template requests.
  18390. *
  18391. * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
  18392. * options if not overridden here.
  18393. *
  18394. * @param {string=} value new value for the {@link $http} options.
  18395. * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.
  18396. */
  18397. this.httpOptions = function(val) {
  18398. if (val) {
  18399. httpOptions = val;
  18400. return this;
  18401. }
  18402. return httpOptions;
  18403. };
  18404. /**
  18405. * @ngdoc service
  18406. * @name $templateRequest
  18407. *
  18408. * @description
  18409. * The `$templateRequest` service runs security checks then downloads the provided template using
  18410. * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
  18411. * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
  18412. * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
  18413. * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
  18414. * when `tpl` is of type string and `$templateCache` has the matching entry.
  18415. *
  18416. * If you want to pass custom options to the `$http` service, such as setting the Accept header you
  18417. * can configure this via {@link $templateRequestProvider#httpOptions}.
  18418. *
  18419. * `$templateRequest` is used internally by {@link $compile}, {@link ngRoute.$route}, and directives such
  18420. * as {@link ngInclude} to download and cache templates.
  18421. *
  18422. * 3rd party modules should use `$templateRequest` if their services or directives are loading
  18423. * templates.
  18424. *
  18425. * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
  18426. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  18427. *
  18428. * @return {Promise} a promise for the HTTP response data of the given URL.
  18429. *
  18430. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  18431. */
  18432. this.$get = ['$exceptionHandler', '$templateCache', '$http', '$q', '$sce',
  18433. function($exceptionHandler, $templateCache, $http, $q, $sce) {
  18434. function handleRequestFn(tpl, ignoreRequestError) {
  18435. handleRequestFn.totalPendingRequests++;
  18436. // We consider the template cache holds only trusted templates, so
  18437. // there's no need to go through whitelisting again for keys that already
  18438. // are included in there. This also makes Angular accept any script
  18439. // directive, no matter its name. However, we still need to unwrap trusted
  18440. // types.
  18441. if (!isString(tpl) || isUndefined($templateCache.get(tpl))) {
  18442. tpl = $sce.getTrustedResourceUrl(tpl);
  18443. }
  18444. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  18445. if (isArray(transformResponse)) {
  18446. transformResponse = transformResponse.filter(function(transformer) {
  18447. return transformer !== defaultHttpResponseTransform;
  18448. });
  18449. } else if (transformResponse === defaultHttpResponseTransform) {
  18450. transformResponse = null;
  18451. }
  18452. return $http.get(tpl, extend({
  18453. cache: $templateCache,
  18454. transformResponse: transformResponse
  18455. }, httpOptions))
  18456. .finally(function() {
  18457. handleRequestFn.totalPendingRequests--;
  18458. })
  18459. .then(function(response) {
  18460. $templateCache.put(tpl, response.data);
  18461. return response.data;
  18462. }, handleError);
  18463. function handleError(resp) {
  18464. if (!ignoreRequestError) {
  18465. resp = $templateRequestMinErr('tpload',
  18466. 'Failed to load template: {0} (HTTP status: {1} {2})',
  18467. tpl, resp.status, resp.statusText);
  18468. $exceptionHandler(resp);
  18469. }
  18470. return $q.reject(resp);
  18471. }
  18472. }
  18473. handleRequestFn.totalPendingRequests = 0;
  18474. return handleRequestFn;
  18475. }
  18476. ];
  18477. }
  18478. /** @this */
  18479. function $$TestabilityProvider() {
  18480. this.$get = ['$rootScope', '$browser', '$location',
  18481. function($rootScope, $browser, $location) {
  18482. /**
  18483. * @name $testability
  18484. *
  18485. * @description
  18486. * The private $$testability service provides a collection of methods for use when debugging
  18487. * or by automated test and debugging tools.
  18488. */
  18489. var testability = {};
  18490. /**
  18491. * @name $$testability#findBindings
  18492. *
  18493. * @description
  18494. * Returns an array of elements that are bound (via ng-bind or {{}})
  18495. * to expressions matching the input.
  18496. *
  18497. * @param {Element} element The element root to search from.
  18498. * @param {string} expression The binding expression to match.
  18499. * @param {boolean} opt_exactMatch If true, only returns exact matches
  18500. * for the expression. Filters and whitespace are ignored.
  18501. */
  18502. testability.findBindings = function(element, expression, opt_exactMatch) {
  18503. var bindings = element.getElementsByClassName('ng-binding');
  18504. var matches = [];
  18505. forEach(bindings, function(binding) {
  18506. var dataBinding = angular.element(binding).data('$binding');
  18507. if (dataBinding) {
  18508. forEach(dataBinding, function(bindingName) {
  18509. if (opt_exactMatch) {
  18510. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  18511. if (matcher.test(bindingName)) {
  18512. matches.push(binding);
  18513. }
  18514. } else {
  18515. if (bindingName.indexOf(expression) !== -1) {
  18516. matches.push(binding);
  18517. }
  18518. }
  18519. });
  18520. }
  18521. });
  18522. return matches;
  18523. };
  18524. /**
  18525. * @name $$testability#findModels
  18526. *
  18527. * @description
  18528. * Returns an array of elements that are two-way found via ng-model to
  18529. * expressions matching the input.
  18530. *
  18531. * @param {Element} element The element root to search from.
  18532. * @param {string} expression The model expression to match.
  18533. * @param {boolean} opt_exactMatch If true, only returns exact matches
  18534. * for the expression.
  18535. */
  18536. testability.findModels = function(element, expression, opt_exactMatch) {
  18537. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  18538. for (var p = 0; p < prefixes.length; ++p) {
  18539. var attributeEquals = opt_exactMatch ? '=' : '*=';
  18540. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  18541. var elements = element.querySelectorAll(selector);
  18542. if (elements.length) {
  18543. return elements;
  18544. }
  18545. }
  18546. };
  18547. /**
  18548. * @name $$testability#getLocation
  18549. *
  18550. * @description
  18551. * Shortcut for getting the location in a browser agnostic way. Returns
  18552. * the path, search, and hash. (e.g. /path?a=b#hash)
  18553. */
  18554. testability.getLocation = function() {
  18555. return $location.url();
  18556. };
  18557. /**
  18558. * @name $$testability#setLocation
  18559. *
  18560. * @description
  18561. * Shortcut for navigating to a location without doing a full page reload.
  18562. *
  18563. * @param {string} url The location url (path, search and hash,
  18564. * e.g. /path?a=b#hash) to go to.
  18565. */
  18566. testability.setLocation = function(url) {
  18567. if (url !== $location.url()) {
  18568. $location.url(url);
  18569. $rootScope.$digest();
  18570. }
  18571. };
  18572. /**
  18573. * @name $$testability#whenStable
  18574. *
  18575. * @description
  18576. * Calls the callback when $timeout and $http requests are completed.
  18577. *
  18578. * @param {function} callback
  18579. */
  18580. testability.whenStable = function(callback) {
  18581. $browser.notifyWhenNoOutstandingRequests(callback);
  18582. };
  18583. return testability;
  18584. }];
  18585. }
  18586. /** @this */
  18587. function $TimeoutProvider() {
  18588. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  18589. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  18590. var deferreds = {};
  18591. /**
  18592. * @ngdoc service
  18593. * @name $timeout
  18594. *
  18595. * @description
  18596. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  18597. * block and delegates any exceptions to
  18598. * {@link ng.$exceptionHandler $exceptionHandler} service.
  18599. *
  18600. * The return value of calling `$timeout` is a promise, which will be resolved when
  18601. * the delay has passed and the timeout function, if provided, is executed.
  18602. *
  18603. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  18604. *
  18605. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  18606. * synchronously flush the queue of deferred functions.
  18607. *
  18608. * If you only want a promise that will be resolved after some specified delay
  18609. * then you can call `$timeout` without the `fn` function.
  18610. *
  18611. * @param {function()=} fn A function, whose execution should be delayed.
  18612. * @param {number=} [delay=0] Delay in milliseconds.
  18613. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  18614. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  18615. * @param {...*=} Pass additional parameters to the executed function.
  18616. * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise
  18617. * will be resolved with the return value of the `fn` function.
  18618. *
  18619. */
  18620. function timeout(fn, delay, invokeApply) {
  18621. if (!isFunction(fn)) {
  18622. invokeApply = delay;
  18623. delay = fn;
  18624. fn = noop;
  18625. }
  18626. var args = sliceArgs(arguments, 3),
  18627. skipApply = (isDefined(invokeApply) && !invokeApply),
  18628. deferred = (skipApply ? $$q : $q).defer(),
  18629. promise = deferred.promise,
  18630. timeoutId;
  18631. timeoutId = $browser.defer(function() {
  18632. try {
  18633. deferred.resolve(fn.apply(null, args));
  18634. } catch (e) {
  18635. deferred.reject(e);
  18636. $exceptionHandler(e);
  18637. } finally {
  18638. delete deferreds[promise.$$timeoutId];
  18639. }
  18640. if (!skipApply) $rootScope.$apply();
  18641. }, delay);
  18642. promise.$$timeoutId = timeoutId;
  18643. deferreds[timeoutId] = deferred;
  18644. return promise;
  18645. }
  18646. /**
  18647. * @ngdoc method
  18648. * @name $timeout#cancel
  18649. *
  18650. * @description
  18651. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  18652. * resolved with a rejection.
  18653. *
  18654. * @param {Promise=} promise Promise returned by the `$timeout` function.
  18655. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  18656. * canceled.
  18657. */
  18658. timeout.cancel = function(promise) {
  18659. if (promise && promise.$$timeoutId in deferreds) {
  18660. // Timeout cancels should not report an unhandled promise.
  18661. markQExceptionHandled(deferreds[promise.$$timeoutId].promise);
  18662. deferreds[promise.$$timeoutId].reject('canceled');
  18663. delete deferreds[promise.$$timeoutId];
  18664. return $browser.defer.cancel(promise.$$timeoutId);
  18665. }
  18666. return false;
  18667. };
  18668. return timeout;
  18669. }];
  18670. }
  18671. // NOTE: The usage of window and document instead of $window and $document here is
  18672. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  18673. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  18674. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  18675. // doesn't know about mocked locations and resolves URLs to the real document - which is
  18676. // exactly the behavior needed here. There is little value is mocking these out for this
  18677. // service.
  18678. var urlParsingNode = window.document.createElement('a');
  18679. var originUrl = urlResolve(window.location.href);
  18680. /**
  18681. *
  18682. * Implementation Notes for non-IE browsers
  18683. * ----------------------------------------
  18684. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  18685. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  18686. * URL will be resolved into an absolute URL in the context of the application document.
  18687. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  18688. * properties are all populated to reflect the normalized URL. This approach has wide
  18689. * compatibility - Safari 1+, Mozilla 1+ etc. See
  18690. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  18691. *
  18692. * Implementation Notes for IE
  18693. * ---------------------------
  18694. * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
  18695. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  18696. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  18697. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  18698. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  18699. * properties such as protocol, hostname, port, etc.
  18700. *
  18701. * References:
  18702. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  18703. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  18704. * http://url.spec.whatwg.org/#urlutils
  18705. * https://github.com/angular/angular.js/pull/2902
  18706. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  18707. *
  18708. * @kind function
  18709. * @param {string} url The URL to be parsed.
  18710. * @description Normalizes and parses a URL.
  18711. * @returns {object} Returns the normalized URL as a dictionary.
  18712. *
  18713. * | member name | Description |
  18714. * |---------------|----------------|
  18715. * | href | A normalized version of the provided URL if it was not an absolute URL |
  18716. * | protocol | The protocol including the trailing colon |
  18717. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  18718. * | search | The search params, minus the question mark |
  18719. * | hash | The hash string, minus the hash symbol
  18720. * | hostname | The hostname
  18721. * | port | The port, without ":"
  18722. * | pathname | The pathname, beginning with "/"
  18723. *
  18724. */
  18725. function urlResolve(url) {
  18726. var href = url;
  18727. // Support: IE 9-11 only
  18728. if (msie) {
  18729. // Normalize before parse. Refer Implementation Notes on why this is
  18730. // done in two steps on IE.
  18731. urlParsingNode.setAttribute('href', href);
  18732. href = urlParsingNode.href;
  18733. }
  18734. urlParsingNode.setAttribute('href', href);
  18735. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  18736. return {
  18737. href: urlParsingNode.href,
  18738. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  18739. host: urlParsingNode.host,
  18740. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  18741. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  18742. hostname: urlParsingNode.hostname,
  18743. port: urlParsingNode.port,
  18744. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  18745. ? urlParsingNode.pathname
  18746. : '/' + urlParsingNode.pathname
  18747. };
  18748. }
  18749. /**
  18750. * Parse a request URL and determine whether this is a same-origin request as the application document.
  18751. *
  18752. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  18753. * or a parsed URL object.
  18754. * @returns {boolean} Whether the request is for the same origin as the application document.
  18755. */
  18756. function urlIsSameOrigin(requestUrl) {
  18757. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  18758. return (parsed.protocol === originUrl.protocol &&
  18759. parsed.host === originUrl.host);
  18760. }
  18761. /**
  18762. * @ngdoc service
  18763. * @name $window
  18764. * @this
  18765. *
  18766. * @description
  18767. * A reference to the browser's `window` object. While `window`
  18768. * is globally available in JavaScript, it causes testability problems, because
  18769. * it is a global variable. In angular we always refer to it through the
  18770. * `$window` service, so it may be overridden, removed or mocked for testing.
  18771. *
  18772. * Expressions, like the one defined for the `ngClick` directive in the example
  18773. * below, are evaluated with respect to the current scope. Therefore, there is
  18774. * no risk of inadvertently coding in a dependency on a global value in such an
  18775. * expression.
  18776. *
  18777. * @example
  18778. <example module="windowExample" name="window-service">
  18779. <file name="index.html">
  18780. <script>
  18781. angular.module('windowExample', [])
  18782. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  18783. $scope.greeting = 'Hello, World!';
  18784. $scope.doGreeting = function(greeting) {
  18785. $window.alert(greeting);
  18786. };
  18787. }]);
  18788. </script>
  18789. <div ng-controller="ExampleController">
  18790. <input type="text" ng-model="greeting" aria-label="greeting" />
  18791. <button ng-click="doGreeting(greeting)">ALERT</button>
  18792. </div>
  18793. </file>
  18794. <file name="protractor.js" type="protractor">
  18795. it('should display the greeting in the input box', function() {
  18796. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  18797. // If we click the button it will block the test runner
  18798. // element(':button').click();
  18799. });
  18800. </file>
  18801. </example>
  18802. */
  18803. function $WindowProvider() {
  18804. this.$get = valueFn(window);
  18805. }
  18806. /**
  18807. * @name $$cookieReader
  18808. * @requires $document
  18809. *
  18810. * @description
  18811. * This is a private service for reading cookies used by $http and ngCookies
  18812. *
  18813. * @return {Object} a key/value map of the current cookies
  18814. */
  18815. function $$CookieReader($document) {
  18816. var rawDocument = $document[0] || {};
  18817. var lastCookies = {};
  18818. var lastCookieString = '';
  18819. function safeGetCookie(rawDocument) {
  18820. try {
  18821. return rawDocument.cookie || '';
  18822. } catch (e) {
  18823. return '';
  18824. }
  18825. }
  18826. function safeDecodeURIComponent(str) {
  18827. try {
  18828. return decodeURIComponent(str);
  18829. } catch (e) {
  18830. return str;
  18831. }
  18832. }
  18833. return function() {
  18834. var cookieArray, cookie, i, index, name;
  18835. var currentCookieString = safeGetCookie(rawDocument);
  18836. if (currentCookieString !== lastCookieString) {
  18837. lastCookieString = currentCookieString;
  18838. cookieArray = lastCookieString.split('; ');
  18839. lastCookies = {};
  18840. for (i = 0; i < cookieArray.length; i++) {
  18841. cookie = cookieArray[i];
  18842. index = cookie.indexOf('=');
  18843. if (index > 0) { //ignore nameless cookies
  18844. name = safeDecodeURIComponent(cookie.substring(0, index));
  18845. // the first value that is seen for a cookie is the most
  18846. // specific one. values for the same cookie name that
  18847. // follow are for less specific paths.
  18848. if (isUndefined(lastCookies[name])) {
  18849. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  18850. }
  18851. }
  18852. }
  18853. }
  18854. return lastCookies;
  18855. };
  18856. }
  18857. $$CookieReader.$inject = ['$document'];
  18858. /** @this */
  18859. function $$CookieReaderProvider() {
  18860. this.$get = $$CookieReader;
  18861. }
  18862. /* global currencyFilter: true,
  18863. dateFilter: true,
  18864. filterFilter: true,
  18865. jsonFilter: true,
  18866. limitToFilter: true,
  18867. lowercaseFilter: true,
  18868. numberFilter: true,
  18869. orderByFilter: true,
  18870. uppercaseFilter: true,
  18871. */
  18872. /**
  18873. * @ngdoc provider
  18874. * @name $filterProvider
  18875. * @description
  18876. *
  18877. * Filters are just functions which transform input to an output. However filters need to be
  18878. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  18879. * annotated with dependencies and is responsible for creating a filter function.
  18880. *
  18881. * <div class="alert alert-warning">
  18882. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  18883. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  18884. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  18885. * (`myapp_subsection_filterx`).
  18886. * </div>
  18887. *
  18888. * ```js
  18889. * // Filter registration
  18890. * function MyModule($provide, $filterProvider) {
  18891. * // create a service to demonstrate injection (not always needed)
  18892. * $provide.value('greet', function(name){
  18893. * return 'Hello ' + name + '!';
  18894. * });
  18895. *
  18896. * // register a filter factory which uses the
  18897. * // greet service to demonstrate DI.
  18898. * $filterProvider.register('greet', function(greet){
  18899. * // return the filter function which uses the greet service
  18900. * // to generate salutation
  18901. * return function(text) {
  18902. * // filters need to be forgiving so check input validity
  18903. * return text && greet(text) || text;
  18904. * };
  18905. * });
  18906. * }
  18907. * ```
  18908. *
  18909. * The filter function is registered with the `$injector` under the filter name suffix with
  18910. * `Filter`.
  18911. *
  18912. * ```js
  18913. * it('should be the same instance', inject(
  18914. * function($filterProvider) {
  18915. * $filterProvider.register('reverse', function(){
  18916. * return ...;
  18917. * });
  18918. * },
  18919. * function($filter, reverseFilter) {
  18920. * expect($filter('reverse')).toBe(reverseFilter);
  18921. * });
  18922. * ```
  18923. *
  18924. *
  18925. * For more information about how angular filters work, and how to create your own filters, see
  18926. * {@link guide/filter Filters} in the Angular Developer Guide.
  18927. */
  18928. /**
  18929. * @ngdoc service
  18930. * @name $filter
  18931. * @kind function
  18932. * @description
  18933. * Filters are used for formatting data displayed to the user.
  18934. *
  18935. * They can be used in view templates, controllers or services.Angular comes
  18936. * with a collection of [built-in filters](api/ng/filter), but it is easy to
  18937. * define your own as well.
  18938. *
  18939. * The general syntax in templates is as follows:
  18940. *
  18941. * ```html
  18942. * {{ expression [| filter_name[:parameter_value] ... ] }}
  18943. * ```
  18944. *
  18945. * @param {String} name Name of the filter function to retrieve
  18946. * @return {Function} the filter function
  18947. * @example
  18948. <example name="$filter" module="filterExample">
  18949. <file name="index.html">
  18950. <div ng-controller="MainCtrl">
  18951. <h3>{{ originalText }}</h3>
  18952. <h3>{{ filteredText }}</h3>
  18953. </div>
  18954. </file>
  18955. <file name="script.js">
  18956. angular.module('filterExample', [])
  18957. .controller('MainCtrl', function($scope, $filter) {
  18958. $scope.originalText = 'hello';
  18959. $scope.filteredText = $filter('uppercase')($scope.originalText);
  18960. });
  18961. </file>
  18962. </example>
  18963. */
  18964. $FilterProvider.$inject = ['$provide'];
  18965. /** @this */
  18966. function $FilterProvider($provide) {
  18967. var suffix = 'Filter';
  18968. /**
  18969. * @ngdoc method
  18970. * @name $filterProvider#register
  18971. * @param {string|Object} name Name of the filter function, or an object map of filters where
  18972. * the keys are the filter names and the values are the filter factories.
  18973. *
  18974. * <div class="alert alert-warning">
  18975. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  18976. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  18977. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  18978. * (`myapp_subsection_filterx`).
  18979. * </div>
  18980. * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
  18981. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  18982. * of the registered filter instances.
  18983. */
  18984. function register(name, factory) {
  18985. if (isObject(name)) {
  18986. var filters = {};
  18987. forEach(name, function(filter, key) {
  18988. filters[key] = register(key, filter);
  18989. });
  18990. return filters;
  18991. } else {
  18992. return $provide.factory(name + suffix, factory);
  18993. }
  18994. }
  18995. this.register = register;
  18996. this.$get = ['$injector', function($injector) {
  18997. return function(name) {
  18998. return $injector.get(name + suffix);
  18999. };
  19000. }];
  19001. ////////////////////////////////////////
  19002. /* global
  19003. currencyFilter: false,
  19004. dateFilter: false,
  19005. filterFilter: false,
  19006. jsonFilter: false,
  19007. limitToFilter: false,
  19008. lowercaseFilter: false,
  19009. numberFilter: false,
  19010. orderByFilter: false,
  19011. uppercaseFilter: false
  19012. */
  19013. register('currency', currencyFilter);
  19014. register('date', dateFilter);
  19015. register('filter', filterFilter);
  19016. register('json', jsonFilter);
  19017. register('limitTo', limitToFilter);
  19018. register('lowercase', lowercaseFilter);
  19019. register('number', numberFilter);
  19020. register('orderBy', orderByFilter);
  19021. register('uppercase', uppercaseFilter);
  19022. }
  19023. /**
  19024. * @ngdoc filter
  19025. * @name filter
  19026. * @kind function
  19027. *
  19028. * @description
  19029. * Selects a subset of items from `array` and returns it as a new array.
  19030. *
  19031. * @param {Array} array The source array.
  19032. * <div class="alert alert-info">
  19033. * **Note**: If the array contains objects that reference themselves, filtering is not possible.
  19034. * </div>
  19035. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  19036. * `array`.
  19037. *
  19038. * Can be one of:
  19039. *
  19040. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  19041. * objects with string properties in `array` that match this string will be returned. This also
  19042. * applies to nested object properties.
  19043. * The predicate can be negated by prefixing the string with `!`.
  19044. *
  19045. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  19046. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  19047. * which have property `name` containing "M" and property `phone` containing "1". A special
  19048. * property name (`$` by default) can be used (e.g. as in `{$: "text"}`) to accept a match
  19049. * against any property of the object or its nested object properties. That's equivalent to the
  19050. * simple substring match with a `string` as described above. The special property name can be
  19051. * overwritten, using the `anyPropertyKey` parameter.
  19052. * The predicate can be negated by prefixing the string with `!`.
  19053. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  19054. * not containing "M".
  19055. *
  19056. * Note that a named property will match properties on the same level only, while the special
  19057. * `$` property will match properties on the same level or deeper. E.g. an array item like
  19058. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  19059. * **will** be matched by `{$: 'John'}`.
  19060. *
  19061. * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
  19062. * The function is called for each element of the array, with the element, its index, and
  19063. * the entire array itself as arguments.
  19064. *
  19065. * The final result is an array of those elements that the predicate returned true for.
  19066. *
  19067. * @param {function(actual, expected)|true|false} [comparator] Comparator which is used in
  19068. * determining if values retrieved using `expression` (when it is not a function) should be
  19069. * considered a match based on the expected value (from the filter expression) and actual
  19070. * value (from the object in the array).
  19071. *
  19072. * Can be one of:
  19073. *
  19074. * - `function(actual, expected)`:
  19075. * The function will be given the object value and the predicate value to compare and
  19076. * should return true if both values should be considered equal.
  19077. *
  19078. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  19079. * This is essentially strict comparison of expected and actual.
  19080. *
  19081. * - `false`: A short hand for a function which will look for a substring match in a case
  19082. * insensitive way. Primitive values are converted to strings. Objects are not compared against
  19083. * primitives, unless they have a custom `toString` method (e.g. `Date` objects).
  19084. *
  19085. *
  19086. * Defaults to `false`.
  19087. *
  19088. * @param {string} [anyPropertyKey] The special property name that matches against any property.
  19089. * By default `$`.
  19090. *
  19091. * @example
  19092. <example name="filter-filter">
  19093. <file name="index.html">
  19094. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  19095. {name:'Mary', phone:'800-BIG-MARY'},
  19096. {name:'Mike', phone:'555-4321'},
  19097. {name:'Adam', phone:'555-5678'},
  19098. {name:'Julie', phone:'555-8765'},
  19099. {name:'Juliette', phone:'555-5678'}]"></div>
  19100. <label>Search: <input ng-model="searchText"></label>
  19101. <table id="searchTextResults">
  19102. <tr><th>Name</th><th>Phone</th></tr>
  19103. <tr ng-repeat="friend in friends | filter:searchText">
  19104. <td>{{friend.name}}</td>
  19105. <td>{{friend.phone}}</td>
  19106. </tr>
  19107. </table>
  19108. <hr>
  19109. <label>Any: <input ng-model="search.$"></label> <br>
  19110. <label>Name only <input ng-model="search.name"></label><br>
  19111. <label>Phone only <input ng-model="search.phone"></label><br>
  19112. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  19113. <table id="searchObjResults">
  19114. <tr><th>Name</th><th>Phone</th></tr>
  19115. <tr ng-repeat="friendObj in friends | filter:search:strict">
  19116. <td>{{friendObj.name}}</td>
  19117. <td>{{friendObj.phone}}</td>
  19118. </tr>
  19119. </table>
  19120. </file>
  19121. <file name="protractor.js" type="protractor">
  19122. var expectFriendNames = function(expectedNames, key) {
  19123. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  19124. arr.forEach(function(wd, i) {
  19125. expect(wd.getText()).toMatch(expectedNames[i]);
  19126. });
  19127. });
  19128. };
  19129. it('should search across all fields when filtering with a string', function() {
  19130. var searchText = element(by.model('searchText'));
  19131. searchText.clear();
  19132. searchText.sendKeys('m');
  19133. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  19134. searchText.clear();
  19135. searchText.sendKeys('76');
  19136. expectFriendNames(['John', 'Julie'], 'friend');
  19137. });
  19138. it('should search in specific fields when filtering with a predicate object', function() {
  19139. var searchAny = element(by.model('search.$'));
  19140. searchAny.clear();
  19141. searchAny.sendKeys('i');
  19142. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  19143. });
  19144. it('should use a equal comparison when comparator is true', function() {
  19145. var searchName = element(by.model('search.name'));
  19146. var strict = element(by.model('strict'));
  19147. searchName.clear();
  19148. searchName.sendKeys('Julie');
  19149. strict.click();
  19150. expectFriendNames(['Julie'], 'friendObj');
  19151. });
  19152. </file>
  19153. </example>
  19154. */
  19155. function filterFilter() {
  19156. return function(array, expression, comparator, anyPropertyKey) {
  19157. if (!isArrayLike(array)) {
  19158. if (array == null) {
  19159. return array;
  19160. } else {
  19161. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  19162. }
  19163. }
  19164. anyPropertyKey = anyPropertyKey || '$';
  19165. var expressionType = getTypeForFilter(expression);
  19166. var predicateFn;
  19167. var matchAgainstAnyProp;
  19168. switch (expressionType) {
  19169. case 'function':
  19170. predicateFn = expression;
  19171. break;
  19172. case 'boolean':
  19173. case 'null':
  19174. case 'number':
  19175. case 'string':
  19176. matchAgainstAnyProp = true;
  19177. // falls through
  19178. case 'object':
  19179. predicateFn = createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp);
  19180. break;
  19181. default:
  19182. return array;
  19183. }
  19184. return Array.prototype.filter.call(array, predicateFn);
  19185. };
  19186. }
  19187. // Helper functions for `filterFilter`
  19188. function createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp) {
  19189. var shouldMatchPrimitives = isObject(expression) && (anyPropertyKey in expression);
  19190. var predicateFn;
  19191. if (comparator === true) {
  19192. comparator = equals;
  19193. } else if (!isFunction(comparator)) {
  19194. comparator = function(actual, expected) {
  19195. if (isUndefined(actual)) {
  19196. // No substring matching against `undefined`
  19197. return false;
  19198. }
  19199. if ((actual === null) || (expected === null)) {
  19200. // No substring matching against `null`; only match against `null`
  19201. return actual === expected;
  19202. }
  19203. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  19204. // Should not compare primitives against objects, unless they have custom `toString` method
  19205. return false;
  19206. }
  19207. actual = lowercase('' + actual);
  19208. expected = lowercase('' + expected);
  19209. return actual.indexOf(expected) !== -1;
  19210. };
  19211. }
  19212. predicateFn = function(item) {
  19213. if (shouldMatchPrimitives && !isObject(item)) {
  19214. return deepCompare(item, expression[anyPropertyKey], comparator, anyPropertyKey, false);
  19215. }
  19216. return deepCompare(item, expression, comparator, anyPropertyKey, matchAgainstAnyProp);
  19217. };
  19218. return predicateFn;
  19219. }
  19220. function deepCompare(actual, expected, comparator, anyPropertyKey, matchAgainstAnyProp, dontMatchWholeObject) {
  19221. var actualType = getTypeForFilter(actual);
  19222. var expectedType = getTypeForFilter(expected);
  19223. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  19224. return !deepCompare(actual, expected.substring(1), comparator, anyPropertyKey, matchAgainstAnyProp);
  19225. } else if (isArray(actual)) {
  19226. // In case `actual` is an array, consider it a match
  19227. // if ANY of it's items matches `expected`
  19228. return actual.some(function(item) {
  19229. return deepCompare(item, expected, comparator, anyPropertyKey, matchAgainstAnyProp);
  19230. });
  19231. }
  19232. switch (actualType) {
  19233. case 'object':
  19234. var key;
  19235. if (matchAgainstAnyProp) {
  19236. for (key in actual) {
  19237. // Under certain, rare, circumstances, key may not be a string and `charAt` will be undefined
  19238. // See: https://github.com/angular/angular.js/issues/15644
  19239. if (key.charAt && (key.charAt(0) !== '$') &&
  19240. deepCompare(actual[key], expected, comparator, anyPropertyKey, true)) {
  19241. return true;
  19242. }
  19243. }
  19244. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, anyPropertyKey, false);
  19245. } else if (expectedType === 'object') {
  19246. for (key in expected) {
  19247. var expectedVal = expected[key];
  19248. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  19249. continue;
  19250. }
  19251. var matchAnyProperty = key === anyPropertyKey;
  19252. var actualVal = matchAnyProperty ? actual : actual[key];
  19253. if (!deepCompare(actualVal, expectedVal, comparator, anyPropertyKey, matchAnyProperty, matchAnyProperty)) {
  19254. return false;
  19255. }
  19256. }
  19257. return true;
  19258. } else {
  19259. return comparator(actual, expected);
  19260. }
  19261. case 'function':
  19262. return false;
  19263. default:
  19264. return comparator(actual, expected);
  19265. }
  19266. }
  19267. // Used for easily differentiating between `null` and actual `object`
  19268. function getTypeForFilter(val) {
  19269. return (val === null) ? 'null' : typeof val;
  19270. }
  19271. var MAX_DIGITS = 22;
  19272. var DECIMAL_SEP = '.';
  19273. var ZERO_CHAR = '0';
  19274. /**
  19275. * @ngdoc filter
  19276. * @name currency
  19277. * @kind function
  19278. *
  19279. * @description
  19280. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  19281. * symbol for current locale is used.
  19282. *
  19283. * @param {number} amount Input to filter.
  19284. * @param {string=} symbol Currency symbol or identifier to be displayed.
  19285. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  19286. * @returns {string} Formatted number.
  19287. *
  19288. *
  19289. * @example
  19290. <example module="currencyExample" name="currency-filter">
  19291. <file name="index.html">
  19292. <script>
  19293. angular.module('currencyExample', [])
  19294. .controller('ExampleController', ['$scope', function($scope) {
  19295. $scope.amount = 1234.56;
  19296. }]);
  19297. </script>
  19298. <div ng-controller="ExampleController">
  19299. <input type="number" ng-model="amount" aria-label="amount"> <br>
  19300. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  19301. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span><br>
  19302. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  19303. </div>
  19304. </file>
  19305. <file name="protractor.js" type="protractor">
  19306. it('should init with 1234.56', function() {
  19307. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  19308. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  19309. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  19310. });
  19311. it('should update', function() {
  19312. if (browser.params.browser === 'safari') {
  19313. // Safari does not understand the minus key. See
  19314. // https://github.com/angular/protractor/issues/481
  19315. return;
  19316. }
  19317. element(by.model('amount')).clear();
  19318. element(by.model('amount')).sendKeys('-1234');
  19319. expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
  19320. expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
  19321. expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
  19322. });
  19323. </file>
  19324. </example>
  19325. */
  19326. currencyFilter.$inject = ['$locale'];
  19327. function currencyFilter($locale) {
  19328. var formats = $locale.NUMBER_FORMATS;
  19329. return function(amount, currencySymbol, fractionSize) {
  19330. if (isUndefined(currencySymbol)) {
  19331. currencySymbol = formats.CURRENCY_SYM;
  19332. }
  19333. if (isUndefined(fractionSize)) {
  19334. fractionSize = formats.PATTERNS[1].maxFrac;
  19335. }
  19336. // if null or undefined pass it through
  19337. return (amount == null)
  19338. ? amount
  19339. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  19340. replace(/\u00A4/g, currencySymbol);
  19341. };
  19342. }
  19343. /**
  19344. * @ngdoc filter
  19345. * @name number
  19346. * @kind function
  19347. *
  19348. * @description
  19349. * Formats a number as text.
  19350. *
  19351. * If the input is null or undefined, it will just be returned.
  19352. * If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively.
  19353. * If the input is not a number an empty string is returned.
  19354. *
  19355. *
  19356. * @param {number|string} number Number to format.
  19357. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  19358. * If this is not provided then the fraction size is computed from the current locale's number
  19359. * formatting pattern. In the case of the default locale, it will be 3.
  19360. * @returns {string} Number rounded to `fractionSize` appropriately formatted based on the current
  19361. * locale (e.g., in the en_US locale it will have "." as the decimal separator and
  19362. * include "," group separators after each third digit).
  19363. *
  19364. * @example
  19365. <example module="numberFilterExample" name="number-filter">
  19366. <file name="index.html">
  19367. <script>
  19368. angular.module('numberFilterExample', [])
  19369. .controller('ExampleController', ['$scope', function($scope) {
  19370. $scope.val = 1234.56789;
  19371. }]);
  19372. </script>
  19373. <div ng-controller="ExampleController">
  19374. <label>Enter number: <input ng-model='val'></label><br>
  19375. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  19376. No fractions: <span>{{val | number:0}}</span><br>
  19377. Negative number: <span>{{-val | number:4}}</span>
  19378. </div>
  19379. </file>
  19380. <file name="protractor.js" type="protractor">
  19381. it('should format numbers', function() {
  19382. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  19383. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  19384. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  19385. });
  19386. it('should update', function() {
  19387. element(by.model('val')).clear();
  19388. element(by.model('val')).sendKeys('3374.333');
  19389. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  19390. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  19391. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  19392. });
  19393. </file>
  19394. </example>
  19395. */
  19396. numberFilter.$inject = ['$locale'];
  19397. function numberFilter($locale) {
  19398. var formats = $locale.NUMBER_FORMATS;
  19399. return function(number, fractionSize) {
  19400. // if null or undefined pass it through
  19401. return (number == null)
  19402. ? number
  19403. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  19404. fractionSize);
  19405. };
  19406. }
  19407. /**
  19408. * Parse a number (as a string) into three components that can be used
  19409. * for formatting the number.
  19410. *
  19411. * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)
  19412. *
  19413. * @param {string} numStr The number to parse
  19414. * @return {object} An object describing this number, containing the following keys:
  19415. * - d : an array of digits containing leading zeros as necessary
  19416. * - i : the number of the digits in `d` that are to the left of the decimal point
  19417. * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`
  19418. *
  19419. */
  19420. function parse(numStr) {
  19421. var exponent = 0, digits, numberOfIntegerDigits;
  19422. var i, j, zeros;
  19423. // Decimal point?
  19424. if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {
  19425. numStr = numStr.replace(DECIMAL_SEP, '');
  19426. }
  19427. // Exponential form?
  19428. if ((i = numStr.search(/e/i)) > 0) {
  19429. // Work out the exponent.
  19430. if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i;
  19431. numberOfIntegerDigits += +numStr.slice(i + 1);
  19432. numStr = numStr.substring(0, i);
  19433. } else if (numberOfIntegerDigits < 0) {
  19434. // There was no decimal point or exponent so it is an integer.
  19435. numberOfIntegerDigits = numStr.length;
  19436. }
  19437. // Count the number of leading zeros.
  19438. for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */ }
  19439. if (i === (zeros = numStr.length)) {
  19440. // The digits are all zero.
  19441. digits = [0];
  19442. numberOfIntegerDigits = 1;
  19443. } else {
  19444. // Count the number of trailing zeros
  19445. zeros--;
  19446. while (numStr.charAt(zeros) === ZERO_CHAR) zeros--;
  19447. // Trailing zeros are insignificant so ignore them
  19448. numberOfIntegerDigits -= i;
  19449. digits = [];
  19450. // Convert string to array of digits without leading/trailing zeros.
  19451. for (j = 0; i <= zeros; i++, j++) {
  19452. digits[j] = +numStr.charAt(i);
  19453. }
  19454. }
  19455. // If the number overflows the maximum allowed digits then use an exponent.
  19456. if (numberOfIntegerDigits > MAX_DIGITS) {
  19457. digits = digits.splice(0, MAX_DIGITS - 1);
  19458. exponent = numberOfIntegerDigits - 1;
  19459. numberOfIntegerDigits = 1;
  19460. }
  19461. return { d: digits, e: exponent, i: numberOfIntegerDigits };
  19462. }
  19463. /**
  19464. * Round the parsed number to the specified number of decimal places
  19465. * This function changed the parsedNumber in-place
  19466. */
  19467. function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
  19468. var digits = parsedNumber.d;
  19469. var fractionLen = digits.length - parsedNumber.i;
  19470. // determine fractionSize if it is not specified; `+fractionSize` converts it to a number
  19471. fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
  19472. // The index of the digit to where rounding is to occur
  19473. var roundAt = fractionSize + parsedNumber.i;
  19474. var digit = digits[roundAt];
  19475. if (roundAt > 0) {
  19476. // Drop fractional digits beyond `roundAt`
  19477. digits.splice(Math.max(parsedNumber.i, roundAt));
  19478. // Set non-fractional digits beyond `roundAt` to 0
  19479. for (var j = roundAt; j < digits.length; j++) {
  19480. digits[j] = 0;
  19481. }
  19482. } else {
  19483. // We rounded to zero so reset the parsedNumber
  19484. fractionLen = Math.max(0, fractionLen);
  19485. parsedNumber.i = 1;
  19486. digits.length = Math.max(1, roundAt = fractionSize + 1);
  19487. digits[0] = 0;
  19488. for (var i = 1; i < roundAt; i++) digits[i] = 0;
  19489. }
  19490. if (digit >= 5) {
  19491. if (roundAt - 1 < 0) {
  19492. for (var k = 0; k > roundAt; k--) {
  19493. digits.unshift(0);
  19494. parsedNumber.i++;
  19495. }
  19496. digits.unshift(1);
  19497. parsedNumber.i++;
  19498. } else {
  19499. digits[roundAt - 1]++;
  19500. }
  19501. }
  19502. // Pad out with zeros to get the required fraction length
  19503. for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);
  19504. // Do any carrying, e.g. a digit was rounded up to 10
  19505. var carry = digits.reduceRight(function(carry, d, i, digits) {
  19506. d = d + carry;
  19507. digits[i] = d % 10;
  19508. return Math.floor(d / 10);
  19509. }, 0);
  19510. if (carry) {
  19511. digits.unshift(carry);
  19512. parsedNumber.i++;
  19513. }
  19514. }
  19515. /**
  19516. * Format a number into a string
  19517. * @param {number} number The number to format
  19518. * @param {{
  19519. * minFrac, // the minimum number of digits required in the fraction part of the number
  19520. * maxFrac, // the maximum number of digits required in the fraction part of the number
  19521. * gSize, // number of digits in each group of separated digits
  19522. * lgSize, // number of digits in the last group of digits before the decimal separator
  19523. * negPre, // the string to go in front of a negative number (e.g. `-` or `(`))
  19524. * posPre, // the string to go in front of a positive number
  19525. * negSuf, // the string to go after a negative number (e.g. `)`)
  19526. * posSuf // the string to go after a positive number
  19527. * }} pattern
  19528. * @param {string} groupSep The string to separate groups of number (e.g. `,`)
  19529. * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`)
  19530. * @param {[type]} fractionSize The size of the fractional part of the number
  19531. * @return {string} The number formatted as a string
  19532. */
  19533. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  19534. if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';
  19535. var isInfinity = !isFinite(number);
  19536. var isZero = false;
  19537. var numStr = Math.abs(number) + '',
  19538. formattedText = '',
  19539. parsedNumber;
  19540. if (isInfinity) {
  19541. formattedText = '\u221e';
  19542. } else {
  19543. parsedNumber = parse(numStr);
  19544. roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);
  19545. var digits = parsedNumber.d;
  19546. var integerLen = parsedNumber.i;
  19547. var exponent = parsedNumber.e;
  19548. var decimals = [];
  19549. isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);
  19550. // pad zeros for small numbers
  19551. while (integerLen < 0) {
  19552. digits.unshift(0);
  19553. integerLen++;
  19554. }
  19555. // extract decimals digits
  19556. if (integerLen > 0) {
  19557. decimals = digits.splice(integerLen, digits.length);
  19558. } else {
  19559. decimals = digits;
  19560. digits = [0];
  19561. }
  19562. // format the integer digits with grouping separators
  19563. var groups = [];
  19564. if (digits.length >= pattern.lgSize) {
  19565. groups.unshift(digits.splice(-pattern.lgSize, digits.length).join(''));
  19566. }
  19567. while (digits.length > pattern.gSize) {
  19568. groups.unshift(digits.splice(-pattern.gSize, digits.length).join(''));
  19569. }
  19570. if (digits.length) {
  19571. groups.unshift(digits.join(''));
  19572. }
  19573. formattedText = groups.join(groupSep);
  19574. // append the decimal digits
  19575. if (decimals.length) {
  19576. formattedText += decimalSep + decimals.join('');
  19577. }
  19578. if (exponent) {
  19579. formattedText += 'e+' + exponent;
  19580. }
  19581. }
  19582. if (number < 0 && !isZero) {
  19583. return pattern.negPre + formattedText + pattern.negSuf;
  19584. } else {
  19585. return pattern.posPre + formattedText + pattern.posSuf;
  19586. }
  19587. }
  19588. function padNumber(num, digits, trim, negWrap) {
  19589. var neg = '';
  19590. if (num < 0 || (negWrap && num <= 0)) {
  19591. if (negWrap) {
  19592. num = -num + 1;
  19593. } else {
  19594. num = -num;
  19595. neg = '-';
  19596. }
  19597. }
  19598. num = '' + num;
  19599. while (num.length < digits) num = ZERO_CHAR + num;
  19600. if (trim) {
  19601. num = num.substr(num.length - digits);
  19602. }
  19603. return neg + num;
  19604. }
  19605. function dateGetter(name, size, offset, trim, negWrap) {
  19606. offset = offset || 0;
  19607. return function(date) {
  19608. var value = date['get' + name]();
  19609. if (offset > 0 || value > -offset) {
  19610. value += offset;
  19611. }
  19612. if (value === 0 && offset === -12) value = 12;
  19613. return padNumber(value, size, trim, negWrap);
  19614. };
  19615. }
  19616. function dateStrGetter(name, shortForm, standAlone) {
  19617. return function(date, formats) {
  19618. var value = date['get' + name]();
  19619. var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : '');
  19620. var get = uppercase(propPrefix + name);
  19621. return formats[get][value];
  19622. };
  19623. }
  19624. function timeZoneGetter(date, formats, offset) {
  19625. var zone = -1 * offset;
  19626. var paddedZone = (zone >= 0) ? '+' : '';
  19627. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  19628. padNumber(Math.abs(zone % 60), 2);
  19629. return paddedZone;
  19630. }
  19631. function getFirstThursdayOfYear(year) {
  19632. // 0 = index of January
  19633. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  19634. // 4 = index of Thursday (+1 to account for 1st = 5)
  19635. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  19636. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  19637. }
  19638. function getThursdayThisWeek(datetime) {
  19639. return new Date(datetime.getFullYear(), datetime.getMonth(),
  19640. // 4 = index of Thursday
  19641. datetime.getDate() + (4 - datetime.getDay()));
  19642. }
  19643. function weekGetter(size) {
  19644. return function(date) {
  19645. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  19646. thisThurs = getThursdayThisWeek(date);
  19647. var diff = +thisThurs - +firstThurs,
  19648. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  19649. return padNumber(result, size);
  19650. };
  19651. }
  19652. function ampmGetter(date, formats) {
  19653. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  19654. }
  19655. function eraGetter(date, formats) {
  19656. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  19657. }
  19658. function longEraGetter(date, formats) {
  19659. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  19660. }
  19661. var DATE_FORMATS = {
  19662. yyyy: dateGetter('FullYear', 4, 0, false, true),
  19663. yy: dateGetter('FullYear', 2, 0, true, true),
  19664. y: dateGetter('FullYear', 1, 0, false, true),
  19665. MMMM: dateStrGetter('Month'),
  19666. MMM: dateStrGetter('Month', true),
  19667. MM: dateGetter('Month', 2, 1),
  19668. M: dateGetter('Month', 1, 1),
  19669. LLLL: dateStrGetter('Month', false, true),
  19670. dd: dateGetter('Date', 2),
  19671. d: dateGetter('Date', 1),
  19672. HH: dateGetter('Hours', 2),
  19673. H: dateGetter('Hours', 1),
  19674. hh: dateGetter('Hours', 2, -12),
  19675. h: dateGetter('Hours', 1, -12),
  19676. mm: dateGetter('Minutes', 2),
  19677. m: dateGetter('Minutes', 1),
  19678. ss: dateGetter('Seconds', 2),
  19679. s: dateGetter('Seconds', 1),
  19680. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  19681. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  19682. sss: dateGetter('Milliseconds', 3),
  19683. EEEE: dateStrGetter('Day'),
  19684. EEE: dateStrGetter('Day', true),
  19685. a: ampmGetter,
  19686. Z: timeZoneGetter,
  19687. ww: weekGetter(2),
  19688. w: weekGetter(1),
  19689. G: eraGetter,
  19690. GG: eraGetter,
  19691. GGG: eraGetter,
  19692. GGGG: longEraGetter
  19693. };
  19694. var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))([\s\S]*)/,
  19695. NUMBER_STRING = /^-?\d+$/;
  19696. /**
  19697. * @ngdoc filter
  19698. * @name date
  19699. * @kind function
  19700. *
  19701. * @description
  19702. * Formats `date` to a string based on the requested `format`.
  19703. *
  19704. * `format` string can be composed of the following elements:
  19705. *
  19706. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  19707. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  19708. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  19709. * * `'MMMM'`: Month in year (January-December)
  19710. * * `'MMM'`: Month in year (Jan-Dec)
  19711. * * `'MM'`: Month in year, padded (01-12)
  19712. * * `'M'`: Month in year (1-12)
  19713. * * `'LLLL'`: Stand-alone month in year (January-December)
  19714. * * `'dd'`: Day in month, padded (01-31)
  19715. * * `'d'`: Day in month (1-31)
  19716. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  19717. * * `'EEE'`: Day in Week, (Sun-Sat)
  19718. * * `'HH'`: Hour in day, padded (00-23)
  19719. * * `'H'`: Hour in day (0-23)
  19720. * * `'hh'`: Hour in AM/PM, padded (01-12)
  19721. * * `'h'`: Hour in AM/PM, (1-12)
  19722. * * `'mm'`: Minute in hour, padded (00-59)
  19723. * * `'m'`: Minute in hour (0-59)
  19724. * * `'ss'`: Second in minute, padded (00-59)
  19725. * * `'s'`: Second in minute (0-59)
  19726. * * `'sss'`: Millisecond in second, padded (000-999)
  19727. * * `'a'`: AM/PM marker
  19728. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  19729. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  19730. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  19731. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  19732. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  19733. *
  19734. * `format` string can also be one of the following predefined
  19735. * {@link guide/i18n localizable formats}:
  19736. *
  19737. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  19738. * (e.g. Sep 3, 2010 12:05:08 PM)
  19739. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  19740. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  19741. * (e.g. Friday, September 3, 2010)
  19742. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  19743. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  19744. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  19745. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  19746. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  19747. *
  19748. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  19749. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  19750. * (e.g. `"h 'o''clock'"`).
  19751. *
  19752. * Any other characters in the `format` string will be output as-is.
  19753. *
  19754. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  19755. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  19756. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  19757. * specified in the string input, the time is considered to be in the local timezone.
  19758. * @param {string=} format Formatting rules (see Description). If not specified,
  19759. * `mediumDate` is used.
  19760. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  19761. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  19762. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  19763. * If not specified, the timezone of the browser will be used.
  19764. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  19765. *
  19766. * @example
  19767. <example name="filter-date">
  19768. <file name="index.html">
  19769. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  19770. <span>{{1288323623006 | date:'medium'}}</span><br>
  19771. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  19772. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  19773. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  19774. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  19775. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  19776. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  19777. </file>
  19778. <file name="protractor.js" type="protractor">
  19779. it('should format date', function() {
  19780. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  19781. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  19782. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  19783. toMatch(/2010-10-2\d \d{2}:\d{2}:\d{2} (-|\+)?\d{4}/);
  19784. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  19785. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  19786. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  19787. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  19788. });
  19789. </file>
  19790. </example>
  19791. */
  19792. dateFilter.$inject = ['$locale'];
  19793. function dateFilter($locale) {
  19794. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  19795. // 1 2 3 4 5 6 7 8 9 10 11
  19796. function jsonStringToDate(string) {
  19797. var match;
  19798. if ((match = string.match(R_ISO8601_STR))) {
  19799. var date = new Date(0),
  19800. tzHour = 0,
  19801. tzMin = 0,
  19802. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  19803. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  19804. if (match[9]) {
  19805. tzHour = toInt(match[9] + match[10]);
  19806. tzMin = toInt(match[9] + match[11]);
  19807. }
  19808. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  19809. var h = toInt(match[4] || 0) - tzHour;
  19810. var m = toInt(match[5] || 0) - tzMin;
  19811. var s = toInt(match[6] || 0);
  19812. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  19813. timeSetter.call(date, h, m, s, ms);
  19814. return date;
  19815. }
  19816. return string;
  19817. }
  19818. return function(date, format, timezone) {
  19819. var text = '',
  19820. parts = [],
  19821. fn, match;
  19822. format = format || 'mediumDate';
  19823. format = $locale.DATETIME_FORMATS[format] || format;
  19824. if (isString(date)) {
  19825. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  19826. }
  19827. if (isNumber(date)) {
  19828. date = new Date(date);
  19829. }
  19830. if (!isDate(date) || !isFinite(date.getTime())) {
  19831. return date;
  19832. }
  19833. while (format) {
  19834. match = DATE_FORMATS_SPLIT.exec(format);
  19835. if (match) {
  19836. parts = concat(parts, match, 1);
  19837. format = parts.pop();
  19838. } else {
  19839. parts.push(format);
  19840. format = null;
  19841. }
  19842. }
  19843. var dateTimezoneOffset = date.getTimezoneOffset();
  19844. if (timezone) {
  19845. dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  19846. date = convertTimezoneToLocal(date, timezone, true);
  19847. }
  19848. forEach(parts, function(value) {
  19849. fn = DATE_FORMATS[value];
  19850. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  19851. : value === '\'\'' ? '\'' : value.replace(/(^'|'$)/g, '').replace(/''/g, '\'');
  19852. });
  19853. return text;
  19854. };
  19855. }
  19856. /**
  19857. * @ngdoc filter
  19858. * @name json
  19859. * @kind function
  19860. *
  19861. * @description
  19862. * Allows you to convert a JavaScript object into JSON string.
  19863. *
  19864. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  19865. * the binding is automatically converted to JSON.
  19866. *
  19867. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  19868. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  19869. * @returns {string} JSON string.
  19870. *
  19871. *
  19872. * @example
  19873. <example name="filter-json">
  19874. <file name="index.html">
  19875. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  19876. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  19877. </file>
  19878. <file name="protractor.js" type="protractor">
  19879. it('should jsonify filtered objects', function() {
  19880. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n {2}"name": ?"value"\n}/);
  19881. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n {4}"name": ?"value"\n}/);
  19882. });
  19883. </file>
  19884. </example>
  19885. *
  19886. */
  19887. function jsonFilter() {
  19888. return function(object, spacing) {
  19889. if (isUndefined(spacing)) {
  19890. spacing = 2;
  19891. }
  19892. return toJson(object, spacing);
  19893. };
  19894. }
  19895. /**
  19896. * @ngdoc filter
  19897. * @name lowercase
  19898. * @kind function
  19899. * @description
  19900. * Converts string to lowercase.
  19901. *
  19902. * See the {@link ng.uppercase uppercase filter documentation} for a functionally identical example.
  19903. *
  19904. * @see angular.lowercase
  19905. */
  19906. var lowercaseFilter = valueFn(lowercase);
  19907. /**
  19908. * @ngdoc filter
  19909. * @name uppercase
  19910. * @kind function
  19911. * @description
  19912. * Converts string to uppercase.
  19913. * @example
  19914. <example module="uppercaseFilterExample" name="filter-uppercase">
  19915. <file name="index.html">
  19916. <script>
  19917. angular.module('uppercaseFilterExample', [])
  19918. .controller('ExampleController', ['$scope', function($scope) {
  19919. $scope.title = 'This is a title';
  19920. }]);
  19921. </script>
  19922. <div ng-controller="ExampleController">
  19923. <!-- This title should be formatted normally -->
  19924. <h1>{{title}}</h1>
  19925. <!-- This title should be capitalized -->
  19926. <h1>{{title | uppercase}}</h1>
  19927. </div>
  19928. </file>
  19929. </example>
  19930. */
  19931. var uppercaseFilter = valueFn(uppercase);
  19932. /**
  19933. * @ngdoc filter
  19934. * @name limitTo
  19935. * @kind function
  19936. *
  19937. * @description
  19938. * Creates a new array or string containing only a specified number of elements. The elements are
  19939. * taken from either the beginning or the end of the source array, string or number, as specified by
  19940. * the value and sign (positive or negative) of `limit`. Other array-like objects are also supported
  19941. * (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input,
  19942. * it is converted to a string.
  19943. *
  19944. * @param {Array|ArrayLike|string|number} input - Array/array-like, string or number to be limited.
  19945. * @param {string|number} limit - The length of the returned array or string. If the `limit` number
  19946. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  19947. * If the number is negative, `limit` number of items from the end of the source array/string
  19948. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  19949. * the input will be returned unchanged.
  19950. * @param {(string|number)=} begin - Index at which to begin limitation. As a negative index,
  19951. * `begin` indicates an offset from the end of `input`. Defaults to `0`.
  19952. * @returns {Array|string} A new sub-array or substring of length `limit` or less if the input had
  19953. * less than `limit` elements.
  19954. *
  19955. * @example
  19956. <example module="limitToExample" name="limit-to-filter">
  19957. <file name="index.html">
  19958. <script>
  19959. angular.module('limitToExample', [])
  19960. .controller('ExampleController', ['$scope', function($scope) {
  19961. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  19962. $scope.letters = "abcdefghi";
  19963. $scope.longNumber = 2345432342;
  19964. $scope.numLimit = 3;
  19965. $scope.letterLimit = 3;
  19966. $scope.longNumberLimit = 3;
  19967. }]);
  19968. </script>
  19969. <div ng-controller="ExampleController">
  19970. <label>
  19971. Limit {{numbers}} to:
  19972. <input type="number" step="1" ng-model="numLimit">
  19973. </label>
  19974. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  19975. <label>
  19976. Limit {{letters}} to:
  19977. <input type="number" step="1" ng-model="letterLimit">
  19978. </label>
  19979. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  19980. <label>
  19981. Limit {{longNumber}} to:
  19982. <input type="number" step="1" ng-model="longNumberLimit">
  19983. </label>
  19984. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  19985. </div>
  19986. </file>
  19987. <file name="protractor.js" type="protractor">
  19988. var numLimitInput = element(by.model('numLimit'));
  19989. var letterLimitInput = element(by.model('letterLimit'));
  19990. var longNumberLimitInput = element(by.model('longNumberLimit'));
  19991. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  19992. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  19993. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  19994. it('should limit the number array to first three items', function() {
  19995. expect(numLimitInput.getAttribute('value')).toBe('3');
  19996. expect(letterLimitInput.getAttribute('value')).toBe('3');
  19997. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  19998. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  19999. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  20000. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  20001. });
  20002. // There is a bug in safari and protractor that doesn't like the minus key
  20003. // it('should update the output when -3 is entered', function() {
  20004. // numLimitInput.clear();
  20005. // numLimitInput.sendKeys('-3');
  20006. // letterLimitInput.clear();
  20007. // letterLimitInput.sendKeys('-3');
  20008. // longNumberLimitInput.clear();
  20009. // longNumberLimitInput.sendKeys('-3');
  20010. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  20011. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  20012. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  20013. // });
  20014. it('should not exceed the maximum size of input array', function() {
  20015. numLimitInput.clear();
  20016. numLimitInput.sendKeys('100');
  20017. letterLimitInput.clear();
  20018. letterLimitInput.sendKeys('100');
  20019. longNumberLimitInput.clear();
  20020. longNumberLimitInput.sendKeys('100');
  20021. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  20022. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  20023. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  20024. });
  20025. </file>
  20026. </example>
  20027. */
  20028. function limitToFilter() {
  20029. return function(input, limit, begin) {
  20030. if (Math.abs(Number(limit)) === Infinity) {
  20031. limit = Number(limit);
  20032. } else {
  20033. limit = toInt(limit);
  20034. }
  20035. if (isNumberNaN(limit)) return input;
  20036. if (isNumber(input)) input = input.toString();
  20037. if (!isArrayLike(input)) return input;
  20038. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  20039. begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
  20040. if (limit >= 0) {
  20041. return sliceFn(input, begin, begin + limit);
  20042. } else {
  20043. if (begin === 0) {
  20044. return sliceFn(input, limit, input.length);
  20045. } else {
  20046. return sliceFn(input, Math.max(0, begin + limit), begin);
  20047. }
  20048. }
  20049. };
  20050. }
  20051. function sliceFn(input, begin, end) {
  20052. if (isString(input)) return input.slice(begin, end);
  20053. return slice.call(input, begin, end);
  20054. }
  20055. /**
  20056. * @ngdoc filter
  20057. * @name orderBy
  20058. * @kind function
  20059. *
  20060. * @description
  20061. * Returns an array containing the items from the specified `collection`, ordered by a `comparator`
  20062. * function based on the values computed using the `expression` predicate.
  20063. *
  20064. * For example, `[{id: 'foo'}, {id: 'bar'}] | orderBy:'id'` would result in
  20065. * `[{id: 'bar'}, {id: 'foo'}]`.
  20066. *
  20067. * The `collection` can be an Array or array-like object (e.g. NodeList, jQuery object, TypedArray,
  20068. * String, etc).
  20069. *
  20070. * The `expression` can be a single predicate, or a list of predicates each serving as a tie-breaker
  20071. * for the preceding one. The `expression` is evaluated against each item and the output is used
  20072. * for comparing with other items.
  20073. *
  20074. * You can change the sorting order by setting `reverse` to `true`. By default, items are sorted in
  20075. * ascending order.
  20076. *
  20077. * The comparison is done using the `comparator` function. If none is specified, a default, built-in
  20078. * comparator is used (see below for details - in a nutshell, it compares numbers numerically and
  20079. * strings alphabetically).
  20080. *
  20081. * ### Under the hood
  20082. *
  20083. * Ordering the specified `collection` happens in two phases:
  20084. *
  20085. * 1. All items are passed through the predicate (or predicates), and the returned values are saved
  20086. * along with their type (`string`, `number` etc). For example, an item `{label: 'foo'}`, passed
  20087. * through a predicate that extracts the value of the `label` property, would be transformed to:
  20088. * ```
  20089. * {
  20090. * value: 'foo',
  20091. * type: 'string',
  20092. * index: ...
  20093. * }
  20094. * ```
  20095. * 2. The comparator function is used to sort the items, based on the derived values, types and
  20096. * indices.
  20097. *
  20098. * If you use a custom comparator, it will be called with pairs of objects of the form
  20099. * `{value: ..., type: '...', index: ...}` and is expected to return `0` if the objects are equal
  20100. * (as far as the comparator is concerned), `-1` if the 1st one should be ranked higher than the
  20101. * second, or `1` otherwise.
  20102. *
  20103. * In order to ensure that the sorting will be deterministic across platforms, if none of the
  20104. * specified predicates can distinguish between two items, `orderBy` will automatically introduce a
  20105. * dummy predicate that returns the item's index as `value`.
  20106. * (If you are using a custom comparator, make sure it can handle this predicate as well.)
  20107. *
  20108. * If a custom comparator still can't distinguish between two items, then they will be sorted based
  20109. * on their index using the built-in comparator.
  20110. *
  20111. * Finally, in an attempt to simplify things, if a predicate returns an object as the extracted
  20112. * value for an item, `orderBy` will try to convert that object to a primitive value, before passing
  20113. * it to the comparator. The following rules govern the conversion:
  20114. *
  20115. * 1. If the object has a `valueOf()` method that returns a primitive, its return value will be
  20116. * used instead.<br />
  20117. * (If the object has a `valueOf()` method that returns another object, then the returned object
  20118. * will be used in subsequent steps.)
  20119. * 2. If the object has a custom `toString()` method (i.e. not the one inherited from `Object`) that
  20120. * returns a primitive, its return value will be used instead.<br />
  20121. * (If the object has a `toString()` method that returns another object, then the returned object
  20122. * will be used in subsequent steps.)
  20123. * 3. No conversion; the object itself is used.
  20124. *
  20125. * ### The default comparator
  20126. *
  20127. * The default, built-in comparator should be sufficient for most usecases. In short, it compares
  20128. * numbers numerically, strings alphabetically (and case-insensitively), for objects falls back to
  20129. * using their index in the original collection, and sorts values of different types by type.
  20130. *
  20131. * More specifically, it follows these steps to determine the relative order of items:
  20132. *
  20133. * 1. If the compared values are of different types, compare the types themselves alphabetically.
  20134. * 2. If both values are of type `string`, compare them alphabetically in a case- and
  20135. * locale-insensitive way.
  20136. * 3. If both values are objects, compare their indices instead.
  20137. * 4. Otherwise, return:
  20138. * - `0`, if the values are equal (by strict equality comparison, i.e. using `===`).
  20139. * - `-1`, if the 1st value is "less than" the 2nd value (compared using the `<` operator).
  20140. * - `1`, otherwise.
  20141. *
  20142. * **Note:** If you notice numbers not being sorted as expected, make sure they are actually being
  20143. * saved as numbers and not strings.
  20144. * **Note:** For the purpose of sorting, `null` values are treated as the string `'null'` (i.e.
  20145. * `type: 'string'`, `value: 'null'`). This may cause unexpected sort order relative to
  20146. * other values.
  20147. *
  20148. * @param {Array|ArrayLike} collection - The collection (array or array-like object) to sort.
  20149. * @param {(Function|string|Array.<Function|string>)=} expression - A predicate (or list of
  20150. * predicates) to be used by the comparator to determine the order of elements.
  20151. *
  20152. * Can be one of:
  20153. *
  20154. * - `Function`: A getter function. This function will be called with each item as argument and
  20155. * the return value will be used for sorting.
  20156. * - `string`: An Angular expression. This expression will be evaluated against each item and the
  20157. * result will be used for sorting. For example, use `'label'` to sort by a property called
  20158. * `label` or `'label.substring(0, 3)'` to sort by the first 3 characters of the `label`
  20159. * property.<br />
  20160. * (The result of a constant expression is interpreted as a property name to be used for
  20161. * comparison. For example, use `'"special name"'` (note the extra pair of quotes) to sort by a
  20162. * property called `special name`.)<br />
  20163. * An expression can be optionally prefixed with `+` or `-` to control the sorting direction,
  20164. * ascending or descending. For example, `'+label'` or `'-label'`. If no property is provided,
  20165. * (e.g. `'+'` or `'-'`), the collection element itself is used in comparisons.
  20166. * - `Array`: An array of function and/or string predicates. If a predicate cannot determine the
  20167. * relative order of two items, the next predicate is used as a tie-breaker.
  20168. *
  20169. * **Note:** If the predicate is missing or empty then it defaults to `'+'`.
  20170. *
  20171. * @param {boolean=} reverse - If `true`, reverse the sorting order.
  20172. * @param {(Function)=} comparator - The comparator function used to determine the relative order of
  20173. * value pairs. If omitted, the built-in comparator will be used.
  20174. *
  20175. * @returns {Array} - The sorted array.
  20176. *
  20177. *
  20178. * @example
  20179. * ### Ordering a table with `ngRepeat`
  20180. *
  20181. * The example below demonstrates a simple {@link ngRepeat ngRepeat}, where the data is sorted by
  20182. * age in descending order (expression is set to `'-age'`). The `comparator` is not set, which means
  20183. * it defaults to the built-in comparator.
  20184. *
  20185. <example name="orderBy-static" module="orderByExample1">
  20186. <file name="index.html">
  20187. <div ng-controller="ExampleController">
  20188. <table class="friends">
  20189. <tr>
  20190. <th>Name</th>
  20191. <th>Phone Number</th>
  20192. <th>Age</th>
  20193. </tr>
  20194. <tr ng-repeat="friend in friends | orderBy:'-age'">
  20195. <td>{{friend.name}}</td>
  20196. <td>{{friend.phone}}</td>
  20197. <td>{{friend.age}}</td>
  20198. </tr>
  20199. </table>
  20200. </div>
  20201. </file>
  20202. <file name="script.js">
  20203. angular.module('orderByExample1', [])
  20204. .controller('ExampleController', ['$scope', function($scope) {
  20205. $scope.friends = [
  20206. {name: 'John', phone: '555-1212', age: 10},
  20207. {name: 'Mary', phone: '555-9876', age: 19},
  20208. {name: 'Mike', phone: '555-4321', age: 21},
  20209. {name: 'Adam', phone: '555-5678', age: 35},
  20210. {name: 'Julie', phone: '555-8765', age: 29}
  20211. ];
  20212. }]);
  20213. </file>
  20214. <file name="style.css">
  20215. .friends {
  20216. border-collapse: collapse;
  20217. }
  20218. .friends th {
  20219. border-bottom: 1px solid;
  20220. }
  20221. .friends td, .friends th {
  20222. border-left: 1px solid;
  20223. padding: 5px 10px;
  20224. }
  20225. .friends td:first-child, .friends th:first-child {
  20226. border-left: none;
  20227. }
  20228. </file>
  20229. <file name="protractor.js" type="protractor">
  20230. // Element locators
  20231. var names = element.all(by.repeater('friends').column('friend.name'));
  20232. it('should sort friends by age in reverse order', function() {
  20233. expect(names.get(0).getText()).toBe('Adam');
  20234. expect(names.get(1).getText()).toBe('Julie');
  20235. expect(names.get(2).getText()).toBe('Mike');
  20236. expect(names.get(3).getText()).toBe('Mary');
  20237. expect(names.get(4).getText()).toBe('John');
  20238. });
  20239. </file>
  20240. </example>
  20241. * <hr />
  20242. *
  20243. * @example
  20244. * ### Changing parameters dynamically
  20245. *
  20246. * All parameters can be changed dynamically. The next example shows how you can make the columns of
  20247. * a table sortable, by binding the `expression` and `reverse` parameters to scope properties.
  20248. *
  20249. <example name="orderBy-dynamic" module="orderByExample2">
  20250. <file name="index.html">
  20251. <div ng-controller="ExampleController">
  20252. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  20253. <hr/>
  20254. <button ng-click="propertyName = null; reverse = false">Set to unsorted</button>
  20255. <hr/>
  20256. <table class="friends">
  20257. <tr>
  20258. <th>
  20259. <button ng-click="sortBy('name')">Name</button>
  20260. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  20261. </th>
  20262. <th>
  20263. <button ng-click="sortBy('phone')">Phone Number</button>
  20264. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  20265. </th>
  20266. <th>
  20267. <button ng-click="sortBy('age')">Age</button>
  20268. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  20269. </th>
  20270. </tr>
  20271. <tr ng-repeat="friend in friends | orderBy:propertyName:reverse">
  20272. <td>{{friend.name}}</td>
  20273. <td>{{friend.phone}}</td>
  20274. <td>{{friend.age}}</td>
  20275. </tr>
  20276. </table>
  20277. </div>
  20278. </file>
  20279. <file name="script.js">
  20280. angular.module('orderByExample2', [])
  20281. .controller('ExampleController', ['$scope', function($scope) {
  20282. var friends = [
  20283. {name: 'John', phone: '555-1212', age: 10},
  20284. {name: 'Mary', phone: '555-9876', age: 19},
  20285. {name: 'Mike', phone: '555-4321', age: 21},
  20286. {name: 'Adam', phone: '555-5678', age: 35},
  20287. {name: 'Julie', phone: '555-8765', age: 29}
  20288. ];
  20289. $scope.propertyName = 'age';
  20290. $scope.reverse = true;
  20291. $scope.friends = friends;
  20292. $scope.sortBy = function(propertyName) {
  20293. $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
  20294. $scope.propertyName = propertyName;
  20295. };
  20296. }]);
  20297. </file>
  20298. <file name="style.css">
  20299. .friends {
  20300. border-collapse: collapse;
  20301. }
  20302. .friends th {
  20303. border-bottom: 1px solid;
  20304. }
  20305. .friends td, .friends th {
  20306. border-left: 1px solid;
  20307. padding: 5px 10px;
  20308. }
  20309. .friends td:first-child, .friends th:first-child {
  20310. border-left: none;
  20311. }
  20312. .sortorder:after {
  20313. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  20314. }
  20315. .sortorder.reverse:after {
  20316. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  20317. }
  20318. </file>
  20319. <file name="protractor.js" type="protractor">
  20320. // Element locators
  20321. var unsortButton = element(by.partialButtonText('unsorted'));
  20322. var nameHeader = element(by.partialButtonText('Name'));
  20323. var phoneHeader = element(by.partialButtonText('Phone'));
  20324. var ageHeader = element(by.partialButtonText('Age'));
  20325. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  20326. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  20327. it('should sort friends by some property, when clicking on the column header', function() {
  20328. expect(firstName.getText()).toBe('Adam');
  20329. expect(lastName.getText()).toBe('John');
  20330. phoneHeader.click();
  20331. expect(firstName.getText()).toBe('John');
  20332. expect(lastName.getText()).toBe('Mary');
  20333. nameHeader.click();
  20334. expect(firstName.getText()).toBe('Adam');
  20335. expect(lastName.getText()).toBe('Mike');
  20336. ageHeader.click();
  20337. expect(firstName.getText()).toBe('John');
  20338. expect(lastName.getText()).toBe('Adam');
  20339. });
  20340. it('should sort friends in reverse order, when clicking on the same column', function() {
  20341. expect(firstName.getText()).toBe('Adam');
  20342. expect(lastName.getText()).toBe('John');
  20343. ageHeader.click();
  20344. expect(firstName.getText()).toBe('John');
  20345. expect(lastName.getText()).toBe('Adam');
  20346. ageHeader.click();
  20347. expect(firstName.getText()).toBe('Adam');
  20348. expect(lastName.getText()).toBe('John');
  20349. });
  20350. it('should restore the original order, when clicking "Set to unsorted"', function() {
  20351. expect(firstName.getText()).toBe('Adam');
  20352. expect(lastName.getText()).toBe('John');
  20353. unsortButton.click();
  20354. expect(firstName.getText()).toBe('John');
  20355. expect(lastName.getText()).toBe('Julie');
  20356. });
  20357. </file>
  20358. </example>
  20359. * <hr />
  20360. *
  20361. * @example
  20362. * ### Using `orderBy` inside a controller
  20363. *
  20364. * It is also possible to call the `orderBy` filter manually, by injecting `orderByFilter`, and
  20365. * calling it with the desired parameters. (Alternatively, you could inject the `$filter` factory
  20366. * and retrieve the `orderBy` filter with `$filter('orderBy')`.)
  20367. *
  20368. <example name="orderBy-call-manually" module="orderByExample3">
  20369. <file name="index.html">
  20370. <div ng-controller="ExampleController">
  20371. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  20372. <hr/>
  20373. <button ng-click="sortBy(null)">Set to unsorted</button>
  20374. <hr/>
  20375. <table class="friends">
  20376. <tr>
  20377. <th>
  20378. <button ng-click="sortBy('name')">Name</button>
  20379. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  20380. </th>
  20381. <th>
  20382. <button ng-click="sortBy('phone')">Phone Number</button>
  20383. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  20384. </th>
  20385. <th>
  20386. <button ng-click="sortBy('age')">Age</button>
  20387. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  20388. </th>
  20389. </tr>
  20390. <tr ng-repeat="friend in friends">
  20391. <td>{{friend.name}}</td>
  20392. <td>{{friend.phone}}</td>
  20393. <td>{{friend.age}}</td>
  20394. </tr>
  20395. </table>
  20396. </div>
  20397. </file>
  20398. <file name="script.js">
  20399. angular.module('orderByExample3', [])
  20400. .controller('ExampleController', ['$scope', 'orderByFilter', function($scope, orderBy) {
  20401. var friends = [
  20402. {name: 'John', phone: '555-1212', age: 10},
  20403. {name: 'Mary', phone: '555-9876', age: 19},
  20404. {name: 'Mike', phone: '555-4321', age: 21},
  20405. {name: 'Adam', phone: '555-5678', age: 35},
  20406. {name: 'Julie', phone: '555-8765', age: 29}
  20407. ];
  20408. $scope.propertyName = 'age';
  20409. $scope.reverse = true;
  20410. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  20411. $scope.sortBy = function(propertyName) {
  20412. $scope.reverse = (propertyName !== null && $scope.propertyName === propertyName)
  20413. ? !$scope.reverse : false;
  20414. $scope.propertyName = propertyName;
  20415. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  20416. };
  20417. }]);
  20418. </file>
  20419. <file name="style.css">
  20420. .friends {
  20421. border-collapse: collapse;
  20422. }
  20423. .friends th {
  20424. border-bottom: 1px solid;
  20425. }
  20426. .friends td, .friends th {
  20427. border-left: 1px solid;
  20428. padding: 5px 10px;
  20429. }
  20430. .friends td:first-child, .friends th:first-child {
  20431. border-left: none;
  20432. }
  20433. .sortorder:after {
  20434. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  20435. }
  20436. .sortorder.reverse:after {
  20437. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  20438. }
  20439. </file>
  20440. <file name="protractor.js" type="protractor">
  20441. // Element locators
  20442. var unsortButton = element(by.partialButtonText('unsorted'));
  20443. var nameHeader = element(by.partialButtonText('Name'));
  20444. var phoneHeader = element(by.partialButtonText('Phone'));
  20445. var ageHeader = element(by.partialButtonText('Age'));
  20446. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  20447. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  20448. it('should sort friends by some property, when clicking on the column header', function() {
  20449. expect(firstName.getText()).toBe('Adam');
  20450. expect(lastName.getText()).toBe('John');
  20451. phoneHeader.click();
  20452. expect(firstName.getText()).toBe('John');
  20453. expect(lastName.getText()).toBe('Mary');
  20454. nameHeader.click();
  20455. expect(firstName.getText()).toBe('Adam');
  20456. expect(lastName.getText()).toBe('Mike');
  20457. ageHeader.click();
  20458. expect(firstName.getText()).toBe('John');
  20459. expect(lastName.getText()).toBe('Adam');
  20460. });
  20461. it('should sort friends in reverse order, when clicking on the same column', function() {
  20462. expect(firstName.getText()).toBe('Adam');
  20463. expect(lastName.getText()).toBe('John');
  20464. ageHeader.click();
  20465. expect(firstName.getText()).toBe('John');
  20466. expect(lastName.getText()).toBe('Adam');
  20467. ageHeader.click();
  20468. expect(firstName.getText()).toBe('Adam');
  20469. expect(lastName.getText()).toBe('John');
  20470. });
  20471. it('should restore the original order, when clicking "Set to unsorted"', function() {
  20472. expect(firstName.getText()).toBe('Adam');
  20473. expect(lastName.getText()).toBe('John');
  20474. unsortButton.click();
  20475. expect(firstName.getText()).toBe('John');
  20476. expect(lastName.getText()).toBe('Julie');
  20477. });
  20478. </file>
  20479. </example>
  20480. * <hr />
  20481. *
  20482. * @example
  20483. * ### Using a custom comparator
  20484. *
  20485. * If you have very specific requirements about the way items are sorted, you can pass your own
  20486. * comparator function. For example, you might need to compare some strings in a locale-sensitive
  20487. * way. (When specifying a custom comparator, you also need to pass a value for the `reverse`
  20488. * argument - passing `false` retains the default sorting order, i.e. ascending.)
  20489. *
  20490. <example name="orderBy-custom-comparator" module="orderByExample4">
  20491. <file name="index.html">
  20492. <div ng-controller="ExampleController">
  20493. <div class="friends-container custom-comparator">
  20494. <h3>Locale-sensitive Comparator</h3>
  20495. <table class="friends">
  20496. <tr>
  20497. <th>Name</th>
  20498. <th>Favorite Letter</th>
  20499. </tr>
  20500. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter':false:localeSensitiveComparator">
  20501. <td>{{friend.name}}</td>
  20502. <td>{{friend.favoriteLetter}}</td>
  20503. </tr>
  20504. </table>
  20505. </div>
  20506. <div class="friends-container default-comparator">
  20507. <h3>Default Comparator</h3>
  20508. <table class="friends">
  20509. <tr>
  20510. <th>Name</th>
  20511. <th>Favorite Letter</th>
  20512. </tr>
  20513. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter'">
  20514. <td>{{friend.name}}</td>
  20515. <td>{{friend.favoriteLetter}}</td>
  20516. </tr>
  20517. </table>
  20518. </div>
  20519. </div>
  20520. </file>
  20521. <file name="script.js">
  20522. angular.module('orderByExample4', [])
  20523. .controller('ExampleController', ['$scope', function($scope) {
  20524. $scope.friends = [
  20525. {name: 'John', favoriteLetter: 'Ä'},
  20526. {name: 'Mary', favoriteLetter: 'Ü'},
  20527. {name: 'Mike', favoriteLetter: 'Ö'},
  20528. {name: 'Adam', favoriteLetter: 'H'},
  20529. {name: 'Julie', favoriteLetter: 'Z'}
  20530. ];
  20531. $scope.localeSensitiveComparator = function(v1, v2) {
  20532. // If we don't get strings, just compare by index
  20533. if (v1.type !== 'string' || v2.type !== 'string') {
  20534. return (v1.index < v2.index) ? -1 : 1;
  20535. }
  20536. // Compare strings alphabetically, taking locale into account
  20537. return v1.value.localeCompare(v2.value);
  20538. };
  20539. }]);
  20540. </file>
  20541. <file name="style.css">
  20542. .friends-container {
  20543. display: inline-block;
  20544. margin: 0 30px;
  20545. }
  20546. .friends {
  20547. border-collapse: collapse;
  20548. }
  20549. .friends th {
  20550. border-bottom: 1px solid;
  20551. }
  20552. .friends td, .friends th {
  20553. border-left: 1px solid;
  20554. padding: 5px 10px;
  20555. }
  20556. .friends td:first-child, .friends th:first-child {
  20557. border-left: none;
  20558. }
  20559. </file>
  20560. <file name="protractor.js" type="protractor">
  20561. // Element locators
  20562. var container = element(by.css('.custom-comparator'));
  20563. var names = container.all(by.repeater('friends').column('friend.name'));
  20564. it('should sort friends by favorite letter (in correct alphabetical order)', function() {
  20565. expect(names.get(0).getText()).toBe('John');
  20566. expect(names.get(1).getText()).toBe('Adam');
  20567. expect(names.get(2).getText()).toBe('Mike');
  20568. expect(names.get(3).getText()).toBe('Mary');
  20569. expect(names.get(4).getText()).toBe('Julie');
  20570. });
  20571. </file>
  20572. </example>
  20573. *
  20574. */
  20575. orderByFilter.$inject = ['$parse'];
  20576. function orderByFilter($parse) {
  20577. return function(array, sortPredicate, reverseOrder, compareFn) {
  20578. if (array == null) return array;
  20579. if (!isArrayLike(array)) {
  20580. throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
  20581. }
  20582. if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
  20583. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  20584. var predicates = processPredicates(sortPredicate);
  20585. var descending = reverseOrder ? -1 : 1;
  20586. // Define the `compare()` function. Use a default comparator if none is specified.
  20587. var compare = isFunction(compareFn) ? compareFn : defaultCompare;
  20588. // The next three lines are a version of a Swartzian Transform idiom from Perl
  20589. // (sometimes called the Decorate-Sort-Undecorate idiom)
  20590. // See https://en.wikipedia.org/wiki/Schwartzian_transform
  20591. var compareValues = Array.prototype.map.call(array, getComparisonObject);
  20592. compareValues.sort(doComparison);
  20593. array = compareValues.map(function(item) { return item.value; });
  20594. return array;
  20595. function getComparisonObject(value, index) {
  20596. // NOTE: We are adding an extra `tieBreaker` value based on the element's index.
  20597. // This will be used to keep the sort stable when none of the input predicates can
  20598. // distinguish between two elements.
  20599. return {
  20600. value: value,
  20601. tieBreaker: {value: index, type: 'number', index: index},
  20602. predicateValues: predicates.map(function(predicate) {
  20603. return getPredicateValue(predicate.get(value), index);
  20604. })
  20605. };
  20606. }
  20607. function doComparison(v1, v2) {
  20608. for (var i = 0, ii = predicates.length; i < ii; i++) {
  20609. var result = compare(v1.predicateValues[i], v2.predicateValues[i]);
  20610. if (result) {
  20611. return result * predicates[i].descending * descending;
  20612. }
  20613. }
  20614. return (compare(v1.tieBreaker, v2.tieBreaker) || defaultCompare(v1.tieBreaker, v2.tieBreaker)) * descending;
  20615. }
  20616. };
  20617. function processPredicates(sortPredicates) {
  20618. return sortPredicates.map(function(predicate) {
  20619. var descending = 1, get = identity;
  20620. if (isFunction(predicate)) {
  20621. get = predicate;
  20622. } else if (isString(predicate)) {
  20623. if ((predicate.charAt(0) === '+' || predicate.charAt(0) === '-')) {
  20624. descending = predicate.charAt(0) === '-' ? -1 : 1;
  20625. predicate = predicate.substring(1);
  20626. }
  20627. if (predicate !== '') {
  20628. get = $parse(predicate);
  20629. if (get.constant) {
  20630. var key = get();
  20631. get = function(value) { return value[key]; };
  20632. }
  20633. }
  20634. }
  20635. return {get: get, descending: descending};
  20636. });
  20637. }
  20638. function isPrimitive(value) {
  20639. switch (typeof value) {
  20640. case 'number': /* falls through */
  20641. case 'boolean': /* falls through */
  20642. case 'string':
  20643. return true;
  20644. default:
  20645. return false;
  20646. }
  20647. }
  20648. function objectValue(value) {
  20649. // If `valueOf` is a valid function use that
  20650. if (isFunction(value.valueOf)) {
  20651. value = value.valueOf();
  20652. if (isPrimitive(value)) return value;
  20653. }
  20654. // If `toString` is a valid function and not the one from `Object.prototype` use that
  20655. if (hasCustomToString(value)) {
  20656. value = value.toString();
  20657. if (isPrimitive(value)) return value;
  20658. }
  20659. return value;
  20660. }
  20661. function getPredicateValue(value, index) {
  20662. var type = typeof value;
  20663. if (value === null) {
  20664. type = 'string';
  20665. value = 'null';
  20666. } else if (type === 'object') {
  20667. value = objectValue(value);
  20668. }
  20669. return {value: value, type: type, index: index};
  20670. }
  20671. function defaultCompare(v1, v2) {
  20672. var result = 0;
  20673. var type1 = v1.type;
  20674. var type2 = v2.type;
  20675. if (type1 === type2) {
  20676. var value1 = v1.value;
  20677. var value2 = v2.value;
  20678. if (type1 === 'string') {
  20679. // Compare strings case-insensitively
  20680. value1 = value1.toLowerCase();
  20681. value2 = value2.toLowerCase();
  20682. } else if (type1 === 'object') {
  20683. // For basic objects, use the position of the object
  20684. // in the collection instead of the value
  20685. if (isObject(value1)) value1 = v1.index;
  20686. if (isObject(value2)) value2 = v2.index;
  20687. }
  20688. if (value1 !== value2) {
  20689. result = value1 < value2 ? -1 : 1;
  20690. }
  20691. } else {
  20692. result = type1 < type2 ? -1 : 1;
  20693. }
  20694. return result;
  20695. }
  20696. }
  20697. function ngDirective(directive) {
  20698. if (isFunction(directive)) {
  20699. directive = {
  20700. link: directive
  20701. };
  20702. }
  20703. directive.restrict = directive.restrict || 'AC';
  20704. return valueFn(directive);
  20705. }
  20706. /**
  20707. * @ngdoc directive
  20708. * @name a
  20709. * @restrict E
  20710. *
  20711. * @description
  20712. * Modifies the default behavior of the html a tag so that the default action is prevented when
  20713. * the href attribute is empty.
  20714. *
  20715. * For dynamically creating `href` attributes for a tags, see the {@link ng.ngHref `ngHref`} directive.
  20716. */
  20717. var htmlAnchorDirective = valueFn({
  20718. restrict: 'E',
  20719. compile: function(element, attr) {
  20720. if (!attr.href && !attr.xlinkHref) {
  20721. return function(scope, element) {
  20722. // If the linked element is not an anchor tag anymore, do nothing
  20723. if (element[0].nodeName.toLowerCase() !== 'a') return;
  20724. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  20725. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  20726. 'xlink:href' : 'href';
  20727. element.on('click', function(event) {
  20728. // if we have no href url, then don't navigate anywhere.
  20729. if (!element.attr(href)) {
  20730. event.preventDefault();
  20731. }
  20732. });
  20733. };
  20734. }
  20735. }
  20736. });
  20737. /**
  20738. * @ngdoc directive
  20739. * @name ngHref
  20740. * @restrict A
  20741. * @priority 99
  20742. *
  20743. * @description
  20744. * Using Angular markup like `{{hash}}` in an href attribute will
  20745. * make the link go to the wrong URL if the user clicks it before
  20746. * Angular has a chance to replace the `{{hash}}` markup with its
  20747. * value. Until Angular replaces the markup the link will be broken
  20748. * and will most likely return a 404 error. The `ngHref` directive
  20749. * solves this problem.
  20750. *
  20751. * The wrong way to write it:
  20752. * ```html
  20753. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  20754. * ```
  20755. *
  20756. * The correct way to write it:
  20757. * ```html
  20758. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  20759. * ```
  20760. *
  20761. * @element A
  20762. * @param {template} ngHref any string which can contain `{{}}` markup.
  20763. *
  20764. * @example
  20765. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  20766. * in links and their different behaviors:
  20767. <example name="ng-href">
  20768. <file name="index.html">
  20769. <input ng-model="value" /><br />
  20770. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  20771. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  20772. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  20773. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  20774. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  20775. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  20776. </file>
  20777. <file name="protractor.js" type="protractor">
  20778. it('should execute ng-click but not reload when href without value', function() {
  20779. element(by.id('link-1')).click();
  20780. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  20781. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  20782. });
  20783. it('should execute ng-click but not reload when href empty string', function() {
  20784. element(by.id('link-2')).click();
  20785. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  20786. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  20787. });
  20788. it('should execute ng-click and change url when ng-href specified', function() {
  20789. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  20790. element(by.id('link-3')).click();
  20791. // At this point, we navigate away from an Angular page, so we need
  20792. // to use browser.driver to get the base webdriver.
  20793. browser.wait(function() {
  20794. return browser.driver.getCurrentUrl().then(function(url) {
  20795. return url.match(/\/123$/);
  20796. });
  20797. }, 5000, 'page should navigate to /123');
  20798. });
  20799. it('should execute ng-click but not reload when href empty string and name specified', function() {
  20800. element(by.id('link-4')).click();
  20801. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  20802. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  20803. });
  20804. it('should execute ng-click but not reload when no href but name specified', function() {
  20805. element(by.id('link-5')).click();
  20806. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  20807. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  20808. });
  20809. it('should only change url when only ng-href', function() {
  20810. element(by.model('value')).clear();
  20811. element(by.model('value')).sendKeys('6');
  20812. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  20813. element(by.id('link-6')).click();
  20814. // At this point, we navigate away from an Angular page, so we need
  20815. // to use browser.driver to get the base webdriver.
  20816. browser.wait(function() {
  20817. return browser.driver.getCurrentUrl().then(function(url) {
  20818. return url.match(/\/6$/);
  20819. });
  20820. }, 5000, 'page should navigate to /6');
  20821. });
  20822. </file>
  20823. </example>
  20824. */
  20825. /**
  20826. * @ngdoc directive
  20827. * @name ngSrc
  20828. * @restrict A
  20829. * @priority 99
  20830. *
  20831. * @description
  20832. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  20833. * work right: The browser will fetch from the URL with the literal
  20834. * text `{{hash}}` until Angular replaces the expression inside
  20835. * `{{hash}}`. The `ngSrc` directive solves this problem.
  20836. *
  20837. * The buggy way to write it:
  20838. * ```html
  20839. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  20840. * ```
  20841. *
  20842. * The correct way to write it:
  20843. * ```html
  20844. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  20845. * ```
  20846. *
  20847. * @element IMG
  20848. * @param {template} ngSrc any string which can contain `{{}}` markup.
  20849. */
  20850. /**
  20851. * @ngdoc directive
  20852. * @name ngSrcset
  20853. * @restrict A
  20854. * @priority 99
  20855. *
  20856. * @description
  20857. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  20858. * work right: The browser will fetch from the URL with the literal
  20859. * text `{{hash}}` until Angular replaces the expression inside
  20860. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  20861. *
  20862. * The buggy way to write it:
  20863. * ```html
  20864. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  20865. * ```
  20866. *
  20867. * The correct way to write it:
  20868. * ```html
  20869. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  20870. * ```
  20871. *
  20872. * @element IMG
  20873. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  20874. */
  20875. /**
  20876. * @ngdoc directive
  20877. * @name ngDisabled
  20878. * @restrict A
  20879. * @priority 100
  20880. *
  20881. * @description
  20882. *
  20883. * This directive sets the `disabled` attribute on the element (typically a form control,
  20884. * e.g. `input`, `button`, `select` etc.) if the
  20885. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  20886. *
  20887. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  20888. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20889. *
  20890. * @example
  20891. <example name="ng-disabled">
  20892. <file name="index.html">
  20893. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  20894. <button ng-model="button" ng-disabled="checked">Button</button>
  20895. </file>
  20896. <file name="protractor.js" type="protractor">
  20897. it('should toggle button', function() {
  20898. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  20899. element(by.model('checked')).click();
  20900. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  20901. });
  20902. </file>
  20903. </example>
  20904. *
  20905. * @element INPUT
  20906. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  20907. * then the `disabled` attribute will be set on the element
  20908. */
  20909. /**
  20910. * @ngdoc directive
  20911. * @name ngChecked
  20912. * @restrict A
  20913. * @priority 100
  20914. *
  20915. * @description
  20916. * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
  20917. *
  20918. * Note that this directive should not be used together with {@link ngModel `ngModel`},
  20919. * as this can lead to unexpected behavior.
  20920. *
  20921. * A special directive is necessary because we cannot use interpolation inside the `checked`
  20922. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20923. *
  20924. * @example
  20925. <example name="ng-checked">
  20926. <file name="index.html">
  20927. <label>Check me to check both: <input type="checkbox" ng-model="leader"></label><br/>
  20928. <input id="checkFollower" type="checkbox" ng-checked="leader" aria-label="Follower input">
  20929. </file>
  20930. <file name="protractor.js" type="protractor">
  20931. it('should check both checkBoxes', function() {
  20932. expect(element(by.id('checkFollower')).getAttribute('checked')).toBeFalsy();
  20933. element(by.model('leader')).click();
  20934. expect(element(by.id('checkFollower')).getAttribute('checked')).toBeTruthy();
  20935. });
  20936. </file>
  20937. </example>
  20938. *
  20939. * @element INPUT
  20940. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  20941. * then the `checked` attribute will be set on the element
  20942. */
  20943. /**
  20944. * @ngdoc directive
  20945. * @name ngReadonly
  20946. * @restrict A
  20947. * @priority 100
  20948. *
  20949. * @description
  20950. *
  20951. * Sets the `readonly` attribute on the element, if the expression inside `ngReadonly` is truthy.
  20952. * Note that `readonly` applies only to `input` elements with specific types. [See the input docs on
  20953. * MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-readonly) for more information.
  20954. *
  20955. * A special directive is necessary because we cannot use interpolation inside the `readonly`
  20956. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20957. *
  20958. * @example
  20959. <example name="ng-readonly">
  20960. <file name="index.html">
  20961. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  20962. <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
  20963. </file>
  20964. <file name="protractor.js" type="protractor">
  20965. it('should toggle readonly attr', function() {
  20966. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  20967. element(by.model('checked')).click();
  20968. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  20969. });
  20970. </file>
  20971. </example>
  20972. *
  20973. * @element INPUT
  20974. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  20975. * then special attribute "readonly" will be set on the element
  20976. */
  20977. /**
  20978. * @ngdoc directive
  20979. * @name ngSelected
  20980. * @restrict A
  20981. * @priority 100
  20982. *
  20983. * @description
  20984. *
  20985. * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy.
  20986. *
  20987. * A special directive is necessary because we cannot use interpolation inside the `selected`
  20988. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  20989. *
  20990. * <div class="alert alert-warning">
  20991. * **Note:** `ngSelected` does not interact with the `select` and `ngModel` directives, it only
  20992. * sets the `selected` attribute on the element. If you are using `ngModel` on the select, you
  20993. * should not use `ngSelected` on the options, as `ngModel` will set the select value and
  20994. * selected options.
  20995. * </div>
  20996. *
  20997. * @example
  20998. <example name="ng-selected">
  20999. <file name="index.html">
  21000. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  21001. <select aria-label="ngSelected demo">
  21002. <option>Hello!</option>
  21003. <option id="greet" ng-selected="selected">Greetings!</option>
  21004. </select>
  21005. </file>
  21006. <file name="protractor.js" type="protractor">
  21007. it('should select Greetings!', function() {
  21008. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  21009. element(by.model('selected')).click();
  21010. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  21011. });
  21012. </file>
  21013. </example>
  21014. *
  21015. * @element OPTION
  21016. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  21017. * then special attribute "selected" will be set on the element
  21018. */
  21019. /**
  21020. * @ngdoc directive
  21021. * @name ngOpen
  21022. * @restrict A
  21023. * @priority 100
  21024. *
  21025. * @description
  21026. *
  21027. * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy.
  21028. *
  21029. * A special directive is necessary because we cannot use interpolation inside the `open`
  21030. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  21031. *
  21032. * ## A note about browser compatibility
  21033. *
  21034. * Internet Explorer and Edge do not support the `details` element, it is
  21035. * recommended to use {@link ng.ngShow} and {@link ng.ngHide} instead.
  21036. *
  21037. * @example
  21038. <example name="ng-open">
  21039. <file name="index.html">
  21040. <label>Toggle details: <input type="checkbox" ng-model="open"></label><br/>
  21041. <details id="details" ng-open="open">
  21042. <summary>List</summary>
  21043. <ul>
  21044. <li>Apple</li>
  21045. <li>Orange</li>
  21046. <li>Durian</li>
  21047. </ul>
  21048. </details>
  21049. </file>
  21050. <file name="protractor.js" type="protractor">
  21051. it('should toggle open', function() {
  21052. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  21053. element(by.model('open')).click();
  21054. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  21055. });
  21056. </file>
  21057. </example>
  21058. *
  21059. * @element DETAILS
  21060. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  21061. * then special attribute "open" will be set on the element
  21062. */
  21063. var ngAttributeAliasDirectives = {};
  21064. // boolean attrs are evaluated
  21065. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  21066. // binding to multiple is not supported
  21067. if (propName === 'multiple') return;
  21068. function defaultLinkFn(scope, element, attr) {
  21069. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  21070. attr.$set(attrName, !!value);
  21071. });
  21072. }
  21073. var normalized = directiveNormalize('ng-' + attrName);
  21074. var linkFn = defaultLinkFn;
  21075. if (propName === 'checked') {
  21076. linkFn = function(scope, element, attr) {
  21077. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  21078. if (attr.ngModel !== attr[normalized]) {
  21079. defaultLinkFn(scope, element, attr);
  21080. }
  21081. };
  21082. }
  21083. ngAttributeAliasDirectives[normalized] = function() {
  21084. return {
  21085. restrict: 'A',
  21086. priority: 100,
  21087. link: linkFn
  21088. };
  21089. };
  21090. });
  21091. // aliased input attrs are evaluated
  21092. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  21093. ngAttributeAliasDirectives[ngAttr] = function() {
  21094. return {
  21095. priority: 100,
  21096. link: function(scope, element, attr) {
  21097. //special case ngPattern when a literal regular expression value
  21098. //is used as the expression (this way we don't have to watch anything).
  21099. if (ngAttr === 'ngPattern' && attr.ngPattern.charAt(0) === '/') {
  21100. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  21101. if (match) {
  21102. attr.$set('ngPattern', new RegExp(match[1], match[2]));
  21103. return;
  21104. }
  21105. }
  21106. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  21107. attr.$set(ngAttr, value);
  21108. });
  21109. }
  21110. };
  21111. };
  21112. });
  21113. // ng-src, ng-srcset, ng-href are interpolated
  21114. forEach(['src', 'srcset', 'href'], function(attrName) {
  21115. var normalized = directiveNormalize('ng-' + attrName);
  21116. ngAttributeAliasDirectives[normalized] = function() {
  21117. return {
  21118. priority: 99, // it needs to run after the attributes are interpolated
  21119. link: function(scope, element, attr) {
  21120. var propName = attrName,
  21121. name = attrName;
  21122. if (attrName === 'href' &&
  21123. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  21124. name = 'xlinkHref';
  21125. attr.$attr[name] = 'xlink:href';
  21126. propName = null;
  21127. }
  21128. attr.$observe(normalized, function(value) {
  21129. if (!value) {
  21130. if (attrName === 'href') {
  21131. attr.$set(name, null);
  21132. }
  21133. return;
  21134. }
  21135. attr.$set(name, value);
  21136. // Support: IE 9-11 only
  21137. // On IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  21138. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  21139. // to set the property as well to achieve the desired effect.
  21140. // We use attr[attrName] value since $set can sanitize the url.
  21141. if (msie && propName) element.prop(propName, attr[name]);
  21142. });
  21143. }
  21144. };
  21145. };
  21146. });
  21147. /* global -nullFormCtrl, -PENDING_CLASS, -SUBMITTED_CLASS
  21148. */
  21149. var nullFormCtrl = {
  21150. $addControl: noop,
  21151. $$renameControl: nullFormRenameControl,
  21152. $removeControl: noop,
  21153. $setValidity: noop,
  21154. $setDirty: noop,
  21155. $setPristine: noop,
  21156. $setSubmitted: noop
  21157. },
  21158. PENDING_CLASS = 'ng-pending',
  21159. SUBMITTED_CLASS = 'ng-submitted';
  21160. function nullFormRenameControl(control, name) {
  21161. control.$name = name;
  21162. }
  21163. /**
  21164. * @ngdoc type
  21165. * @name form.FormController
  21166. *
  21167. * @property {boolean} $pristine True if user has not interacted with the form yet.
  21168. * @property {boolean} $dirty True if user has already interacted with the form.
  21169. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  21170. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  21171. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  21172. *
  21173. * @property {Object} $pending An object hash, containing references to controls or forms with
  21174. * pending validators, where:
  21175. *
  21176. * - keys are validations tokens (error names).
  21177. * - values are arrays of controls or forms that have a pending validator for the given error name.
  21178. *
  21179. * See {@link form.FormController#$error $error} for a list of built-in validation tokens.
  21180. *
  21181. * @property {Object} $error An object hash, containing references to controls or forms with failing
  21182. * validators, where:
  21183. *
  21184. * - keys are validation tokens (error names),
  21185. * - values are arrays of controls or forms that have a failing validator for the given error name.
  21186. *
  21187. * Built-in validation tokens:
  21188. * - `email`
  21189. * - `max`
  21190. * - `maxlength`
  21191. * - `min`
  21192. * - `minlength`
  21193. * - `number`
  21194. * - `pattern`
  21195. * - `required`
  21196. * - `url`
  21197. * - `date`
  21198. * - `datetimelocal`
  21199. * - `time`
  21200. * - `week`
  21201. * - `month`
  21202. *
  21203. * @description
  21204. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  21205. * such as being valid/invalid or dirty/pristine.
  21206. *
  21207. * Each {@link ng.directive:form form} directive creates an instance
  21208. * of `FormController`.
  21209. *
  21210. */
  21211. //asks for $scope to fool the BC controller module
  21212. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  21213. function FormController($element, $attrs, $scope, $animate, $interpolate) {
  21214. this.$$controls = [];
  21215. // init state
  21216. this.$error = {};
  21217. this.$$success = {};
  21218. this.$pending = undefined;
  21219. this.$name = $interpolate($attrs.name || $attrs.ngForm || '')($scope);
  21220. this.$dirty = false;
  21221. this.$pristine = true;
  21222. this.$valid = true;
  21223. this.$invalid = false;
  21224. this.$submitted = false;
  21225. this.$$parentForm = nullFormCtrl;
  21226. this.$$element = $element;
  21227. this.$$animate = $animate;
  21228. setupValidity(this);
  21229. }
  21230. FormController.prototype = {
  21231. /**
  21232. * @ngdoc method
  21233. * @name form.FormController#$rollbackViewValue
  21234. *
  21235. * @description
  21236. * Rollback all form controls pending updates to the `$modelValue`.
  21237. *
  21238. * Updates may be pending by a debounced event or because the input is waiting for a some future
  21239. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  21240. * a form that uses `ng-model-options` to pend updates.
  21241. */
  21242. $rollbackViewValue: function() {
  21243. forEach(this.$$controls, function(control) {
  21244. control.$rollbackViewValue();
  21245. });
  21246. },
  21247. /**
  21248. * @ngdoc method
  21249. * @name form.FormController#$commitViewValue
  21250. *
  21251. * @description
  21252. * Commit all form controls pending updates to the `$modelValue`.
  21253. *
  21254. * Updates may be pending by a debounced event or because the input is waiting for a some future
  21255. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  21256. * usually handles calling this in response to input events.
  21257. */
  21258. $commitViewValue: function() {
  21259. forEach(this.$$controls, function(control) {
  21260. control.$commitViewValue();
  21261. });
  21262. },
  21263. /**
  21264. * @ngdoc method
  21265. * @name form.FormController#$addControl
  21266. * @param {object} control control object, either a {@link form.FormController} or an
  21267. * {@link ngModel.NgModelController}
  21268. *
  21269. * @description
  21270. * Register a control with the form. Input elements using ngModelController do this automatically
  21271. * when they are linked.
  21272. *
  21273. * Note that the current state of the control will not be reflected on the new parent form. This
  21274. * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
  21275. * state.
  21276. *
  21277. * However, if the method is used programmatically, for example by adding dynamically created controls,
  21278. * or controls that have been previously removed without destroying their corresponding DOM element,
  21279. * it's the developers responsibility to make sure the current state propagates to the parent form.
  21280. *
  21281. * For example, if an input control is added that is already `$dirty` and has `$error` properties,
  21282. * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
  21283. */
  21284. $addControl: function(control) {
  21285. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  21286. // and not added to the scope. Now we throw an error.
  21287. assertNotHasOwnProperty(control.$name, 'input');
  21288. this.$$controls.push(control);
  21289. if (control.$name) {
  21290. this[control.$name] = control;
  21291. }
  21292. control.$$parentForm = this;
  21293. },
  21294. // Private API: rename a form control
  21295. $$renameControl: function(control, newName) {
  21296. var oldName = control.$name;
  21297. if (this[oldName] === control) {
  21298. delete this[oldName];
  21299. }
  21300. this[newName] = control;
  21301. control.$name = newName;
  21302. },
  21303. /**
  21304. * @ngdoc method
  21305. * @name form.FormController#$removeControl
  21306. * @param {object} control control object, either a {@link form.FormController} or an
  21307. * {@link ngModel.NgModelController}
  21308. *
  21309. * @description
  21310. * Deregister a control from the form.
  21311. *
  21312. * Input elements using ngModelController do this automatically when they are destroyed.
  21313. *
  21314. * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
  21315. * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
  21316. * different from case to case. For example, removing the only `$dirty` control from a form may or
  21317. * may not mean that the form is still `$dirty`.
  21318. */
  21319. $removeControl: function(control) {
  21320. if (control.$name && this[control.$name] === control) {
  21321. delete this[control.$name];
  21322. }
  21323. forEach(this.$pending, function(value, name) {
  21324. // eslint-disable-next-line no-invalid-this
  21325. this.$setValidity(name, null, control);
  21326. }, this);
  21327. forEach(this.$error, function(value, name) {
  21328. // eslint-disable-next-line no-invalid-this
  21329. this.$setValidity(name, null, control);
  21330. }, this);
  21331. forEach(this.$$success, function(value, name) {
  21332. // eslint-disable-next-line no-invalid-this
  21333. this.$setValidity(name, null, control);
  21334. }, this);
  21335. arrayRemove(this.$$controls, control);
  21336. control.$$parentForm = nullFormCtrl;
  21337. },
  21338. /**
  21339. * @ngdoc method
  21340. * @name form.FormController#$setDirty
  21341. *
  21342. * @description
  21343. * Sets the form to a dirty state.
  21344. *
  21345. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  21346. * state (ng-dirty class). This method will also propagate to parent forms.
  21347. */
  21348. $setDirty: function() {
  21349. this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);
  21350. this.$$animate.addClass(this.$$element, DIRTY_CLASS);
  21351. this.$dirty = true;
  21352. this.$pristine = false;
  21353. this.$$parentForm.$setDirty();
  21354. },
  21355. /**
  21356. * @ngdoc method
  21357. * @name form.FormController#$setPristine
  21358. *
  21359. * @description
  21360. * Sets the form to its pristine state.
  21361. *
  21362. * This method sets the form's `$pristine` state to true, the `$dirty` state to false, removes
  21363. * the `ng-dirty` class and adds the `ng-pristine` class. Additionally, it sets the `$submitted`
  21364. * state to false.
  21365. *
  21366. * This method will also propagate to all the controls contained in this form.
  21367. *
  21368. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  21369. * saving or resetting it.
  21370. */
  21371. $setPristine: function() {
  21372. this.$$animate.setClass(this.$$element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  21373. this.$dirty = false;
  21374. this.$pristine = true;
  21375. this.$submitted = false;
  21376. forEach(this.$$controls, function(control) {
  21377. control.$setPristine();
  21378. });
  21379. },
  21380. /**
  21381. * @ngdoc method
  21382. * @name form.FormController#$setUntouched
  21383. *
  21384. * @description
  21385. * Sets the form to its untouched state.
  21386. *
  21387. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  21388. * untouched state (ng-untouched class).
  21389. *
  21390. * Setting a form controls back to their untouched state is often useful when setting the form
  21391. * back to its pristine state.
  21392. */
  21393. $setUntouched: function() {
  21394. forEach(this.$$controls, function(control) {
  21395. control.$setUntouched();
  21396. });
  21397. },
  21398. /**
  21399. * @ngdoc method
  21400. * @name form.FormController#$setSubmitted
  21401. *
  21402. * @description
  21403. * Sets the form to its submitted state.
  21404. */
  21405. $setSubmitted: function() {
  21406. this.$$animate.addClass(this.$$element, SUBMITTED_CLASS);
  21407. this.$submitted = true;
  21408. this.$$parentForm.$setSubmitted();
  21409. }
  21410. };
  21411. /**
  21412. * @ngdoc method
  21413. * @name form.FormController#$setValidity
  21414. *
  21415. * @description
  21416. * Change the validity state of the form, and notify the parent form (if any).
  21417. *
  21418. * Application developers will rarely need to call this method directly. It is used internally, by
  21419. * {@link ngModel.NgModelController#$setValidity NgModelController.$setValidity()}, to propagate a
  21420. * control's validity state to the parent `FormController`.
  21421. *
  21422. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be
  21423. * assigned to either `$error[validationErrorKey]` or `$pending[validationErrorKey]` (for
  21424. * unfulfilled `$asyncValidators`), so that it is available for data-binding. The
  21425. * `validationErrorKey` should be in camelCase and will get converted into dash-case for
  21426. * class name. Example: `myError` will result in `ng-valid-my-error` and
  21427. * `ng-invalid-my-error` classes and can be bound to as `{{ someForm.$error.myError }}`.
  21428. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending
  21429. * (undefined), or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  21430. * Skipped is used by AngularJS when validators do not run because of parse errors and when
  21431. * `$asyncValidators` do not run because any of the `$validators` failed.
  21432. * @param {NgModelController | FormController} controller - The controller whose validity state is
  21433. * triggering the change.
  21434. */
  21435. addSetValidityMethod({
  21436. clazz: FormController,
  21437. set: function(object, property, controller) {
  21438. var list = object[property];
  21439. if (!list) {
  21440. object[property] = [controller];
  21441. } else {
  21442. var index = list.indexOf(controller);
  21443. if (index === -1) {
  21444. list.push(controller);
  21445. }
  21446. }
  21447. },
  21448. unset: function(object, property, controller) {
  21449. var list = object[property];
  21450. if (!list) {
  21451. return;
  21452. }
  21453. arrayRemove(list, controller);
  21454. if (list.length === 0) {
  21455. delete object[property];
  21456. }
  21457. }
  21458. });
  21459. /**
  21460. * @ngdoc directive
  21461. * @name ngForm
  21462. * @restrict EAC
  21463. *
  21464. * @description
  21465. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  21466. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  21467. * sub-group of controls needs to be determined.
  21468. *
  21469. * Note: the purpose of `ngForm` is to group controls,
  21470. * but not to be a replacement for the `<form>` tag with all of its capabilities
  21471. * (e.g. posting to the server, ...).
  21472. *
  21473. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  21474. * related scope, under this name.
  21475. *
  21476. */
  21477. /**
  21478. * @ngdoc directive
  21479. * @name form
  21480. * @restrict E
  21481. *
  21482. * @description
  21483. * Directive that instantiates
  21484. * {@link form.FormController FormController}.
  21485. *
  21486. * If the `name` attribute is specified, the form controller is published onto the current scope under
  21487. * this name.
  21488. *
  21489. * ## Alias: {@link ng.directive:ngForm `ngForm`}
  21490. *
  21491. * In Angular, forms can be nested. This means that the outer form is valid when all of the child
  21492. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  21493. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to
  21494. * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group
  21495. * of controls needs to be determined.
  21496. *
  21497. * ## CSS classes
  21498. * - `ng-valid` is set if the form is valid.
  21499. * - `ng-invalid` is set if the form is invalid.
  21500. * - `ng-pending` is set if the form is pending.
  21501. * - `ng-pristine` is set if the form is pristine.
  21502. * - `ng-dirty` is set if the form is dirty.
  21503. * - `ng-submitted` is set if the form was submitted.
  21504. *
  21505. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  21506. *
  21507. *
  21508. * ## Submitting a form and preventing the default action
  21509. *
  21510. * Since the role of forms in client-side Angular applications is different than in classical
  21511. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  21512. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  21513. * to handle the form submission in an application-specific way.
  21514. *
  21515. * For this reason, Angular prevents the default action (form submission to the server) unless the
  21516. * `<form>` element has an `action` attribute specified.
  21517. *
  21518. * You can use one of the following two ways to specify what javascript method should be called when
  21519. * a form is submitted:
  21520. *
  21521. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  21522. * - {@link ng.directive:ngClick ngClick} directive on the first
  21523. * button or input field of type submit (input[type=submit])
  21524. *
  21525. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  21526. * or {@link ng.directive:ngClick ngClick} directives.
  21527. * This is because of the following form submission rules in the HTML specification:
  21528. *
  21529. * - If a form has only one input field then hitting enter in this field triggers form submit
  21530. * (`ngSubmit`)
  21531. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  21532. * doesn't trigger submit
  21533. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  21534. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  21535. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  21536. *
  21537. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  21538. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  21539. * to have access to the updated model.
  21540. *
  21541. * @animations
  21542. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  21543. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  21544. * other validations that are performed within the form. Animations in ngForm are similar to how
  21545. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  21546. * as JS animations.
  21547. *
  21548. * The following example shows a simple way to utilize CSS transitions to style a form element
  21549. * that has been rendered as invalid after it has been validated:
  21550. *
  21551. * <pre>
  21552. * //be sure to include ngAnimate as a module to hook into more
  21553. * //advanced animations
  21554. * .my-form {
  21555. * transition:0.5s linear all;
  21556. * background: white;
  21557. * }
  21558. * .my-form.ng-invalid {
  21559. * background: red;
  21560. * color:white;
  21561. * }
  21562. * </pre>
  21563. *
  21564. * @example
  21565. <example name="ng-form" deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  21566. <file name="index.html">
  21567. <script>
  21568. angular.module('formExample', [])
  21569. .controller('FormController', ['$scope', function($scope) {
  21570. $scope.userType = 'guest';
  21571. }]);
  21572. </script>
  21573. <style>
  21574. .my-form {
  21575. transition:all linear 0.5s;
  21576. background: transparent;
  21577. }
  21578. .my-form.ng-invalid {
  21579. background: red;
  21580. }
  21581. </style>
  21582. <form name="myForm" ng-controller="FormController" class="my-form">
  21583. userType: <input name="input" ng-model="userType" required>
  21584. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  21585. <code>userType = {{userType}}</code><br>
  21586. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  21587. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  21588. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  21589. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  21590. </form>
  21591. </file>
  21592. <file name="protractor.js" type="protractor">
  21593. it('should initialize to model', function() {
  21594. var userType = element(by.binding('userType'));
  21595. var valid = element(by.binding('myForm.input.$valid'));
  21596. expect(userType.getText()).toContain('guest');
  21597. expect(valid.getText()).toContain('true');
  21598. });
  21599. it('should be invalid if empty', function() {
  21600. var userType = element(by.binding('userType'));
  21601. var valid = element(by.binding('myForm.input.$valid'));
  21602. var userInput = element(by.model('userType'));
  21603. userInput.clear();
  21604. userInput.sendKeys('');
  21605. expect(userType.getText()).toEqual('userType =');
  21606. expect(valid.getText()).toContain('false');
  21607. });
  21608. </file>
  21609. </example>
  21610. *
  21611. * @param {string=} name Name of the form. If specified, the form controller will be published into
  21612. * related scope, under this name.
  21613. */
  21614. var formDirectiveFactory = function(isNgForm) {
  21615. return ['$timeout', '$parse', function($timeout, $parse) {
  21616. var formDirective = {
  21617. name: 'form',
  21618. restrict: isNgForm ? 'EAC' : 'E',
  21619. require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
  21620. controller: FormController,
  21621. compile: function ngFormCompile(formElement, attr) {
  21622. // Setup initial state of the control
  21623. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  21624. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  21625. return {
  21626. pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
  21627. var controller = ctrls[0];
  21628. // if `action` attr is not present on the form, prevent the default action (submission)
  21629. if (!('action' in attr)) {
  21630. // we can't use jq events because if a form is destroyed during submission the default
  21631. // action is not prevented. see #1238
  21632. //
  21633. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  21634. // page reload if the form was destroyed by submission of the form via a click handler
  21635. // on a button in the form. Looks like an IE9 specific bug.
  21636. var handleFormSubmission = function(event) {
  21637. scope.$apply(function() {
  21638. controller.$commitViewValue();
  21639. controller.$setSubmitted();
  21640. });
  21641. event.preventDefault();
  21642. };
  21643. formElement[0].addEventListener('submit', handleFormSubmission);
  21644. // unregister the preventDefault listener so that we don't not leak memory but in a
  21645. // way that will achieve the prevention of the default action.
  21646. formElement.on('$destroy', function() {
  21647. $timeout(function() {
  21648. formElement[0].removeEventListener('submit', handleFormSubmission);
  21649. }, 0, false);
  21650. });
  21651. }
  21652. var parentFormCtrl = ctrls[1] || controller.$$parentForm;
  21653. parentFormCtrl.$addControl(controller);
  21654. var setter = nameAttr ? getSetter(controller.$name) : noop;
  21655. if (nameAttr) {
  21656. setter(scope, controller);
  21657. attr.$observe(nameAttr, function(newValue) {
  21658. if (controller.$name === newValue) return;
  21659. setter(scope, undefined);
  21660. controller.$$parentForm.$$renameControl(controller, newValue);
  21661. setter = getSetter(controller.$name);
  21662. setter(scope, controller);
  21663. });
  21664. }
  21665. formElement.on('$destroy', function() {
  21666. controller.$$parentForm.$removeControl(controller);
  21667. setter(scope, undefined);
  21668. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  21669. });
  21670. }
  21671. };
  21672. }
  21673. };
  21674. return formDirective;
  21675. function getSetter(expression) {
  21676. if (expression === '') {
  21677. //create an assignable expression, so forms with an empty name can be renamed later
  21678. return $parse('this[""]').assign;
  21679. }
  21680. return $parse(expression).assign || noop;
  21681. }
  21682. }];
  21683. };
  21684. var formDirective = formDirectiveFactory();
  21685. var ngFormDirective = formDirectiveFactory(true);
  21686. // helper methods
  21687. function setupValidity(instance) {
  21688. instance.$$classCache = {};
  21689. instance.$$classCache[INVALID_CLASS] = !(instance.$$classCache[VALID_CLASS] = instance.$$element.hasClass(VALID_CLASS));
  21690. }
  21691. function addSetValidityMethod(context) {
  21692. var clazz = context.clazz,
  21693. set = context.set,
  21694. unset = context.unset;
  21695. clazz.prototype.$setValidity = function(validationErrorKey, state, controller) {
  21696. if (isUndefined(state)) {
  21697. createAndSet(this, '$pending', validationErrorKey, controller);
  21698. } else {
  21699. unsetAndCleanup(this, '$pending', validationErrorKey, controller);
  21700. }
  21701. if (!isBoolean(state)) {
  21702. unset(this.$error, validationErrorKey, controller);
  21703. unset(this.$$success, validationErrorKey, controller);
  21704. } else {
  21705. if (state) {
  21706. unset(this.$error, validationErrorKey, controller);
  21707. set(this.$$success, validationErrorKey, controller);
  21708. } else {
  21709. set(this.$error, validationErrorKey, controller);
  21710. unset(this.$$success, validationErrorKey, controller);
  21711. }
  21712. }
  21713. if (this.$pending) {
  21714. cachedToggleClass(this, PENDING_CLASS, true);
  21715. this.$valid = this.$invalid = undefined;
  21716. toggleValidationCss(this, '', null);
  21717. } else {
  21718. cachedToggleClass(this, PENDING_CLASS, false);
  21719. this.$valid = isObjectEmpty(this.$error);
  21720. this.$invalid = !this.$valid;
  21721. toggleValidationCss(this, '', this.$valid);
  21722. }
  21723. // re-read the state as the set/unset methods could have
  21724. // combined state in this.$error[validationError] (used for forms),
  21725. // where setting/unsetting only increments/decrements the value,
  21726. // and does not replace it.
  21727. var combinedState;
  21728. if (this.$pending && this.$pending[validationErrorKey]) {
  21729. combinedState = undefined;
  21730. } else if (this.$error[validationErrorKey]) {
  21731. combinedState = false;
  21732. } else if (this.$$success[validationErrorKey]) {
  21733. combinedState = true;
  21734. } else {
  21735. combinedState = null;
  21736. }
  21737. toggleValidationCss(this, validationErrorKey, combinedState);
  21738. this.$$parentForm.$setValidity(validationErrorKey, combinedState, this);
  21739. };
  21740. function createAndSet(ctrl, name, value, controller) {
  21741. if (!ctrl[name]) {
  21742. ctrl[name] = {};
  21743. }
  21744. set(ctrl[name], value, controller);
  21745. }
  21746. function unsetAndCleanup(ctrl, name, value, controller) {
  21747. if (ctrl[name]) {
  21748. unset(ctrl[name], value, controller);
  21749. }
  21750. if (isObjectEmpty(ctrl[name])) {
  21751. ctrl[name] = undefined;
  21752. }
  21753. }
  21754. function cachedToggleClass(ctrl, className, switchValue) {
  21755. if (switchValue && !ctrl.$$classCache[className]) {
  21756. ctrl.$$animate.addClass(ctrl.$$element, className);
  21757. ctrl.$$classCache[className] = true;
  21758. } else if (!switchValue && ctrl.$$classCache[className]) {
  21759. ctrl.$$animate.removeClass(ctrl.$$element, className);
  21760. ctrl.$$classCache[className] = false;
  21761. }
  21762. }
  21763. function toggleValidationCss(ctrl, validationErrorKey, isValid) {
  21764. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  21765. cachedToggleClass(ctrl, VALID_CLASS + validationErrorKey, isValid === true);
  21766. cachedToggleClass(ctrl, INVALID_CLASS + validationErrorKey, isValid === false);
  21767. }
  21768. }
  21769. function isObjectEmpty(obj) {
  21770. if (obj) {
  21771. for (var prop in obj) {
  21772. if (obj.hasOwnProperty(prop)) {
  21773. return false;
  21774. }
  21775. }
  21776. }
  21777. return true;
  21778. }
  21779. /* global
  21780. VALID_CLASS: false,
  21781. INVALID_CLASS: false,
  21782. PRISTINE_CLASS: false,
  21783. DIRTY_CLASS: false,
  21784. ngModelMinErr: false
  21785. */
  21786. // Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  21787. 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)$/;
  21788. // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
  21789. // Note: We are being more lenient, because browsers are too.
  21790. // 1. Scheme
  21791. // 2. Slashes
  21792. // 3. Username
  21793. // 4. Password
  21794. // 5. Hostname
  21795. // 6. Port
  21796. // 7. Path
  21797. // 8. Query
  21798. // 9. Fragment
  21799. // 1111111111111111 222 333333 44444 55555555555555555555555 666 77777777 8888888 999
  21800. var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
  21801. // eslint-disable-next-line max-len
  21802. 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])?)*$/;
  21803. var NUMBER_REGEXP = /^\s*(-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
  21804. var DATE_REGEXP = /^(\d{4,})-(\d{2})-(\d{2})$/;
  21805. var DATETIMELOCAL_REGEXP = /^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  21806. var WEEK_REGEXP = /^(\d{4,})-W(\d\d)$/;
  21807. var MONTH_REGEXP = /^(\d{4,})-(\d\d)$/;
  21808. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  21809. var PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown';
  21810. var PARTIAL_VALIDATION_TYPES = createMap();
  21811. forEach('date,datetime-local,month,time,week'.split(','), function(type) {
  21812. PARTIAL_VALIDATION_TYPES[type] = true;
  21813. });
  21814. var inputType = {
  21815. /**
  21816. * @ngdoc input
  21817. * @name input[text]
  21818. *
  21819. * @description
  21820. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  21821. *
  21822. *
  21823. * @param {string} ngModel Assignable angular expression to data-bind to.
  21824. * @param {string=} name Property name of the form under which the control is published.
  21825. * @param {string=} required Adds `required` validation error key if the value is not entered.
  21826. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21827. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21828. * `required` when you want to data-bind to the `required` attribute.
  21829. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21830. * minlength.
  21831. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21832. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  21833. * any length.
  21834. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  21835. * that contains the regular expression body that will be converted to a regular expression
  21836. * as in the ngPattern directive.
  21837. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21838. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21839. * If the expression evaluates to a RegExp object, then this is used directly.
  21840. * If the expression evaluates to a string, then it will be converted to a RegExp
  21841. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21842. * `new RegExp('^abc$')`.<br />
  21843. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21844. * start at the index of the last search's match, thus not taking the whole input value into
  21845. * account.
  21846. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21847. * interaction with the input element.
  21848. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  21849. * This parameter is ignored for input[type=password] controls, which will never trim the
  21850. * input.
  21851. *
  21852. * @example
  21853. <example name="text-input-directive" module="textInputExample">
  21854. <file name="index.html">
  21855. <script>
  21856. angular.module('textInputExample', [])
  21857. .controller('ExampleController', ['$scope', function($scope) {
  21858. $scope.example = {
  21859. text: 'guest',
  21860. word: /^\s*\w*\s*$/
  21861. };
  21862. }]);
  21863. </script>
  21864. <form name="myForm" ng-controller="ExampleController">
  21865. <label>Single word:
  21866. <input type="text" name="input" ng-model="example.text"
  21867. ng-pattern="example.word" required ng-trim="false">
  21868. </label>
  21869. <div role="alert">
  21870. <span class="error" ng-show="myForm.input.$error.required">
  21871. Required!</span>
  21872. <span class="error" ng-show="myForm.input.$error.pattern">
  21873. Single word only!</span>
  21874. </div>
  21875. <code>text = {{example.text}}</code><br/>
  21876. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br/>
  21877. <code>myForm.input.$error = {{myForm.input.$error}}</code><br/>
  21878. <code>myForm.$valid = {{myForm.$valid}}</code><br/>
  21879. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br/>
  21880. </form>
  21881. </file>
  21882. <file name="protractor.js" type="protractor">
  21883. var text = element(by.binding('example.text'));
  21884. var valid = element(by.binding('myForm.input.$valid'));
  21885. var input = element(by.model('example.text'));
  21886. it('should initialize to model', function() {
  21887. expect(text.getText()).toContain('guest');
  21888. expect(valid.getText()).toContain('true');
  21889. });
  21890. it('should be invalid if empty', function() {
  21891. input.clear();
  21892. input.sendKeys('');
  21893. expect(text.getText()).toEqual('text =');
  21894. expect(valid.getText()).toContain('false');
  21895. });
  21896. it('should be invalid if multi word', function() {
  21897. input.clear();
  21898. input.sendKeys('hello world');
  21899. expect(valid.getText()).toContain('false');
  21900. });
  21901. </file>
  21902. </example>
  21903. */
  21904. 'text': textInputType,
  21905. /**
  21906. * @ngdoc input
  21907. * @name input[date]
  21908. *
  21909. * @description
  21910. * Input with date validation and transformation. In browsers that do not yet support
  21911. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  21912. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  21913. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  21914. * expected input format via a placeholder or label.
  21915. *
  21916. * The model must always be a Date object, otherwise Angular will throw an error.
  21917. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21918. *
  21919. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21920. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21921. *
  21922. * @param {string} ngModel Assignable angular expression to data-bind to.
  21923. * @param {string=} name Property name of the form under which the control is published.
  21924. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  21925. * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  21926. * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
  21927. * constraint validation.
  21928. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  21929. * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  21930. * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
  21931. * constraint validation.
  21932. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
  21933. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21934. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
  21935. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21936. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21937. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21938. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21939. * `required` when you want to data-bind to the `required` attribute.
  21940. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21941. * interaction with the input element.
  21942. *
  21943. * @example
  21944. <example name="date-input-directive" module="dateInputExample">
  21945. <file name="index.html">
  21946. <script>
  21947. angular.module('dateInputExample', [])
  21948. .controller('DateController', ['$scope', function($scope) {
  21949. $scope.example = {
  21950. value: new Date(2013, 9, 22)
  21951. };
  21952. }]);
  21953. </script>
  21954. <form name="myForm" ng-controller="DateController as dateCtrl">
  21955. <label for="exampleInput">Pick a date in 2013:</label>
  21956. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  21957. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  21958. <div role="alert">
  21959. <span class="error" ng-show="myForm.input.$error.required">
  21960. Required!</span>
  21961. <span class="error" ng-show="myForm.input.$error.date">
  21962. Not a valid date!</span>
  21963. </div>
  21964. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  21965. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21966. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21967. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21968. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21969. </form>
  21970. </file>
  21971. <file name="protractor.js" type="protractor">
  21972. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  21973. var valid = element(by.binding('myForm.input.$valid'));
  21974. // currently protractor/webdriver does not support
  21975. // sending keys to all known HTML5 input controls
  21976. // for various browsers (see https://github.com/angular/protractor/issues/562).
  21977. function setInput(val) {
  21978. // set the value of the element and force validation.
  21979. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21980. "ipt.value = '" + val + "';" +
  21981. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21982. browser.executeScript(scr);
  21983. }
  21984. it('should initialize to model', function() {
  21985. expect(value.getText()).toContain('2013-10-22');
  21986. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21987. });
  21988. it('should be invalid if empty', function() {
  21989. setInput('');
  21990. expect(value.getText()).toEqual('value =');
  21991. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21992. });
  21993. it('should be invalid if over max', function() {
  21994. setInput('2015-01-01');
  21995. expect(value.getText()).toContain('');
  21996. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21997. });
  21998. </file>
  21999. </example>
  22000. */
  22001. 'date': createDateInputType('date', DATE_REGEXP,
  22002. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  22003. 'yyyy-MM-dd'),
  22004. /**
  22005. * @ngdoc input
  22006. * @name input[datetime-local]
  22007. *
  22008. * @description
  22009. * Input with datetime validation and transformation. In browsers that do not yet support
  22010. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  22011. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  22012. *
  22013. * The model must always be a Date object, otherwise Angular will throw an error.
  22014. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  22015. *
  22016. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  22017. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  22018. *
  22019. * @param {string} ngModel Assignable angular expression to data-bind to.
  22020. * @param {string=} name Property name of the form under which the control is published.
  22021. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  22022. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  22023. * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  22024. * Note that `min` will also add native HTML5 constraint validation.
  22025. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  22026. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  22027. * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  22028. * Note that `max` will also add native HTML5 constraint validation.
  22029. * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
  22030. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  22031. * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
  22032. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  22033. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22034. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22035. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22036. * `required` when you want to data-bind to the `required` attribute.
  22037. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22038. * interaction with the input element.
  22039. *
  22040. * @example
  22041. <example name="datetimelocal-input-directive" module="dateExample">
  22042. <file name="index.html">
  22043. <script>
  22044. angular.module('dateExample', [])
  22045. .controller('DateController', ['$scope', function($scope) {
  22046. $scope.example = {
  22047. value: new Date(2010, 11, 28, 14, 57)
  22048. };
  22049. }]);
  22050. </script>
  22051. <form name="myForm" ng-controller="DateController as dateCtrl">
  22052. <label for="exampleInput">Pick a date between in 2013:</label>
  22053. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  22054. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  22055. <div role="alert">
  22056. <span class="error" ng-show="myForm.input.$error.required">
  22057. Required!</span>
  22058. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  22059. Not a valid date!</span>
  22060. </div>
  22061. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  22062. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22063. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22064. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22065. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22066. </form>
  22067. </file>
  22068. <file name="protractor.js" type="protractor">
  22069. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  22070. var valid = element(by.binding('myForm.input.$valid'));
  22071. // currently protractor/webdriver does not support
  22072. // sending keys to all known HTML5 input controls
  22073. // for various browsers (https://github.com/angular/protractor/issues/562).
  22074. function setInput(val) {
  22075. // set the value of the element and force validation.
  22076. var scr = "var ipt = document.getElementById('exampleInput'); " +
  22077. "ipt.value = '" + val + "';" +
  22078. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  22079. browser.executeScript(scr);
  22080. }
  22081. it('should initialize to model', function() {
  22082. expect(value.getText()).toContain('2010-12-28T14:57:00');
  22083. expect(valid.getText()).toContain('myForm.input.$valid = true');
  22084. });
  22085. it('should be invalid if empty', function() {
  22086. setInput('');
  22087. expect(value.getText()).toEqual('value =');
  22088. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22089. });
  22090. it('should be invalid if over max', function() {
  22091. setInput('2015-01-01T23:59:00');
  22092. expect(value.getText()).toContain('');
  22093. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22094. });
  22095. </file>
  22096. </example>
  22097. */
  22098. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  22099. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  22100. 'yyyy-MM-ddTHH:mm:ss.sss'),
  22101. /**
  22102. * @ngdoc input
  22103. * @name input[time]
  22104. *
  22105. * @description
  22106. * Input with time validation and transformation. In browsers that do not yet support
  22107. * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  22108. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  22109. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  22110. *
  22111. * The model must always be a Date object, otherwise Angular will throw an error.
  22112. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  22113. *
  22114. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  22115. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  22116. *
  22117. * @param {string} ngModel Assignable angular expression to data-bind to.
  22118. * @param {string=} name Property name of the form under which the control is published.
  22119. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  22120. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  22121. * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
  22122. * native HTML5 constraint validation.
  22123. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  22124. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  22125. * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
  22126. * native HTML5 constraint validation.
  22127. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
  22128. * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  22129. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
  22130. * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  22131. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22132. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22133. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22134. * `required` when you want to data-bind to the `required` attribute.
  22135. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22136. * interaction with the input element.
  22137. *
  22138. * @example
  22139. <example name="time-input-directive" module="timeExample">
  22140. <file name="index.html">
  22141. <script>
  22142. angular.module('timeExample', [])
  22143. .controller('DateController', ['$scope', function($scope) {
  22144. $scope.example = {
  22145. value: new Date(1970, 0, 1, 14, 57, 0)
  22146. };
  22147. }]);
  22148. </script>
  22149. <form name="myForm" ng-controller="DateController as dateCtrl">
  22150. <label for="exampleInput">Pick a time between 8am and 5pm:</label>
  22151. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  22152. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  22153. <div role="alert">
  22154. <span class="error" ng-show="myForm.input.$error.required">
  22155. Required!</span>
  22156. <span class="error" ng-show="myForm.input.$error.time">
  22157. Not a valid date!</span>
  22158. </div>
  22159. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  22160. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22161. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22162. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22163. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22164. </form>
  22165. </file>
  22166. <file name="protractor.js" type="protractor">
  22167. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  22168. var valid = element(by.binding('myForm.input.$valid'));
  22169. // currently protractor/webdriver does not support
  22170. // sending keys to all known HTML5 input controls
  22171. // for various browsers (https://github.com/angular/protractor/issues/562).
  22172. function setInput(val) {
  22173. // set the value of the element and force validation.
  22174. var scr = "var ipt = document.getElementById('exampleInput'); " +
  22175. "ipt.value = '" + val + "';" +
  22176. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  22177. browser.executeScript(scr);
  22178. }
  22179. it('should initialize to model', function() {
  22180. expect(value.getText()).toContain('14:57:00');
  22181. expect(valid.getText()).toContain('myForm.input.$valid = true');
  22182. });
  22183. it('should be invalid if empty', function() {
  22184. setInput('');
  22185. expect(value.getText()).toEqual('value =');
  22186. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22187. });
  22188. it('should be invalid if over max', function() {
  22189. setInput('23:59:00');
  22190. expect(value.getText()).toContain('');
  22191. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22192. });
  22193. </file>
  22194. </example>
  22195. */
  22196. 'time': createDateInputType('time', TIME_REGEXP,
  22197. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  22198. 'HH:mm:ss.sss'),
  22199. /**
  22200. * @ngdoc input
  22201. * @name input[week]
  22202. *
  22203. * @description
  22204. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  22205. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  22206. * week format (yyyy-W##), for example: `2013-W02`.
  22207. *
  22208. * The model must always be a Date object, otherwise Angular will throw an error.
  22209. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  22210. *
  22211. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  22212. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  22213. *
  22214. * @param {string} ngModel Assignable angular expression to data-bind to.
  22215. * @param {string=} name Property name of the form under which the control is published.
  22216. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  22217. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  22218. * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
  22219. * native HTML5 constraint validation.
  22220. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  22221. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  22222. * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
  22223. * native HTML5 constraint validation.
  22224. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  22225. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  22226. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  22227. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  22228. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22229. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22230. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22231. * `required` when you want to data-bind to the `required` attribute.
  22232. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22233. * interaction with the input element.
  22234. *
  22235. * @example
  22236. <example name="week-input-directive" module="weekExample">
  22237. <file name="index.html">
  22238. <script>
  22239. angular.module('weekExample', [])
  22240. .controller('DateController', ['$scope', function($scope) {
  22241. $scope.example = {
  22242. value: new Date(2013, 0, 3)
  22243. };
  22244. }]);
  22245. </script>
  22246. <form name="myForm" ng-controller="DateController as dateCtrl">
  22247. <label>Pick a date between in 2013:
  22248. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  22249. placeholder="YYYY-W##" min="2012-W32"
  22250. max="2013-W52" required />
  22251. </label>
  22252. <div role="alert">
  22253. <span class="error" ng-show="myForm.input.$error.required">
  22254. Required!</span>
  22255. <span class="error" ng-show="myForm.input.$error.week">
  22256. Not a valid date!</span>
  22257. </div>
  22258. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  22259. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22260. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22261. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22262. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22263. </form>
  22264. </file>
  22265. <file name="protractor.js" type="protractor">
  22266. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  22267. var valid = element(by.binding('myForm.input.$valid'));
  22268. // currently protractor/webdriver does not support
  22269. // sending keys to all known HTML5 input controls
  22270. // for various browsers (https://github.com/angular/protractor/issues/562).
  22271. function setInput(val) {
  22272. // set the value of the element and force validation.
  22273. var scr = "var ipt = document.getElementById('exampleInput'); " +
  22274. "ipt.value = '" + val + "';" +
  22275. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  22276. browser.executeScript(scr);
  22277. }
  22278. it('should initialize to model', function() {
  22279. expect(value.getText()).toContain('2013-W01');
  22280. expect(valid.getText()).toContain('myForm.input.$valid = true');
  22281. });
  22282. it('should be invalid if empty', function() {
  22283. setInput('');
  22284. expect(value.getText()).toEqual('value =');
  22285. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22286. });
  22287. it('should be invalid if over max', function() {
  22288. setInput('2015-W01');
  22289. expect(value.getText()).toContain('');
  22290. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22291. });
  22292. </file>
  22293. </example>
  22294. */
  22295. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  22296. /**
  22297. * @ngdoc input
  22298. * @name input[month]
  22299. *
  22300. * @description
  22301. * Input with month validation and transformation. In browsers that do not yet support
  22302. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  22303. * month format (yyyy-MM), for example: `2009-01`.
  22304. *
  22305. * The model must always be a Date object, otherwise Angular will throw an error.
  22306. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  22307. * If the model is not set to the first of the month, the next view to model update will set it
  22308. * to the first of the month.
  22309. *
  22310. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  22311. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  22312. *
  22313. * @param {string} ngModel Assignable angular expression to data-bind to.
  22314. * @param {string=} name Property name of the form under which the control is published.
  22315. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  22316. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  22317. * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
  22318. * native HTML5 constraint validation.
  22319. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  22320. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  22321. * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
  22322. * native HTML5 constraint validation.
  22323. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  22324. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  22325. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  22326. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  22327. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22328. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22329. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22330. * `required` when you want to data-bind to the `required` attribute.
  22331. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22332. * interaction with the input element.
  22333. *
  22334. * @example
  22335. <example name="month-input-directive" module="monthExample">
  22336. <file name="index.html">
  22337. <script>
  22338. angular.module('monthExample', [])
  22339. .controller('DateController', ['$scope', function($scope) {
  22340. $scope.example = {
  22341. value: new Date(2013, 9, 1)
  22342. };
  22343. }]);
  22344. </script>
  22345. <form name="myForm" ng-controller="DateController as dateCtrl">
  22346. <label for="exampleInput">Pick a month in 2013:</label>
  22347. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  22348. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  22349. <div role="alert">
  22350. <span class="error" ng-show="myForm.input.$error.required">
  22351. Required!</span>
  22352. <span class="error" ng-show="myForm.input.$error.month">
  22353. Not a valid month!</span>
  22354. </div>
  22355. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  22356. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22357. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22358. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22359. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22360. </form>
  22361. </file>
  22362. <file name="protractor.js" type="protractor">
  22363. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  22364. var valid = element(by.binding('myForm.input.$valid'));
  22365. // currently protractor/webdriver does not support
  22366. // sending keys to all known HTML5 input controls
  22367. // for various browsers (https://github.com/angular/protractor/issues/562).
  22368. function setInput(val) {
  22369. // set the value of the element and force validation.
  22370. var scr = "var ipt = document.getElementById('exampleInput'); " +
  22371. "ipt.value = '" + val + "';" +
  22372. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  22373. browser.executeScript(scr);
  22374. }
  22375. it('should initialize to model', function() {
  22376. expect(value.getText()).toContain('2013-10');
  22377. expect(valid.getText()).toContain('myForm.input.$valid = true');
  22378. });
  22379. it('should be invalid if empty', function() {
  22380. setInput('');
  22381. expect(value.getText()).toEqual('value =');
  22382. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22383. });
  22384. it('should be invalid if over max', function() {
  22385. setInput('2015-01');
  22386. expect(value.getText()).toContain('');
  22387. expect(valid.getText()).toContain('myForm.input.$valid = false');
  22388. });
  22389. </file>
  22390. </example>
  22391. */
  22392. 'month': createDateInputType('month', MONTH_REGEXP,
  22393. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  22394. 'yyyy-MM'),
  22395. /**
  22396. * @ngdoc input
  22397. * @name input[number]
  22398. *
  22399. * @description
  22400. * Text input with number validation and transformation. Sets the `number` validation
  22401. * error if not a valid number.
  22402. *
  22403. * <div class="alert alert-warning">
  22404. * The model must always be of type `number` otherwise Angular will throw an error.
  22405. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  22406. * error docs for more information and an example of how to convert your model if necessary.
  22407. * </div>
  22408. *
  22409. * ## Issues with HTML5 constraint validation
  22410. *
  22411. * In browsers that follow the
  22412. * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
  22413. * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
  22414. * If a non-number is entered in the input, the browser will report the value as an empty string,
  22415. * which means the view / model values in `ngModel` and subsequently the scope value
  22416. * will also be an empty string.
  22417. *
  22418. *
  22419. * @param {string} ngModel Assignable angular expression to data-bind to.
  22420. * @param {string=} name Property name of the form under which the control is published.
  22421. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  22422. * Can be interpolated.
  22423. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  22424. * Can be interpolated.
  22425. * @param {string=} ngMin Like `min`, sets the `min` validation error key if the value entered is less than `ngMin`,
  22426. * but does not trigger HTML5 native validation. Takes an expression.
  22427. * @param {string=} ngMax Like `max`, sets the `max` validation error key if the value entered is greater than `ngMax`,
  22428. * but does not trigger HTML5 native validation. Takes an expression.
  22429. * @param {string=} step Sets the `step` validation error key if the value entered does not fit the `step` constraint.
  22430. * Can be interpolated.
  22431. * @param {string=} ngStep Like `step`, sets the `step` validation error key if the value entered does not fit the `ngStep` constraint,
  22432. * but does not trigger HTML5 native validation. Takes an expression.
  22433. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22434. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22435. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22436. * `required` when you want to data-bind to the `required` attribute.
  22437. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22438. * minlength.
  22439. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22440. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  22441. * any length.
  22442. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  22443. * that contains the regular expression body that will be converted to a regular expression
  22444. * as in the ngPattern directive.
  22445. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22446. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  22447. * If the expression evaluates to a RegExp object, then this is used directly.
  22448. * If the expression evaluates to a string, then it will be converted to a RegExp
  22449. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22450. * `new RegExp('^abc$')`.<br />
  22451. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22452. * start at the index of the last search's match, thus not taking the whole input value into
  22453. * account.
  22454. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22455. * interaction with the input element.
  22456. *
  22457. * @example
  22458. <example name="number-input-directive" module="numberExample">
  22459. <file name="index.html">
  22460. <script>
  22461. angular.module('numberExample', [])
  22462. .controller('ExampleController', ['$scope', function($scope) {
  22463. $scope.example = {
  22464. value: 12
  22465. };
  22466. }]);
  22467. </script>
  22468. <form name="myForm" ng-controller="ExampleController">
  22469. <label>Number:
  22470. <input type="number" name="input" ng-model="example.value"
  22471. min="0" max="99" required>
  22472. </label>
  22473. <div role="alert">
  22474. <span class="error" ng-show="myForm.input.$error.required">
  22475. Required!</span>
  22476. <span class="error" ng-show="myForm.input.$error.number">
  22477. Not valid number!</span>
  22478. </div>
  22479. <tt>value = {{example.value}}</tt><br/>
  22480. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22481. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22482. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22483. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22484. </form>
  22485. </file>
  22486. <file name="protractor.js" type="protractor">
  22487. var value = element(by.binding('example.value'));
  22488. var valid = element(by.binding('myForm.input.$valid'));
  22489. var input = element(by.model('example.value'));
  22490. it('should initialize to model', function() {
  22491. expect(value.getText()).toContain('12');
  22492. expect(valid.getText()).toContain('true');
  22493. });
  22494. it('should be invalid if empty', function() {
  22495. input.clear();
  22496. input.sendKeys('');
  22497. expect(value.getText()).toEqual('value =');
  22498. expect(valid.getText()).toContain('false');
  22499. });
  22500. it('should be invalid if over max', function() {
  22501. input.clear();
  22502. input.sendKeys('123');
  22503. expect(value.getText()).toEqual('value =');
  22504. expect(valid.getText()).toContain('false');
  22505. });
  22506. </file>
  22507. </example>
  22508. */
  22509. 'number': numberInputType,
  22510. /**
  22511. * @ngdoc input
  22512. * @name input[url]
  22513. *
  22514. * @description
  22515. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  22516. * valid URL.
  22517. *
  22518. * <div class="alert alert-warning">
  22519. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  22520. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  22521. * the built-in validators (see the {@link guide/forms Forms guide})
  22522. * </div>
  22523. *
  22524. * @param {string} ngModel Assignable angular expression to data-bind to.
  22525. * @param {string=} name Property name of the form under which the control is published.
  22526. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22527. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22528. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22529. * `required` when you want to data-bind to the `required` attribute.
  22530. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22531. * minlength.
  22532. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22533. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  22534. * any length.
  22535. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  22536. * that contains the regular expression body that will be converted to a regular expression
  22537. * as in the ngPattern directive.
  22538. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22539. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  22540. * If the expression evaluates to a RegExp object, then this is used directly.
  22541. * If the expression evaluates to a string, then it will be converted to a RegExp
  22542. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22543. * `new RegExp('^abc$')`.<br />
  22544. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22545. * start at the index of the last search's match, thus not taking the whole input value into
  22546. * account.
  22547. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22548. * interaction with the input element.
  22549. *
  22550. * @example
  22551. <example name="url-input-directive" module="urlExample">
  22552. <file name="index.html">
  22553. <script>
  22554. angular.module('urlExample', [])
  22555. .controller('ExampleController', ['$scope', function($scope) {
  22556. $scope.url = {
  22557. text: 'http://google.com'
  22558. };
  22559. }]);
  22560. </script>
  22561. <form name="myForm" ng-controller="ExampleController">
  22562. <label>URL:
  22563. <input type="url" name="input" ng-model="url.text" required>
  22564. <label>
  22565. <div role="alert">
  22566. <span class="error" ng-show="myForm.input.$error.required">
  22567. Required!</span>
  22568. <span class="error" ng-show="myForm.input.$error.url">
  22569. Not valid url!</span>
  22570. </div>
  22571. <tt>text = {{url.text}}</tt><br/>
  22572. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22573. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22574. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22575. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22576. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  22577. </form>
  22578. </file>
  22579. <file name="protractor.js" type="protractor">
  22580. var text = element(by.binding('url.text'));
  22581. var valid = element(by.binding('myForm.input.$valid'));
  22582. var input = element(by.model('url.text'));
  22583. it('should initialize to model', function() {
  22584. expect(text.getText()).toContain('http://google.com');
  22585. expect(valid.getText()).toContain('true');
  22586. });
  22587. it('should be invalid if empty', function() {
  22588. input.clear();
  22589. input.sendKeys('');
  22590. expect(text.getText()).toEqual('text =');
  22591. expect(valid.getText()).toContain('false');
  22592. });
  22593. it('should be invalid if not url', function() {
  22594. input.clear();
  22595. input.sendKeys('box');
  22596. expect(valid.getText()).toContain('false');
  22597. });
  22598. </file>
  22599. </example>
  22600. */
  22601. 'url': urlInputType,
  22602. /**
  22603. * @ngdoc input
  22604. * @name input[email]
  22605. *
  22606. * @description
  22607. * Text input with email validation. Sets the `email` validation error key if not a valid email
  22608. * address.
  22609. *
  22610. * <div class="alert alert-warning">
  22611. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  22612. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  22613. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  22614. * </div>
  22615. *
  22616. * @param {string} ngModel Assignable angular expression to data-bind to.
  22617. * @param {string=} name Property name of the form under which the control is published.
  22618. * @param {string=} required Sets `required` validation error key if the value is not entered.
  22619. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22620. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22621. * `required` when you want to data-bind to the `required` attribute.
  22622. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  22623. * minlength.
  22624. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  22625. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  22626. * any length.
  22627. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  22628. * that contains the regular expression body that will be converted to a regular expression
  22629. * as in the ngPattern directive.
  22630. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  22631. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  22632. * If the expression evaluates to a RegExp object, then this is used directly.
  22633. * If the expression evaluates to a string, then it will be converted to a RegExp
  22634. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  22635. * `new RegExp('^abc$')`.<br />
  22636. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  22637. * start at the index of the last search's match, thus not taking the whole input value into
  22638. * account.
  22639. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22640. * interaction with the input element.
  22641. *
  22642. * @example
  22643. <example name="email-input-directive" module="emailExample">
  22644. <file name="index.html">
  22645. <script>
  22646. angular.module('emailExample', [])
  22647. .controller('ExampleController', ['$scope', function($scope) {
  22648. $scope.email = {
  22649. text: 'me@example.com'
  22650. };
  22651. }]);
  22652. </script>
  22653. <form name="myForm" ng-controller="ExampleController">
  22654. <label>Email:
  22655. <input type="email" name="input" ng-model="email.text" required>
  22656. </label>
  22657. <div role="alert">
  22658. <span class="error" ng-show="myForm.input.$error.required">
  22659. Required!</span>
  22660. <span class="error" ng-show="myForm.input.$error.email">
  22661. Not valid email!</span>
  22662. </div>
  22663. <tt>text = {{email.text}}</tt><br/>
  22664. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  22665. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  22666. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22667. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22668. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  22669. </form>
  22670. </file>
  22671. <file name="protractor.js" type="protractor">
  22672. var text = element(by.binding('email.text'));
  22673. var valid = element(by.binding('myForm.input.$valid'));
  22674. var input = element(by.model('email.text'));
  22675. it('should initialize to model', function() {
  22676. expect(text.getText()).toContain('me@example.com');
  22677. expect(valid.getText()).toContain('true');
  22678. });
  22679. it('should be invalid if empty', function() {
  22680. input.clear();
  22681. input.sendKeys('');
  22682. expect(text.getText()).toEqual('text =');
  22683. expect(valid.getText()).toContain('false');
  22684. });
  22685. it('should be invalid if not email', function() {
  22686. input.clear();
  22687. input.sendKeys('xxx');
  22688. expect(valid.getText()).toContain('false');
  22689. });
  22690. </file>
  22691. </example>
  22692. */
  22693. 'email': emailInputType,
  22694. /**
  22695. * @ngdoc input
  22696. * @name input[radio]
  22697. *
  22698. * @description
  22699. * HTML radio button.
  22700. *
  22701. * @param {string} ngModel Assignable angular expression to data-bind to.
  22702. * @param {string} value The value to which the `ngModel` expression should be set when selected.
  22703. * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
  22704. * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
  22705. * @param {string=} name Property name of the form under which the control is published.
  22706. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22707. * interaction with the input element.
  22708. * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
  22709. * is selected. Should be used instead of the `value` attribute if you need
  22710. * a non-string `ngModel` (`boolean`, `array`, ...).
  22711. *
  22712. * @example
  22713. <example name="radio-input-directive" module="radioExample">
  22714. <file name="index.html">
  22715. <script>
  22716. angular.module('radioExample', [])
  22717. .controller('ExampleController', ['$scope', function($scope) {
  22718. $scope.color = {
  22719. name: 'blue'
  22720. };
  22721. $scope.specialValue = {
  22722. "id": "12345",
  22723. "value": "green"
  22724. };
  22725. }]);
  22726. </script>
  22727. <form name="myForm" ng-controller="ExampleController">
  22728. <label>
  22729. <input type="radio" ng-model="color.name" value="red">
  22730. Red
  22731. </label><br/>
  22732. <label>
  22733. <input type="radio" ng-model="color.name" ng-value="specialValue">
  22734. Green
  22735. </label><br/>
  22736. <label>
  22737. <input type="radio" ng-model="color.name" value="blue">
  22738. Blue
  22739. </label><br/>
  22740. <tt>color = {{color.name | json}}</tt><br/>
  22741. </form>
  22742. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  22743. </file>
  22744. <file name="protractor.js" type="protractor">
  22745. it('should change state', function() {
  22746. var inputs = element.all(by.model('color.name'));
  22747. var color = element(by.binding('color.name'));
  22748. expect(color.getText()).toContain('blue');
  22749. inputs.get(0).click();
  22750. expect(color.getText()).toContain('red');
  22751. inputs.get(1).click();
  22752. expect(color.getText()).toContain('green');
  22753. });
  22754. </file>
  22755. </example>
  22756. */
  22757. 'radio': radioInputType,
  22758. /**
  22759. * @ngdoc input
  22760. * @name input[range]
  22761. *
  22762. * @description
  22763. * Native range input with validation and transformation.
  22764. *
  22765. * The model for the range input must always be a `Number`.
  22766. *
  22767. * IE9 and other browsers that do not support the `range` type fall back
  22768. * to a text input without any default values for `min`, `max` and `step`. Model binding,
  22769. * validation and number parsing are nevertheless supported.
  22770. *
  22771. * Browsers that support range (latest Chrome, Safari, Firefox, Edge) treat `input[range]`
  22772. * in a way that never allows the input to hold an invalid value. That means:
  22773. * - any non-numerical value is set to `(max + min) / 2`.
  22774. * - any numerical value that is less than the current min val, or greater than the current max val
  22775. * is set to the min / max val respectively.
  22776. * - additionally, the current `step` is respected, so the nearest value that satisfies a step
  22777. * is used.
  22778. *
  22779. * See the [HTML Spec on input[type=range]](https://www.w3.org/TR/html5/forms.html#range-state-(type=range))
  22780. * for more info.
  22781. *
  22782. * This has the following consequences for Angular:
  22783. *
  22784. * Since the element value should always reflect the current model value, a range input
  22785. * will set the bound ngModel expression to the value that the browser has set for the
  22786. * input element. For example, in the following input `<input type="range" ng-model="model.value">`,
  22787. * if the application sets `model.value = null`, the browser will set the input to `'50'`.
  22788. * Angular will then set the model to `50`, to prevent input and model value being out of sync.
  22789. *
  22790. * That means the model for range will immediately be set to `50` after `ngModel` has been
  22791. * initialized. It also means a range input can never have the required error.
  22792. *
  22793. * This does not only affect changes to the model value, but also to the values of the `min`,
  22794. * `max`, and `step` attributes. When these change in a way that will cause the browser to modify
  22795. * the input value, Angular will also update the model value.
  22796. *
  22797. * Automatic value adjustment also means that a range input element can never have the `required`,
  22798. * `min`, or `max` errors.
  22799. *
  22800. * However, `step` is currently only fully implemented by Firefox. Other browsers have problems
  22801. * when the step value changes dynamically - they do not adjust the element value correctly, but
  22802. * instead may set the `stepMismatch` error. If that's the case, the Angular will set the `step`
  22803. * error on the input, and set the model to `undefined`.
  22804. *
  22805. * Note that `input[range]` is not compatible with`ngMax`, `ngMin`, and `ngStep`, because they do
  22806. * not set the `min` and `max` attributes, which means that the browser won't automatically adjust
  22807. * the input value based on their values, and will always assume min = 0, max = 100, and step = 1.
  22808. *
  22809. * @param {string} ngModel Assignable angular expression to data-bind to.
  22810. * @param {string=} name Property name of the form under which the control is published.
  22811. * @param {string=} min Sets the `min` validation to ensure that the value entered is greater
  22812. * than `min`. Can be interpolated.
  22813. * @param {string=} max Sets the `max` validation to ensure that the value entered is less than `max`.
  22814. * Can be interpolated.
  22815. * @param {string=} step Sets the `step` validation to ensure that the value entered matches the `step`
  22816. * Can be interpolated.
  22817. * @param {expression=} ngChange AngularJS expression to be executed when the ngModel value changes due
  22818. * to user interaction with the input element.
  22819. * @param {expression=} ngChecked If the expression is truthy, then the `checked` attribute will be set on the
  22820. * element. **Note** : `ngChecked` should not be used alongside `ngModel`.
  22821. * Checkout {@link ng.directive:ngChecked ngChecked} for usage.
  22822. *
  22823. * @example
  22824. <example name="range-input-directive" module="rangeExample">
  22825. <file name="index.html">
  22826. <script>
  22827. angular.module('rangeExample', [])
  22828. .controller('ExampleController', ['$scope', function($scope) {
  22829. $scope.value = 75;
  22830. $scope.min = 10;
  22831. $scope.max = 90;
  22832. }]);
  22833. </script>
  22834. <form name="myForm" ng-controller="ExampleController">
  22835. Model as range: <input type="range" name="range" ng-model="value" min="{{min}}" max="{{max}}">
  22836. <hr>
  22837. Model as number: <input type="number" ng-model="value"><br>
  22838. Min: <input type="number" ng-model="min"><br>
  22839. Max: <input type="number" ng-model="max"><br>
  22840. value = <code>{{value}}</code><br/>
  22841. myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
  22842. myForm.range.$error = <code>{{myForm.range.$error}}</code>
  22843. </form>
  22844. </file>
  22845. </example>
  22846. * ## Range Input with ngMin & ngMax attributes
  22847. * @example
  22848. <example name="range-input-directive-ng" module="rangeExample">
  22849. <file name="index.html">
  22850. <script>
  22851. angular.module('rangeExample', [])
  22852. .controller('ExampleController', ['$scope', function($scope) {
  22853. $scope.value = 75;
  22854. $scope.min = 10;
  22855. $scope.max = 90;
  22856. }]);
  22857. </script>
  22858. <form name="myForm" ng-controller="ExampleController">
  22859. Model as range: <input type="range" name="range" ng-model="value" ng-min="min" ng-max="max">
  22860. <hr>
  22861. Model as number: <input type="number" ng-model="value"><br>
  22862. Min: <input type="number" ng-model="min"><br>
  22863. Max: <input type="number" ng-model="max"><br>
  22864. value = <code>{{value}}</code><br/>
  22865. myForm.range.$valid = <code>{{myForm.range.$valid}}</code><br/>
  22866. myForm.range.$error = <code>{{myForm.range.$error}}</code>
  22867. </form>
  22868. </file>
  22869. </example>
  22870. */
  22871. 'range': rangeInputType,
  22872. /**
  22873. * @ngdoc input
  22874. * @name input[checkbox]
  22875. *
  22876. * @description
  22877. * HTML checkbox.
  22878. *
  22879. * @param {string} ngModel Assignable angular expression to data-bind to.
  22880. * @param {string=} name Property name of the form under which the control is published.
  22881. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  22882. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  22883. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  22884. * interaction with the input element.
  22885. *
  22886. * @example
  22887. <example name="checkbox-input-directive" module="checkboxExample">
  22888. <file name="index.html">
  22889. <script>
  22890. angular.module('checkboxExample', [])
  22891. .controller('ExampleController', ['$scope', function($scope) {
  22892. $scope.checkboxModel = {
  22893. value1 : true,
  22894. value2 : 'YES'
  22895. };
  22896. }]);
  22897. </script>
  22898. <form name="myForm" ng-controller="ExampleController">
  22899. <label>Value1:
  22900. <input type="checkbox" ng-model="checkboxModel.value1">
  22901. </label><br/>
  22902. <label>Value2:
  22903. <input type="checkbox" ng-model="checkboxModel.value2"
  22904. ng-true-value="'YES'" ng-false-value="'NO'">
  22905. </label><br/>
  22906. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  22907. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  22908. </form>
  22909. </file>
  22910. <file name="protractor.js" type="protractor">
  22911. it('should change state', function() {
  22912. var value1 = element(by.binding('checkboxModel.value1'));
  22913. var value2 = element(by.binding('checkboxModel.value2'));
  22914. expect(value1.getText()).toContain('true');
  22915. expect(value2.getText()).toContain('YES');
  22916. element(by.model('checkboxModel.value1')).click();
  22917. element(by.model('checkboxModel.value2')).click();
  22918. expect(value1.getText()).toContain('false');
  22919. expect(value2.getText()).toContain('NO');
  22920. });
  22921. </file>
  22922. </example>
  22923. */
  22924. 'checkbox': checkboxInputType,
  22925. 'hidden': noop,
  22926. 'button': noop,
  22927. 'submit': noop,
  22928. 'reset': noop,
  22929. 'file': noop
  22930. };
  22931. function stringBasedInputType(ctrl) {
  22932. ctrl.$formatters.push(function(value) {
  22933. return ctrl.$isEmpty(value) ? value : value.toString();
  22934. });
  22935. }
  22936. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22937. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  22938. stringBasedInputType(ctrl);
  22939. }
  22940. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  22941. var type = lowercase(element[0].type);
  22942. // In composition mode, users are still inputting intermediate text buffer,
  22943. // hold the listener until composition is done.
  22944. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  22945. if (!$sniffer.android) {
  22946. var composing = false;
  22947. element.on('compositionstart', function() {
  22948. composing = true;
  22949. });
  22950. element.on('compositionend', function() {
  22951. composing = false;
  22952. listener();
  22953. });
  22954. }
  22955. var timeout;
  22956. var listener = function(ev) {
  22957. if (timeout) {
  22958. $browser.defer.cancel(timeout);
  22959. timeout = null;
  22960. }
  22961. if (composing) return;
  22962. var value = element.val(),
  22963. event = ev && ev.type;
  22964. // By default we will trim the value
  22965. // If the attribute ng-trim exists we will avoid trimming
  22966. // If input type is 'password', the value is never trimmed
  22967. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  22968. value = trim(value);
  22969. }
  22970. // If a control is suffering from bad input (due to native validators), browsers discard its
  22971. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  22972. // control's value is the same empty value twice in a row.
  22973. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  22974. ctrl.$setViewValue(value, event);
  22975. }
  22976. };
  22977. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  22978. // input event on backspace, delete or cut
  22979. if ($sniffer.hasEvent('input')) {
  22980. element.on('input', listener);
  22981. } else {
  22982. var deferListener = function(ev, input, origValue) {
  22983. if (!timeout) {
  22984. timeout = $browser.defer(function() {
  22985. timeout = null;
  22986. if (!input || input.value !== origValue) {
  22987. listener(ev);
  22988. }
  22989. });
  22990. }
  22991. };
  22992. element.on('keydown', /** @this */ function(event) {
  22993. var key = event.keyCode;
  22994. // ignore
  22995. // command modifiers arrows
  22996. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  22997. deferListener(event, this, this.value);
  22998. });
  22999. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  23000. if ($sniffer.hasEvent('paste')) {
  23001. element.on('paste cut', deferListener);
  23002. }
  23003. }
  23004. // if user paste into input using mouse on older browser
  23005. // or form autocomplete on newer browser, we need "change" event to catch it
  23006. element.on('change', listener);
  23007. // Some native input types (date-family) have the ability to change validity without
  23008. // firing any input/change events.
  23009. // For these event types, when native validators are present and the browser supports the type,
  23010. // check for validity changes on various DOM events.
  23011. if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) {
  23012. element.on(PARTIAL_VALIDATION_EVENTS, /** @this */ function(ev) {
  23013. if (!timeout) {
  23014. var validity = this[VALIDITY_STATE_PROPERTY];
  23015. var origBadInput = validity.badInput;
  23016. var origTypeMismatch = validity.typeMismatch;
  23017. timeout = $browser.defer(function() {
  23018. timeout = null;
  23019. if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) {
  23020. listener(ev);
  23021. }
  23022. });
  23023. }
  23024. });
  23025. }
  23026. ctrl.$render = function() {
  23027. // Workaround for Firefox validation #12102.
  23028. var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
  23029. if (element.val() !== value) {
  23030. element.val(value);
  23031. }
  23032. };
  23033. }
  23034. function weekParser(isoWeek, existingDate) {
  23035. if (isDate(isoWeek)) {
  23036. return isoWeek;
  23037. }
  23038. if (isString(isoWeek)) {
  23039. WEEK_REGEXP.lastIndex = 0;
  23040. var parts = WEEK_REGEXP.exec(isoWeek);
  23041. if (parts) {
  23042. var year = +parts[1],
  23043. week = +parts[2],
  23044. hours = 0,
  23045. minutes = 0,
  23046. seconds = 0,
  23047. milliseconds = 0,
  23048. firstThurs = getFirstThursdayOfYear(year),
  23049. addDays = (week - 1) * 7;
  23050. if (existingDate) {
  23051. hours = existingDate.getHours();
  23052. minutes = existingDate.getMinutes();
  23053. seconds = existingDate.getSeconds();
  23054. milliseconds = existingDate.getMilliseconds();
  23055. }
  23056. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  23057. }
  23058. }
  23059. return NaN;
  23060. }
  23061. function createDateParser(regexp, mapping) {
  23062. return function(iso, date) {
  23063. var parts, map;
  23064. if (isDate(iso)) {
  23065. return iso;
  23066. }
  23067. if (isString(iso)) {
  23068. // When a date is JSON'ified to wraps itself inside of an extra
  23069. // set of double quotes. This makes the date parsing code unable
  23070. // to match the date string and parse it as a date.
  23071. if (iso.charAt(0) === '"' && iso.charAt(iso.length - 1) === '"') {
  23072. iso = iso.substring(1, iso.length - 1);
  23073. }
  23074. if (ISO_DATE_REGEXP.test(iso)) {
  23075. return new Date(iso);
  23076. }
  23077. regexp.lastIndex = 0;
  23078. parts = regexp.exec(iso);
  23079. if (parts) {
  23080. parts.shift();
  23081. if (date) {
  23082. map = {
  23083. yyyy: date.getFullYear(),
  23084. MM: date.getMonth() + 1,
  23085. dd: date.getDate(),
  23086. HH: date.getHours(),
  23087. mm: date.getMinutes(),
  23088. ss: date.getSeconds(),
  23089. sss: date.getMilliseconds() / 1000
  23090. };
  23091. } else {
  23092. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  23093. }
  23094. forEach(parts, function(part, index) {
  23095. if (index < mapping.length) {
  23096. map[mapping[index]] = +part;
  23097. }
  23098. });
  23099. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  23100. }
  23101. }
  23102. return NaN;
  23103. };
  23104. }
  23105. function createDateInputType(type, regexp, parseDate, format) {
  23106. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  23107. badInputChecker(scope, element, attr, ctrl);
  23108. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  23109. var timezone = ctrl && ctrl.$options.getOption('timezone');
  23110. var previousDate;
  23111. ctrl.$$parserName = type;
  23112. ctrl.$parsers.push(function(value) {
  23113. if (ctrl.$isEmpty(value)) return null;
  23114. if (regexp.test(value)) {
  23115. // Note: We cannot read ctrl.$modelValue, as there might be a different
  23116. // parser/formatter in the processing chain so that the model
  23117. // contains some different data format!
  23118. var parsedDate = parseDate(value, previousDate);
  23119. if (timezone) {
  23120. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  23121. }
  23122. return parsedDate;
  23123. }
  23124. return undefined;
  23125. });
  23126. ctrl.$formatters.push(function(value) {
  23127. if (value && !isDate(value)) {
  23128. throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  23129. }
  23130. if (isValidDate(value)) {
  23131. previousDate = value;
  23132. if (previousDate && timezone) {
  23133. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  23134. }
  23135. return $filter('date')(value, format, timezone);
  23136. } else {
  23137. previousDate = null;
  23138. return '';
  23139. }
  23140. });
  23141. if (isDefined(attr.min) || attr.ngMin) {
  23142. var minVal;
  23143. ctrl.$validators.min = function(value) {
  23144. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  23145. };
  23146. attr.$observe('min', function(val) {
  23147. minVal = parseObservedDateValue(val);
  23148. ctrl.$validate();
  23149. });
  23150. }
  23151. if (isDefined(attr.max) || attr.ngMax) {
  23152. var maxVal;
  23153. ctrl.$validators.max = function(value) {
  23154. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  23155. };
  23156. attr.$observe('max', function(val) {
  23157. maxVal = parseObservedDateValue(val);
  23158. ctrl.$validate();
  23159. });
  23160. }
  23161. function isValidDate(value) {
  23162. // Invalid Date: getTime() returns NaN
  23163. return value && !(value.getTime && value.getTime() !== value.getTime());
  23164. }
  23165. function parseObservedDateValue(val) {
  23166. return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
  23167. }
  23168. };
  23169. }
  23170. function badInputChecker(scope, element, attr, ctrl) {
  23171. var node = element[0];
  23172. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  23173. if (nativeValidation) {
  23174. ctrl.$parsers.push(function(value) {
  23175. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  23176. return validity.badInput || validity.typeMismatch ? undefined : value;
  23177. });
  23178. }
  23179. }
  23180. function numberFormatterParser(ctrl) {
  23181. ctrl.$$parserName = 'number';
  23182. ctrl.$parsers.push(function(value) {
  23183. if (ctrl.$isEmpty(value)) return null;
  23184. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  23185. return undefined;
  23186. });
  23187. ctrl.$formatters.push(function(value) {
  23188. if (!ctrl.$isEmpty(value)) {
  23189. if (!isNumber(value)) {
  23190. throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  23191. }
  23192. value = value.toString();
  23193. }
  23194. return value;
  23195. });
  23196. }
  23197. function parseNumberAttrVal(val) {
  23198. if (isDefined(val) && !isNumber(val)) {
  23199. val = parseFloat(val);
  23200. }
  23201. return !isNumberNaN(val) ? val : undefined;
  23202. }
  23203. function isNumberInteger(num) {
  23204. // See http://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript#14794066
  23205. // (minus the assumption that `num` is a number)
  23206. // eslint-disable-next-line no-bitwise
  23207. return (num | 0) === num;
  23208. }
  23209. function countDecimals(num) {
  23210. var numString = num.toString();
  23211. var decimalSymbolIndex = numString.indexOf('.');
  23212. if (decimalSymbolIndex === -1) {
  23213. if (-1 < num && num < 1) {
  23214. // It may be in the exponential notation format (`1e-X`)
  23215. var match = /e-(\d+)$/.exec(numString);
  23216. if (match) {
  23217. return Number(match[1]);
  23218. }
  23219. }
  23220. return 0;
  23221. }
  23222. return numString.length - decimalSymbolIndex - 1;
  23223. }
  23224. function isValidForStep(viewValue, stepBase, step) {
  23225. // At this point `stepBase` and `step` are expected to be non-NaN values
  23226. // and `viewValue` is expected to be a valid stringified number.
  23227. var value = Number(viewValue);
  23228. var isNonIntegerValue = !isNumberInteger(value);
  23229. var isNonIntegerStepBase = !isNumberInteger(stepBase);
  23230. var isNonIntegerStep = !isNumberInteger(step);
  23231. // Due to limitations in Floating Point Arithmetic (e.g. `0.3 - 0.2 !== 0.1` or
  23232. // `0.5 % 0.1 !== 0`), we need to convert all numbers to integers.
  23233. if (isNonIntegerValue || isNonIntegerStepBase || isNonIntegerStep) {
  23234. var valueDecimals = isNonIntegerValue ? countDecimals(value) : 0;
  23235. var stepBaseDecimals = isNonIntegerStepBase ? countDecimals(stepBase) : 0;
  23236. var stepDecimals = isNonIntegerStep ? countDecimals(step) : 0;
  23237. var decimalCount = Math.max(valueDecimals, stepBaseDecimals, stepDecimals);
  23238. var multiplier = Math.pow(10, decimalCount);
  23239. value = value * multiplier;
  23240. stepBase = stepBase * multiplier;
  23241. step = step * multiplier;
  23242. if (isNonIntegerValue) value = Math.round(value);
  23243. if (isNonIntegerStepBase) stepBase = Math.round(stepBase);
  23244. if (isNonIntegerStep) step = Math.round(step);
  23245. }
  23246. return (value - stepBase) % step === 0;
  23247. }
  23248. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  23249. badInputChecker(scope, element, attr, ctrl);
  23250. numberFormatterParser(ctrl);
  23251. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  23252. var minVal;
  23253. var maxVal;
  23254. if (isDefined(attr.min) || attr.ngMin) {
  23255. ctrl.$validators.min = function(value) {
  23256. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  23257. };
  23258. attr.$observe('min', function(val) {
  23259. minVal = parseNumberAttrVal(val);
  23260. // TODO(matsko): implement validateLater to reduce number of validations
  23261. ctrl.$validate();
  23262. });
  23263. }
  23264. if (isDefined(attr.max) || attr.ngMax) {
  23265. ctrl.$validators.max = function(value) {
  23266. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  23267. };
  23268. attr.$observe('max', function(val) {
  23269. maxVal = parseNumberAttrVal(val);
  23270. // TODO(matsko): implement validateLater to reduce number of validations
  23271. ctrl.$validate();
  23272. });
  23273. }
  23274. if (isDefined(attr.step) || attr.ngStep) {
  23275. var stepVal;
  23276. ctrl.$validators.step = function(modelValue, viewValue) {
  23277. return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||
  23278. isValidForStep(viewValue, minVal || 0, stepVal);
  23279. };
  23280. attr.$observe('step', function(val) {
  23281. stepVal = parseNumberAttrVal(val);
  23282. // TODO(matsko): implement validateLater to reduce number of validations
  23283. ctrl.$validate();
  23284. });
  23285. }
  23286. }
  23287. function rangeInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  23288. badInputChecker(scope, element, attr, ctrl);
  23289. numberFormatterParser(ctrl);
  23290. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  23291. var supportsRange = ctrl.$$hasNativeValidators && element[0].type === 'range',
  23292. minVal = supportsRange ? 0 : undefined,
  23293. maxVal = supportsRange ? 100 : undefined,
  23294. stepVal = supportsRange ? 1 : undefined,
  23295. validity = element[0].validity,
  23296. hasMinAttr = isDefined(attr.min),
  23297. hasMaxAttr = isDefined(attr.max),
  23298. hasStepAttr = isDefined(attr.step);
  23299. var originalRender = ctrl.$render;
  23300. ctrl.$render = supportsRange && isDefined(validity.rangeUnderflow) && isDefined(validity.rangeOverflow) ?
  23301. //Browsers that implement range will set these values automatically, but reading the adjusted values after
  23302. //$render would cause the min / max validators to be applied with the wrong value
  23303. function rangeRender() {
  23304. originalRender();
  23305. ctrl.$setViewValue(element.val());
  23306. } :
  23307. originalRender;
  23308. if (hasMinAttr) {
  23309. ctrl.$validators.min = supportsRange ?
  23310. // Since all browsers set the input to a valid value, we don't need to check validity
  23311. function noopMinValidator() { return true; } :
  23312. // non-support browsers validate the min val
  23313. function minValidator(modelValue, viewValue) {
  23314. return ctrl.$isEmpty(viewValue) || isUndefined(minVal) || viewValue >= minVal;
  23315. };
  23316. setInitialValueAndObserver('min', minChange);
  23317. }
  23318. if (hasMaxAttr) {
  23319. ctrl.$validators.max = supportsRange ?
  23320. // Since all browsers set the input to a valid value, we don't need to check validity
  23321. function noopMaxValidator() { return true; } :
  23322. // non-support browsers validate the max val
  23323. function maxValidator(modelValue, viewValue) {
  23324. return ctrl.$isEmpty(viewValue) || isUndefined(maxVal) || viewValue <= maxVal;
  23325. };
  23326. setInitialValueAndObserver('max', maxChange);
  23327. }
  23328. if (hasStepAttr) {
  23329. ctrl.$validators.step = supportsRange ?
  23330. function nativeStepValidator() {
  23331. // Currently, only FF implements the spec on step change correctly (i.e. adjusting the
  23332. // input element value to a valid value). It's possible that other browsers set the stepMismatch
  23333. // validity error instead, so we can at least report an error in that case.
  23334. return !validity.stepMismatch;
  23335. } :
  23336. // ngStep doesn't set the setp attr, so the browser doesn't adjust the input value as setting step would
  23337. function stepValidator(modelValue, viewValue) {
  23338. return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) ||
  23339. isValidForStep(viewValue, minVal || 0, stepVal);
  23340. };
  23341. setInitialValueAndObserver('step', stepChange);
  23342. }
  23343. function setInitialValueAndObserver(htmlAttrName, changeFn) {
  23344. // interpolated attributes set the attribute value only after a digest, but we need the
  23345. // attribute value when the input is first rendered, so that the browser can adjust the
  23346. // input value based on the min/max value
  23347. element.attr(htmlAttrName, attr[htmlAttrName]);
  23348. attr.$observe(htmlAttrName, changeFn);
  23349. }
  23350. function minChange(val) {
  23351. minVal = parseNumberAttrVal(val);
  23352. // ignore changes before model is initialized
  23353. if (isNumberNaN(ctrl.$modelValue)) {
  23354. return;
  23355. }
  23356. if (supportsRange) {
  23357. var elVal = element.val();
  23358. // IE11 doesn't set the el val correctly if the minVal is greater than the element value
  23359. if (minVal > elVal) {
  23360. elVal = minVal;
  23361. element.val(elVal);
  23362. }
  23363. ctrl.$setViewValue(elVal);
  23364. } else {
  23365. // TODO(matsko): implement validateLater to reduce number of validations
  23366. ctrl.$validate();
  23367. }
  23368. }
  23369. function maxChange(val) {
  23370. maxVal = parseNumberAttrVal(val);
  23371. // ignore changes before model is initialized
  23372. if (isNumberNaN(ctrl.$modelValue)) {
  23373. return;
  23374. }
  23375. if (supportsRange) {
  23376. var elVal = element.val();
  23377. // IE11 doesn't set the el val correctly if the maxVal is less than the element value
  23378. if (maxVal < elVal) {
  23379. element.val(maxVal);
  23380. // IE11 and Chrome don't set the value to the minVal when max < min
  23381. elVal = maxVal < minVal ? minVal : maxVal;
  23382. }
  23383. ctrl.$setViewValue(elVal);
  23384. } else {
  23385. // TODO(matsko): implement validateLater to reduce number of validations
  23386. ctrl.$validate();
  23387. }
  23388. }
  23389. function stepChange(val) {
  23390. stepVal = parseNumberAttrVal(val);
  23391. // ignore changes before model is initialized
  23392. if (isNumberNaN(ctrl.$modelValue)) {
  23393. return;
  23394. }
  23395. // Some browsers don't adjust the input value correctly, but set the stepMismatch error
  23396. if (supportsRange && ctrl.$viewValue !== element.val()) {
  23397. ctrl.$setViewValue(element.val());
  23398. } else {
  23399. // TODO(matsko): implement validateLater to reduce number of validations
  23400. ctrl.$validate();
  23401. }
  23402. }
  23403. }
  23404. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  23405. // Note: no badInputChecker here by purpose as `url` is only a validation
  23406. // in browsers, i.e. we can always read out input.value even if it is not valid!
  23407. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  23408. stringBasedInputType(ctrl);
  23409. ctrl.$$parserName = 'url';
  23410. ctrl.$validators.url = function(modelValue, viewValue) {
  23411. var value = modelValue || viewValue;
  23412. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  23413. };
  23414. }
  23415. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  23416. // Note: no badInputChecker here by purpose as `url` is only a validation
  23417. // in browsers, i.e. we can always read out input.value even if it is not valid!
  23418. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  23419. stringBasedInputType(ctrl);
  23420. ctrl.$$parserName = 'email';
  23421. ctrl.$validators.email = function(modelValue, viewValue) {
  23422. var value = modelValue || viewValue;
  23423. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  23424. };
  23425. }
  23426. function radioInputType(scope, element, attr, ctrl) {
  23427. var doTrim = !attr.ngTrim || trim(attr.ngTrim) !== 'false';
  23428. // make the name unique, if not defined
  23429. if (isUndefined(attr.name)) {
  23430. element.attr('name', nextUid());
  23431. }
  23432. var listener = function(ev) {
  23433. var value;
  23434. if (element[0].checked) {
  23435. value = attr.value;
  23436. if (doTrim) {
  23437. value = trim(value);
  23438. }
  23439. ctrl.$setViewValue(value, ev && ev.type);
  23440. }
  23441. };
  23442. element.on('click', listener);
  23443. ctrl.$render = function() {
  23444. var value = attr.value;
  23445. if (doTrim) {
  23446. value = trim(value);
  23447. }
  23448. element[0].checked = (value === ctrl.$viewValue);
  23449. };
  23450. attr.$observe('value', ctrl.$render);
  23451. }
  23452. function parseConstantExpr($parse, context, name, expression, fallback) {
  23453. var parseFn;
  23454. if (isDefined(expression)) {
  23455. parseFn = $parse(expression);
  23456. if (!parseFn.constant) {
  23457. throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  23458. '`{1}`.', name, expression);
  23459. }
  23460. return parseFn(context);
  23461. }
  23462. return fallback;
  23463. }
  23464. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  23465. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  23466. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  23467. var listener = function(ev) {
  23468. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  23469. };
  23470. element.on('click', listener);
  23471. ctrl.$render = function() {
  23472. element[0].checked = ctrl.$viewValue;
  23473. };
  23474. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  23475. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  23476. // it to a boolean.
  23477. ctrl.$isEmpty = function(value) {
  23478. return value === false;
  23479. };
  23480. ctrl.$formatters.push(function(value) {
  23481. return equals(value, trueValue);
  23482. });
  23483. ctrl.$parsers.push(function(value) {
  23484. return value ? trueValue : falseValue;
  23485. });
  23486. }
  23487. /**
  23488. * @ngdoc directive
  23489. * @name textarea
  23490. * @restrict E
  23491. *
  23492. * @description
  23493. * HTML textarea element control with angular data-binding. The data-binding and validation
  23494. * properties of this element are exactly the same as those of the
  23495. * {@link ng.directive:input input element}.
  23496. *
  23497. * @param {string} ngModel Assignable angular expression to data-bind to.
  23498. * @param {string=} name Property name of the form under which the control is published.
  23499. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23500. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23501. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23502. * `required` when you want to data-bind to the `required` attribute.
  23503. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  23504. * minlength.
  23505. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  23506. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  23507. * length.
  23508. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  23509. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  23510. * If the expression evaluates to a RegExp object, then this is used directly.
  23511. * If the expression evaluates to a string, then it will be converted to a RegExp
  23512. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  23513. * `new RegExp('^abc$')`.<br />
  23514. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  23515. * start at the index of the last search's match, thus not taking the whole input value into
  23516. * account.
  23517. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  23518. * interaction with the input element.
  23519. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  23520. *
  23521. * @knownIssue
  23522. *
  23523. * When specifying the `placeholder` attribute of `<textarea>`, Internet Explorer will temporarily
  23524. * insert the placeholder value as the textarea's content. If the placeholder value contains
  23525. * interpolation (`{{ ... }}`), an error will be logged in the console when Angular tries to update
  23526. * the value of the by-then-removed text node. This doesn't affect the functionality of the
  23527. * textarea, but can be undesirable.
  23528. *
  23529. * You can work around this Internet Explorer issue by using `ng-attr-placeholder` instead of
  23530. * `placeholder` on textareas, whenever you need interpolation in the placeholder value. You can
  23531. * find more details on `ngAttr` in the
  23532. * [Interpolation](guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes) section of the
  23533. * Developer Guide.
  23534. */
  23535. /**
  23536. * @ngdoc directive
  23537. * @name input
  23538. * @restrict E
  23539. *
  23540. * @description
  23541. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  23542. * input state control, and validation.
  23543. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  23544. *
  23545. * <div class="alert alert-warning">
  23546. * **Note:** Not every feature offered is available for all input types.
  23547. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  23548. * </div>
  23549. *
  23550. * @param {string} ngModel Assignable angular expression to data-bind to.
  23551. * @param {string=} name Property name of the form under which the control is published.
  23552. * @param {string=} required Sets `required` validation error key if the value is not entered.
  23553. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  23554. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  23555. * minlength.
  23556. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  23557. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  23558. * length.
  23559. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  23560. * value does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  23561. * If the expression evaluates to a RegExp object, then this is used directly.
  23562. * If the expression evaluates to a string, then it will be converted to a RegExp
  23563. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  23564. * `new RegExp('^abc$')`.<br />
  23565. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  23566. * start at the index of the last search's match, thus not taking the whole input value into
  23567. * account.
  23568. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  23569. * interaction with the input element.
  23570. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  23571. * This parameter is ignored for input[type=password] controls, which will never trim the
  23572. * input.
  23573. *
  23574. * @example
  23575. <example name="input-directive" module="inputExample">
  23576. <file name="index.html">
  23577. <script>
  23578. angular.module('inputExample', [])
  23579. .controller('ExampleController', ['$scope', function($scope) {
  23580. $scope.user = {name: 'guest', last: 'visitor'};
  23581. }]);
  23582. </script>
  23583. <div ng-controller="ExampleController">
  23584. <form name="myForm">
  23585. <label>
  23586. User name:
  23587. <input type="text" name="userName" ng-model="user.name" required>
  23588. </label>
  23589. <div role="alert">
  23590. <span class="error" ng-show="myForm.userName.$error.required">
  23591. Required!</span>
  23592. </div>
  23593. <label>
  23594. Last name:
  23595. <input type="text" name="lastName" ng-model="user.last"
  23596. ng-minlength="3" ng-maxlength="10">
  23597. </label>
  23598. <div role="alert">
  23599. <span class="error" ng-show="myForm.lastName.$error.minlength">
  23600. Too short!</span>
  23601. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  23602. Too long!</span>
  23603. </div>
  23604. </form>
  23605. <hr>
  23606. <tt>user = {{user}}</tt><br/>
  23607. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  23608. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  23609. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  23610. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  23611. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23612. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23613. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  23614. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  23615. </div>
  23616. </file>
  23617. <file name="protractor.js" type="protractor">
  23618. var user = element(by.exactBinding('user'));
  23619. var userNameValid = element(by.binding('myForm.userName.$valid'));
  23620. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  23621. var lastNameError = element(by.binding('myForm.lastName.$error'));
  23622. var formValid = element(by.binding('myForm.$valid'));
  23623. var userNameInput = element(by.model('user.name'));
  23624. var userLastInput = element(by.model('user.last'));
  23625. it('should initialize to model', function() {
  23626. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  23627. expect(userNameValid.getText()).toContain('true');
  23628. expect(formValid.getText()).toContain('true');
  23629. });
  23630. it('should be invalid if empty when required', function() {
  23631. userNameInput.clear();
  23632. userNameInput.sendKeys('');
  23633. expect(user.getText()).toContain('{"last":"visitor"}');
  23634. expect(userNameValid.getText()).toContain('false');
  23635. expect(formValid.getText()).toContain('false');
  23636. });
  23637. it('should be valid if empty when min length is set', function() {
  23638. userLastInput.clear();
  23639. userLastInput.sendKeys('');
  23640. expect(user.getText()).toContain('{"name":"guest","last":""}');
  23641. expect(lastNameValid.getText()).toContain('true');
  23642. expect(formValid.getText()).toContain('true');
  23643. });
  23644. it('should be invalid if less than required min length', function() {
  23645. userLastInput.clear();
  23646. userLastInput.sendKeys('xx');
  23647. expect(user.getText()).toContain('{"name":"guest"}');
  23648. expect(lastNameValid.getText()).toContain('false');
  23649. expect(lastNameError.getText()).toContain('minlength');
  23650. expect(formValid.getText()).toContain('false');
  23651. });
  23652. it('should be invalid if longer than max length', function() {
  23653. userLastInput.clear();
  23654. userLastInput.sendKeys('some ridiculously long name');
  23655. expect(user.getText()).toContain('{"name":"guest"}');
  23656. expect(lastNameValid.getText()).toContain('false');
  23657. expect(lastNameError.getText()).toContain('maxlength');
  23658. expect(formValid.getText()).toContain('false');
  23659. });
  23660. </file>
  23661. </example>
  23662. */
  23663. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  23664. function($browser, $sniffer, $filter, $parse) {
  23665. return {
  23666. restrict: 'E',
  23667. require: ['?ngModel'],
  23668. link: {
  23669. pre: function(scope, element, attr, ctrls) {
  23670. if (ctrls[0]) {
  23671. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  23672. $browser, $filter, $parse);
  23673. }
  23674. }
  23675. }
  23676. };
  23677. }];
  23678. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  23679. /**
  23680. * @ngdoc directive
  23681. * @name ngValue
  23682. * @restrict A
  23683. * @priority 100
  23684. *
  23685. * @description
  23686. * Binds the given expression to the value of the element.
  23687. *
  23688. * It is mainly used on {@link input[radio] `input[radio]`} and option elements,
  23689. * so that when the element is selected, the {@link ngModel `ngModel`} of that element (or its
  23690. * {@link select `select`} parent element) is set to the bound value. It is especially useful
  23691. * for dynamically generated lists using {@link ngRepeat `ngRepeat`}, as shown below.
  23692. *
  23693. * It can also be used to achieve one-way binding of a given expression to an input element
  23694. * such as an `input[text]` or a `textarea`, when that element does not use ngModel.
  23695. *
  23696. * @element ANY
  23697. * @param {string=} ngValue AngularJS expression, whose value will be bound to the `value` attribute
  23698. * and `value` property of the element.
  23699. *
  23700. * @example
  23701. <example name="ngValue-directive" module="valueExample">
  23702. <file name="index.html">
  23703. <script>
  23704. angular.module('valueExample', [])
  23705. .controller('ExampleController', ['$scope', function($scope) {
  23706. $scope.names = ['pizza', 'unicorns', 'robots'];
  23707. $scope.my = { favorite: 'unicorns' };
  23708. }]);
  23709. </script>
  23710. <form ng-controller="ExampleController">
  23711. <h2>Which is your favorite?</h2>
  23712. <label ng-repeat="name in names" for="{{name}}">
  23713. {{name}}
  23714. <input type="radio"
  23715. ng-model="my.favorite"
  23716. ng-value="name"
  23717. id="{{name}}"
  23718. name="favorite">
  23719. </label>
  23720. <div>You chose {{my.favorite}}</div>
  23721. </form>
  23722. </file>
  23723. <file name="protractor.js" type="protractor">
  23724. var favorite = element(by.binding('my.favorite'));
  23725. it('should initialize to model', function() {
  23726. expect(favorite.getText()).toContain('unicorns');
  23727. });
  23728. it('should bind the values to the inputs', function() {
  23729. element.all(by.model('my.favorite')).get(0).click();
  23730. expect(favorite.getText()).toContain('pizza');
  23731. });
  23732. </file>
  23733. </example>
  23734. */
  23735. var ngValueDirective = function() {
  23736. /**
  23737. * inputs use the value attribute as their default value if the value property is not set.
  23738. * Once the value property has been set (by adding input), it will not react to changes to
  23739. * the value attribute anymore. Setting both attribute and property fixes this behavior, and
  23740. * makes it possible to use ngValue as a sort of one-way bind.
  23741. */
  23742. function updateElementValue(element, attr, value) {
  23743. // Support: IE9 only
  23744. // In IE9 values are converted to string (e.g. `input.value = null` results in `input.value === 'null'`).
  23745. var propValue = isDefined(value) ? value : (msie === 9) ? '' : null;
  23746. element.prop('value', propValue);
  23747. attr.$set('value', value);
  23748. }
  23749. return {
  23750. restrict: 'A',
  23751. priority: 100,
  23752. compile: function(tpl, tplAttr) {
  23753. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  23754. return function ngValueConstantLink(scope, elm, attr) {
  23755. var value = scope.$eval(attr.ngValue);
  23756. updateElementValue(elm, attr, value);
  23757. };
  23758. } else {
  23759. return function ngValueLink(scope, elm, attr) {
  23760. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  23761. updateElementValue(elm, attr, value);
  23762. });
  23763. };
  23764. }
  23765. }
  23766. };
  23767. };
  23768. /**
  23769. * @ngdoc directive
  23770. * @name ngBind
  23771. * @restrict AC
  23772. *
  23773. * @description
  23774. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  23775. * with the value of a given expression, and to update the text content when the value of that
  23776. * expression changes.
  23777. *
  23778. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  23779. * `{{ expression }}` which is similar but less verbose.
  23780. *
  23781. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  23782. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  23783. * element attribute, it makes the bindings invisible to the user while the page is loading.
  23784. *
  23785. * An alternative solution to this problem would be using the
  23786. * {@link ng.directive:ngCloak ngCloak} directive.
  23787. *
  23788. *
  23789. * @element ANY
  23790. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  23791. *
  23792. * @example
  23793. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  23794. <example module="bindExample" name="ng-bind">
  23795. <file name="index.html">
  23796. <script>
  23797. angular.module('bindExample', [])
  23798. .controller('ExampleController', ['$scope', function($scope) {
  23799. $scope.name = 'Whirled';
  23800. }]);
  23801. </script>
  23802. <div ng-controller="ExampleController">
  23803. <label>Enter name: <input type="text" ng-model="name"></label><br>
  23804. Hello <span ng-bind="name"></span>!
  23805. </div>
  23806. </file>
  23807. <file name="protractor.js" type="protractor">
  23808. it('should check ng-bind', function() {
  23809. var nameInput = element(by.model('name'));
  23810. expect(element(by.binding('name')).getText()).toBe('Whirled');
  23811. nameInput.clear();
  23812. nameInput.sendKeys('world');
  23813. expect(element(by.binding('name')).getText()).toBe('world');
  23814. });
  23815. </file>
  23816. </example>
  23817. */
  23818. var ngBindDirective = ['$compile', function($compile) {
  23819. return {
  23820. restrict: 'AC',
  23821. compile: function ngBindCompile(templateElement) {
  23822. $compile.$$addBindingClass(templateElement);
  23823. return function ngBindLink(scope, element, attr) {
  23824. $compile.$$addBindingInfo(element, attr.ngBind);
  23825. element = element[0];
  23826. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  23827. element.textContent = stringify(value);
  23828. });
  23829. };
  23830. }
  23831. };
  23832. }];
  23833. /**
  23834. * @ngdoc directive
  23835. * @name ngBindTemplate
  23836. *
  23837. * @description
  23838. * The `ngBindTemplate` directive specifies that the element
  23839. * text content should be replaced with the interpolation of the template
  23840. * in the `ngBindTemplate` attribute.
  23841. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  23842. * expressions. This directive is needed since some HTML elements
  23843. * (such as TITLE and OPTION) cannot contain SPAN elements.
  23844. *
  23845. * @element ANY
  23846. * @param {string} ngBindTemplate template of form
  23847. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  23848. *
  23849. * @example
  23850. * Try it here: enter text in text box and watch the greeting change.
  23851. <example module="bindExample" name="ng-bind-template">
  23852. <file name="index.html">
  23853. <script>
  23854. angular.module('bindExample', [])
  23855. .controller('ExampleController', ['$scope', function($scope) {
  23856. $scope.salutation = 'Hello';
  23857. $scope.name = 'World';
  23858. }]);
  23859. </script>
  23860. <div ng-controller="ExampleController">
  23861. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  23862. <label>Name: <input type="text" ng-model="name"></label><br>
  23863. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  23864. </div>
  23865. </file>
  23866. <file name="protractor.js" type="protractor">
  23867. it('should check ng-bind', function() {
  23868. var salutationElem = element(by.binding('salutation'));
  23869. var salutationInput = element(by.model('salutation'));
  23870. var nameInput = element(by.model('name'));
  23871. expect(salutationElem.getText()).toBe('Hello World!');
  23872. salutationInput.clear();
  23873. salutationInput.sendKeys('Greetings');
  23874. nameInput.clear();
  23875. nameInput.sendKeys('user');
  23876. expect(salutationElem.getText()).toBe('Greetings user!');
  23877. });
  23878. </file>
  23879. </example>
  23880. */
  23881. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  23882. return {
  23883. compile: function ngBindTemplateCompile(templateElement) {
  23884. $compile.$$addBindingClass(templateElement);
  23885. return function ngBindTemplateLink(scope, element, attr) {
  23886. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  23887. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  23888. element = element[0];
  23889. attr.$observe('ngBindTemplate', function(value) {
  23890. element.textContent = isUndefined(value) ? '' : value;
  23891. });
  23892. };
  23893. }
  23894. };
  23895. }];
  23896. /**
  23897. * @ngdoc directive
  23898. * @name ngBindHtml
  23899. *
  23900. * @description
  23901. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  23902. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  23903. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  23904. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  23905. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  23906. *
  23907. * You may also bypass sanitization for values you know are safe. To do so, bind to
  23908. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  23909. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  23910. *
  23911. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  23912. * will have an exception (instead of an exploit.)
  23913. *
  23914. * @element ANY
  23915. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  23916. *
  23917. * @example
  23918. <example module="bindHtmlExample" deps="angular-sanitize.js" name="ng-bind-html">
  23919. <file name="index.html">
  23920. <div ng-controller="ExampleController">
  23921. <p ng-bind-html="myHTML"></p>
  23922. </div>
  23923. </file>
  23924. <file name="script.js">
  23925. angular.module('bindHtmlExample', ['ngSanitize'])
  23926. .controller('ExampleController', ['$scope', function($scope) {
  23927. $scope.myHTML =
  23928. 'I am an <code>HTML</code>string with ' +
  23929. '<a href="#">links!</a> and other <em>stuff</em>';
  23930. }]);
  23931. </file>
  23932. <file name="protractor.js" type="protractor">
  23933. it('should check ng-bind-html', function() {
  23934. expect(element(by.binding('myHTML')).getText()).toBe(
  23935. 'I am an HTMLstring with links! and other stuff');
  23936. });
  23937. </file>
  23938. </example>
  23939. */
  23940. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  23941. return {
  23942. restrict: 'A',
  23943. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  23944. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  23945. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function sceValueOf(val) {
  23946. // Unwrap the value to compare the actual inner safe value, not the wrapper object.
  23947. return $sce.valueOf(val);
  23948. });
  23949. $compile.$$addBindingClass(tElement);
  23950. return function ngBindHtmlLink(scope, element, attr) {
  23951. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  23952. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  23953. // The watched value is the unwrapped value. To avoid re-escaping, use the direct getter.
  23954. var value = ngBindHtmlGetter(scope);
  23955. element.html($sce.getTrustedHtml(value) || '');
  23956. });
  23957. };
  23958. }
  23959. };
  23960. }];
  23961. /**
  23962. * @ngdoc directive
  23963. * @name ngChange
  23964. * @restrict A
  23965. *
  23966. * @description
  23967. * Evaluate the given expression when the user changes the input.
  23968. * The expression is evaluated immediately, unlike the JavaScript onchange event
  23969. * which only triggers at the end of a change (usually, when the user leaves the
  23970. * form element or presses the return key).
  23971. *
  23972. * The `ngChange` expression is only evaluated when a change in the input value causes
  23973. * a new value to be committed to the model.
  23974. *
  23975. * It will not be evaluated:
  23976. * * if the value returned from the `$parsers` transformation pipeline has not changed
  23977. * * if the input has continued to be invalid since the model will stay `null`
  23978. * * if the model is changed programmatically and not by a change to the input value
  23979. *
  23980. *
  23981. * Note, this directive requires `ngModel` to be present.
  23982. *
  23983. * @element ANY
  23984. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  23985. * in input value.
  23986. *
  23987. * @example
  23988. * <example name="ngChange-directive" module="changeExample">
  23989. * <file name="index.html">
  23990. * <script>
  23991. * angular.module('changeExample', [])
  23992. * .controller('ExampleController', ['$scope', function($scope) {
  23993. * $scope.counter = 0;
  23994. * $scope.change = function() {
  23995. * $scope.counter++;
  23996. * };
  23997. * }]);
  23998. * </script>
  23999. * <div ng-controller="ExampleController">
  24000. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  24001. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  24002. * <label for="ng-change-example2">Confirmed</label><br />
  24003. * <tt>debug = {{confirmed}}</tt><br/>
  24004. * <tt>counter = {{counter}}</tt><br/>
  24005. * </div>
  24006. * </file>
  24007. * <file name="protractor.js" type="protractor">
  24008. * var counter = element(by.binding('counter'));
  24009. * var debug = element(by.binding('confirmed'));
  24010. *
  24011. * it('should evaluate the expression if changing from view', function() {
  24012. * expect(counter.getText()).toContain('0');
  24013. *
  24014. * element(by.id('ng-change-example1')).click();
  24015. *
  24016. * expect(counter.getText()).toContain('1');
  24017. * expect(debug.getText()).toContain('true');
  24018. * });
  24019. *
  24020. * it('should not evaluate the expression if changing from model', function() {
  24021. * element(by.id('ng-change-example2')).click();
  24022. * expect(counter.getText()).toContain('0');
  24023. * expect(debug.getText()).toContain('true');
  24024. * });
  24025. * </file>
  24026. * </example>
  24027. */
  24028. var ngChangeDirective = valueFn({
  24029. restrict: 'A',
  24030. require: 'ngModel',
  24031. link: function(scope, element, attr, ctrl) {
  24032. ctrl.$viewChangeListeners.push(function() {
  24033. scope.$eval(attr.ngChange);
  24034. });
  24035. }
  24036. });
  24037. /* exported
  24038. ngClassDirective,
  24039. ngClassEvenDirective,
  24040. ngClassOddDirective
  24041. */
  24042. function classDirective(name, selector) {
  24043. name = 'ngClass' + name;
  24044. var indexWatchExpression;
  24045. return ['$parse', function($parse) {
  24046. return {
  24047. restrict: 'AC',
  24048. link: function(scope, element, attr) {
  24049. var expression = attr[name].trim();
  24050. var isOneTime = (expression.charAt(0) === ':') && (expression.charAt(1) === ':');
  24051. var watchInterceptor = isOneTime ? toFlatValue : toClassString;
  24052. var watchExpression = $parse(expression, watchInterceptor);
  24053. var watchAction = isOneTime ? ngClassOneTimeWatchAction : ngClassWatchAction;
  24054. var classCounts = element.data('$classCounts');
  24055. var oldModulo = true;
  24056. var oldClassString;
  24057. if (!classCounts) {
  24058. // Use createMap() to prevent class assumptions involving property
  24059. // names in Object.prototype
  24060. classCounts = createMap();
  24061. element.data('$classCounts', classCounts);
  24062. }
  24063. if (name !== 'ngClass') {
  24064. if (!indexWatchExpression) {
  24065. indexWatchExpression = $parse('$index', function moduloTwo($index) {
  24066. // eslint-disable-next-line no-bitwise
  24067. return $index & 1;
  24068. });
  24069. }
  24070. scope.$watch(indexWatchExpression, ngClassIndexWatchAction);
  24071. }
  24072. scope.$watch(watchExpression, watchAction, isOneTime);
  24073. function addClasses(classString) {
  24074. classString = digestClassCounts(split(classString), 1);
  24075. attr.$addClass(classString);
  24076. }
  24077. function removeClasses(classString) {
  24078. classString = digestClassCounts(split(classString), -1);
  24079. attr.$removeClass(classString);
  24080. }
  24081. function updateClasses(oldClassString, newClassString) {
  24082. var oldClassArray = split(oldClassString);
  24083. var newClassArray = split(newClassString);
  24084. var toRemoveArray = arrayDifference(oldClassArray, newClassArray);
  24085. var toAddArray = arrayDifference(newClassArray, oldClassArray);
  24086. var toRemoveString = digestClassCounts(toRemoveArray, -1);
  24087. var toAddString = digestClassCounts(toAddArray, 1);
  24088. attr.$addClass(toAddString);
  24089. attr.$removeClass(toRemoveString);
  24090. }
  24091. function digestClassCounts(classArray, count) {
  24092. var classesToUpdate = [];
  24093. forEach(classArray, function(className) {
  24094. if (count > 0 || classCounts[className]) {
  24095. classCounts[className] = (classCounts[className] || 0) + count;
  24096. if (classCounts[className] === +(count > 0)) {
  24097. classesToUpdate.push(className);
  24098. }
  24099. }
  24100. });
  24101. return classesToUpdate.join(' ');
  24102. }
  24103. function ngClassIndexWatchAction(newModulo) {
  24104. // This watch-action should run before the `ngClass[OneTime]WatchAction()`, thus it
  24105. // adds/removes `oldClassString`. If the `ngClass` expression has changed as well, the
  24106. // `ngClass[OneTime]WatchAction()` will update the classes.
  24107. if (newModulo === selector) {
  24108. addClasses(oldClassString);
  24109. } else {
  24110. removeClasses(oldClassString);
  24111. }
  24112. oldModulo = newModulo;
  24113. }
  24114. function ngClassOneTimeWatchAction(newClassValue) {
  24115. var newClassString = toClassString(newClassValue);
  24116. if (newClassString !== oldClassString) {
  24117. ngClassWatchAction(newClassString);
  24118. }
  24119. }
  24120. function ngClassWatchAction(newClassString) {
  24121. if (oldModulo === selector) {
  24122. updateClasses(oldClassString, newClassString);
  24123. }
  24124. oldClassString = newClassString;
  24125. }
  24126. }
  24127. };
  24128. }];
  24129. // Helpers
  24130. function arrayDifference(tokens1, tokens2) {
  24131. if (!tokens1 || !tokens1.length) return [];
  24132. if (!tokens2 || !tokens2.length) return tokens1;
  24133. var values = [];
  24134. outer:
  24135. for (var i = 0; i < tokens1.length; i++) {
  24136. var token = tokens1[i];
  24137. for (var j = 0; j < tokens2.length; j++) {
  24138. if (token === tokens2[j]) continue outer;
  24139. }
  24140. values.push(token);
  24141. }
  24142. return values;
  24143. }
  24144. function split(classString) {
  24145. return classString && classString.split(' ');
  24146. }
  24147. function toClassString(classValue) {
  24148. var classString = classValue;
  24149. if (isArray(classValue)) {
  24150. classString = classValue.map(toClassString).join(' ');
  24151. } else if (isObject(classValue)) {
  24152. classString = Object.keys(classValue).
  24153. filter(function(key) { return classValue[key]; }).
  24154. join(' ');
  24155. }
  24156. return classString;
  24157. }
  24158. function toFlatValue(classValue) {
  24159. var flatValue = classValue;
  24160. if (isArray(classValue)) {
  24161. flatValue = classValue.map(toFlatValue);
  24162. } else if (isObject(classValue)) {
  24163. var hasUndefined = false;
  24164. flatValue = Object.keys(classValue).filter(function(key) {
  24165. var value = classValue[key];
  24166. if (!hasUndefined && isUndefined(value)) {
  24167. hasUndefined = true;
  24168. }
  24169. return value;
  24170. });
  24171. if (hasUndefined) {
  24172. // Prevent the `oneTimeLiteralWatchInterceptor` from unregistering
  24173. // the watcher, by including at least one `undefined` value.
  24174. flatValue.push(undefined);
  24175. }
  24176. }
  24177. return flatValue;
  24178. }
  24179. }
  24180. /**
  24181. * @ngdoc directive
  24182. * @name ngClass
  24183. * @restrict AC
  24184. * @element ANY
  24185. *
  24186. * @description
  24187. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  24188. * an expression that represents all classes to be added.
  24189. *
  24190. * The directive operates in three different ways, depending on which of three types the expression
  24191. * evaluates to:
  24192. *
  24193. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  24194. * names.
  24195. *
  24196. * 2. If the expression evaluates to an object, then for each key-value pair of the
  24197. * object with a truthy value the corresponding key is used as a class name.
  24198. *
  24199. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  24200. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  24201. * to give you more control over what CSS classes appear. See the code below for an example of this.
  24202. *
  24203. *
  24204. * The directive won't add duplicate classes if a particular class was already set.
  24205. *
  24206. * When the expression changes, the previously added classes are removed and only then are the
  24207. * new classes added.
  24208. *
  24209. * @knownIssue
  24210. * You should not use {@link guide/interpolation interpolation} in the value of the `class`
  24211. * attribute, when using the `ngClass` directive on the same element.
  24212. * See {@link guide/interpolation#known-issues here} for more info.
  24213. *
  24214. * @animations
  24215. * | Animation | Occurs |
  24216. * |----------------------------------|-------------------------------------|
  24217. * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element |
  24218. * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element |
  24219. *
  24220. * ### ngClass and pre-existing CSS3 Transitions/Animations
  24221. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  24222. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  24223. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  24224. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  24225. {@link $animate#removeClass $animate.removeClass}.
  24226. *
  24227. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  24228. * of the evaluation can be a string representing space delimited class
  24229. * names, an array, or a map of class names to boolean values. In the case of a map, the
  24230. * names of the properties whose values are truthy will be added as css classes to the
  24231. * element.
  24232. *
  24233. * @example
  24234. * ### Basic
  24235. <example name="ng-class">
  24236. <file name="index.html">
  24237. <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
  24238. <label>
  24239. <input type="checkbox" ng-model="deleted">
  24240. deleted (apply "strike" class)
  24241. </label><br>
  24242. <label>
  24243. <input type="checkbox" ng-model="important">
  24244. important (apply "bold" class)
  24245. </label><br>
  24246. <label>
  24247. <input type="checkbox" ng-model="error">
  24248. error (apply "has-error" class)
  24249. </label>
  24250. <hr>
  24251. <p ng-class="style">Using String Syntax</p>
  24252. <input type="text" ng-model="style"
  24253. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  24254. <hr>
  24255. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  24256. <input ng-model="style1"
  24257. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  24258. <input ng-model="style2"
  24259. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  24260. <input ng-model="style3"
  24261. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  24262. <hr>
  24263. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  24264. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  24265. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  24266. </file>
  24267. <file name="style.css">
  24268. .strike {
  24269. text-decoration: line-through;
  24270. }
  24271. .bold {
  24272. font-weight: bold;
  24273. }
  24274. .red {
  24275. color: red;
  24276. }
  24277. .has-error {
  24278. color: red;
  24279. background-color: yellow;
  24280. }
  24281. .orange {
  24282. color: orange;
  24283. }
  24284. </file>
  24285. <file name="protractor.js" type="protractor">
  24286. var ps = element.all(by.css('p'));
  24287. it('should let you toggle the class', function() {
  24288. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  24289. expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
  24290. element(by.model('important')).click();
  24291. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  24292. element(by.model('error')).click();
  24293. expect(ps.first().getAttribute('class')).toMatch(/has-error/);
  24294. });
  24295. it('should let you toggle string example', function() {
  24296. expect(ps.get(1).getAttribute('class')).toBe('');
  24297. element(by.model('style')).clear();
  24298. element(by.model('style')).sendKeys('red');
  24299. expect(ps.get(1).getAttribute('class')).toBe('red');
  24300. });
  24301. it('array example should have 3 classes', function() {
  24302. expect(ps.get(2).getAttribute('class')).toBe('');
  24303. element(by.model('style1')).sendKeys('bold');
  24304. element(by.model('style2')).sendKeys('strike');
  24305. element(by.model('style3')).sendKeys('red');
  24306. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  24307. });
  24308. it('array with map example should have 2 classes', function() {
  24309. expect(ps.last().getAttribute('class')).toBe('');
  24310. element(by.model('style4')).sendKeys('bold');
  24311. element(by.model('warning')).click();
  24312. expect(ps.last().getAttribute('class')).toBe('bold orange');
  24313. });
  24314. </file>
  24315. </example>
  24316. @example
  24317. ### Animations
  24318. The example below demonstrates how to perform animations using ngClass.
  24319. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-class">
  24320. <file name="index.html">
  24321. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  24322. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  24323. <br>
  24324. <span class="base-class" ng-class="myVar">Sample Text</span>
  24325. </file>
  24326. <file name="style.css">
  24327. .base-class {
  24328. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  24329. }
  24330. .base-class.my-class {
  24331. color: red;
  24332. font-size:3em;
  24333. }
  24334. </file>
  24335. <file name="protractor.js" type="protractor">
  24336. it('should check ng-class', function() {
  24337. expect(element(by.css('.base-class')).getAttribute('class')).not.
  24338. toMatch(/my-class/);
  24339. element(by.id('setbtn')).click();
  24340. expect(element(by.css('.base-class')).getAttribute('class')).
  24341. toMatch(/my-class/);
  24342. element(by.id('clearbtn')).click();
  24343. expect(element(by.css('.base-class')).getAttribute('class')).not.
  24344. toMatch(/my-class/);
  24345. });
  24346. </file>
  24347. </example>
  24348. */
  24349. var ngClassDirective = classDirective('', true);
  24350. /**
  24351. * @ngdoc directive
  24352. * @name ngClassOdd
  24353. * @restrict AC
  24354. *
  24355. * @description
  24356. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  24357. * {@link ng.directive:ngClass ngClass}, except they work in
  24358. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  24359. *
  24360. * This directive can be applied only within the scope of an
  24361. * {@link ng.directive:ngRepeat ngRepeat}.
  24362. *
  24363. * @element ANY
  24364. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  24365. * of the evaluation can be a string representing space delimited class names or an array.
  24366. *
  24367. * @example
  24368. <example name="ng-class-odd">
  24369. <file name="index.html">
  24370. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  24371. <li ng-repeat="name in names">
  24372. <span ng-class-odd="'odd'" ng-class-even="'even'">
  24373. {{name}}
  24374. </span>
  24375. </li>
  24376. </ol>
  24377. </file>
  24378. <file name="style.css">
  24379. .odd {
  24380. color: red;
  24381. }
  24382. .even {
  24383. color: blue;
  24384. }
  24385. </file>
  24386. <file name="protractor.js" type="protractor">
  24387. it('should check ng-class-odd and ng-class-even', function() {
  24388. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  24389. toMatch(/odd/);
  24390. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  24391. toMatch(/even/);
  24392. });
  24393. </file>
  24394. </example>
  24395. */
  24396. var ngClassOddDirective = classDirective('Odd', 0);
  24397. /**
  24398. * @ngdoc directive
  24399. * @name ngClassEven
  24400. * @restrict AC
  24401. *
  24402. * @description
  24403. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  24404. * {@link ng.directive:ngClass ngClass}, except they work in
  24405. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  24406. *
  24407. * This directive can be applied only within the scope of an
  24408. * {@link ng.directive:ngRepeat ngRepeat}.
  24409. *
  24410. * @element ANY
  24411. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  24412. * result of the evaluation can be a string representing space delimited class names or an array.
  24413. *
  24414. * @example
  24415. <example name="ng-class-even">
  24416. <file name="index.html">
  24417. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  24418. <li ng-repeat="name in names">
  24419. <span ng-class-odd="'odd'" ng-class-even="'even'">
  24420. {{name}} &nbsp; &nbsp; &nbsp;
  24421. </span>
  24422. </li>
  24423. </ol>
  24424. </file>
  24425. <file name="style.css">
  24426. .odd {
  24427. color: red;
  24428. }
  24429. .even {
  24430. color: blue;
  24431. }
  24432. </file>
  24433. <file name="protractor.js" type="protractor">
  24434. it('should check ng-class-odd and ng-class-even', function() {
  24435. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  24436. toMatch(/odd/);
  24437. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  24438. toMatch(/even/);
  24439. });
  24440. </file>
  24441. </example>
  24442. */
  24443. var ngClassEvenDirective = classDirective('Even', 1);
  24444. /**
  24445. * @ngdoc directive
  24446. * @name ngCloak
  24447. * @restrict AC
  24448. *
  24449. * @description
  24450. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  24451. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  24452. * directive to avoid the undesirable flicker effect caused by the html template display.
  24453. *
  24454. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  24455. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  24456. * of the browser view.
  24457. *
  24458. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  24459. * `angular.min.js`.
  24460. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  24461. *
  24462. * ```css
  24463. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  24464. * display: none !important;
  24465. * }
  24466. * ```
  24467. *
  24468. * When this css rule is loaded by the browser, all html elements (including their children) that
  24469. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  24470. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  24471. * the compiled element visible.
  24472. *
  24473. * For the best result, the `angular.js` script must be loaded in the head section of the html
  24474. * document; alternatively, the css rule above must be included in the external stylesheet of the
  24475. * application.
  24476. *
  24477. * @element ANY
  24478. *
  24479. * @example
  24480. <example name="ng-cloak">
  24481. <file name="index.html">
  24482. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  24483. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  24484. </file>
  24485. <file name="protractor.js" type="protractor">
  24486. it('should remove the template directive and css class', function() {
  24487. expect($('#template1').getAttribute('ng-cloak')).
  24488. toBeNull();
  24489. expect($('#template2').getAttribute('ng-cloak')).
  24490. toBeNull();
  24491. });
  24492. </file>
  24493. </example>
  24494. *
  24495. */
  24496. var ngCloakDirective = ngDirective({
  24497. compile: function(element, attr) {
  24498. attr.$set('ngCloak', undefined);
  24499. element.removeClass('ng-cloak');
  24500. }
  24501. });
  24502. /**
  24503. * @ngdoc directive
  24504. * @name ngController
  24505. *
  24506. * @description
  24507. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  24508. * supports the principles behind the Model-View-Controller design pattern.
  24509. *
  24510. * MVC components in angular:
  24511. *
  24512. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  24513. * are accessed through bindings.
  24514. * * View — The template (HTML with data bindings) that is rendered into the View.
  24515. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  24516. * logic behind the application to decorate the scope with functions and values
  24517. *
  24518. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  24519. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  24520. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  24521. * and executed twice.
  24522. *
  24523. * @element ANY
  24524. * @scope
  24525. * @priority 500
  24526. * @param {expression} ngController Name of a constructor function registered with the current
  24527. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  24528. * that on the current scope evaluates to a constructor function.
  24529. *
  24530. * The controller instance can be published into a scope property by specifying
  24531. * `ng-controller="as propertyName"`.
  24532. *
  24533. * If the current `$controllerProvider` is configured to use globals (via
  24534. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  24535. * also be the name of a globally accessible constructor function (deprecated, not recommended).
  24536. *
  24537. * @example
  24538. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  24539. * greeting are methods declared on the controller (see source tab). These methods can
  24540. * easily be called from the angular markup. Any changes to the data are automatically reflected
  24541. * in the View without the need for a manual update.
  24542. *
  24543. * Two different declaration styles are included below:
  24544. *
  24545. * * one binds methods and properties directly onto the controller using `this`:
  24546. * `ng-controller="SettingsController1 as settings"`
  24547. * * one injects `$scope` into the controller:
  24548. * `ng-controller="SettingsController2"`
  24549. *
  24550. * The second option is more common in the Angular community, and is generally used in boilerplates
  24551. * and in this guide. However, there are advantages to binding properties directly to the controller
  24552. * and avoiding scope.
  24553. *
  24554. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  24555. * multiple controllers apply to an element.
  24556. * * If you are writing your controllers as classes you have easier access to the properties and
  24557. * methods, which will appear on the scope, from inside the controller code.
  24558. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  24559. * inheritance masking primitives.
  24560. *
  24561. * This example demonstrates the `controller as` syntax.
  24562. *
  24563. * <example name="ngControllerAs" module="controllerAsExample">
  24564. * <file name="index.html">
  24565. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  24566. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  24567. * <button ng-click="settings.greet()">greet</button><br/>
  24568. * Contact:
  24569. * <ul>
  24570. * <li ng-repeat="contact in settings.contacts">
  24571. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  24572. * <option>phone</option>
  24573. * <option>email</option>
  24574. * </select>
  24575. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  24576. * <button ng-click="settings.clearContact(contact)">clear</button>
  24577. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  24578. * </li>
  24579. * <li><button ng-click="settings.addContact()">add</button></li>
  24580. * </ul>
  24581. * </div>
  24582. * </file>
  24583. * <file name="app.js">
  24584. * angular.module('controllerAsExample', [])
  24585. * .controller('SettingsController1', SettingsController1);
  24586. *
  24587. * function SettingsController1() {
  24588. * this.name = 'John Smith';
  24589. * this.contacts = [
  24590. * {type: 'phone', value: '408 555 1212'},
  24591. * {type: 'email', value: 'john.smith@example.org'}
  24592. * ];
  24593. * }
  24594. *
  24595. * SettingsController1.prototype.greet = function() {
  24596. * alert(this.name);
  24597. * };
  24598. *
  24599. * SettingsController1.prototype.addContact = function() {
  24600. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  24601. * };
  24602. *
  24603. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  24604. * var index = this.contacts.indexOf(contactToRemove);
  24605. * this.contacts.splice(index, 1);
  24606. * };
  24607. *
  24608. * SettingsController1.prototype.clearContact = function(contact) {
  24609. * contact.type = 'phone';
  24610. * contact.value = '';
  24611. * };
  24612. * </file>
  24613. * <file name="protractor.js" type="protractor">
  24614. * it('should check controller as', function() {
  24615. * var container = element(by.id('ctrl-as-exmpl'));
  24616. * expect(container.element(by.model('settings.name'))
  24617. * .getAttribute('value')).toBe('John Smith');
  24618. *
  24619. * var firstRepeat =
  24620. * container.element(by.repeater('contact in settings.contacts').row(0));
  24621. * var secondRepeat =
  24622. * container.element(by.repeater('contact in settings.contacts').row(1));
  24623. *
  24624. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24625. * .toBe('408 555 1212');
  24626. *
  24627. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  24628. * .toBe('john.smith@example.org');
  24629. *
  24630. * firstRepeat.element(by.buttonText('clear')).click();
  24631. *
  24632. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24633. * .toBe('');
  24634. *
  24635. * container.element(by.buttonText('add')).click();
  24636. *
  24637. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  24638. * .element(by.model('contact.value'))
  24639. * .getAttribute('value'))
  24640. * .toBe('yourname@example.org');
  24641. * });
  24642. * </file>
  24643. * </example>
  24644. *
  24645. * This example demonstrates the "attach to `$scope`" style of controller.
  24646. *
  24647. * <example name="ngController" module="controllerExample">
  24648. * <file name="index.html">
  24649. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  24650. * <label>Name: <input type="text" ng-model="name"/></label>
  24651. * <button ng-click="greet()">greet</button><br/>
  24652. * Contact:
  24653. * <ul>
  24654. * <li ng-repeat="contact in contacts">
  24655. * <select ng-model="contact.type" id="select_{{$index}}">
  24656. * <option>phone</option>
  24657. * <option>email</option>
  24658. * </select>
  24659. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  24660. * <button ng-click="clearContact(contact)">clear</button>
  24661. * <button ng-click="removeContact(contact)">X</button>
  24662. * </li>
  24663. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  24664. * </ul>
  24665. * </div>
  24666. * </file>
  24667. * <file name="app.js">
  24668. * angular.module('controllerExample', [])
  24669. * .controller('SettingsController2', ['$scope', SettingsController2]);
  24670. *
  24671. * function SettingsController2($scope) {
  24672. * $scope.name = 'John Smith';
  24673. * $scope.contacts = [
  24674. * {type:'phone', value:'408 555 1212'},
  24675. * {type:'email', value:'john.smith@example.org'}
  24676. * ];
  24677. *
  24678. * $scope.greet = function() {
  24679. * alert($scope.name);
  24680. * };
  24681. *
  24682. * $scope.addContact = function() {
  24683. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  24684. * };
  24685. *
  24686. * $scope.removeContact = function(contactToRemove) {
  24687. * var index = $scope.contacts.indexOf(contactToRemove);
  24688. * $scope.contacts.splice(index, 1);
  24689. * };
  24690. *
  24691. * $scope.clearContact = function(contact) {
  24692. * contact.type = 'phone';
  24693. * contact.value = '';
  24694. * };
  24695. * }
  24696. * </file>
  24697. * <file name="protractor.js" type="protractor">
  24698. * it('should check controller', function() {
  24699. * var container = element(by.id('ctrl-exmpl'));
  24700. *
  24701. * expect(container.element(by.model('name'))
  24702. * .getAttribute('value')).toBe('John Smith');
  24703. *
  24704. * var firstRepeat =
  24705. * container.element(by.repeater('contact in contacts').row(0));
  24706. * var secondRepeat =
  24707. * container.element(by.repeater('contact in contacts').row(1));
  24708. *
  24709. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24710. * .toBe('408 555 1212');
  24711. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  24712. * .toBe('john.smith@example.org');
  24713. *
  24714. * firstRepeat.element(by.buttonText('clear')).click();
  24715. *
  24716. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  24717. * .toBe('');
  24718. *
  24719. * container.element(by.buttonText('add')).click();
  24720. *
  24721. * expect(container.element(by.repeater('contact in contacts').row(2))
  24722. * .element(by.model('contact.value'))
  24723. * .getAttribute('value'))
  24724. * .toBe('yourname@example.org');
  24725. * });
  24726. * </file>
  24727. *</example>
  24728. */
  24729. var ngControllerDirective = [function() {
  24730. return {
  24731. restrict: 'A',
  24732. scope: true,
  24733. controller: '@',
  24734. priority: 500
  24735. };
  24736. }];
  24737. /**
  24738. * @ngdoc directive
  24739. * @name ngCsp
  24740. *
  24741. * @restrict A
  24742. * @element ANY
  24743. * @description
  24744. *
  24745. * Angular has some features that can conflict with certain restrictions that are applied when using
  24746. * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
  24747. *
  24748. * If you intend to implement CSP with these rules then you must tell Angular not to use these
  24749. * features.
  24750. *
  24751. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  24752. *
  24753. *
  24754. * The following default rules in CSP affect Angular:
  24755. *
  24756. * * The use of `eval()`, `Function(string)` and similar functions to dynamically create and execute
  24757. * code from strings is forbidden. Angular makes use of this in the {@link $parse} service to
  24758. * provide a 30% increase in the speed of evaluating Angular expressions. (This CSP rule can be
  24759. * disabled with the CSP keyword `unsafe-eval`, but it is generally not recommended as it would
  24760. * weaken the protections offered by CSP.)
  24761. *
  24762. * * The use of inline resources, such as inline `<script>` and `<style>` elements, are forbidden.
  24763. * This prevents apps from injecting custom styles directly into the document. Angular makes use of
  24764. * this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}). To make these
  24765. * directives work when a CSP rule is blocking inline styles, you must link to the `angular-csp.css`
  24766. * in your HTML manually. (This CSP rule can be disabled with the CSP keyword `unsafe-inline`, but
  24767. * it is generally not recommended as it would weaken the protections offered by CSP.)
  24768. *
  24769. * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking dynamic code
  24770. * creation from strings (e.g., `unsafe-eval` not specified in CSP header) and automatically
  24771. * deactivates this feature in the {@link $parse} service. This autodetection, however, triggers a
  24772. * CSP error to be logged in the console:
  24773. *
  24774. * ```
  24775. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  24776. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  24777. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  24778. * ```
  24779. *
  24780. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  24781. * directive on an element of the HTML document that appears before the `<script>` tag that loads
  24782. * the `angular.js` file.
  24783. *
  24784. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  24785. *
  24786. * You can specify which of the CSP related Angular features should be deactivated by providing
  24787. * a value for the `ng-csp` attribute. The options are as follows:
  24788. *
  24789. * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
  24790. *
  24791. * * no-unsafe-eval: this stops Angular from optimizing $parse with unsafe eval of strings
  24792. *
  24793. * You can use these values in the following combinations:
  24794. *
  24795. *
  24796. * * No declaration means that Angular will assume that you can do inline styles, but it will do
  24797. * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous
  24798. * versions of Angular.
  24799. *
  24800. * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
  24801. * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous
  24802. * versions of Angular.
  24803. *
  24804. * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can
  24805. * inject inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
  24806. *
  24807. * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
  24808. * run eval - no automatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
  24809. *
  24810. * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
  24811. * styles nor use eval, which is the same as an empty: ng-csp.
  24812. * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
  24813. *
  24814. * @example
  24815. *
  24816. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  24817. ```html
  24818. <!doctype html>
  24819. <html ng-app ng-csp>
  24820. ...
  24821. ...
  24822. </html>
  24823. ```
  24824. <!-- Note: the `.csp` suffix in the example name triggers CSP mode in our http server! -->
  24825. <example name="example.csp" module="cspExample" ng-csp="true">
  24826. <file name="index.html">
  24827. <div ng-controller="MainController as ctrl">
  24828. <div>
  24829. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  24830. <span id="counter">
  24831. {{ctrl.counter}}
  24832. </span>
  24833. </div>
  24834. <div>
  24835. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  24836. <span id="evilError">
  24837. {{ctrl.evilError}}
  24838. </span>
  24839. </div>
  24840. </div>
  24841. </file>
  24842. <file name="script.js">
  24843. angular.module('cspExample', [])
  24844. .controller('MainController', function MainController() {
  24845. this.counter = 0;
  24846. this.inc = function() {
  24847. this.counter++;
  24848. };
  24849. this.evil = function() {
  24850. try {
  24851. eval('1+2'); // eslint-disable-line no-eval
  24852. } catch (e) {
  24853. this.evilError = e.message;
  24854. }
  24855. };
  24856. });
  24857. </file>
  24858. <file name="protractor.js" type="protractor">
  24859. var util, webdriver;
  24860. var incBtn = element(by.id('inc'));
  24861. var counter = element(by.id('counter'));
  24862. var evilBtn = element(by.id('evil'));
  24863. var evilError = element(by.id('evilError'));
  24864. function getAndClearSevereErrors() {
  24865. return browser.manage().logs().get('browser').then(function(browserLog) {
  24866. return browserLog.filter(function(logEntry) {
  24867. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  24868. });
  24869. });
  24870. }
  24871. function clearErrors() {
  24872. getAndClearSevereErrors();
  24873. }
  24874. function expectNoErrors() {
  24875. getAndClearSevereErrors().then(function(filteredLog) {
  24876. expect(filteredLog.length).toEqual(0);
  24877. if (filteredLog.length) {
  24878. console.log('browser console errors: ' + util.inspect(filteredLog));
  24879. }
  24880. });
  24881. }
  24882. function expectError(regex) {
  24883. getAndClearSevereErrors().then(function(filteredLog) {
  24884. var found = false;
  24885. filteredLog.forEach(function(log) {
  24886. if (log.message.match(regex)) {
  24887. found = true;
  24888. }
  24889. });
  24890. if (!found) {
  24891. throw new Error('expected an error that matches ' + regex);
  24892. }
  24893. });
  24894. }
  24895. beforeEach(function() {
  24896. util = require('util');
  24897. webdriver = require('selenium-webdriver');
  24898. });
  24899. // For now, we only test on Chrome,
  24900. // as Safari does not load the page with Protractor's injected scripts,
  24901. // and Firefox webdriver always disables content security policy (#6358)
  24902. if (browser.params.browser !== 'chrome') {
  24903. return;
  24904. }
  24905. it('should not report errors when the page is loaded', function() {
  24906. // clear errors so we are not dependent on previous tests
  24907. clearErrors();
  24908. // Need to reload the page as the page is already loaded when
  24909. // we come here
  24910. browser.driver.getCurrentUrl().then(function(url) {
  24911. browser.get(url);
  24912. });
  24913. expectNoErrors();
  24914. });
  24915. it('should evaluate expressions', function() {
  24916. expect(counter.getText()).toEqual('0');
  24917. incBtn.click();
  24918. expect(counter.getText()).toEqual('1');
  24919. expectNoErrors();
  24920. });
  24921. it('should throw and report an error when using "eval"', function() {
  24922. evilBtn.click();
  24923. expect(evilError.getText()).toMatch(/Content Security Policy/);
  24924. expectError(/Content Security Policy/);
  24925. });
  24926. </file>
  24927. </example>
  24928. */
  24929. // `ngCsp` is not implemented as a proper directive any more, because we need it be processed while
  24930. // we bootstrap the app (before `$parse` is instantiated). For this reason, we just have the `csp()`
  24931. // fn that looks for the `ng-csp` attribute anywhere in the current doc.
  24932. /**
  24933. * @ngdoc directive
  24934. * @name ngClick
  24935. * @restrict A
  24936. * @element ANY
  24937. * @priority 0
  24938. *
  24939. * @description
  24940. * The ngClick directive allows you to specify custom behavior when
  24941. * an element is clicked.
  24942. *
  24943. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  24944. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  24945. *
  24946. * @example
  24947. <example name="ng-click">
  24948. <file name="index.html">
  24949. <button ng-click="count = count + 1" ng-init="count=0">
  24950. Increment
  24951. </button>
  24952. <span>
  24953. count: {{count}}
  24954. </span>
  24955. </file>
  24956. <file name="protractor.js" type="protractor">
  24957. it('should check ng-click', function() {
  24958. expect(element(by.binding('count')).getText()).toMatch('0');
  24959. element(by.css('button')).click();
  24960. expect(element(by.binding('count')).getText()).toMatch('1');
  24961. });
  24962. </file>
  24963. </example>
  24964. */
  24965. /*
  24966. * A collection of directives that allows creation of custom event handlers that are defined as
  24967. * angular expressions and are compiled and executed within the current scope.
  24968. */
  24969. var ngEventDirectives = {};
  24970. // For events that might fire synchronously during DOM manipulation
  24971. // we need to execute their event handlers asynchronously using $evalAsync,
  24972. // so that they are not executed in an inconsistent state.
  24973. var forceAsyncEvents = {
  24974. 'blur': true,
  24975. 'focus': true
  24976. };
  24977. forEach(
  24978. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  24979. function(eventName) {
  24980. var directiveName = directiveNormalize('ng-' + eventName);
  24981. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  24982. return {
  24983. restrict: 'A',
  24984. compile: function($element, attr) {
  24985. // NOTE:
  24986. // We expose the powerful `$event` object on the scope that provides access to the Window,
  24987. // etc. This is OK, because expressions are not sandboxed any more (and the expression
  24988. // sandbox was never meant to be a security feature anyway).
  24989. var fn = $parse(attr[directiveName]);
  24990. return function ngEventHandler(scope, element) {
  24991. element.on(eventName, function(event) {
  24992. var callback = function() {
  24993. fn(scope, {$event: event});
  24994. };
  24995. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  24996. scope.$evalAsync(callback);
  24997. } else {
  24998. scope.$apply(callback);
  24999. }
  25000. });
  25001. };
  25002. }
  25003. };
  25004. }];
  25005. }
  25006. );
  25007. /**
  25008. * @ngdoc directive
  25009. * @name ngDblclick
  25010. * @restrict A
  25011. * @element ANY
  25012. * @priority 0
  25013. *
  25014. * @description
  25015. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  25016. *
  25017. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  25018. * a dblclick. (The Event object is available as `$event`)
  25019. *
  25020. * @example
  25021. <example name="ng-dblclick">
  25022. <file name="index.html">
  25023. <button ng-dblclick="count = count + 1" ng-init="count=0">
  25024. Increment (on double click)
  25025. </button>
  25026. count: {{count}}
  25027. </file>
  25028. </example>
  25029. */
  25030. /**
  25031. * @ngdoc directive
  25032. * @name ngMousedown
  25033. * @restrict A
  25034. * @element ANY
  25035. * @priority 0
  25036. *
  25037. * @description
  25038. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  25039. *
  25040. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  25041. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  25042. *
  25043. * @example
  25044. <example name="ng-mousedown">
  25045. <file name="index.html">
  25046. <button ng-mousedown="count = count + 1" ng-init="count=0">
  25047. Increment (on mouse down)
  25048. </button>
  25049. count: {{count}}
  25050. </file>
  25051. </example>
  25052. */
  25053. /**
  25054. * @ngdoc directive
  25055. * @name ngMouseup
  25056. * @restrict A
  25057. * @element ANY
  25058. * @priority 0
  25059. *
  25060. * @description
  25061. * Specify custom behavior on mouseup event.
  25062. *
  25063. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  25064. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  25065. *
  25066. * @example
  25067. <example name="ng-mouseup">
  25068. <file name="index.html">
  25069. <button ng-mouseup="count = count + 1" ng-init="count=0">
  25070. Increment (on mouse up)
  25071. </button>
  25072. count: {{count}}
  25073. </file>
  25074. </example>
  25075. */
  25076. /**
  25077. * @ngdoc directive
  25078. * @name ngMouseover
  25079. * @restrict A
  25080. * @element ANY
  25081. * @priority 0
  25082. *
  25083. * @description
  25084. * Specify custom behavior on mouseover event.
  25085. *
  25086. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  25087. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  25088. *
  25089. * @example
  25090. <example name="ng-mouseover">
  25091. <file name="index.html">
  25092. <button ng-mouseover="count = count + 1" ng-init="count=0">
  25093. Increment (when mouse is over)
  25094. </button>
  25095. count: {{count}}
  25096. </file>
  25097. </example>
  25098. */
  25099. /**
  25100. * @ngdoc directive
  25101. * @name ngMouseenter
  25102. * @restrict A
  25103. * @element ANY
  25104. * @priority 0
  25105. *
  25106. * @description
  25107. * Specify custom behavior on mouseenter event.
  25108. *
  25109. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  25110. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  25111. *
  25112. * @example
  25113. <example name="ng-mouseenter">
  25114. <file name="index.html">
  25115. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  25116. Increment (when mouse enters)
  25117. </button>
  25118. count: {{count}}
  25119. </file>
  25120. </example>
  25121. */
  25122. /**
  25123. * @ngdoc directive
  25124. * @name ngMouseleave
  25125. * @restrict A
  25126. * @element ANY
  25127. * @priority 0
  25128. *
  25129. * @description
  25130. * Specify custom behavior on mouseleave event.
  25131. *
  25132. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  25133. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  25134. *
  25135. * @example
  25136. <example name="ng-mouseleave">
  25137. <file name="index.html">
  25138. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  25139. Increment (when mouse leaves)
  25140. </button>
  25141. count: {{count}}
  25142. </file>
  25143. </example>
  25144. */
  25145. /**
  25146. * @ngdoc directive
  25147. * @name ngMousemove
  25148. * @restrict A
  25149. * @element ANY
  25150. * @priority 0
  25151. *
  25152. * @description
  25153. * Specify custom behavior on mousemove event.
  25154. *
  25155. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  25156. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  25157. *
  25158. * @example
  25159. <example name="ng-mousemove">
  25160. <file name="index.html">
  25161. <button ng-mousemove="count = count + 1" ng-init="count=0">
  25162. Increment (when mouse moves)
  25163. </button>
  25164. count: {{count}}
  25165. </file>
  25166. </example>
  25167. */
  25168. /**
  25169. * @ngdoc directive
  25170. * @name ngKeydown
  25171. * @restrict A
  25172. * @element ANY
  25173. * @priority 0
  25174. *
  25175. * @description
  25176. * Specify custom behavior on keydown event.
  25177. *
  25178. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  25179. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  25180. *
  25181. * @example
  25182. <example name="ng-keydown">
  25183. <file name="index.html">
  25184. <input ng-keydown="count = count + 1" ng-init="count=0">
  25185. key down count: {{count}}
  25186. </file>
  25187. </example>
  25188. */
  25189. /**
  25190. * @ngdoc directive
  25191. * @name ngKeyup
  25192. * @restrict A
  25193. * @element ANY
  25194. * @priority 0
  25195. *
  25196. * @description
  25197. * Specify custom behavior on keyup event.
  25198. *
  25199. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  25200. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  25201. *
  25202. * @example
  25203. <example name="ng-keyup">
  25204. <file name="index.html">
  25205. <p>Typing in the input box below updates the key count</p>
  25206. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  25207. <p>Typing in the input box below updates the keycode</p>
  25208. <input ng-keyup="event=$event">
  25209. <p>event keyCode: {{ event.keyCode }}</p>
  25210. <p>event altKey: {{ event.altKey }}</p>
  25211. </file>
  25212. </example>
  25213. */
  25214. /**
  25215. * @ngdoc directive
  25216. * @name ngKeypress
  25217. * @restrict A
  25218. * @element ANY
  25219. *
  25220. * @description
  25221. * Specify custom behavior on keypress event.
  25222. *
  25223. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  25224. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  25225. * and can be interrogated for keyCode, altKey, etc.)
  25226. *
  25227. * @example
  25228. <example name="ng-keypress">
  25229. <file name="index.html">
  25230. <input ng-keypress="count = count + 1" ng-init="count=0">
  25231. key press count: {{count}}
  25232. </file>
  25233. </example>
  25234. */
  25235. /**
  25236. * @ngdoc directive
  25237. * @name ngSubmit
  25238. * @restrict A
  25239. * @element form
  25240. * @priority 0
  25241. *
  25242. * @description
  25243. * Enables binding angular expressions to onsubmit events.
  25244. *
  25245. * Additionally it prevents the default action (which for form means sending the request to the
  25246. * server and reloading the current page), but only if the form does not contain `action`,
  25247. * `data-action`, or `x-action` attributes.
  25248. *
  25249. * <div class="alert alert-warning">
  25250. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  25251. * `ngSubmit` handlers together. See the
  25252. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  25253. * for a detailed discussion of when `ngSubmit` may be triggered.
  25254. * </div>
  25255. *
  25256. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  25257. * ({@link guide/expression#-event- Event object is available as `$event`})
  25258. *
  25259. * @example
  25260. <example module="submitExample" name="ng-submit">
  25261. <file name="index.html">
  25262. <script>
  25263. angular.module('submitExample', [])
  25264. .controller('ExampleController', ['$scope', function($scope) {
  25265. $scope.list = [];
  25266. $scope.text = 'hello';
  25267. $scope.submit = function() {
  25268. if ($scope.text) {
  25269. $scope.list.push(this.text);
  25270. $scope.text = '';
  25271. }
  25272. };
  25273. }]);
  25274. </script>
  25275. <form ng-submit="submit()" ng-controller="ExampleController">
  25276. Enter text and hit enter:
  25277. <input type="text" ng-model="text" name="text" />
  25278. <input type="submit" id="submit" value="Submit" />
  25279. <pre>list={{list}}</pre>
  25280. </form>
  25281. </file>
  25282. <file name="protractor.js" type="protractor">
  25283. it('should check ng-submit', function() {
  25284. expect(element(by.binding('list')).getText()).toBe('list=[]');
  25285. element(by.css('#submit')).click();
  25286. expect(element(by.binding('list')).getText()).toContain('hello');
  25287. expect(element(by.model('text')).getAttribute('value')).toBe('');
  25288. });
  25289. it('should ignore empty strings', function() {
  25290. expect(element(by.binding('list')).getText()).toBe('list=[]');
  25291. element(by.css('#submit')).click();
  25292. element(by.css('#submit')).click();
  25293. expect(element(by.binding('list')).getText()).toContain('hello');
  25294. });
  25295. </file>
  25296. </example>
  25297. */
  25298. /**
  25299. * @ngdoc directive
  25300. * @name ngFocus
  25301. * @restrict A
  25302. * @element window, input, select, textarea, a
  25303. * @priority 0
  25304. *
  25305. * @description
  25306. * Specify custom behavior on focus event.
  25307. *
  25308. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  25309. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  25310. * during an `$apply` to ensure a consistent state.
  25311. *
  25312. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  25313. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  25314. *
  25315. * @example
  25316. * See {@link ng.directive:ngClick ngClick}
  25317. */
  25318. /**
  25319. * @ngdoc directive
  25320. * @name ngBlur
  25321. * @restrict A
  25322. * @element window, input, select, textarea, a
  25323. * @priority 0
  25324. *
  25325. * @description
  25326. * Specify custom behavior on blur event.
  25327. *
  25328. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  25329. * an element has lost focus.
  25330. *
  25331. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  25332. * (e.g. removing a focussed input),
  25333. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  25334. * during an `$apply` to ensure a consistent state.
  25335. *
  25336. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  25337. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  25338. *
  25339. * @example
  25340. * See {@link ng.directive:ngClick ngClick}
  25341. */
  25342. /**
  25343. * @ngdoc directive
  25344. * @name ngCopy
  25345. * @restrict A
  25346. * @element window, input, select, textarea, a
  25347. * @priority 0
  25348. *
  25349. * @description
  25350. * Specify custom behavior on copy event.
  25351. *
  25352. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  25353. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  25354. *
  25355. * @example
  25356. <example name="ng-copy">
  25357. <file name="index.html">
  25358. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  25359. copied: {{copied}}
  25360. </file>
  25361. </example>
  25362. */
  25363. /**
  25364. * @ngdoc directive
  25365. * @name ngCut
  25366. * @restrict A
  25367. * @element window, input, select, textarea, a
  25368. * @priority 0
  25369. *
  25370. * @description
  25371. * Specify custom behavior on cut event.
  25372. *
  25373. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  25374. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  25375. *
  25376. * @example
  25377. <example name="ng-cut">
  25378. <file name="index.html">
  25379. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  25380. cut: {{cut}}
  25381. </file>
  25382. </example>
  25383. */
  25384. /**
  25385. * @ngdoc directive
  25386. * @name ngPaste
  25387. * @restrict A
  25388. * @element window, input, select, textarea, a
  25389. * @priority 0
  25390. *
  25391. * @description
  25392. * Specify custom behavior on paste event.
  25393. *
  25394. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  25395. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  25396. *
  25397. * @example
  25398. <example name="ng-paste">
  25399. <file name="index.html">
  25400. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  25401. pasted: {{paste}}
  25402. </file>
  25403. </example>
  25404. */
  25405. /**
  25406. * @ngdoc directive
  25407. * @name ngIf
  25408. * @restrict A
  25409. * @multiElement
  25410. *
  25411. * @description
  25412. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  25413. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  25414. * value then the element is removed from the DOM, otherwise a clone of the
  25415. * element is reinserted into the DOM.
  25416. *
  25417. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  25418. * element in the DOM rather than changing its visibility via the `display` css property. A common
  25419. * case when this difference is significant is when using css selectors that rely on an element's
  25420. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  25421. *
  25422. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  25423. * is created when the element is restored. The scope created within `ngIf` inherits from
  25424. * its parent scope using
  25425. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  25426. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  25427. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  25428. * variable within the child scope will override (hide) the value in the parent scope.
  25429. *
  25430. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  25431. * is if an element's class attribute is directly modified after it's compiled, using something like
  25432. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  25433. * the added class will be lost because the original compiled state is used to regenerate the element.
  25434. *
  25435. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  25436. * and `leave` effects.
  25437. *
  25438. * @animations
  25439. * | Animation | Occurs |
  25440. * |----------------------------------|-------------------------------------|
  25441. * | {@link ng.$animate#enter enter} | just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container |
  25442. * | {@link ng.$animate#leave leave} | just before the `ngIf` contents are removed from the DOM |
  25443. *
  25444. * @element ANY
  25445. * @scope
  25446. * @priority 600
  25447. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  25448. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  25449. * element is added to the DOM tree.
  25450. *
  25451. * @example
  25452. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-if">
  25453. <file name="index.html">
  25454. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  25455. Show when checked:
  25456. <span ng-if="checked" class="animate-if">
  25457. This is removed when the checkbox is unchecked.
  25458. </span>
  25459. </file>
  25460. <file name="animations.css">
  25461. .animate-if {
  25462. background:white;
  25463. border:1px solid black;
  25464. padding:10px;
  25465. }
  25466. .animate-if.ng-enter, .animate-if.ng-leave {
  25467. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  25468. }
  25469. .animate-if.ng-enter,
  25470. .animate-if.ng-leave.ng-leave-active {
  25471. opacity:0;
  25472. }
  25473. .animate-if.ng-leave,
  25474. .animate-if.ng-enter.ng-enter-active {
  25475. opacity:1;
  25476. }
  25477. </file>
  25478. </example>
  25479. */
  25480. var ngIfDirective = ['$animate', '$compile', function($animate, $compile) {
  25481. return {
  25482. multiElement: true,
  25483. transclude: 'element',
  25484. priority: 600,
  25485. terminal: true,
  25486. restrict: 'A',
  25487. $$tlb: true,
  25488. link: function($scope, $element, $attr, ctrl, $transclude) {
  25489. var block, childScope, previousElements;
  25490. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  25491. if (value) {
  25492. if (!childScope) {
  25493. $transclude(function(clone, newScope) {
  25494. childScope = newScope;
  25495. clone[clone.length++] = $compile.$$createComment('end ngIf', $attr.ngIf);
  25496. // Note: We only need the first/last node of the cloned nodes.
  25497. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  25498. // by a directive with templateUrl when its template arrives.
  25499. block = {
  25500. clone: clone
  25501. };
  25502. $animate.enter(clone, $element.parent(), $element);
  25503. });
  25504. }
  25505. } else {
  25506. if (previousElements) {
  25507. previousElements.remove();
  25508. previousElements = null;
  25509. }
  25510. if (childScope) {
  25511. childScope.$destroy();
  25512. childScope = null;
  25513. }
  25514. if (block) {
  25515. previousElements = getBlockNodes(block.clone);
  25516. $animate.leave(previousElements).done(function(response) {
  25517. if (response !== false) previousElements = null;
  25518. });
  25519. block = null;
  25520. }
  25521. }
  25522. });
  25523. }
  25524. };
  25525. }];
  25526. /**
  25527. * @ngdoc directive
  25528. * @name ngInclude
  25529. * @restrict ECA
  25530. * @scope
  25531. * @priority -400
  25532. *
  25533. * @description
  25534. * Fetches, compiles and includes an external HTML fragment.
  25535. *
  25536. * By default, the template URL is restricted to the same domain and protocol as the
  25537. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  25538. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  25539. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  25540. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  25541. * ng.$sce Strict Contextual Escaping}.
  25542. *
  25543. * In addition, the browser's
  25544. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  25545. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  25546. * policy may further restrict whether the template is successfully loaded.
  25547. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  25548. * access on some browsers.
  25549. *
  25550. * @animations
  25551. * | Animation | Occurs |
  25552. * |----------------------------------|-------------------------------------|
  25553. * | {@link ng.$animate#enter enter} | when the expression changes, on the new include |
  25554. * | {@link ng.$animate#leave leave} | when the expression changes, on the old include |
  25555. *
  25556. * The enter and leave animation occur concurrently.
  25557. *
  25558. * @param {string} ngInclude|src AngularJS expression evaluating to URL. If the source is a string constant,
  25559. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  25560. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  25561. * <div class="alert alert-warning">
  25562. * **Note:** When using onload on SVG elements in IE11, the browser will try to call
  25563. * a function with the name on the window element, which will usually throw a
  25564. * "function is undefined" error. To fix this, you can instead use `data-onload` or a
  25565. * different form that {@link guide/directive#normalization matches} `onload`.
  25566. * </div>
  25567. *
  25568. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  25569. * $anchorScroll} to scroll the viewport after the content is loaded.
  25570. *
  25571. * - If the attribute is not set, disable scrolling.
  25572. * - If the attribute is set without value, enable scrolling.
  25573. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  25574. *
  25575. * @example
  25576. <example module="includeExample" deps="angular-animate.js" animations="true" name="ng-include">
  25577. <file name="index.html">
  25578. <div ng-controller="ExampleController">
  25579. <select ng-model="template" ng-options="t.name for t in templates">
  25580. <option value="">(blank)</option>
  25581. </select>
  25582. url of the template: <code>{{template.url}}</code>
  25583. <hr/>
  25584. <div class="slide-animate-container">
  25585. <div class="slide-animate" ng-include="template.url"></div>
  25586. </div>
  25587. </div>
  25588. </file>
  25589. <file name="script.js">
  25590. angular.module('includeExample', ['ngAnimate'])
  25591. .controller('ExampleController', ['$scope', function($scope) {
  25592. $scope.templates =
  25593. [{ name: 'template1.html', url: 'template1.html'},
  25594. { name: 'template2.html', url: 'template2.html'}];
  25595. $scope.template = $scope.templates[0];
  25596. }]);
  25597. </file>
  25598. <file name="template1.html">
  25599. Content of template1.html
  25600. </file>
  25601. <file name="template2.html">
  25602. Content of template2.html
  25603. </file>
  25604. <file name="animations.css">
  25605. .slide-animate-container {
  25606. position:relative;
  25607. background:white;
  25608. border:1px solid black;
  25609. height:40px;
  25610. overflow:hidden;
  25611. }
  25612. .slide-animate {
  25613. padding:10px;
  25614. }
  25615. .slide-animate.ng-enter, .slide-animate.ng-leave {
  25616. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  25617. position:absolute;
  25618. top:0;
  25619. left:0;
  25620. right:0;
  25621. bottom:0;
  25622. display:block;
  25623. padding:10px;
  25624. }
  25625. .slide-animate.ng-enter {
  25626. top:-50px;
  25627. }
  25628. .slide-animate.ng-enter.ng-enter-active {
  25629. top:0;
  25630. }
  25631. .slide-animate.ng-leave {
  25632. top:0;
  25633. }
  25634. .slide-animate.ng-leave.ng-leave-active {
  25635. top:50px;
  25636. }
  25637. </file>
  25638. <file name="protractor.js" type="protractor">
  25639. var templateSelect = element(by.model('template'));
  25640. var includeElem = element(by.css('[ng-include]'));
  25641. it('should load template1.html', function() {
  25642. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  25643. });
  25644. it('should load template2.html', function() {
  25645. if (browser.params.browser === 'firefox') {
  25646. // Firefox can't handle using selects
  25647. // See https://github.com/angular/protractor/issues/480
  25648. return;
  25649. }
  25650. templateSelect.click();
  25651. templateSelect.all(by.css('option')).get(2).click();
  25652. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  25653. });
  25654. it('should change to blank', function() {
  25655. if (browser.params.browser === 'firefox') {
  25656. // Firefox can't handle using selects
  25657. return;
  25658. }
  25659. templateSelect.click();
  25660. templateSelect.all(by.css('option')).get(0).click();
  25661. expect(includeElem.isPresent()).toBe(false);
  25662. });
  25663. </file>
  25664. </example>
  25665. */
  25666. /**
  25667. * @ngdoc event
  25668. * @name ngInclude#$includeContentRequested
  25669. * @eventType emit on the scope ngInclude was declared in
  25670. * @description
  25671. * Emitted every time the ngInclude content is requested.
  25672. *
  25673. * @param {Object} angularEvent Synthetic event object.
  25674. * @param {String} src URL of content to load.
  25675. */
  25676. /**
  25677. * @ngdoc event
  25678. * @name ngInclude#$includeContentLoaded
  25679. * @eventType emit on the current ngInclude scope
  25680. * @description
  25681. * Emitted every time the ngInclude content is reloaded.
  25682. *
  25683. * @param {Object} angularEvent Synthetic event object.
  25684. * @param {String} src URL of content to load.
  25685. */
  25686. /**
  25687. * @ngdoc event
  25688. * @name ngInclude#$includeContentError
  25689. * @eventType emit on the scope ngInclude was declared in
  25690. * @description
  25691. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  25692. *
  25693. * @param {Object} angularEvent Synthetic event object.
  25694. * @param {String} src URL of content to load.
  25695. */
  25696. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
  25697. function($templateRequest, $anchorScroll, $animate) {
  25698. return {
  25699. restrict: 'ECA',
  25700. priority: 400,
  25701. terminal: true,
  25702. transclude: 'element',
  25703. controller: angular.noop,
  25704. compile: function(element, attr) {
  25705. var srcExp = attr.ngInclude || attr.src,
  25706. onloadExp = attr.onload || '',
  25707. autoScrollExp = attr.autoscroll;
  25708. return function(scope, $element, $attr, ctrl, $transclude) {
  25709. var changeCounter = 0,
  25710. currentScope,
  25711. previousElement,
  25712. currentElement;
  25713. var cleanupLastIncludeContent = function() {
  25714. if (previousElement) {
  25715. previousElement.remove();
  25716. previousElement = null;
  25717. }
  25718. if (currentScope) {
  25719. currentScope.$destroy();
  25720. currentScope = null;
  25721. }
  25722. if (currentElement) {
  25723. $animate.leave(currentElement).done(function(response) {
  25724. if (response !== false) previousElement = null;
  25725. });
  25726. previousElement = currentElement;
  25727. currentElement = null;
  25728. }
  25729. };
  25730. scope.$watch(srcExp, function ngIncludeWatchAction(src) {
  25731. var afterAnimation = function(response) {
  25732. if (response !== false && isDefined(autoScrollExp) &&
  25733. (!autoScrollExp || scope.$eval(autoScrollExp))) {
  25734. $anchorScroll();
  25735. }
  25736. };
  25737. var thisChangeId = ++changeCounter;
  25738. if (src) {
  25739. //set the 2nd param to true to ignore the template request error so that the inner
  25740. //contents and scope can be cleaned up.
  25741. $templateRequest(src, true).then(function(response) {
  25742. if (scope.$$destroyed) return;
  25743. if (thisChangeId !== changeCounter) return;
  25744. var newScope = scope.$new();
  25745. ctrl.template = response;
  25746. // Note: This will also link all children of ng-include that were contained in the original
  25747. // html. If that content contains controllers, ... they could pollute/change the scope.
  25748. // However, using ng-include on an element with additional content does not make sense...
  25749. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  25750. // function is called before linking the content, which would apply child
  25751. // directives to non existing elements.
  25752. var clone = $transclude(newScope, function(clone) {
  25753. cleanupLastIncludeContent();
  25754. $animate.enter(clone, null, $element).done(afterAnimation);
  25755. });
  25756. currentScope = newScope;
  25757. currentElement = clone;
  25758. currentScope.$emit('$includeContentLoaded', src);
  25759. scope.$eval(onloadExp);
  25760. }, function() {
  25761. if (scope.$$destroyed) return;
  25762. if (thisChangeId === changeCounter) {
  25763. cleanupLastIncludeContent();
  25764. scope.$emit('$includeContentError', src);
  25765. }
  25766. });
  25767. scope.$emit('$includeContentRequested', src);
  25768. } else {
  25769. cleanupLastIncludeContent();
  25770. ctrl.template = null;
  25771. }
  25772. });
  25773. };
  25774. }
  25775. };
  25776. }];
  25777. // This directive is called during the $transclude call of the first `ngInclude` directive.
  25778. // It will replace and compile the content of the element with the loaded template.
  25779. // We need this directive so that the element content is already filled when
  25780. // the link function of another directive on the same element as ngInclude
  25781. // is called.
  25782. var ngIncludeFillContentDirective = ['$compile',
  25783. function($compile) {
  25784. return {
  25785. restrict: 'ECA',
  25786. priority: -400,
  25787. require: 'ngInclude',
  25788. link: function(scope, $element, $attr, ctrl) {
  25789. if (toString.call($element[0]).match(/SVG/)) {
  25790. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  25791. // support innerHTML, so detect this here and try to generate the contents
  25792. // specially.
  25793. $element.empty();
  25794. $compile(jqLiteBuildFragment(ctrl.template, window.document).childNodes)(scope,
  25795. function namespaceAdaptedClone(clone) {
  25796. $element.append(clone);
  25797. }, {futureParentElement: $element});
  25798. return;
  25799. }
  25800. $element.html(ctrl.template);
  25801. $compile($element.contents())(scope);
  25802. }
  25803. };
  25804. }];
  25805. /**
  25806. * @ngdoc directive
  25807. * @name ngInit
  25808. * @restrict AC
  25809. * @priority 450
  25810. * @element ANY
  25811. *
  25812. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  25813. *
  25814. * @description
  25815. * The `ngInit` directive allows you to evaluate an expression in the
  25816. * current scope.
  25817. *
  25818. * <div class="alert alert-danger">
  25819. * This directive can be abused to add unnecessary amounts of logic into your templates.
  25820. * There are only a few appropriate uses of `ngInit`:
  25821. * <ul>
  25822. * <li>aliasing special properties of {@link ng.directive:ngRepeat `ngRepeat`},
  25823. * as seen in the demo below.</li>
  25824. * <li>initializing data during development, or for examples, as seen throughout these docs.</li>
  25825. * <li>injecting data via server side scripting.</li>
  25826. * </ul>
  25827. *
  25828. * Besides these few cases, you should use {@link guide/component Components} or
  25829. * {@link guide/controller Controllers} rather than `ngInit` to initialize values on a scope.
  25830. * </div>
  25831. *
  25832. * <div class="alert alert-warning">
  25833. * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
  25834. * sure you have parentheses to ensure correct operator precedence:
  25835. * <pre class="prettyprint">
  25836. * `<div ng-init="test1 = ($index | toString)"></div>`
  25837. * </pre>
  25838. * </div>
  25839. *
  25840. * @example
  25841. <example module="initExample" name="ng-init">
  25842. <file name="index.html">
  25843. <script>
  25844. angular.module('initExample', [])
  25845. .controller('ExampleController', ['$scope', function($scope) {
  25846. $scope.list = [['a', 'b'], ['c', 'd']];
  25847. }]);
  25848. </script>
  25849. <div ng-controller="ExampleController">
  25850. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  25851. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  25852. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  25853. </div>
  25854. </div>
  25855. </div>
  25856. </file>
  25857. <file name="protractor.js" type="protractor">
  25858. it('should alias index positions', function() {
  25859. var elements = element.all(by.css('.example-init'));
  25860. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  25861. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  25862. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  25863. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  25864. });
  25865. </file>
  25866. </example>
  25867. */
  25868. var ngInitDirective = ngDirective({
  25869. priority: 450,
  25870. compile: function() {
  25871. return {
  25872. pre: function(scope, element, attrs) {
  25873. scope.$eval(attrs.ngInit);
  25874. }
  25875. };
  25876. }
  25877. });
  25878. /**
  25879. * @ngdoc directive
  25880. * @name ngList
  25881. * @restrict A
  25882. * @priority 100
  25883. *
  25884. * @param {string=} ngList optional delimiter that should be used to split the value.
  25885. *
  25886. * @description
  25887. * Text input that converts between a delimited string and an array of strings. The default
  25888. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  25889. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  25890. *
  25891. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  25892. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  25893. * list item is respected. This implies that the user of the directive is responsible for
  25894. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  25895. * tab or newline character.
  25896. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  25897. * when joining the list items back together) and whitespace around each list item is stripped
  25898. * before it is added to the model.
  25899. *
  25900. * @example
  25901. * ### Validation
  25902. *
  25903. * <example name="ngList-directive" module="listExample">
  25904. * <file name="app.js">
  25905. * angular.module('listExample', [])
  25906. * .controller('ExampleController', ['$scope', function($scope) {
  25907. * $scope.names = ['morpheus', 'neo', 'trinity'];
  25908. * }]);
  25909. * </file>
  25910. * <file name="index.html">
  25911. * <form name="myForm" ng-controller="ExampleController">
  25912. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  25913. * <span role="alert">
  25914. * <span class="error" ng-show="myForm.namesInput.$error.required">
  25915. * Required!</span>
  25916. * </span>
  25917. * <br>
  25918. * <tt>names = {{names}}</tt><br/>
  25919. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  25920. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  25921. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  25922. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  25923. * </form>
  25924. * </file>
  25925. * <file name="protractor.js" type="protractor">
  25926. * var listInput = element(by.model('names'));
  25927. * var names = element(by.exactBinding('names'));
  25928. * var valid = element(by.binding('myForm.namesInput.$valid'));
  25929. * var error = element(by.css('span.error'));
  25930. *
  25931. * it('should initialize to model', function() {
  25932. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  25933. * expect(valid.getText()).toContain('true');
  25934. * expect(error.getCssValue('display')).toBe('none');
  25935. * });
  25936. *
  25937. * it('should be invalid if empty', function() {
  25938. * listInput.clear();
  25939. * listInput.sendKeys('');
  25940. *
  25941. * expect(names.getText()).toContain('');
  25942. * expect(valid.getText()).toContain('false');
  25943. * expect(error.getCssValue('display')).not.toBe('none');
  25944. * });
  25945. * </file>
  25946. * </example>
  25947. *
  25948. * @example
  25949. * ### Splitting on newline
  25950. *
  25951. * <example name="ngList-directive-newlines">
  25952. * <file name="index.html">
  25953. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  25954. * <pre>{{ list | json }}</pre>
  25955. * </file>
  25956. * <file name="protractor.js" type="protractor">
  25957. * it("should split the text by newlines", function() {
  25958. * var listInput = element(by.model('list'));
  25959. * var output = element(by.binding('list | json'));
  25960. * listInput.sendKeys('abc\ndef\nghi');
  25961. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  25962. * });
  25963. * </file>
  25964. * </example>
  25965. *
  25966. */
  25967. var ngListDirective = function() {
  25968. return {
  25969. restrict: 'A',
  25970. priority: 100,
  25971. require: 'ngModel',
  25972. link: function(scope, element, attr, ctrl) {
  25973. var ngList = attr.ngList || ', ';
  25974. var trimValues = attr.ngTrim !== 'false';
  25975. var separator = trimValues ? trim(ngList) : ngList;
  25976. var parse = function(viewValue) {
  25977. // If the viewValue is invalid (say required but empty) it will be `undefined`
  25978. if (isUndefined(viewValue)) return;
  25979. var list = [];
  25980. if (viewValue) {
  25981. forEach(viewValue.split(separator), function(value) {
  25982. if (value) list.push(trimValues ? trim(value) : value);
  25983. });
  25984. }
  25985. return list;
  25986. };
  25987. ctrl.$parsers.push(parse);
  25988. ctrl.$formatters.push(function(value) {
  25989. if (isArray(value)) {
  25990. return value.join(ngList);
  25991. }
  25992. return undefined;
  25993. });
  25994. // Override the standard $isEmpty because an empty array means the input is empty.
  25995. ctrl.$isEmpty = function(value) {
  25996. return !value || !value.length;
  25997. };
  25998. }
  25999. };
  26000. };
  26001. /* global VALID_CLASS: true,
  26002. INVALID_CLASS: true,
  26003. PRISTINE_CLASS: true,
  26004. DIRTY_CLASS: true,
  26005. UNTOUCHED_CLASS: true,
  26006. TOUCHED_CLASS: true,
  26007. PENDING_CLASS: true,
  26008. addSetValidityMethod: true,
  26009. setupValidity: true,
  26010. defaultModelOptions: false
  26011. */
  26012. var VALID_CLASS = 'ng-valid',
  26013. INVALID_CLASS = 'ng-invalid',
  26014. PRISTINE_CLASS = 'ng-pristine',
  26015. DIRTY_CLASS = 'ng-dirty',
  26016. UNTOUCHED_CLASS = 'ng-untouched',
  26017. TOUCHED_CLASS = 'ng-touched',
  26018. EMPTY_CLASS = 'ng-empty',
  26019. NOT_EMPTY_CLASS = 'ng-not-empty';
  26020. var ngModelMinErr = minErr('ngModel');
  26021. /**
  26022. * @ngdoc type
  26023. * @name ngModel.NgModelController
  26024. * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
  26025. * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
  26026. * is set.
  26027. *
  26028. * @property {*} $modelValue The value in the model that the control is bound to.
  26029. *
  26030. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  26031. * the control updates the ngModelController with a new {@link ngModel.NgModelController#$viewValue
  26032. `$viewValue`} from the DOM, usually via user input.
  26033. See {@link ngModel.NgModelController#$setViewValue `$setViewValue()`} for a detailed lifecycle explanation.
  26034. Note that the `$parsers` are not called when the bound ngModel expression changes programmatically.
  26035. The functions are called in array order, each passing
  26036. its return value through to the next. The last return value is forwarded to the
  26037. {@link ngModel.NgModelController#$validators `$validators`} collection.
  26038. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  26039. `$viewValue`}.
  26040. Returning `undefined` from a parser means a parse error occurred. In that case,
  26041. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  26042. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  26043. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  26044. This simple example shows a parser that would convert text input value to lowercase:
  26045. * ```js
  26046. * function parse(value) {
  26047. * if (value) {
  26048. * return value.toLowerCase();
  26049. * }
  26050. * }
  26051. * ngModelController.$parsers.push(parse);
  26052. * ```
  26053. *
  26054. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  26055. the bound ngModel expression changes programmatically. The `$formatters` are not called when the
  26056. value of the control is changed by user interaction.
  26057. Formatters are used to format / convert the {@link ngModel.NgModelController#$modelValue
  26058. `$modelValue`} for display in the control.
  26059. The functions are called in reverse array order, each passing the value through to the
  26060. next. The last return value is used as the actual DOM value.
  26061. This simple example shows a formatter that would convert the model value to uppercase:
  26062. * ```js
  26063. * function format(value) {
  26064. * if (value) {
  26065. * return value.toUpperCase();
  26066. * }
  26067. * }
  26068. * ngModel.$formatters.push(format);
  26069. * ```
  26070. *
  26071. * @property {Object.<string, function>} $validators A collection of validators that are applied
  26072. * whenever the model value changes. The key value within the object refers to the name of the
  26073. * validator while the function refers to the validation operation. The validation operation is
  26074. * provided with the model value as an argument and must return a true or false value depending
  26075. * on the response of that validation.
  26076. *
  26077. * ```js
  26078. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  26079. * var value = modelValue || viewValue;
  26080. * return /[0-9]+/.test(value) &&
  26081. * /[a-z]+/.test(value) &&
  26082. * /[A-Z]+/.test(value) &&
  26083. * /\W+/.test(value);
  26084. * };
  26085. * ```
  26086. *
  26087. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  26088. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  26089. * is expected to return a promise when it is run during the model validation process. Once the promise
  26090. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  26091. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  26092. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  26093. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  26094. * will only run once all synchronous validators have passed.
  26095. *
  26096. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  26097. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  26098. *
  26099. * ```js
  26100. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  26101. * var value = modelValue || viewValue;
  26102. *
  26103. * // Lookup user by username
  26104. * return $http.get('/api/users/' + value).
  26105. * then(function resolved() {
  26106. * //username exists, this means validation fails
  26107. * return $q.reject('exists');
  26108. * }, function rejected() {
  26109. * //username does not exist, therefore this validation passes
  26110. * return true;
  26111. * });
  26112. * };
  26113. * ```
  26114. *
  26115. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  26116. * view value has changed. It is called with no arguments, and its return value is ignored.
  26117. * This can be used in place of additional $watches against the model value.
  26118. *
  26119. * @property {Object} $error An object hash with all failing validator ids as keys.
  26120. * @property {Object} $pending An object hash with all pending validator ids as keys.
  26121. *
  26122. * @property {boolean} $untouched True if control has not lost focus yet.
  26123. * @property {boolean} $touched True if control has lost focus.
  26124. * @property {boolean} $pristine True if user has not interacted with the control yet.
  26125. * @property {boolean} $dirty True if user has already interacted with the control.
  26126. * @property {boolean} $valid True if there is no error.
  26127. * @property {boolean} $invalid True if at least one error on the control.
  26128. * @property {string} $name The name attribute of the control.
  26129. *
  26130. * @description
  26131. *
  26132. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  26133. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  26134. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  26135. * listening to DOM events.
  26136. * Such DOM related logic should be provided by other directives which make use of
  26137. * `NgModelController` for data-binding to control elements.
  26138. * Angular provides this DOM logic for most {@link input `input`} elements.
  26139. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  26140. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  26141. *
  26142. * @example
  26143. * ### Custom Control Example
  26144. * This example shows how to use `NgModelController` with a custom control to achieve
  26145. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  26146. * collaborate together to achieve the desired result.
  26147. *
  26148. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  26149. * contents be edited in place by the user.
  26150. *
  26151. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  26152. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  26153. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  26154. * that content using the `$sce` service.
  26155. *
  26156. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  26157. <file name="style.css">
  26158. [contenteditable] {
  26159. border: 1px solid black;
  26160. background-color: white;
  26161. min-height: 20px;
  26162. }
  26163. .ng-invalid {
  26164. border: 1px solid red;
  26165. }
  26166. </file>
  26167. <file name="script.js">
  26168. angular.module('customControl', ['ngSanitize']).
  26169. directive('contenteditable', ['$sce', function($sce) {
  26170. return {
  26171. restrict: 'A', // only activate on element attribute
  26172. require: '?ngModel', // get a hold of NgModelController
  26173. link: function(scope, element, attrs, ngModel) {
  26174. if (!ngModel) return; // do nothing if no ng-model
  26175. // Specify how UI should be updated
  26176. ngModel.$render = function() {
  26177. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  26178. };
  26179. // Listen for change events to enable binding
  26180. element.on('blur keyup change', function() {
  26181. scope.$evalAsync(read);
  26182. });
  26183. read(); // initialize
  26184. // Write data to the model
  26185. function read() {
  26186. var html = element.html();
  26187. // When we clear the content editable the browser leaves a <br> behind
  26188. // If strip-br attribute is provided then we strip this out
  26189. if (attrs.stripBr && html === '<br>') {
  26190. html = '';
  26191. }
  26192. ngModel.$setViewValue(html);
  26193. }
  26194. }
  26195. };
  26196. }]);
  26197. </file>
  26198. <file name="index.html">
  26199. <form name="myForm">
  26200. <div contenteditable
  26201. name="myWidget" ng-model="userContent"
  26202. strip-br="true"
  26203. required>Change me!</div>
  26204. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  26205. <hr>
  26206. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  26207. </form>
  26208. </file>
  26209. <file name="protractor.js" type="protractor">
  26210. it('should data-bind and become invalid', function() {
  26211. if (browser.params.browser === 'safari' || browser.params.browser === 'firefox') {
  26212. // SafariDriver can't handle contenteditable
  26213. // and Firefox driver can't clear contenteditables very well
  26214. return;
  26215. }
  26216. var contentEditable = element(by.css('[contenteditable]'));
  26217. var content = 'Change me!';
  26218. expect(contentEditable.getText()).toEqual(content);
  26219. contentEditable.clear();
  26220. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  26221. expect(contentEditable.getText()).toEqual('');
  26222. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  26223. });
  26224. </file>
  26225. * </example>
  26226. *
  26227. *
  26228. */
  26229. NgModelController.$inject = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$q', '$interpolate'];
  26230. function NgModelController($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $q, $interpolate) {
  26231. this.$viewValue = Number.NaN;
  26232. this.$modelValue = Number.NaN;
  26233. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  26234. this.$validators = {};
  26235. this.$asyncValidators = {};
  26236. this.$parsers = [];
  26237. this.$formatters = [];
  26238. this.$viewChangeListeners = [];
  26239. this.$untouched = true;
  26240. this.$touched = false;
  26241. this.$pristine = true;
  26242. this.$dirty = false;
  26243. this.$valid = true;
  26244. this.$invalid = false;
  26245. this.$error = {}; // keep invalid keys here
  26246. this.$$success = {}; // keep valid keys here
  26247. this.$pending = undefined; // keep pending keys here
  26248. this.$name = $interpolate($attr.name || '', false)($scope);
  26249. this.$$parentForm = nullFormCtrl;
  26250. this.$options = defaultModelOptions;
  26251. this.$$parsedNgModel = $parse($attr.ngModel);
  26252. this.$$parsedNgModelAssign = this.$$parsedNgModel.assign;
  26253. this.$$ngModelGet = this.$$parsedNgModel;
  26254. this.$$ngModelSet = this.$$parsedNgModelAssign;
  26255. this.$$pendingDebounce = null;
  26256. this.$$parserValid = undefined;
  26257. this.$$currentValidationRunId = 0;
  26258. // https://github.com/angular/angular.js/issues/15833
  26259. // Prevent `$$scope` from being iterated over by `copy` when NgModelController is deep watched
  26260. Object.defineProperty(this, '$$scope', {value: $scope});
  26261. this.$$attr = $attr;
  26262. this.$$element = $element;
  26263. this.$$animate = $animate;
  26264. this.$$timeout = $timeout;
  26265. this.$$parse = $parse;
  26266. this.$$q = $q;
  26267. this.$$exceptionHandler = $exceptionHandler;
  26268. setupValidity(this);
  26269. setupModelWatcher(this);
  26270. }
  26271. NgModelController.prototype = {
  26272. $$initGetterSetters: function() {
  26273. if (this.$options.getOption('getterSetter')) {
  26274. var invokeModelGetter = this.$$parse(this.$$attr.ngModel + '()'),
  26275. invokeModelSetter = this.$$parse(this.$$attr.ngModel + '($$$p)');
  26276. this.$$ngModelGet = function($scope) {
  26277. var modelValue = this.$$parsedNgModel($scope);
  26278. if (isFunction(modelValue)) {
  26279. modelValue = invokeModelGetter($scope);
  26280. }
  26281. return modelValue;
  26282. };
  26283. this.$$ngModelSet = function($scope, newValue) {
  26284. if (isFunction(this.$$parsedNgModel($scope))) {
  26285. invokeModelSetter($scope, {$$$p: newValue});
  26286. } else {
  26287. this.$$parsedNgModelAssign($scope, newValue);
  26288. }
  26289. };
  26290. } else if (!this.$$parsedNgModel.assign) {
  26291. throw ngModelMinErr('nonassign', 'Expression \'{0}\' is non-assignable. Element: {1}',
  26292. this.$$attr.ngModel, startingTag(this.$$element));
  26293. }
  26294. },
  26295. /**
  26296. * @ngdoc method
  26297. * @name ngModel.NgModelController#$render
  26298. *
  26299. * @description
  26300. * Called when the view needs to be updated. It is expected that the user of the ng-model
  26301. * directive will implement this method.
  26302. *
  26303. * The `$render()` method is invoked in the following situations:
  26304. *
  26305. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  26306. * committed value then `$render()` is called to update the input control.
  26307. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  26308. * the `$viewValue` are different from last time.
  26309. *
  26310. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  26311. * `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue`
  26312. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  26313. * invoked if you only change a property on the objects.
  26314. */
  26315. $render: noop,
  26316. /**
  26317. * @ngdoc method
  26318. * @name ngModel.NgModelController#$isEmpty
  26319. *
  26320. * @description
  26321. * This is called when we need to determine if the value of an input is empty.
  26322. *
  26323. * For instance, the required directive does this to work out if the input has data or not.
  26324. *
  26325. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  26326. *
  26327. * You can override this for input directives whose concept of being empty is different from the
  26328. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  26329. * implies empty.
  26330. *
  26331. * @param {*} value The value of the input to check for emptiness.
  26332. * @returns {boolean} True if `value` is "empty".
  26333. */
  26334. $isEmpty: function(value) {
  26335. // eslint-disable-next-line no-self-compare
  26336. return isUndefined(value) || value === '' || value === null || value !== value;
  26337. },
  26338. $$updateEmptyClasses: function(value) {
  26339. if (this.$isEmpty(value)) {
  26340. this.$$animate.removeClass(this.$$element, NOT_EMPTY_CLASS);
  26341. this.$$animate.addClass(this.$$element, EMPTY_CLASS);
  26342. } else {
  26343. this.$$animate.removeClass(this.$$element, EMPTY_CLASS);
  26344. this.$$animate.addClass(this.$$element, NOT_EMPTY_CLASS);
  26345. }
  26346. },
  26347. /**
  26348. * @ngdoc method
  26349. * @name ngModel.NgModelController#$setPristine
  26350. *
  26351. * @description
  26352. * Sets the control to its pristine state.
  26353. *
  26354. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  26355. * state (`ng-pristine` class). A model is considered to be pristine when the control
  26356. * has not been changed from when first compiled.
  26357. */
  26358. $setPristine: function() {
  26359. this.$dirty = false;
  26360. this.$pristine = true;
  26361. this.$$animate.removeClass(this.$$element, DIRTY_CLASS);
  26362. this.$$animate.addClass(this.$$element, PRISTINE_CLASS);
  26363. },
  26364. /**
  26365. * @ngdoc method
  26366. * @name ngModel.NgModelController#$setDirty
  26367. *
  26368. * @description
  26369. * Sets the control to its dirty state.
  26370. *
  26371. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  26372. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  26373. * from when first compiled.
  26374. */
  26375. $setDirty: function() {
  26376. this.$dirty = true;
  26377. this.$pristine = false;
  26378. this.$$animate.removeClass(this.$$element, PRISTINE_CLASS);
  26379. this.$$animate.addClass(this.$$element, DIRTY_CLASS);
  26380. this.$$parentForm.$setDirty();
  26381. },
  26382. /**
  26383. * @ngdoc method
  26384. * @name ngModel.NgModelController#$setUntouched
  26385. *
  26386. * @description
  26387. * Sets the control to its untouched state.
  26388. *
  26389. * This method can be called to remove the `ng-touched` class and set the control to its
  26390. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  26391. * by default, however this function can be used to restore that state if the model has
  26392. * already been touched by the user.
  26393. */
  26394. $setUntouched: function() {
  26395. this.$touched = false;
  26396. this.$untouched = true;
  26397. this.$$animate.setClass(this.$$element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  26398. },
  26399. /**
  26400. * @ngdoc method
  26401. * @name ngModel.NgModelController#$setTouched
  26402. *
  26403. * @description
  26404. * Sets the control to its touched state.
  26405. *
  26406. * This method can be called to remove the `ng-untouched` class and set the control to its
  26407. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  26408. * first focused the control element and then shifted focus away from the control (blur event).
  26409. */
  26410. $setTouched: function() {
  26411. this.$touched = true;
  26412. this.$untouched = false;
  26413. this.$$animate.setClass(this.$$element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  26414. },
  26415. /**
  26416. * @ngdoc method
  26417. * @name ngModel.NgModelController#$rollbackViewValue
  26418. *
  26419. * @description
  26420. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  26421. * which may be caused by a pending debounced event or because the input is waiting for some
  26422. * future event.
  26423. *
  26424. * If you have an input that uses `ng-model-options` to set up debounced updates or updates that
  26425. * depend on special events such as `blur`, there can be a period when the `$viewValue` is out of
  26426. * sync with the ngModel's `$modelValue`.
  26427. *
  26428. * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update
  26429. * and reset the input to the last committed view value.
  26430. *
  26431. * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`
  26432. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  26433. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  26434. *
  26435. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  26436. * input which may have such events pending. This is important in order to make sure that the
  26437. * input field will be updated with the new model value and any pending operations are cancelled.
  26438. *
  26439. * @example
  26440. * <example name="ng-model-cancel-update" module="cancel-update-example">
  26441. * <file name="app.js">
  26442. * angular.module('cancel-update-example', [])
  26443. *
  26444. * .controller('CancelUpdateController', ['$scope', function($scope) {
  26445. * $scope.model = {value1: '', value2: ''};
  26446. *
  26447. * $scope.setEmpty = function(e, value, rollback) {
  26448. * if (e.keyCode === 27) {
  26449. * e.preventDefault();
  26450. * if (rollback) {
  26451. * $scope.myForm[value].$rollbackViewValue();
  26452. * }
  26453. * $scope.model[value] = '';
  26454. * }
  26455. * };
  26456. * }]);
  26457. * </file>
  26458. * <file name="index.html">
  26459. * <div ng-controller="CancelUpdateController">
  26460. * <p>Both of these inputs are only updated if they are blurred. Hitting escape should
  26461. * empty them. Follow these steps and observe the difference:</p>
  26462. * <ol>
  26463. * <li>Type something in the input. You will see that the model is not yet updated</li>
  26464. * <li>Press the Escape key.
  26465. * <ol>
  26466. * <li> In the first example, nothing happens, because the model is already '', and no
  26467. * update is detected. If you blur the input, the model will be set to the current view.
  26468. * </li>
  26469. * <li> In the second example, the pending update is cancelled, and the input is set back
  26470. * to the last committed view value (''). Blurring the input does nothing.
  26471. * </li>
  26472. * </ol>
  26473. * </li>
  26474. * </ol>
  26475. *
  26476. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  26477. * <div>
  26478. * <p id="inputDescription1">Without $rollbackViewValue():</p>
  26479. * <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1"
  26480. * ng-keydown="setEmpty($event, 'value1')">
  26481. * value1: "{{ model.value1 }}"
  26482. * </div>
  26483. *
  26484. * <div>
  26485. * <p id="inputDescription2">With $rollbackViewValue():</p>
  26486. * <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2"
  26487. * ng-keydown="setEmpty($event, 'value2', true)">
  26488. * value2: "{{ model.value2 }}"
  26489. * </div>
  26490. * </form>
  26491. * </div>
  26492. * </file>
  26493. <file name="style.css">
  26494. div {
  26495. display: table-cell;
  26496. }
  26497. div:nth-child(1) {
  26498. padding-right: 30px;
  26499. }
  26500. </file>
  26501. * </example>
  26502. */
  26503. $rollbackViewValue: function() {
  26504. this.$$timeout.cancel(this.$$pendingDebounce);
  26505. this.$viewValue = this.$$lastCommittedViewValue;
  26506. this.$render();
  26507. },
  26508. /**
  26509. * @ngdoc method
  26510. * @name ngModel.NgModelController#$validate
  26511. *
  26512. * @description
  26513. * Runs each of the registered validators (first synchronous validators and then
  26514. * asynchronous validators).
  26515. * If the validity changes to invalid, the model will be set to `undefined`,
  26516. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  26517. * If the validity changes to valid, it will set the model to the last available valid
  26518. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  26519. */
  26520. $validate: function() {
  26521. // ignore $validate before model is initialized
  26522. if (isNumberNaN(this.$modelValue)) {
  26523. return;
  26524. }
  26525. var viewValue = this.$$lastCommittedViewValue;
  26526. // Note: we use the $$rawModelValue as $modelValue might have been
  26527. // set to undefined during a view -> model update that found validation
  26528. // errors. We can't parse the view here, since that could change
  26529. // the model although neither viewValue nor the model on the scope changed
  26530. var modelValue = this.$$rawModelValue;
  26531. var prevValid = this.$valid;
  26532. var prevModelValue = this.$modelValue;
  26533. var allowInvalid = this.$options.getOption('allowInvalid');
  26534. var that = this;
  26535. this.$$runValidators(modelValue, viewValue, function(allValid) {
  26536. // If there was no change in validity, don't update the model
  26537. // This prevents changing an invalid modelValue to undefined
  26538. if (!allowInvalid && prevValid !== allValid) {
  26539. // Note: Don't check this.$valid here, as we could have
  26540. // external validators (e.g. calculated on the server),
  26541. // that just call $setValidity and need the model value
  26542. // to calculate their validity.
  26543. that.$modelValue = allValid ? modelValue : undefined;
  26544. if (that.$modelValue !== prevModelValue) {
  26545. that.$$writeModelToScope();
  26546. }
  26547. }
  26548. });
  26549. },
  26550. $$runValidators: function(modelValue, viewValue, doneCallback) {
  26551. this.$$currentValidationRunId++;
  26552. var localValidationRunId = this.$$currentValidationRunId;
  26553. var that = this;
  26554. // check parser error
  26555. if (!processParseErrors()) {
  26556. validationDone(false);
  26557. return;
  26558. }
  26559. if (!processSyncValidators()) {
  26560. validationDone(false);
  26561. return;
  26562. }
  26563. processAsyncValidators();
  26564. function processParseErrors() {
  26565. var errorKey = that.$$parserName || 'parse';
  26566. if (isUndefined(that.$$parserValid)) {
  26567. setValidity(errorKey, null);
  26568. } else {
  26569. if (!that.$$parserValid) {
  26570. forEach(that.$validators, function(v, name) {
  26571. setValidity(name, null);
  26572. });
  26573. forEach(that.$asyncValidators, function(v, name) {
  26574. setValidity(name, null);
  26575. });
  26576. }
  26577. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  26578. setValidity(errorKey, that.$$parserValid);
  26579. return that.$$parserValid;
  26580. }
  26581. return true;
  26582. }
  26583. function processSyncValidators() {
  26584. var syncValidatorsValid = true;
  26585. forEach(that.$validators, function(validator, name) {
  26586. var result = Boolean(validator(modelValue, viewValue));
  26587. syncValidatorsValid = syncValidatorsValid && result;
  26588. setValidity(name, result);
  26589. });
  26590. if (!syncValidatorsValid) {
  26591. forEach(that.$asyncValidators, function(v, name) {
  26592. setValidity(name, null);
  26593. });
  26594. return false;
  26595. }
  26596. return true;
  26597. }
  26598. function processAsyncValidators() {
  26599. var validatorPromises = [];
  26600. var allValid = true;
  26601. forEach(that.$asyncValidators, function(validator, name) {
  26602. var promise = validator(modelValue, viewValue);
  26603. if (!isPromiseLike(promise)) {
  26604. throw ngModelMinErr('nopromise',
  26605. 'Expected asynchronous validator to return a promise but got \'{0}\' instead.', promise);
  26606. }
  26607. setValidity(name, undefined);
  26608. validatorPromises.push(promise.then(function() {
  26609. setValidity(name, true);
  26610. }, function() {
  26611. allValid = false;
  26612. setValidity(name, false);
  26613. }));
  26614. });
  26615. if (!validatorPromises.length) {
  26616. validationDone(true);
  26617. } else {
  26618. that.$$q.all(validatorPromises).then(function() {
  26619. validationDone(allValid);
  26620. }, noop);
  26621. }
  26622. }
  26623. function setValidity(name, isValid) {
  26624. if (localValidationRunId === that.$$currentValidationRunId) {
  26625. that.$setValidity(name, isValid);
  26626. }
  26627. }
  26628. function validationDone(allValid) {
  26629. if (localValidationRunId === that.$$currentValidationRunId) {
  26630. doneCallback(allValid);
  26631. }
  26632. }
  26633. },
  26634. /**
  26635. * @ngdoc method
  26636. * @name ngModel.NgModelController#$commitViewValue
  26637. *
  26638. * @description
  26639. * Commit a pending update to the `$modelValue`.
  26640. *
  26641. * Updates may be pending by a debounced event or because the input is waiting for a some future
  26642. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  26643. * usually handles calling this in response to input events.
  26644. */
  26645. $commitViewValue: function() {
  26646. var viewValue = this.$viewValue;
  26647. this.$$timeout.cancel(this.$$pendingDebounce);
  26648. // If the view value has not changed then we should just exit, except in the case where there is
  26649. // a native validator on the element. In this case the validation state may have changed even though
  26650. // the viewValue has stayed empty.
  26651. if (this.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !this.$$hasNativeValidators)) {
  26652. return;
  26653. }
  26654. this.$$updateEmptyClasses(viewValue);
  26655. this.$$lastCommittedViewValue = viewValue;
  26656. // change to dirty
  26657. if (this.$pristine) {
  26658. this.$setDirty();
  26659. }
  26660. this.$$parseAndValidate();
  26661. },
  26662. $$parseAndValidate: function() {
  26663. var viewValue = this.$$lastCommittedViewValue;
  26664. var modelValue = viewValue;
  26665. var that = this;
  26666. this.$$parserValid = isUndefined(modelValue) ? undefined : true;
  26667. if (this.$$parserValid) {
  26668. for (var i = 0; i < this.$parsers.length; i++) {
  26669. modelValue = this.$parsers[i](modelValue);
  26670. if (isUndefined(modelValue)) {
  26671. this.$$parserValid = false;
  26672. break;
  26673. }
  26674. }
  26675. }
  26676. if (isNumberNaN(this.$modelValue)) {
  26677. // this.$modelValue has not been touched yet...
  26678. this.$modelValue = this.$$ngModelGet(this.$$scope);
  26679. }
  26680. var prevModelValue = this.$modelValue;
  26681. var allowInvalid = this.$options.getOption('allowInvalid');
  26682. this.$$rawModelValue = modelValue;
  26683. if (allowInvalid) {
  26684. this.$modelValue = modelValue;
  26685. writeToModelIfNeeded();
  26686. }
  26687. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  26688. // This can happen if e.g. $setViewValue is called from inside a parser
  26689. this.$$runValidators(modelValue, this.$$lastCommittedViewValue, function(allValid) {
  26690. if (!allowInvalid) {
  26691. // Note: Don't check this.$valid here, as we could have
  26692. // external validators (e.g. calculated on the server),
  26693. // that just call $setValidity and need the model value
  26694. // to calculate their validity.
  26695. that.$modelValue = allValid ? modelValue : undefined;
  26696. writeToModelIfNeeded();
  26697. }
  26698. });
  26699. function writeToModelIfNeeded() {
  26700. if (that.$modelValue !== prevModelValue) {
  26701. that.$$writeModelToScope();
  26702. }
  26703. }
  26704. },
  26705. $$writeModelToScope: function() {
  26706. this.$$ngModelSet(this.$$scope, this.$modelValue);
  26707. forEach(this.$viewChangeListeners, function(listener) {
  26708. try {
  26709. listener();
  26710. } catch (e) {
  26711. // eslint-disable-next-line no-invalid-this
  26712. this.$$exceptionHandler(e);
  26713. }
  26714. }, this);
  26715. },
  26716. /**
  26717. * @ngdoc method
  26718. * @name ngModel.NgModelController#$setViewValue
  26719. *
  26720. * @description
  26721. * Update the view value.
  26722. *
  26723. * This method should be called when a control wants to change the view value; typically,
  26724. * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
  26725. * directive calls it when the value of the input changes and {@link ng.directive:select select}
  26726. * calls it when an option is selected.
  26727. *
  26728. * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
  26729. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  26730. * value is sent directly for processing through the `$parsers` pipeline. After this, the `$validators` and
  26731. * `$asyncValidators` are called and the value is applied to `$modelValue`.
  26732. * Finally, the value is set to the **expression** specified in the `ng-model` attribute and
  26733. * all the registered change listeners, in the `$viewChangeListeners` list are called.
  26734. *
  26735. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  26736. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  26737. * `updateOn` events is triggered on the DOM element.
  26738. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  26739. * directive is used with a custom debounce for this particular event.
  26740. * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
  26741. * is specified, once the timer runs out.
  26742. *
  26743. * When used with standard inputs, the view value will always be a string (which is in some cases
  26744. * parsed into another type, such as a `Date` object for `input[date]`.)
  26745. * However, custom controls might also pass objects to this method. In this case, we should make
  26746. * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
  26747. * perform a deep watch of objects, it only looks for a change of identity. If you only change
  26748. * the property of the object then ngModel will not realize that the object has changed and
  26749. * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
  26750. * not change properties of the copy once it has been passed to `$setViewValue`.
  26751. * Otherwise you may cause the model value on the scope to change incorrectly.
  26752. *
  26753. * <div class="alert alert-info">
  26754. * In any case, the value passed to the method should always reflect the current value
  26755. * of the control. For example, if you are calling `$setViewValue` for an input element,
  26756. * you should pass the input DOM value. Otherwise, the control and the scope model become
  26757. * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
  26758. * the control's DOM value in any way. If we want to change the control's DOM value
  26759. * programmatically, we should update the `ngModel` scope expression. Its new value will be
  26760. * picked up by the model controller, which will run it through the `$formatters`, `$render` it
  26761. * to update the DOM, and finally call `$validate` on it.
  26762. * </div>
  26763. *
  26764. * @param {*} value value from the view.
  26765. * @param {string} trigger Event that triggered the update.
  26766. */
  26767. $setViewValue: function(value, trigger) {
  26768. this.$viewValue = value;
  26769. if (this.$options.getOption('updateOnDefault')) {
  26770. this.$$debounceViewValueCommit(trigger);
  26771. }
  26772. },
  26773. $$debounceViewValueCommit: function(trigger) {
  26774. var debounceDelay = this.$options.getOption('debounce');
  26775. if (isNumber(debounceDelay[trigger])) {
  26776. debounceDelay = debounceDelay[trigger];
  26777. } else if (isNumber(debounceDelay['default'])) {
  26778. debounceDelay = debounceDelay['default'];
  26779. }
  26780. this.$$timeout.cancel(this.$$pendingDebounce);
  26781. var that = this;
  26782. if (debounceDelay > 0) { // this fails if debounceDelay is an object
  26783. this.$$pendingDebounce = this.$$timeout(function() {
  26784. that.$commitViewValue();
  26785. }, debounceDelay);
  26786. } else if (this.$$scope.$root.$$phase) {
  26787. this.$commitViewValue();
  26788. } else {
  26789. this.$$scope.$apply(function() {
  26790. that.$commitViewValue();
  26791. });
  26792. }
  26793. },
  26794. /**
  26795. * @ngdoc method
  26796. *
  26797. * @name ngModel.NgModelController#$overrideModelOptions
  26798. *
  26799. * @description
  26800. *
  26801. * Override the current model options settings programmatically.
  26802. *
  26803. * The previous `ModelOptions` value will not be modified. Instead, a
  26804. * new `ModelOptions` object will inherit from the previous one overriding
  26805. * or inheriting settings that are defined in the given parameter.
  26806. *
  26807. * See {@link ngModelOptions} for information about what options can be specified
  26808. * and how model option inheritance works.
  26809. *
  26810. * @param {Object} options a hash of settings to override the previous options
  26811. *
  26812. */
  26813. $overrideModelOptions: function(options) {
  26814. this.$options = this.$options.createChild(options);
  26815. },
  26816. /**
  26817. * @ngdoc method
  26818. *
  26819. * @name ngModel.NgModelController#$processModelValue
  26820. * @description
  26821. *
  26822. * Runs the model -> view pipeline on the current
  26823. * {@link ngModel.NgModelController#$modelValue $modelValue}.
  26824. *
  26825. * The following actions are performed by this method:
  26826. *
  26827. * - the `$modelValue` is run through the {@link ngModel.NgModelController#$formatters $formatters}
  26828. * and the result is set to the {@link ngModel.NgModelController#$viewValue $viewValue}
  26829. * - the `ng-empty` or `ng-not-empty` class is set on the element
  26830. * - if the `$viewValue` has changed:
  26831. * - {@link ngModel.NgModelController#$render $render} is called on the control
  26832. * - the {@link ngModel.NgModelController#$validators $validators} are run and
  26833. * the validation status is set.
  26834. *
  26835. * This method is called by ngModel internally when the bound scope value changes.
  26836. * Application developers usually do not have to call this function themselves.
  26837. *
  26838. * This function can be used when the `$viewValue` or the rendered DOM value are not correctly
  26839. * formatted and the `$modelValue` must be run through the `$formatters` again.
  26840. *
  26841. * @example
  26842. * Consider a text input with an autocomplete list (for fruit), where the items are
  26843. * objects with a name and an id.
  26844. * A user enters `ap` and then selects `Apricot` from the list.
  26845. * Based on this, the autocomplete widget will call `$setViewValue({name: 'Apricot', id: 443})`,
  26846. * but the rendered value will still be `ap`.
  26847. * The widget can then call `ctrl.$processModelValue()` to run the model -> view
  26848. * pipeline again, which formats the object to the string `Apricot`,
  26849. * then updates the `$viewValue`, and finally renders it in the DOM.
  26850. *
  26851. * <example module="inputExample" name="ng-model-process">
  26852. <file name="index.html">
  26853. <div ng-controller="inputController" style="display: flex;">
  26854. <div style="margin-right: 30px;">
  26855. Search Fruit:
  26856. <basic-autocomplete items="items" on-select="selectedFruit = item"></basic-autocomplete>
  26857. </div>
  26858. <div>
  26859. Model:<br>
  26860. <pre>{{selectedFruit | json}}</pre>
  26861. </div>
  26862. </div>
  26863. </file>
  26864. <file name="app.js">
  26865. angular.module('inputExample', [])
  26866. .controller('inputController', function($scope) {
  26867. $scope.items = [
  26868. {name: 'Apricot', id: 443},
  26869. {name: 'Clementine', id: 972},
  26870. {name: 'Durian', id: 169},
  26871. {name: 'Jackfruit', id: 982},
  26872. {name: 'Strawberry', id: 863}
  26873. ];
  26874. })
  26875. .component('basicAutocomplete', {
  26876. bindings: {
  26877. items: '<',
  26878. onSelect: '&'
  26879. },
  26880. templateUrl: 'autocomplete.html',
  26881. controller: function($element, $scope) {
  26882. var that = this;
  26883. var ngModel;
  26884. that.$postLink = function() {
  26885. ngModel = $element.find('input').controller('ngModel');
  26886. ngModel.$formatters.push(function(value) {
  26887. return (value && value.name) || value;
  26888. });
  26889. ngModel.$parsers.push(function(value) {
  26890. var match = value;
  26891. for (var i = 0; i < that.items.length; i++) {
  26892. if (that.items[i].name === value) {
  26893. match = that.items[i];
  26894. break;
  26895. }
  26896. }
  26897. return match;
  26898. });
  26899. };
  26900. that.selectItem = function(item) {
  26901. ngModel.$setViewValue(item);
  26902. ngModel.$processModelValue();
  26903. that.onSelect({item: item});
  26904. };
  26905. }
  26906. });
  26907. </file>
  26908. <file name="autocomplete.html">
  26909. <div>
  26910. <input type="search" ng-model="$ctrl.searchTerm" />
  26911. <ul>
  26912. <li ng-repeat="item in $ctrl.items | filter:$ctrl.searchTerm">
  26913. <button ng-click="$ctrl.selectItem(item)">{{ item.name }}</button>
  26914. </li>
  26915. </ul>
  26916. </div>
  26917. </file>
  26918. * </example>
  26919. *
  26920. */
  26921. $processModelValue: function() {
  26922. var viewValue = this.$$format();
  26923. if (this.$viewValue !== viewValue) {
  26924. this.$$updateEmptyClasses(viewValue);
  26925. this.$viewValue = this.$$lastCommittedViewValue = viewValue;
  26926. this.$render();
  26927. // It is possible that model and view value have been updated during render
  26928. this.$$runValidators(this.$modelValue, this.$viewValue, noop);
  26929. }
  26930. },
  26931. /**
  26932. * This method is called internally to run the $formatters on the $modelValue
  26933. */
  26934. $$format: function() {
  26935. var formatters = this.$formatters,
  26936. idx = formatters.length;
  26937. var viewValue = this.$modelValue;
  26938. while (idx--) {
  26939. viewValue = formatters[idx](viewValue);
  26940. }
  26941. return viewValue;
  26942. },
  26943. /**
  26944. * This method is called internally when the bound scope value changes.
  26945. */
  26946. $$setModelValue: function(modelValue) {
  26947. this.$modelValue = this.$$rawModelValue = modelValue;
  26948. this.$$parserValid = undefined;
  26949. this.$processModelValue();
  26950. }
  26951. };
  26952. function setupModelWatcher(ctrl) {
  26953. // model -> value
  26954. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  26955. // 1. scope value is 'a'
  26956. // 2. user enters 'b'
  26957. // 3. ng-change kicks in and reverts scope value to 'a'
  26958. // -> scope value did not change since the last digest as
  26959. // ng-change executes in apply phase
  26960. // 4. view should be changed back to 'a'
  26961. ctrl.$$scope.$watch(function ngModelWatch(scope) {
  26962. var modelValue = ctrl.$$ngModelGet(scope);
  26963. // if scope model value and ngModel value are out of sync
  26964. // This cannot be moved to the action function, because it would not catch the
  26965. // case where the model is changed in the ngChange function or the model setter
  26966. if (modelValue !== ctrl.$modelValue &&
  26967. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  26968. // eslint-disable-next-line no-self-compare
  26969. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  26970. ) {
  26971. ctrl.$$setModelValue(modelValue);
  26972. }
  26973. return modelValue;
  26974. });
  26975. }
  26976. /**
  26977. * @ngdoc method
  26978. * @name ngModel.NgModelController#$setValidity
  26979. *
  26980. * @description
  26981. * Change the validity state, and notify the form.
  26982. *
  26983. * This method can be called within $parsers/$formatters or a custom validation implementation.
  26984. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  26985. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  26986. *
  26987. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  26988. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  26989. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  26990. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  26991. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  26992. * classes and can be bound to as `{{ someForm.someControl.$error.myError }}`.
  26993. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  26994. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  26995. * Skipped is used by Angular when validators do not run because of parse errors and
  26996. * when `$asyncValidators` do not run because any of the `$validators` failed.
  26997. */
  26998. addSetValidityMethod({
  26999. clazz: NgModelController,
  27000. set: function(object, property) {
  27001. object[property] = true;
  27002. },
  27003. unset: function(object, property) {
  27004. delete object[property];
  27005. }
  27006. });
  27007. /**
  27008. * @ngdoc directive
  27009. * @name ngModel
  27010. * @restrict A
  27011. * @priority 1
  27012. * @param {expression} ngModel assignable {@link guide/expression Expression} to bind to.
  27013. *
  27014. * @description
  27015. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  27016. * property on the scope using {@link ngModel.NgModelController NgModelController},
  27017. * which is created and exposed by this directive.
  27018. *
  27019. * `ngModel` is responsible for:
  27020. *
  27021. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  27022. * require.
  27023. * - Providing validation behavior (i.e. required, number, email, url).
  27024. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  27025. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
  27026. * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
  27027. * - Registering the control with its parent {@link ng.directive:form form}.
  27028. *
  27029. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  27030. * current scope. If the property doesn't already exist on this scope, it will be created
  27031. * implicitly and added to the scope.
  27032. *
  27033. * For best practices on using `ngModel`, see:
  27034. *
  27035. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  27036. *
  27037. * For basic examples, how to use `ngModel`, see:
  27038. *
  27039. * - {@link ng.directive:input input}
  27040. * - {@link input[text] text}
  27041. * - {@link input[checkbox] checkbox}
  27042. * - {@link input[radio] radio}
  27043. * - {@link input[number] number}
  27044. * - {@link input[email] email}
  27045. * - {@link input[url] url}
  27046. * - {@link input[date] date}
  27047. * - {@link input[datetime-local] datetime-local}
  27048. * - {@link input[time] time}
  27049. * - {@link input[month] month}
  27050. * - {@link input[week] week}
  27051. * - {@link ng.directive:select select}
  27052. * - {@link ng.directive:textarea textarea}
  27053. *
  27054. * ## Complex Models (objects or collections)
  27055. *
  27056. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  27057. * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the
  27058. * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered.
  27059. *
  27060. * The model must be assigned an entirely new object or collection before a re-rendering will occur.
  27061. *
  27062. * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression
  27063. * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or
  27064. * if the select is given the `multiple` attribute.
  27065. *
  27066. * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the
  27067. * first level of the object (or only changing the properties of an item in the collection if it's an array) will still
  27068. * not trigger a re-rendering of the model.
  27069. *
  27070. * ## CSS classes
  27071. * The following CSS classes are added and removed on the associated input/select/textarea element
  27072. * depending on the validity of the model.
  27073. *
  27074. * - `ng-valid`: the model is valid
  27075. * - `ng-invalid`: the model is invalid
  27076. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  27077. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  27078. * - `ng-pristine`: the control hasn't been interacted with yet
  27079. * - `ng-dirty`: the control has been interacted with
  27080. * - `ng-touched`: the control has been blurred
  27081. * - `ng-untouched`: the control hasn't been blurred
  27082. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  27083. * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
  27084. * by the {@link ngModel.NgModelController#$isEmpty} method
  27085. * - `ng-not-empty`: the view contains a non-empty value
  27086. *
  27087. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  27088. *
  27089. * @animations
  27090. * Animations within models are triggered when any of the associated CSS classes are added and removed
  27091. * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
  27092. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  27093. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  27094. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  27095. *
  27096. * The following example shows a simple way to utilize CSS transitions to style an input element
  27097. * that has been rendered as invalid after it has been validated:
  27098. *
  27099. * <pre>
  27100. * //be sure to include ngAnimate as a module to hook into more
  27101. * //advanced animations
  27102. * .my-input {
  27103. * transition:0.5s linear all;
  27104. * background: white;
  27105. * }
  27106. * .my-input.ng-invalid {
  27107. * background: red;
  27108. * color:white;
  27109. * }
  27110. * </pre>
  27111. *
  27112. * @example
  27113. * ### Basic Usage
  27114. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample" name="ng-model">
  27115. <file name="index.html">
  27116. <script>
  27117. angular.module('inputExample', [])
  27118. .controller('ExampleController', ['$scope', function($scope) {
  27119. $scope.val = '1';
  27120. }]);
  27121. </script>
  27122. <style>
  27123. .my-input {
  27124. transition:all linear 0.5s;
  27125. background: transparent;
  27126. }
  27127. .my-input.ng-invalid {
  27128. color:white;
  27129. background: red;
  27130. }
  27131. </style>
  27132. <p id="inputDescription">
  27133. Update input to see transitions when valid/invalid.
  27134. Integer is a valid value.
  27135. </p>
  27136. <form name="testForm" ng-controller="ExampleController">
  27137. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  27138. aria-describedby="inputDescription" />
  27139. </form>
  27140. </file>
  27141. * </example>
  27142. *
  27143. * @example
  27144. * ### Binding to a getter/setter
  27145. *
  27146. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  27147. * function that returns a representation of the model when called with zero arguments, and sets
  27148. * the internal state of a model when called with an argument. It's sometimes useful to use this
  27149. * for models that have an internal representation that's different from what the model exposes
  27150. * to the view.
  27151. *
  27152. * <div class="alert alert-success">
  27153. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  27154. * frequently than other parts of your code.
  27155. * </div>
  27156. *
  27157. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  27158. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  27159. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  27160. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  27161. *
  27162. * The following example shows how to use `ngModel` with a getter/setter:
  27163. *
  27164. * @example
  27165. * <example name="ngModel-getter-setter" module="getterSetterExample">
  27166. <file name="index.html">
  27167. <div ng-controller="ExampleController">
  27168. <form name="userForm">
  27169. <label>Name:
  27170. <input type="text" name="userName"
  27171. ng-model="user.name"
  27172. ng-model-options="{ getterSetter: true }" />
  27173. </label>
  27174. </form>
  27175. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  27176. </div>
  27177. </file>
  27178. <file name="app.js">
  27179. angular.module('getterSetterExample', [])
  27180. .controller('ExampleController', ['$scope', function($scope) {
  27181. var _name = 'Brian';
  27182. $scope.user = {
  27183. name: function(newName) {
  27184. // Note that newName can be undefined for two reasons:
  27185. // 1. Because it is called as a getter and thus called with no arguments
  27186. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  27187. // input is invalid
  27188. return arguments.length ? (_name = newName) : _name;
  27189. }
  27190. };
  27191. }]);
  27192. </file>
  27193. * </example>
  27194. */
  27195. var ngModelDirective = ['$rootScope', function($rootScope) {
  27196. return {
  27197. restrict: 'A',
  27198. require: ['ngModel', '^?form', '^?ngModelOptions'],
  27199. controller: NgModelController,
  27200. // Prelink needs to run before any input directive
  27201. // so that we can set the NgModelOptions in NgModelController
  27202. // before anyone else uses it.
  27203. priority: 1,
  27204. compile: function ngModelCompile(element) {
  27205. // Setup initial state of the control
  27206. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  27207. return {
  27208. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  27209. var modelCtrl = ctrls[0],
  27210. formCtrl = ctrls[1] || modelCtrl.$$parentForm,
  27211. optionsCtrl = ctrls[2];
  27212. if (optionsCtrl) {
  27213. modelCtrl.$options = optionsCtrl.$options;
  27214. }
  27215. modelCtrl.$$initGetterSetters();
  27216. // notify others, especially parent forms
  27217. formCtrl.$addControl(modelCtrl);
  27218. attr.$observe('name', function(newValue) {
  27219. if (modelCtrl.$name !== newValue) {
  27220. modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
  27221. }
  27222. });
  27223. scope.$on('$destroy', function() {
  27224. modelCtrl.$$parentForm.$removeControl(modelCtrl);
  27225. });
  27226. },
  27227. post: function ngModelPostLink(scope, element, attr, ctrls) {
  27228. var modelCtrl = ctrls[0];
  27229. if (modelCtrl.$options.getOption('updateOn')) {
  27230. element.on(modelCtrl.$options.getOption('updateOn'), function(ev) {
  27231. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  27232. });
  27233. }
  27234. function setTouched() {
  27235. modelCtrl.$setTouched();
  27236. }
  27237. element.on('blur', function() {
  27238. if (modelCtrl.$touched) return;
  27239. if ($rootScope.$$phase) {
  27240. scope.$evalAsync(setTouched);
  27241. } else {
  27242. scope.$apply(setTouched);
  27243. }
  27244. });
  27245. }
  27246. };
  27247. }
  27248. };
  27249. }];
  27250. /* exported defaultModelOptions */
  27251. var defaultModelOptions;
  27252. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  27253. /**
  27254. * @ngdoc type
  27255. * @name ModelOptions
  27256. * @description
  27257. * A container for the options set by the {@link ngModelOptions} directive
  27258. */
  27259. function ModelOptions(options) {
  27260. this.$$options = options;
  27261. }
  27262. ModelOptions.prototype = {
  27263. /**
  27264. * @ngdoc method
  27265. * @name ModelOptions#getOption
  27266. * @param {string} name the name of the option to retrieve
  27267. * @returns {*} the value of the option
  27268. * @description
  27269. * Returns the value of the given option
  27270. */
  27271. getOption: function(name) {
  27272. return this.$$options[name];
  27273. },
  27274. /**
  27275. * @ngdoc method
  27276. * @name ModelOptions#createChild
  27277. * @param {Object} options a hash of options for the new child that will override the parent's options
  27278. * @return {ModelOptions} a new `ModelOptions` object initialized with the given options.
  27279. */
  27280. createChild: function(options) {
  27281. var inheritAll = false;
  27282. // make a shallow copy
  27283. options = extend({}, options);
  27284. // Inherit options from the parent if specified by the value `"$inherit"`
  27285. forEach(options, /* @this */ function(option, key) {
  27286. if (option === '$inherit') {
  27287. if (key === '*') {
  27288. inheritAll = true;
  27289. } else {
  27290. options[key] = this.$$options[key];
  27291. // `updateOn` is special so we must also inherit the `updateOnDefault` option
  27292. if (key === 'updateOn') {
  27293. options.updateOnDefault = this.$$options.updateOnDefault;
  27294. }
  27295. }
  27296. } else {
  27297. if (key === 'updateOn') {
  27298. // If the `updateOn` property contains the `default` event then we have to remove
  27299. // it from the event list and set the `updateOnDefault` flag.
  27300. options.updateOnDefault = false;
  27301. options[key] = trim(option.replace(DEFAULT_REGEXP, function() {
  27302. options.updateOnDefault = true;
  27303. return ' ';
  27304. }));
  27305. }
  27306. }
  27307. }, this);
  27308. if (inheritAll) {
  27309. // We have a property of the form: `"*": "$inherit"`
  27310. delete options['*'];
  27311. defaults(options, this.$$options);
  27312. }
  27313. // Finally add in any missing defaults
  27314. defaults(options, defaultModelOptions.$$options);
  27315. return new ModelOptions(options);
  27316. }
  27317. };
  27318. defaultModelOptions = new ModelOptions({
  27319. updateOn: '',
  27320. updateOnDefault: true,
  27321. debounce: 0,
  27322. getterSetter: false,
  27323. allowInvalid: false,
  27324. timezone: null
  27325. });
  27326. /**
  27327. * @ngdoc directive
  27328. * @name ngModelOptions
  27329. * @restrict A
  27330. * @priority 10
  27331. *
  27332. * @description
  27333. * This directive allows you to modify the behaviour of {@link ngModel} directives within your
  27334. * application. You can specify an `ngModelOptions` directive on any element. All {@link ngModel}
  27335. * directives will use the options of their nearest `ngModelOptions` ancestor.
  27336. *
  27337. * The `ngModelOptions` settings are found by evaluating the value of the attribute directive as
  27338. * an Angular expression. This expression should evaluate to an object, whose properties contain
  27339. * the settings. For example: `<div "ng-model-options"="{ debounce: 100 }"`.
  27340. *
  27341. * ## Inheriting Options
  27342. *
  27343. * You can specify that an `ngModelOptions` setting should be inherited from a parent `ngModelOptions`
  27344. * directive by giving it the value of `"$inherit"`.
  27345. * Then it will inherit that setting from the first `ngModelOptions` directive found by traversing up the
  27346. * DOM tree. If there is no ancestor element containing an `ngModelOptions` directive then default settings
  27347. * will be used.
  27348. *
  27349. * For example given the following fragment of HTML
  27350. *
  27351. *
  27352. * ```html
  27353. * <div ng-model-options="{ allowInvalid: true, debounce: 200 }">
  27354. * <form ng-model-options="{ updateOn: 'blur', allowInvalid: '$inherit' }">
  27355. * <input ng-model-options="{ updateOn: 'default', allowInvalid: '$inherit' }" />
  27356. * </form>
  27357. * </div>
  27358. * ```
  27359. *
  27360. * the `input` element will have the following settings
  27361. *
  27362. * ```js
  27363. * { allowInvalid: true, updateOn: 'default', debounce: 0 }
  27364. * ```
  27365. *
  27366. * Notice that the `debounce` setting was not inherited and used the default value instead.
  27367. *
  27368. * You can specify that all undefined settings are automatically inherited from an ancestor by
  27369. * including a property with key of `"*"` and value of `"$inherit"`.
  27370. *
  27371. * For example given the following fragment of HTML
  27372. *
  27373. *
  27374. * ```html
  27375. * <div ng-model-options="{ allowInvalid: true, debounce: 200 }">
  27376. * <form ng-model-options="{ updateOn: 'blur', "*": '$inherit' }">
  27377. * <input ng-model-options="{ updateOn: 'default', "*": '$inherit' }" />
  27378. * </form>
  27379. * </div>
  27380. * ```
  27381. *
  27382. * the `input` element will have the following settings
  27383. *
  27384. * ```js
  27385. * { allowInvalid: true, updateOn: 'default', debounce: 200 }
  27386. * ```
  27387. *
  27388. * Notice that the `debounce` setting now inherits the value from the outer `<div>` element.
  27389. *
  27390. * If you are creating a reusable component then you should be careful when using `"*": "$inherit"`
  27391. * since you may inadvertently inherit a setting in the future that changes the behavior of your component.
  27392. *
  27393. *
  27394. * ## Triggering and debouncing model updates
  27395. *
  27396. * The `updateOn` and `debounce` properties allow you to specify a custom list of events that will
  27397. * trigger a model update and/or a debouncing delay so that the actual update only takes place when
  27398. * a timer expires; this timer will be reset after another change takes place.
  27399. *
  27400. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  27401. * be different from the value in the actual model. This means that if you update the model you
  27402. * should also invoke {@link ngModel.NgModelController#$rollbackViewValue} on the relevant input field in
  27403. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  27404. *
  27405. * The easiest way to reference the control's {@link ngModel.NgModelController#$rollbackViewValue}
  27406. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  27407. * important because `form` controllers are published to the related scope under the name in their
  27408. * `name` attribute.
  27409. *
  27410. * Any pending changes will take place immediately when an enclosing form is submitted via the
  27411. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  27412. * to have access to the updated model.
  27413. *
  27414. * The following example shows how to override immediate updates. Changes on the inputs within the
  27415. * form will update the model only when the control loses focus (blur event). If `escape` key is
  27416. * pressed while the input field is focused, the value is reset to the value in the current model.
  27417. *
  27418. * <example name="ngModelOptions-directive-blur" module="optionsExample">
  27419. * <file name="index.html">
  27420. * <div ng-controller="ExampleController">
  27421. * <form name="userForm">
  27422. * <label>
  27423. * Name:
  27424. * <input type="text" name="userName"
  27425. * ng-model="user.name"
  27426. * ng-model-options="{ updateOn: 'blur' }"
  27427. * ng-keyup="cancel($event)" />
  27428. * </label><br />
  27429. * <label>
  27430. * Other data:
  27431. * <input type="text" ng-model="user.data" />
  27432. * </label><br />
  27433. * </form>
  27434. * <pre>user.name = <span ng-bind="user.name"></span></pre>
  27435. * </div>
  27436. * </file>
  27437. * <file name="app.js">
  27438. * angular.module('optionsExample', [])
  27439. * .controller('ExampleController', ['$scope', function($scope) {
  27440. * $scope.user = { name: 'say', data: '' };
  27441. *
  27442. * $scope.cancel = function(e) {
  27443. * if (e.keyCode === 27) {
  27444. * $scope.userForm.userName.$rollbackViewValue();
  27445. * }
  27446. * };
  27447. * }]);
  27448. * </file>
  27449. * <file name="protractor.js" type="protractor">
  27450. * var model = element(by.binding('user.name'));
  27451. * var input = element(by.model('user.name'));
  27452. * var other = element(by.model('user.data'));
  27453. *
  27454. * it('should allow custom events', function() {
  27455. * input.sendKeys(' hello');
  27456. * input.click();
  27457. * expect(model.getText()).toEqual('say');
  27458. * other.click();
  27459. * expect(model.getText()).toEqual('say hello');
  27460. * });
  27461. *
  27462. * it('should $rollbackViewValue when model changes', function() {
  27463. * input.sendKeys(' hello');
  27464. * expect(input.getAttribute('value')).toEqual('say hello');
  27465. * input.sendKeys(protractor.Key.ESCAPE);
  27466. * expect(input.getAttribute('value')).toEqual('say');
  27467. * other.click();
  27468. * expect(model.getText()).toEqual('say');
  27469. * });
  27470. * </file>
  27471. * </example>
  27472. *
  27473. * The next example shows how to debounce model changes. Model will be updated only 1 sec after last change.
  27474. * If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  27475. *
  27476. * <example name="ngModelOptions-directive-debounce" module="optionsExample">
  27477. * <file name="index.html">
  27478. * <div ng-controller="ExampleController">
  27479. * <form name="userForm">
  27480. * Name:
  27481. * <input type="text" name="userName"
  27482. * ng-model="user.name"
  27483. * ng-model-options="{ debounce: 1000 }" />
  27484. * <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
  27485. * </form>
  27486. * <pre>user.name = <span ng-bind="user.name"></span></pre>
  27487. * </div>
  27488. * </file>
  27489. * <file name="app.js">
  27490. * angular.module('optionsExample', [])
  27491. * .controller('ExampleController', ['$scope', function($scope) {
  27492. * $scope.user = { name: 'say' };
  27493. * }]);
  27494. * </file>
  27495. * </example>
  27496. *
  27497. * ## Model updates and validation
  27498. *
  27499. * The default behaviour in `ngModel` is that the model value is set to `undefined` when the
  27500. * validation determines that the value is invalid. By setting the `allowInvalid` property to true,
  27501. * the model will still be updated even if the value is invalid.
  27502. *
  27503. *
  27504. * ## Connecting to the scope
  27505. *
  27506. * By setting the `getterSetter` property to true you are telling ngModel that the `ngModel` expression
  27507. * on the scope refers to a "getter/setter" function rather than the value itself.
  27508. *
  27509. * The following example shows how to bind to getter/setters:
  27510. *
  27511. * <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  27512. * <file name="index.html">
  27513. * <div ng-controller="ExampleController">
  27514. * <form name="userForm">
  27515. * <label>
  27516. * Name:
  27517. * <input type="text" name="userName"
  27518. * ng-model="user.name"
  27519. * ng-model-options="{ getterSetter: true }" />
  27520. * </label>
  27521. * </form>
  27522. * <pre>user.name = <span ng-bind="user.name()"></span></pre>
  27523. * </div>
  27524. * </file>
  27525. * <file name="app.js">
  27526. * angular.module('getterSetterExample', [])
  27527. * .controller('ExampleController', ['$scope', function($scope) {
  27528. * var _name = 'Brian';
  27529. * $scope.user = {
  27530. * name: function(newName) {
  27531. * return angular.isDefined(newName) ? (_name = newName) : _name;
  27532. * }
  27533. * };
  27534. * }]);
  27535. * </file>
  27536. * </example>
  27537. *
  27538. *
  27539. * ## Specifying timezones
  27540. *
  27541. * You can specify the timezone that date/time input directives expect by providing its name in the
  27542. * `timezone` property.
  27543. *
  27544. * @param {Object} ngModelOptions options to apply to {@link ngModel} directives on this element and
  27545. * and its descendents. Valid keys are:
  27546. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  27547. * events using an space delimited list. There is a special event called `default` that
  27548. * matches the default events belonging to the control.
  27549. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  27550. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  27551. * custom value for each event. For example:
  27552. * ```
  27553. * ng-model-options="{
  27554. * updateOn: 'default blur',
  27555. * debounce: { 'default': 500, 'blur': 0 }
  27556. * }"
  27557. * ```
  27558. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  27559. * not validate correctly instead of the default behavior of setting the model to undefined.
  27560. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  27561. * `ngModel` as getters/setters.
  27562. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  27563. * `<input type="date" />`, `<input type="time" />`, ... . It understands UTC/GMT and the
  27564. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  27565. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  27566. * If not specified, the timezone of the browser will be used.
  27567. *
  27568. */
  27569. var ngModelOptionsDirective = function() {
  27570. NgModelOptionsController.$inject = ['$attrs', '$scope'];
  27571. function NgModelOptionsController($attrs, $scope) {
  27572. this.$$attrs = $attrs;
  27573. this.$$scope = $scope;
  27574. }
  27575. NgModelOptionsController.prototype = {
  27576. $onInit: function() {
  27577. var parentOptions = this.parentCtrl ? this.parentCtrl.$options : defaultModelOptions;
  27578. var modelOptionsDefinition = this.$$scope.$eval(this.$$attrs.ngModelOptions);
  27579. this.$options = parentOptions.createChild(modelOptionsDefinition);
  27580. }
  27581. };
  27582. return {
  27583. restrict: 'A',
  27584. // ngModelOptions needs to run before ngModel and input directives
  27585. priority: 10,
  27586. require: {parentCtrl: '?^^ngModelOptions'},
  27587. bindToController: true,
  27588. controller: NgModelOptionsController
  27589. };
  27590. };
  27591. // shallow copy over values from `src` that are not already specified on `dst`
  27592. function defaults(dst, src) {
  27593. forEach(src, function(value, key) {
  27594. if (!isDefined(dst[key])) {
  27595. dst[key] = value;
  27596. }
  27597. });
  27598. }
  27599. /**
  27600. * @ngdoc directive
  27601. * @name ngNonBindable
  27602. * @restrict AC
  27603. * @priority 1000
  27604. * @element ANY
  27605. *
  27606. * @description
  27607. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  27608. * DOM element. This is useful if the element contains what appears to be Angular directives and
  27609. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  27610. * displays snippets of code, for instance.
  27611. *
  27612. * @example
  27613. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  27614. * but the one wrapped in `ngNonBindable` is left alone.
  27615. *
  27616. <example name="ng-non-bindable">
  27617. <file name="index.html">
  27618. <div>Normal: {{1 + 2}}</div>
  27619. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  27620. </file>
  27621. <file name="protractor.js" type="protractor">
  27622. it('should check ng-non-bindable', function() {
  27623. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  27624. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  27625. });
  27626. </file>
  27627. </example>
  27628. */
  27629. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  27630. /* exported ngOptionsDirective */
  27631. /* global jqLiteRemove */
  27632. var ngOptionsMinErr = minErr('ngOptions');
  27633. /**
  27634. * @ngdoc directive
  27635. * @name ngOptions
  27636. * @restrict A
  27637. *
  27638. * @description
  27639. *
  27640. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  27641. * elements for the `<select>` element using the array or object obtained by evaluating the
  27642. * `ngOptions` comprehension expression.
  27643. *
  27644. * In many cases, {@link ng.directive:ngRepeat ngRepeat} can be used on `<option>` elements instead of
  27645. * `ngOptions` to achieve a similar result. However, `ngOptions` provides some benefits:
  27646. * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  27647. * comprehension expression
  27648. * - reduced memory consumption by not creating a new scope for each repeated instance
  27649. * - increased render speed by creating the options in a documentFragment instead of individually
  27650. *
  27651. * When an item in the `<select>` menu is selected, the array element or object property
  27652. * represented by the selected option will be bound to the model identified by the `ngModel`
  27653. * directive.
  27654. *
  27655. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  27656. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  27657. * option. See example below for demonstration.
  27658. *
  27659. * ## Complex Models (objects or collections)
  27660. *
  27661. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  27662. * binding the select to a model that is an object or a collection.
  27663. *
  27664. * One issue occurs if you want to preselect an option. For example, if you set
  27665. * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
  27666. * because the objects are not identical. So by default, you should always reference the item in your collection
  27667. * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
  27668. *
  27669. * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
  27670. * of the item not by reference, but by the result of the `track by` expression. For example, if your
  27671. * collection items have an id property, you would `track by item.id`.
  27672. *
  27673. * A different issue with objects or collections is that ngModel won't detect if an object property or
  27674. * a collection item changes. For that reason, `ngOptions` additionally watches the model using
  27675. * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
  27676. * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
  27677. * has not changed identity, but only a property on the object or an item in the collection changes.
  27678. *
  27679. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  27680. * if the model is an array). This means that changing a property deeper than the first level inside the
  27681. * object/collection will not trigger a re-rendering.
  27682. *
  27683. * ## `select` **`as`**
  27684. *
  27685. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  27686. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  27687. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  27688. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  27689. *
  27690. *
  27691. * ### `select` **`as`** and **`track by`**
  27692. *
  27693. * <div class="alert alert-warning">
  27694. * Be careful when using `select` **`as`** and **`track by`** in the same expression.
  27695. * </div>
  27696. *
  27697. * Given this array of items on the $scope:
  27698. *
  27699. * ```js
  27700. * $scope.items = [{
  27701. * id: 1,
  27702. * label: 'aLabel',
  27703. * subItem: { name: 'aSubItem' }
  27704. * }, {
  27705. * id: 2,
  27706. * label: 'bLabel',
  27707. * subItem: { name: 'bSubItem' }
  27708. * }];
  27709. * ```
  27710. *
  27711. * This will work:
  27712. *
  27713. * ```html
  27714. * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
  27715. * ```
  27716. * ```js
  27717. * $scope.selected = $scope.items[0];
  27718. * ```
  27719. *
  27720. * but this will not work:
  27721. *
  27722. * ```html
  27723. * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
  27724. * ```
  27725. * ```js
  27726. * $scope.selected = $scope.items[0].subItem;
  27727. * ```
  27728. *
  27729. * In both examples, the **`track by`** expression is applied successfully to each `item` in the
  27730. * `items` array. Because the selected option has been set programmatically in the controller, the
  27731. * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
  27732. * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
  27733. * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
  27734. * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
  27735. * is not matched against any `<option>` and the `<select>` appears as having no selected value.
  27736. *
  27737. *
  27738. * @param {string} ngModel Assignable AngularJS expression to data-bind to.
  27739. * @param {comprehension_expression} ngOptions in one of the following forms:
  27740. *
  27741. * * for array data sources:
  27742. * * `label` **`for`** `value` **`in`** `array`
  27743. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  27744. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  27745. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  27746. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  27747. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  27748. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  27749. * (for including a filter with `track by`)
  27750. * * for object data sources:
  27751. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  27752. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  27753. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  27754. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  27755. * * `select` **`as`** `label` **`group by`** `group`
  27756. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  27757. * * `select` **`as`** `label` **`disable when`** `disable`
  27758. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  27759. *
  27760. * Where:
  27761. *
  27762. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  27763. * * `value`: local variable which will refer to each item in the `array` or each property value
  27764. * of `object` during iteration.
  27765. * * `key`: local variable which will refer to a property name in `object` during iteration.
  27766. * * `label`: The result of this expression will be the label for `<option>` element. The
  27767. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  27768. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  27769. * element. If not specified, `select` expression will default to `value`.
  27770. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  27771. * DOM element.
  27772. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  27773. * element. Return `true` to disable.
  27774. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  27775. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  27776. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  27777. * even when the options are recreated (e.g. reloaded from the server).
  27778. * @param {string=} name Property name of the form under which the control is published.
  27779. * @param {string=} required The control is considered valid only if value is entered.
  27780. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  27781. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  27782. * `required` when you want to data-bind to the `required` attribute.
  27783. * @param {string=} ngAttrSize sets the size of the select element dynamically. Uses the
  27784. * {@link guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes ngAttr} directive.
  27785. *
  27786. * @example
  27787. <example module="selectExample" name="select">
  27788. <file name="index.html">
  27789. <script>
  27790. angular.module('selectExample', [])
  27791. .controller('ExampleController', ['$scope', function($scope) {
  27792. $scope.colors = [
  27793. {name:'black', shade:'dark'},
  27794. {name:'white', shade:'light', notAnOption: true},
  27795. {name:'red', shade:'dark'},
  27796. {name:'blue', shade:'dark', notAnOption: true},
  27797. {name:'yellow', shade:'light', notAnOption: false}
  27798. ];
  27799. $scope.myColor = $scope.colors[2]; // red
  27800. }]);
  27801. </script>
  27802. <div ng-controller="ExampleController">
  27803. <ul>
  27804. <li ng-repeat="color in colors">
  27805. <label>Name: <input ng-model="color.name"></label>
  27806. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  27807. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  27808. </li>
  27809. <li>
  27810. <button ng-click="colors.push({})">add</button>
  27811. </li>
  27812. </ul>
  27813. <hr/>
  27814. <label>Color (null not allowed):
  27815. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  27816. </label><br/>
  27817. <label>Color (null allowed):
  27818. <span class="nullable">
  27819. <select ng-model="myColor" ng-options="color.name for color in colors">
  27820. <option value="">-- choose color --</option>
  27821. </select>
  27822. </span></label><br/>
  27823. <label>Color grouped by shade:
  27824. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  27825. </select>
  27826. </label><br/>
  27827. <label>Color grouped by shade, with some disabled:
  27828. <select ng-model="myColor"
  27829. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  27830. </select>
  27831. </label><br/>
  27832. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  27833. <br/>
  27834. <hr/>
  27835. Currently selected: {{ {selected_color:myColor} }}
  27836. <div style="border:solid 1px black; height:20px"
  27837. ng-style="{'background-color':myColor.name}">
  27838. </div>
  27839. </div>
  27840. </file>
  27841. <file name="protractor.js" type="protractor">
  27842. it('should check ng-options', function() {
  27843. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  27844. element.all(by.model('myColor')).first().click();
  27845. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  27846. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  27847. element(by.css('.nullable select[ng-model="myColor"]')).click();
  27848. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  27849. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  27850. });
  27851. </file>
  27852. </example>
  27853. */
  27854. /* eslint-disable max-len */
  27855. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555000000000666666666666600000007777777777777000000000000000888888888800000000000000000009999999999
  27856. 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]+?))?$/;
  27857. // 1: value expression (valueFn)
  27858. // 2: label expression (displayFn)
  27859. // 3: group by expression (groupByFn)
  27860. // 4: disable when expression (disableWhenFn)
  27861. // 5: array item variable name
  27862. // 6: object item key variable name
  27863. // 7: object item value variable name
  27864. // 8: collection expression
  27865. // 9: track by expression
  27866. /* eslint-enable */
  27867. var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, $document, $parse) {
  27868. function parseOptionsExpression(optionsExp, selectElement, scope) {
  27869. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  27870. if (!(match)) {
  27871. throw ngOptionsMinErr('iexp',
  27872. 'Expected expression in form of ' +
  27873. '\'_select_ (as _label_)? for (_key_,)?_value_ in _collection_\'' +
  27874. ' but got \'{0}\'. Element: {1}',
  27875. optionsExp, startingTag(selectElement));
  27876. }
  27877. // Extract the parts from the ngOptions expression
  27878. // The variable name for the value of the item in the collection
  27879. var valueName = match[5] || match[7];
  27880. // The variable name for the key of the item in the collection
  27881. var keyName = match[6];
  27882. // An expression that generates the viewValue for an option if there is a label expression
  27883. var selectAs = / as /.test(match[0]) && match[1];
  27884. // An expression that is used to track the id of each object in the options collection
  27885. var trackBy = match[9];
  27886. // An expression that generates the viewValue for an option if there is no label expression
  27887. var valueFn = $parse(match[2] ? match[1] : valueName);
  27888. var selectAsFn = selectAs && $parse(selectAs);
  27889. var viewValueFn = selectAsFn || valueFn;
  27890. var trackByFn = trackBy && $parse(trackBy);
  27891. // Get the value by which we are going to track the option
  27892. // if we have a trackFn then use that (passing scope and locals)
  27893. // otherwise just hash the given viewValue
  27894. var getTrackByValueFn = trackBy ?
  27895. function(value, locals) { return trackByFn(scope, locals); } :
  27896. function getHashOfValue(value) { return hashKey(value); };
  27897. var getTrackByValue = function(value, key) {
  27898. return getTrackByValueFn(value, getLocals(value, key));
  27899. };
  27900. var displayFn = $parse(match[2] || match[1]);
  27901. var groupByFn = $parse(match[3] || '');
  27902. var disableWhenFn = $parse(match[4] || '');
  27903. var valuesFn = $parse(match[8]);
  27904. var locals = {};
  27905. var getLocals = keyName ? function(value, key) {
  27906. locals[keyName] = key;
  27907. locals[valueName] = value;
  27908. return locals;
  27909. } : function(value) {
  27910. locals[valueName] = value;
  27911. return locals;
  27912. };
  27913. function Option(selectValue, viewValue, label, group, disabled) {
  27914. this.selectValue = selectValue;
  27915. this.viewValue = viewValue;
  27916. this.label = label;
  27917. this.group = group;
  27918. this.disabled = disabled;
  27919. }
  27920. function getOptionValuesKeys(optionValues) {
  27921. var optionValuesKeys;
  27922. if (!keyName && isArrayLike(optionValues)) {
  27923. optionValuesKeys = optionValues;
  27924. } else {
  27925. // if object, extract keys, in enumeration order, unsorted
  27926. optionValuesKeys = [];
  27927. for (var itemKey in optionValues) {
  27928. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  27929. optionValuesKeys.push(itemKey);
  27930. }
  27931. }
  27932. }
  27933. return optionValuesKeys;
  27934. }
  27935. return {
  27936. trackBy: trackBy,
  27937. getTrackByValue: getTrackByValue,
  27938. getWatchables: $parse(valuesFn, function(optionValues) {
  27939. // Create a collection of things that we would like to watch (watchedArray)
  27940. // so that they can all be watched using a single $watchCollection
  27941. // that only runs the handler once if anything changes
  27942. var watchedArray = [];
  27943. optionValues = optionValues || [];
  27944. var optionValuesKeys = getOptionValuesKeys(optionValues);
  27945. var optionValuesLength = optionValuesKeys.length;
  27946. for (var index = 0; index < optionValuesLength; index++) {
  27947. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  27948. var value = optionValues[key];
  27949. var locals = getLocals(value, key);
  27950. var selectValue = getTrackByValueFn(value, locals);
  27951. watchedArray.push(selectValue);
  27952. // Only need to watch the displayFn if there is a specific label expression
  27953. if (match[2] || match[1]) {
  27954. var label = displayFn(scope, locals);
  27955. watchedArray.push(label);
  27956. }
  27957. // Only need to watch the disableWhenFn if there is a specific disable expression
  27958. if (match[4]) {
  27959. var disableWhen = disableWhenFn(scope, locals);
  27960. watchedArray.push(disableWhen);
  27961. }
  27962. }
  27963. return watchedArray;
  27964. }),
  27965. getOptions: function() {
  27966. var optionItems = [];
  27967. var selectValueMap = {};
  27968. // The option values were already computed in the `getWatchables` fn,
  27969. // which must have been called to trigger `getOptions`
  27970. var optionValues = valuesFn(scope) || [];
  27971. var optionValuesKeys = getOptionValuesKeys(optionValues);
  27972. var optionValuesLength = optionValuesKeys.length;
  27973. for (var index = 0; index < optionValuesLength; index++) {
  27974. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  27975. var value = optionValues[key];
  27976. var locals = getLocals(value, key);
  27977. var viewValue = viewValueFn(scope, locals);
  27978. var selectValue = getTrackByValueFn(viewValue, locals);
  27979. var label = displayFn(scope, locals);
  27980. var group = groupByFn(scope, locals);
  27981. var disabled = disableWhenFn(scope, locals);
  27982. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  27983. optionItems.push(optionItem);
  27984. selectValueMap[selectValue] = optionItem;
  27985. }
  27986. return {
  27987. items: optionItems,
  27988. selectValueMap: selectValueMap,
  27989. getOptionFromViewValue: function(value) {
  27990. return selectValueMap[getTrackByValue(value)];
  27991. },
  27992. getViewValueFromOption: function(option) {
  27993. // If the viewValue could be an object that may be mutated by the application,
  27994. // we need to make a copy and not return the reference to the value on the option.
  27995. return trackBy ? copy(option.viewValue) : option.viewValue;
  27996. }
  27997. };
  27998. }
  27999. };
  28000. }
  28001. // Support: IE 9 only
  28002. // We can't just jqLite('<option>') since jqLite is not smart enough
  28003. // to create it in <select> and IE barfs otherwise.
  28004. var optionTemplate = window.document.createElement('option'),
  28005. optGroupTemplate = window.document.createElement('optgroup');
  28006. function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
  28007. var selectCtrl = ctrls[0];
  28008. var ngModelCtrl = ctrls[1];
  28009. var multiple = attr.multiple;
  28010. // The emptyOption allows the application developer to provide their own custom "empty"
  28011. // option when the viewValue does not match any of the option values.
  28012. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  28013. if (children[i].value === '') {
  28014. selectCtrl.hasEmptyOption = true;
  28015. selectCtrl.emptyOption = children.eq(i);
  28016. break;
  28017. }
  28018. }
  28019. // The empty option will be compiled and rendered before we first generate the options
  28020. selectElement.empty();
  28021. var providedEmptyOption = !!selectCtrl.emptyOption;
  28022. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  28023. unknownOption.val('?');
  28024. var options;
  28025. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  28026. // This stores the newly created options before they are appended to the select.
  28027. // Since the contents are removed from the fragment when it is appended,
  28028. // we only need to create it once.
  28029. var listFragment = $document[0].createDocumentFragment();
  28030. // Overwrite the implementation. ngOptions doesn't use hashes
  28031. selectCtrl.generateUnknownOptionValue = function(val) {
  28032. return '?';
  28033. };
  28034. // Update the controller methods for multiple selectable options
  28035. if (!multiple) {
  28036. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  28037. // The options might not be defined yet when ngModel tries to render
  28038. if (!options) return;
  28039. var selectedOption = selectElement[0].options[selectElement[0].selectedIndex];
  28040. var option = options.getOptionFromViewValue(value);
  28041. // Make sure to remove the selected attribute from the previously selected option
  28042. // Otherwise, screen readers might get confused
  28043. if (selectedOption) selectedOption.removeAttribute('selected');
  28044. if (option) {
  28045. // Don't update the option when it is already selected.
  28046. // For example, the browser will select the first option by default. In that case,
  28047. // most properties are set automatically - except the `selected` attribute, which we
  28048. // set always
  28049. if (selectElement[0].value !== option.selectValue) {
  28050. selectCtrl.removeUnknownOption();
  28051. selectElement[0].value = option.selectValue;
  28052. option.element.selected = true;
  28053. }
  28054. option.element.setAttribute('selected', 'selected');
  28055. } else {
  28056. selectCtrl.selectUnknownOrEmptyOption(value);
  28057. }
  28058. };
  28059. selectCtrl.readValue = function readNgOptionsValue() {
  28060. var selectedOption = options.selectValueMap[selectElement.val()];
  28061. if (selectedOption && !selectedOption.disabled) {
  28062. selectCtrl.unselectEmptyOption();
  28063. selectCtrl.removeUnknownOption();
  28064. return options.getViewValueFromOption(selectedOption);
  28065. }
  28066. return null;
  28067. };
  28068. // If we are using `track by` then we must watch the tracked value on the model
  28069. // since ngModel only watches for object identity change
  28070. // FIXME: When a user selects an option, this watch will fire needlessly
  28071. if (ngOptions.trackBy) {
  28072. scope.$watch(
  28073. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  28074. function() { ngModelCtrl.$render(); }
  28075. );
  28076. }
  28077. } else {
  28078. selectCtrl.writeValue = function writeNgOptionsMultiple(values) {
  28079. // The options might not be defined yet when ngModel tries to render
  28080. if (!options) return;
  28081. // Only set `<option>.selected` if necessary, in order to prevent some browsers from
  28082. // scrolling to `<option>` elements that are outside the `<select>` element's viewport.
  28083. var selectedOptions = values && values.map(getAndUpdateSelectedOption) || [];
  28084. options.items.forEach(function(option) {
  28085. if (option.element.selected && !includes(selectedOptions, option)) {
  28086. option.element.selected = false;
  28087. }
  28088. });
  28089. };
  28090. selectCtrl.readValue = function readNgOptionsMultiple() {
  28091. var selectedValues = selectElement.val() || [],
  28092. selections = [];
  28093. forEach(selectedValues, function(value) {
  28094. var option = options.selectValueMap[value];
  28095. if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
  28096. });
  28097. return selections;
  28098. };
  28099. // If we are using `track by` then we must watch these tracked values on the model
  28100. // since ngModel only watches for object identity change
  28101. if (ngOptions.trackBy) {
  28102. scope.$watchCollection(function() {
  28103. if (isArray(ngModelCtrl.$viewValue)) {
  28104. return ngModelCtrl.$viewValue.map(function(value) {
  28105. return ngOptions.getTrackByValue(value);
  28106. });
  28107. }
  28108. }, function() {
  28109. ngModelCtrl.$render();
  28110. });
  28111. }
  28112. }
  28113. if (providedEmptyOption) {
  28114. // compile the element since there might be bindings in it
  28115. $compile(selectCtrl.emptyOption)(scope);
  28116. selectElement.prepend(selectCtrl.emptyOption);
  28117. if (selectCtrl.emptyOption[0].nodeType === NODE_TYPE_COMMENT) {
  28118. // This means the empty option has currently no actual DOM node, probably because
  28119. // it has been modified by a transclusion directive.
  28120. selectCtrl.hasEmptyOption = false;
  28121. // Redefine the registerOption function, which will catch
  28122. // options that are added by ngIf etc. (rendering of the node is async because of
  28123. // lazy transclusion)
  28124. selectCtrl.registerOption = function(optionScope, optionEl) {
  28125. if (optionEl.val() === '') {
  28126. selectCtrl.hasEmptyOption = true;
  28127. selectCtrl.emptyOption = optionEl;
  28128. selectCtrl.emptyOption.removeClass('ng-scope');
  28129. // This ensures the new empty option is selected if previously no option was selected
  28130. ngModelCtrl.$render();
  28131. optionEl.on('$destroy', function() {
  28132. var needsRerender = selectCtrl.$isEmptyOptionSelected();
  28133. selectCtrl.hasEmptyOption = false;
  28134. selectCtrl.emptyOption = undefined;
  28135. if (needsRerender) ngModelCtrl.$render();
  28136. });
  28137. }
  28138. };
  28139. } else {
  28140. // remove the class, which is added automatically because we recompile the element and it
  28141. // becomes the compilation root
  28142. selectCtrl.emptyOption.removeClass('ng-scope');
  28143. }
  28144. }
  28145. // We will re-render the option elements if the option values or labels change
  28146. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  28147. // ------------------------------------------------------------------ //
  28148. function addOptionElement(option, parent) {
  28149. var optionElement = optionTemplate.cloneNode(false);
  28150. parent.appendChild(optionElement);
  28151. updateOptionElement(option, optionElement);
  28152. }
  28153. function getAndUpdateSelectedOption(viewValue) {
  28154. var option = options.getOptionFromViewValue(viewValue);
  28155. var element = option && option.element;
  28156. if (element && !element.selected) element.selected = true;
  28157. return option;
  28158. }
  28159. function updateOptionElement(option, element) {
  28160. option.element = element;
  28161. element.disabled = option.disabled;
  28162. // Support: IE 11 only, Edge 12-13 only
  28163. // NOTE: The label must be set before the value, otherwise IE 11 & Edge create unresponsive
  28164. // selects in certain circumstances when multiple selects are next to each other and display
  28165. // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
  28166. // See https://github.com/angular/angular.js/issues/11314 for more info.
  28167. // This is unfortunately untestable with unit / e2e tests
  28168. if (option.label !== element.label) {
  28169. element.label = option.label;
  28170. element.textContent = option.label;
  28171. }
  28172. element.value = option.selectValue;
  28173. }
  28174. function updateOptions() {
  28175. var previousValue = options && selectCtrl.readValue();
  28176. // We must remove all current options, but cannot simply set innerHTML = null
  28177. // since the providedEmptyOption might have an ngIf on it that inserts comments which we
  28178. // must preserve.
  28179. // Instead, iterate over the current option elements and remove them or their optgroup
  28180. // parents
  28181. if (options) {
  28182. for (var i = options.items.length - 1; i >= 0; i--) {
  28183. var option = options.items[i];
  28184. if (isDefined(option.group)) {
  28185. jqLiteRemove(option.element.parentNode);
  28186. } else {
  28187. jqLiteRemove(option.element);
  28188. }
  28189. }
  28190. }
  28191. options = ngOptions.getOptions();
  28192. var groupElementMap = {};
  28193. options.items.forEach(function addOption(option) {
  28194. var groupElement;
  28195. if (isDefined(option.group)) {
  28196. // This option is to live in a group
  28197. // See if we have already created this group
  28198. groupElement = groupElementMap[option.group];
  28199. if (!groupElement) {
  28200. groupElement = optGroupTemplate.cloneNode(false);
  28201. listFragment.appendChild(groupElement);
  28202. // Update the label on the group element
  28203. // "null" is special cased because of Safari
  28204. groupElement.label = option.group === null ? 'null' : option.group;
  28205. // Store it for use later
  28206. groupElementMap[option.group] = groupElement;
  28207. }
  28208. addOptionElement(option, groupElement);
  28209. } else {
  28210. // This option is not in a group
  28211. addOptionElement(option, listFragment);
  28212. }
  28213. });
  28214. selectElement[0].appendChild(listFragment);
  28215. ngModelCtrl.$render();
  28216. // Check to see if the value has changed due to the update to the options
  28217. if (!ngModelCtrl.$isEmpty(previousValue)) {
  28218. var nextValue = selectCtrl.readValue();
  28219. var isNotPrimitive = ngOptions.trackBy || multiple;
  28220. if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
  28221. ngModelCtrl.$setViewValue(nextValue);
  28222. ngModelCtrl.$render();
  28223. }
  28224. }
  28225. }
  28226. }
  28227. return {
  28228. restrict: 'A',
  28229. terminal: true,
  28230. require: ['select', 'ngModel'],
  28231. link: {
  28232. pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
  28233. // Deactivate the SelectController.register method to prevent
  28234. // option directives from accidentally registering themselves
  28235. // (and unwanted $destroy handlers etc.)
  28236. ctrls[0].registerOption = noop;
  28237. },
  28238. post: ngOptionsPostLink
  28239. }
  28240. };
  28241. }];
  28242. /**
  28243. * @ngdoc directive
  28244. * @name ngPluralize
  28245. * @restrict EA
  28246. *
  28247. * @description
  28248. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  28249. * These rules are bundled with angular.js, but can be overridden
  28250. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  28251. * by specifying the mappings between
  28252. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  28253. * and the strings to be displayed.
  28254. *
  28255. * ## Plural categories and explicit number rules
  28256. * There are two
  28257. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  28258. * in Angular's default en-US locale: "one" and "other".
  28259. *
  28260. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  28261. * any number that is not 1), an explicit number rule can only match one number. For example, the
  28262. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  28263. * and explicit number rules throughout the rest of this documentation.
  28264. *
  28265. * ## Configuring ngPluralize
  28266. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  28267. * You can also provide an optional attribute, `offset`.
  28268. *
  28269. * The value of the `count` attribute can be either a string or an {@link guide/expression
  28270. * Angular expression}; these are evaluated on the current scope for its bound value.
  28271. *
  28272. * The `when` attribute specifies the mappings between plural categories and the actual
  28273. * string to be displayed. The value of the attribute should be a JSON object.
  28274. *
  28275. * The following example shows how to configure ngPluralize:
  28276. *
  28277. * ```html
  28278. * <ng-pluralize count="personCount"
  28279. when="{'0': 'Nobody is viewing.',
  28280. * 'one': '1 person is viewing.',
  28281. * 'other': '{} people are viewing.'}">
  28282. * </ng-pluralize>
  28283. *```
  28284. *
  28285. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  28286. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  28287. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  28288. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  28289. * show "a dozen people are viewing".
  28290. *
  28291. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  28292. * into pluralized strings. In the previous example, Angular will replace `{}` with
  28293. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  28294. * for <span ng-non-bindable>{{numberExpression}}</span>.
  28295. *
  28296. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  28297. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  28298. *
  28299. * ## Configuring ngPluralize with offset
  28300. * The `offset` attribute allows further customization of pluralized text, which can result in
  28301. * a better user experience. For example, instead of the message "4 people are viewing this document",
  28302. * you might display "John, Kate and 2 others are viewing this document".
  28303. * The offset attribute allows you to offset a number by any desired value.
  28304. * Let's take a look at an example:
  28305. *
  28306. * ```html
  28307. * <ng-pluralize count="personCount" offset=2
  28308. * when="{'0': 'Nobody is viewing.',
  28309. * '1': '{{person1}} is viewing.',
  28310. * '2': '{{person1}} and {{person2}} are viewing.',
  28311. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  28312. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  28313. * </ng-pluralize>
  28314. * ```
  28315. *
  28316. * Notice that we are still using two plural categories(one, other), but we added
  28317. * three explicit number rules 0, 1 and 2.
  28318. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  28319. * When three people view the document, no explicit number rule is found, so
  28320. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  28321. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  28322. * is shown.
  28323. *
  28324. * Note that when you specify offsets, you must provide explicit number rules for
  28325. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  28326. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  28327. * plural categories "one" and "other".
  28328. *
  28329. * @param {string|expression} count The variable to be bound to.
  28330. * @param {string} when The mapping between plural category to its corresponding strings.
  28331. * @param {number=} offset Offset to deduct from the total number.
  28332. *
  28333. * @example
  28334. <example module="pluralizeExample" name="ng-pluralize">
  28335. <file name="index.html">
  28336. <script>
  28337. angular.module('pluralizeExample', [])
  28338. .controller('ExampleController', ['$scope', function($scope) {
  28339. $scope.person1 = 'Igor';
  28340. $scope.person2 = 'Misko';
  28341. $scope.personCount = 1;
  28342. }]);
  28343. </script>
  28344. <div ng-controller="ExampleController">
  28345. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  28346. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  28347. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  28348. <!--- Example with simple pluralization rules for en locale --->
  28349. Without Offset:
  28350. <ng-pluralize count="personCount"
  28351. when="{'0': 'Nobody is viewing.',
  28352. 'one': '1 person is viewing.',
  28353. 'other': '{} people are viewing.'}">
  28354. </ng-pluralize><br>
  28355. <!--- Example with offset --->
  28356. With Offset(2):
  28357. <ng-pluralize count="personCount" offset=2
  28358. when="{'0': 'Nobody is viewing.',
  28359. '1': '{{person1}} is viewing.',
  28360. '2': '{{person1}} and {{person2}} are viewing.',
  28361. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  28362. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  28363. </ng-pluralize>
  28364. </div>
  28365. </file>
  28366. <file name="protractor.js" type="protractor">
  28367. it('should show correct pluralized string', function() {
  28368. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  28369. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  28370. var countInput = element(by.model('personCount'));
  28371. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  28372. expect(withOffset.getText()).toEqual('Igor is viewing.');
  28373. countInput.clear();
  28374. countInput.sendKeys('0');
  28375. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  28376. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  28377. countInput.clear();
  28378. countInput.sendKeys('2');
  28379. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  28380. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  28381. countInput.clear();
  28382. countInput.sendKeys('3');
  28383. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  28384. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  28385. countInput.clear();
  28386. countInput.sendKeys('4');
  28387. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  28388. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  28389. });
  28390. it('should show data-bound names', function() {
  28391. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  28392. var personCount = element(by.model('personCount'));
  28393. var person1 = element(by.model('person1'));
  28394. var person2 = element(by.model('person2'));
  28395. personCount.clear();
  28396. personCount.sendKeys('4');
  28397. person1.clear();
  28398. person1.sendKeys('Di');
  28399. person2.clear();
  28400. person2.sendKeys('Vojta');
  28401. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  28402. });
  28403. </file>
  28404. </example>
  28405. */
  28406. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  28407. var BRACE = /{}/g,
  28408. IS_WHEN = /^when(Minus)?(.+)$/;
  28409. return {
  28410. link: function(scope, element, attr) {
  28411. var numberExp = attr.count,
  28412. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  28413. offset = attr.offset || 0,
  28414. whens = scope.$eval(whenExp) || {},
  28415. whensExpFns = {},
  28416. startSymbol = $interpolate.startSymbol(),
  28417. endSymbol = $interpolate.endSymbol(),
  28418. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  28419. watchRemover = angular.noop,
  28420. lastCount;
  28421. forEach(attr, function(expression, attributeName) {
  28422. var tmpMatch = IS_WHEN.exec(attributeName);
  28423. if (tmpMatch) {
  28424. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  28425. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  28426. }
  28427. });
  28428. forEach(whens, function(expression, key) {
  28429. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  28430. });
  28431. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  28432. var count = parseFloat(newVal);
  28433. var countIsNaN = isNumberNaN(count);
  28434. if (!countIsNaN && !(count in whens)) {
  28435. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  28436. // Otherwise, check it against pluralization rules in $locale service.
  28437. count = $locale.pluralCat(count - offset);
  28438. }
  28439. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  28440. // In JS `NaN !== NaN`, so we have to explicitly check.
  28441. if ((count !== lastCount) && !(countIsNaN && isNumberNaN(lastCount))) {
  28442. watchRemover();
  28443. var whenExpFn = whensExpFns[count];
  28444. if (isUndefined(whenExpFn)) {
  28445. if (newVal != null) {
  28446. $log.debug('ngPluralize: no rule defined for \'' + count + '\' in ' + whenExp);
  28447. }
  28448. watchRemover = noop;
  28449. updateElementText();
  28450. } else {
  28451. watchRemover = scope.$watch(whenExpFn, updateElementText);
  28452. }
  28453. lastCount = count;
  28454. }
  28455. });
  28456. function updateElementText(newText) {
  28457. element.text(newText || '');
  28458. }
  28459. }
  28460. };
  28461. }];
  28462. /* exported ngRepeatDirective */
  28463. /**
  28464. * @ngdoc directive
  28465. * @name ngRepeat
  28466. * @multiElement
  28467. * @restrict A
  28468. *
  28469. * @description
  28470. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  28471. * instance gets its own scope, where the given loop variable is set to the current collection item,
  28472. * and `$index` is set to the item index or key.
  28473. *
  28474. * Special properties are exposed on the local scope of each template instance, including:
  28475. *
  28476. * | Variable | Type | Details |
  28477. * |-----------|-----------------|-----------------------------------------------------------------------------|
  28478. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  28479. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  28480. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  28481. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  28482. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  28483. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  28484. *
  28485. * <div class="alert alert-info">
  28486. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  28487. * This may be useful when, for instance, nesting ngRepeats.
  28488. * </div>
  28489. *
  28490. *
  28491. * ## Iterating over object properties
  28492. *
  28493. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  28494. * syntax:
  28495. *
  28496. * ```js
  28497. * <div ng-repeat="(key, value) in myObj"> ... </div>
  28498. * ```
  28499. *
  28500. * However, there are a few limitations compared to array iteration:
  28501. *
  28502. * - The JavaScript specification does not define the order of keys
  28503. * returned for an object, so Angular relies on the order returned by the browser
  28504. * when running `for key in myObj`. Browsers generally follow the strategy of providing
  28505. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  28506. * and reinstated. See the
  28507. * [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
  28508. *
  28509. * - `ngRepeat` will silently *ignore* object keys starting with `$`, because
  28510. * it's a prefix used by Angular for public (`$`) and private (`$$`) properties.
  28511. *
  28512. * - The built-in filters {@link ng.orderBy orderBy} and {@link ng.filter filter} do not work with
  28513. * objects, and will throw an error if used with one.
  28514. *
  28515. * If you are hitting any of these limitations, the recommended workaround is to convert your object into an array
  28516. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  28517. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  28518. * or implement a `$watch` on the object yourself.
  28519. *
  28520. *
  28521. * ## Tracking and Duplicates
  28522. *
  28523. * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
  28524. * the collection. When a change happens, `ngRepeat` then makes the corresponding changes to the DOM:
  28525. *
  28526. * * When an item is added, a new instance of the template is added to the DOM.
  28527. * * When an item is removed, its template instance is removed from the DOM.
  28528. * * When items are reordered, their respective templates are reordered in the DOM.
  28529. *
  28530. * To minimize creation of DOM elements, `ngRepeat` uses a function
  28531. * to "keep track" of all items in the collection and their corresponding DOM elements.
  28532. * For example, if an item is added to the collection, `ngRepeat` will know that all other items
  28533. * already have DOM elements, and will not re-render them.
  28534. *
  28535. * The default tracking function (which tracks items by their identity) does not allow
  28536. * duplicate items in arrays. This is because when there are duplicates, it is not possible
  28537. * to maintain a one-to-one mapping between collection items and DOM elements.
  28538. *
  28539. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  28540. * with your own using the `track by` expression.
  28541. *
  28542. * For example, you may track items by the index of each item in the collection, using the
  28543. * special scope property `$index`:
  28544. * ```html
  28545. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  28546. * {{n}}
  28547. * </div>
  28548. * ```
  28549. *
  28550. * You may also use arbitrary expressions in `track by`, including references to custom functions
  28551. * on the scope:
  28552. * ```html
  28553. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  28554. * {{n}}
  28555. * </div>
  28556. * ```
  28557. *
  28558. * <div class="alert alert-success">
  28559. * If you are working with objects that have a unique identifier property, you should track
  28560. * by this identifier instead of the object instance. Should you reload your data later, `ngRepeat`
  28561. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  28562. * JavaScript objects in the collection have been substituted for new ones. For large collections,
  28563. * this significantly improves rendering performance. If you don't have a unique identifier,
  28564. * `track by $index` can also provide a performance boost.
  28565. * </div>
  28566. *
  28567. * ```html
  28568. * <div ng-repeat="model in collection track by model.id">
  28569. * {{model.name}}
  28570. * </div>
  28571. * ```
  28572. *
  28573. * <br />
  28574. * <div class="alert alert-warning">
  28575. * Avoid using `track by $index` when the repeated template contains
  28576. * {@link guide/expression#one-time-binding one-time bindings}. In such cases, the `nth` DOM
  28577. * element will always be matched with the `nth` item of the array, so the bindings on that element
  28578. * will not be updated even when the corresponding item changes, essentially causing the view to get
  28579. * out-of-sync with the underlying data.
  28580. * </div>
  28581. *
  28582. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  28583. * `$id` function, which tracks items by their identity:
  28584. * ```html
  28585. * <div ng-repeat="obj in collection track by $id(obj)">
  28586. * {{obj.prop}}
  28587. * </div>
  28588. * ```
  28589. *
  28590. * <br />
  28591. * <div class="alert alert-warning">
  28592. * **Note:** `track by` must always be the last expression:
  28593. * </div>
  28594. * ```
  28595. * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
  28596. * {{model.name}}
  28597. * </div>
  28598. * ```
  28599. *
  28600. *
  28601. * ## Special repeat start and end points
  28602. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  28603. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  28604. * 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)
  28605. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  28606. *
  28607. * The example below makes use of this feature:
  28608. * ```html
  28609. * <header ng-repeat-start="item in items">
  28610. * Header {{ item }}
  28611. * </header>
  28612. * <div class="body">
  28613. * Body {{ item }}
  28614. * </div>
  28615. * <footer ng-repeat-end>
  28616. * Footer {{ item }}
  28617. * </footer>
  28618. * ```
  28619. *
  28620. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  28621. * ```html
  28622. * <header>
  28623. * Header A
  28624. * </header>
  28625. * <div class="body">
  28626. * Body A
  28627. * </div>
  28628. * <footer>
  28629. * Footer A
  28630. * </footer>
  28631. * <header>
  28632. * Header B
  28633. * </header>
  28634. * <div class="body">
  28635. * Body B
  28636. * </div>
  28637. * <footer>
  28638. * Footer B
  28639. * </footer>
  28640. * ```
  28641. *
  28642. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  28643. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  28644. *
  28645. * @animations
  28646. * | Animation | Occurs |
  28647. * |----------------------------------|-------------------------------------|
  28648. * | {@link ng.$animate#enter enter} | when a new item is added to the list or when an item is revealed after a filter |
  28649. * | {@link ng.$animate#leave leave} | when an item is removed from the list or when an item is filtered out |
  28650. * | {@link ng.$animate#move move } | when an adjacent item is filtered out causing a reorder or when the item contents are reordered |
  28651. *
  28652. * See the example below for defining CSS animations with ngRepeat.
  28653. *
  28654. * @element ANY
  28655. * @scope
  28656. * @priority 1000
  28657. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  28658. * formats are currently supported:
  28659. *
  28660. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  28661. * is a scope expression giving the collection to enumerate.
  28662. *
  28663. * For example: `album in artist.albums`.
  28664. *
  28665. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  28666. * and `expression` is the scope expression giving the collection to enumerate.
  28667. *
  28668. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  28669. *
  28670. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  28671. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  28672. * is specified, ng-repeat associates elements by identity. It is an error to have
  28673. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  28674. * mapped to the same DOM element, which is not possible.)
  28675. *
  28676. * <div class="alert alert-warning">
  28677. * <strong>Note:</strong> the `track by` expression must come last - after any filters, and the alias expression.
  28678. * </div>
  28679. *
  28680. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  28681. * will be associated by item identity in the array.
  28682. *
  28683. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  28684. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  28685. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  28686. * element in the same way in the DOM.
  28687. *
  28688. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  28689. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  28690. * property is same.
  28691. *
  28692. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  28693. * to items in conjunction with a tracking expression.
  28694. *
  28695. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  28696. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  28697. * when a filter is active on the repeater, but the filtered result set is empty.
  28698. *
  28699. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  28700. * the items have been processed through the filter.
  28701. *
  28702. * 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
  28703. * (and not as operator, inside an expression).
  28704. *
  28705. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
  28706. *
  28707. * @example
  28708. * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed
  28709. * results by name or by age. New (entering) and removed (leaving) items are animated.
  28710. <example module="ngRepeat" name="ngRepeat" deps="angular-animate.js" animations="true">
  28711. <file name="index.html">
  28712. <div ng-controller="repeatController">
  28713. I have {{friends.length}} friends. They are:
  28714. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  28715. <ul class="example-animate-container">
  28716. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  28717. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  28718. </li>
  28719. <li class="animate-repeat" ng-if="results.length === 0">
  28720. <strong>No results found...</strong>
  28721. </li>
  28722. </ul>
  28723. </div>
  28724. </file>
  28725. <file name="script.js">
  28726. angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
  28727. $scope.friends = [
  28728. {name:'John', age:25, gender:'boy'},
  28729. {name:'Jessie', age:30, gender:'girl'},
  28730. {name:'Johanna', age:28, gender:'girl'},
  28731. {name:'Joy', age:15, gender:'girl'},
  28732. {name:'Mary', age:28, gender:'girl'},
  28733. {name:'Peter', age:95, gender:'boy'},
  28734. {name:'Sebastian', age:50, gender:'boy'},
  28735. {name:'Erika', age:27, gender:'girl'},
  28736. {name:'Patrick', age:40, gender:'boy'},
  28737. {name:'Samantha', age:60, gender:'girl'}
  28738. ];
  28739. });
  28740. </file>
  28741. <file name="animations.css">
  28742. .example-animate-container {
  28743. background:white;
  28744. border:1px solid black;
  28745. list-style:none;
  28746. margin:0;
  28747. padding:0 10px;
  28748. }
  28749. .animate-repeat {
  28750. line-height:30px;
  28751. list-style:none;
  28752. box-sizing:border-box;
  28753. }
  28754. .animate-repeat.ng-move,
  28755. .animate-repeat.ng-enter,
  28756. .animate-repeat.ng-leave {
  28757. transition:all linear 0.5s;
  28758. }
  28759. .animate-repeat.ng-leave.ng-leave-active,
  28760. .animate-repeat.ng-move,
  28761. .animate-repeat.ng-enter {
  28762. opacity:0;
  28763. max-height:0;
  28764. }
  28765. .animate-repeat.ng-leave,
  28766. .animate-repeat.ng-move.ng-move-active,
  28767. .animate-repeat.ng-enter.ng-enter-active {
  28768. opacity:1;
  28769. max-height:30px;
  28770. }
  28771. </file>
  28772. <file name="protractor.js" type="protractor">
  28773. var friends = element.all(by.repeater('friend in friends'));
  28774. it('should render initial data set', function() {
  28775. expect(friends.count()).toBe(10);
  28776. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  28777. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  28778. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  28779. expect(element(by.binding('friends.length')).getText())
  28780. .toMatch("I have 10 friends. They are:");
  28781. });
  28782. it('should update repeater when filter predicate changes', function() {
  28783. expect(friends.count()).toBe(10);
  28784. element(by.model('q')).sendKeys('ma');
  28785. expect(friends.count()).toBe(2);
  28786. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  28787. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  28788. });
  28789. </file>
  28790. </example>
  28791. */
  28792. var ngRepeatDirective = ['$parse', '$animate', '$compile', function($parse, $animate, $compile) {
  28793. var NG_REMOVED = '$$NG_REMOVED';
  28794. var ngRepeatMinErr = minErr('ngRepeat');
  28795. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  28796. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  28797. scope[valueIdentifier] = value;
  28798. if (keyIdentifier) scope[keyIdentifier] = key;
  28799. scope.$index = index;
  28800. scope.$first = (index === 0);
  28801. scope.$last = (index === (arrayLength - 1));
  28802. scope.$middle = !(scope.$first || scope.$last);
  28803. // eslint-disable-next-line no-bitwise
  28804. scope.$odd = !(scope.$even = (index & 1) === 0);
  28805. };
  28806. var getBlockStart = function(block) {
  28807. return block.clone[0];
  28808. };
  28809. var getBlockEnd = function(block) {
  28810. return block.clone[block.clone.length - 1];
  28811. };
  28812. return {
  28813. restrict: 'A',
  28814. multiElement: true,
  28815. transclude: 'element',
  28816. priority: 1000,
  28817. terminal: true,
  28818. $$tlb: true,
  28819. compile: function ngRepeatCompile($element, $attr) {
  28820. var expression = $attr.ngRepeat;
  28821. var ngRepeatEndComment = $compile.$$createComment('end ngRepeat', expression);
  28822. 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*$/);
  28823. if (!match) {
  28824. throw ngRepeatMinErr('iexp', 'Expected expression in form of \'_item_ in _collection_[ track by _id_]\' but got \'{0}\'.',
  28825. expression);
  28826. }
  28827. var lhs = match[1];
  28828. var rhs = match[2];
  28829. var aliasAs = match[3];
  28830. var trackByExp = match[4];
  28831. match = lhs.match(/^(?:(\s*[$\w]+)|\(\s*([$\w]+)\s*,\s*([$\w]+)\s*\))$/);
  28832. if (!match) {
  28833. throw ngRepeatMinErr('iidexp', '\'_item_\' in \'_item_ in _collection_\' should be an identifier or \'(_key_, _value_)\' expression, but got \'{0}\'.',
  28834. lhs);
  28835. }
  28836. var valueIdentifier = match[3] || match[1];
  28837. var keyIdentifier = match[2];
  28838. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  28839. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  28840. throw ngRepeatMinErr('badident', 'alias \'{0}\' is invalid --- must be a valid JS identifier which is not a reserved name.',
  28841. aliasAs);
  28842. }
  28843. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  28844. var hashFnLocals = {$id: hashKey};
  28845. if (trackByExp) {
  28846. trackByExpGetter = $parse(trackByExp);
  28847. } else {
  28848. trackByIdArrayFn = function(key, value) {
  28849. return hashKey(value);
  28850. };
  28851. trackByIdObjFn = function(key) {
  28852. return key;
  28853. };
  28854. }
  28855. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  28856. if (trackByExpGetter) {
  28857. trackByIdExpFn = function(key, value, index) {
  28858. // assign key, value, and $index to the locals so that they can be used in hash functions
  28859. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  28860. hashFnLocals[valueIdentifier] = value;
  28861. hashFnLocals.$index = index;
  28862. return trackByExpGetter($scope, hashFnLocals);
  28863. };
  28864. }
  28865. // Store a list of elements from previous run. This is a hash where key is the item from the
  28866. // iterator, and the value is objects with following properties.
  28867. // - scope: bound scope
  28868. // - clone: previous element.
  28869. // - index: position
  28870. //
  28871. // We are using no-proto object so that we don't need to guard against inherited props via
  28872. // hasOwnProperty.
  28873. var lastBlockMap = createMap();
  28874. //watch props
  28875. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  28876. var index, length,
  28877. previousNode = $element[0], // node that cloned nodes should be inserted after
  28878. // initialized to the comment node anchor
  28879. nextNode,
  28880. // Same as lastBlockMap but it has the current state. It will become the
  28881. // lastBlockMap on the next iteration.
  28882. nextBlockMap = createMap(),
  28883. collectionLength,
  28884. key, value, // key/value of iteration
  28885. trackById,
  28886. trackByIdFn,
  28887. collectionKeys,
  28888. block, // last object information {scope, element, id}
  28889. nextBlockOrder,
  28890. elementsToRemove;
  28891. if (aliasAs) {
  28892. $scope[aliasAs] = collection;
  28893. }
  28894. if (isArrayLike(collection)) {
  28895. collectionKeys = collection;
  28896. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  28897. } else {
  28898. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  28899. // if object, extract keys, in enumeration order, unsorted
  28900. collectionKeys = [];
  28901. for (var itemKey in collection) {
  28902. if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
  28903. collectionKeys.push(itemKey);
  28904. }
  28905. }
  28906. }
  28907. collectionLength = collectionKeys.length;
  28908. nextBlockOrder = new Array(collectionLength);
  28909. // locate existing items
  28910. for (index = 0; index < collectionLength; index++) {
  28911. key = (collection === collectionKeys) ? index : collectionKeys[index];
  28912. value = collection[key];
  28913. trackById = trackByIdFn(key, value, index);
  28914. if (lastBlockMap[trackById]) {
  28915. // found previously seen block
  28916. block = lastBlockMap[trackById];
  28917. delete lastBlockMap[trackById];
  28918. nextBlockMap[trackById] = block;
  28919. nextBlockOrder[index] = block;
  28920. } else if (nextBlockMap[trackById]) {
  28921. // if collision detected. restore lastBlockMap and throw an error
  28922. forEach(nextBlockOrder, function(block) {
  28923. if (block && block.scope) lastBlockMap[block.id] = block;
  28924. });
  28925. throw ngRepeatMinErr('dupes',
  28926. 'Duplicates in a repeater are not allowed. Use \'track by\' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}',
  28927. expression, trackById, value);
  28928. } else {
  28929. // new never before seen block
  28930. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  28931. nextBlockMap[trackById] = true;
  28932. }
  28933. }
  28934. // remove leftover items
  28935. for (var blockKey in lastBlockMap) {
  28936. block = lastBlockMap[blockKey];
  28937. elementsToRemove = getBlockNodes(block.clone);
  28938. $animate.leave(elementsToRemove);
  28939. if (elementsToRemove[0].parentNode) {
  28940. // if the element was not removed yet because of pending animation, mark it as deleted
  28941. // so that we can ignore it later
  28942. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  28943. elementsToRemove[index][NG_REMOVED] = true;
  28944. }
  28945. }
  28946. block.scope.$destroy();
  28947. }
  28948. // we are not using forEach for perf reasons (trying to avoid #call)
  28949. for (index = 0; index < collectionLength; index++) {
  28950. key = (collection === collectionKeys) ? index : collectionKeys[index];
  28951. value = collection[key];
  28952. block = nextBlockOrder[index];
  28953. if (block.scope) {
  28954. // if we have already seen this object, then we need to reuse the
  28955. // associated scope/element
  28956. nextNode = previousNode;
  28957. // skip nodes that are already pending removal via leave animation
  28958. do {
  28959. nextNode = nextNode.nextSibling;
  28960. } while (nextNode && nextNode[NG_REMOVED]);
  28961. if (getBlockStart(block) !== nextNode) {
  28962. // existing item which got moved
  28963. $animate.move(getBlockNodes(block.clone), null, previousNode);
  28964. }
  28965. previousNode = getBlockEnd(block);
  28966. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  28967. } else {
  28968. // new item which we don't know about
  28969. $transclude(function ngRepeatTransclude(clone, scope) {
  28970. block.scope = scope;
  28971. // http://jsperf.com/clone-vs-createcomment
  28972. var endNode = ngRepeatEndComment.cloneNode(false);
  28973. clone[clone.length++] = endNode;
  28974. $animate.enter(clone, null, previousNode);
  28975. previousNode = endNode;
  28976. // Note: We only need the first/last node of the cloned nodes.
  28977. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  28978. // by a directive with templateUrl when its template arrives.
  28979. block.clone = clone;
  28980. nextBlockMap[block.id] = block;
  28981. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  28982. });
  28983. }
  28984. }
  28985. lastBlockMap = nextBlockMap;
  28986. });
  28987. };
  28988. }
  28989. };
  28990. }];
  28991. var NG_HIDE_CLASS = 'ng-hide';
  28992. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  28993. /**
  28994. * @ngdoc directive
  28995. * @name ngShow
  28996. * @multiElement
  28997. *
  28998. * @description
  28999. * The `ngShow` directive shows or hides the given HTML element based on the expression provided to
  29000. * the `ngShow` attribute.
  29001. *
  29002. * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element.
  29003. * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an
  29004. * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see
  29005. * {@link ng.directive:ngCsp ngCsp}).
  29006. *
  29007. * ```html
  29008. * <!-- when $scope.myValue is truthy (element is visible) -->
  29009. * <div ng-show="myValue"></div>
  29010. *
  29011. * <!-- when $scope.myValue is falsy (element is hidden) -->
  29012. * <div ng-show="myValue" class="ng-hide"></div>
  29013. * ```
  29014. *
  29015. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added
  29016. * to the class attribute on the element causing it to become hidden. When truthy, the `.ng-hide`
  29017. * CSS class is removed from the element causing the element not to appear hidden.
  29018. *
  29019. * ## Why is `!important` used?
  29020. *
  29021. * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the
  29022. * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as
  29023. * simple as changing the display style on a HTML list item would make hidden elements appear
  29024. * visible. This also becomes a bigger issue when dealing with CSS frameworks.
  29025. *
  29026. * By using `!important`, the show and hide behavior will work as expected despite any clash between
  29027. * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a
  29028. * developer chooses to override the styling to change how to hide an element then it is just a
  29029. * matter of using `!important` in their own CSS code.
  29030. *
  29031. * ### Overriding `.ng-hide`
  29032. *
  29033. * By default, the `.ng-hide` class will style the element with `display: none !important`. If you
  29034. * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for
  29035. * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually
  29036. * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added.
  29037. *
  29038. * ```css
  29039. * .ng-hide:not(.ng-hide-animate) {
  29040. * /&#42; These are just alternative ways of hiding an element &#42;/
  29041. * display: block!important;
  29042. * position: absolute;
  29043. * top: -9999px;
  29044. * left: -9999px;
  29045. * }
  29046. * ```
  29047. *
  29048. * By default you don't need to override anything in CSS and the animations will work around the
  29049. * display style.
  29050. *
  29051. * @animations
  29052. * | Animation | Occurs |
  29053. * |-----------------------------------------------------|---------------------------------------------------------------------------------------------------------------|
  29054. * | {@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. |
  29055. * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngShow` expression evaluates to a truthy value and just before contents are set to visible. |
  29056. *
  29057. * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the
  29058. * directive expression is true and false. This system works like the animation system present with
  29059. * `ngClass` except that you must also include the `!important` flag to override the display
  29060. * property so that the elements are not actually hidden during the animation.
  29061. *
  29062. * ```css
  29063. * /&#42; A working example can be found at the bottom of this page. &#42;/
  29064. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  29065. * transition: all 0.5s linear;
  29066. * }
  29067. *
  29068. * .my-element.ng-hide-add { ... }
  29069. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  29070. * .my-element.ng-hide-remove { ... }
  29071. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  29072. * ```
  29073. *
  29074. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property
  29075. * to block during animation states - ngAnimate will automatically handle the style toggling for you.
  29076. *
  29077. * @element ANY
  29078. * @param {expression} ngShow If the {@link guide/expression expression} is truthy/falsy then the
  29079. * element is shown/hidden respectively.
  29080. *
  29081. * @example
  29082. * A simple example, animating the element's opacity:
  29083. *
  29084. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show-simple">
  29085. <file name="index.html">
  29086. Show: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br />
  29087. <div class="check-element animate-show-hide" ng-show="checked">
  29088. I show up when your checkbox is checked.
  29089. </div>
  29090. </file>
  29091. <file name="animations.css">
  29092. .animate-show-hide.ng-hide {
  29093. opacity: 0;
  29094. }
  29095. .animate-show-hide.ng-hide-add,
  29096. .animate-show-hide.ng-hide-remove {
  29097. transition: all linear 0.5s;
  29098. }
  29099. .check-element {
  29100. border: 1px solid black;
  29101. opacity: 1;
  29102. padding: 10px;
  29103. }
  29104. </file>
  29105. <file name="protractor.js" type="protractor">
  29106. it('should check ngShow', function() {
  29107. var checkbox = element(by.model('checked'));
  29108. var checkElem = element(by.css('.check-element'));
  29109. expect(checkElem.isDisplayed()).toBe(false);
  29110. checkbox.click();
  29111. expect(checkElem.isDisplayed()).toBe(true);
  29112. });
  29113. </file>
  29114. </example>
  29115. *
  29116. * <hr />
  29117. * @example
  29118. * A more complex example, featuring different show/hide animations:
  29119. *
  29120. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-show-complex">
  29121. <file name="index.html">
  29122. Show: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br />
  29123. <div class="check-element funky-show-hide" ng-show="checked">
  29124. I show up when your checkbox is checked.
  29125. </div>
  29126. </file>
  29127. <file name="animations.css">
  29128. body {
  29129. overflow: hidden;
  29130. perspective: 1000px;
  29131. }
  29132. .funky-show-hide.ng-hide-add {
  29133. transform: rotateZ(0);
  29134. transform-origin: right;
  29135. transition: all 0.5s ease-in-out;
  29136. }
  29137. .funky-show-hide.ng-hide-add.ng-hide-add-active {
  29138. transform: rotateZ(-135deg);
  29139. }
  29140. .funky-show-hide.ng-hide-remove {
  29141. transform: rotateY(90deg);
  29142. transform-origin: left;
  29143. transition: all 0.5s ease;
  29144. }
  29145. .funky-show-hide.ng-hide-remove.ng-hide-remove-active {
  29146. transform: rotateY(0);
  29147. }
  29148. .check-element {
  29149. border: 1px solid black;
  29150. opacity: 1;
  29151. padding: 10px;
  29152. }
  29153. </file>
  29154. <file name="protractor.js" type="protractor">
  29155. it('should check ngShow', function() {
  29156. var checkbox = element(by.model('checked'));
  29157. var checkElem = element(by.css('.check-element'));
  29158. expect(checkElem.isDisplayed()).toBe(false);
  29159. checkbox.click();
  29160. expect(checkElem.isDisplayed()).toBe(true);
  29161. });
  29162. </file>
  29163. </example>
  29164. */
  29165. var ngShowDirective = ['$animate', function($animate) {
  29166. return {
  29167. restrict: 'A',
  29168. multiElement: true,
  29169. link: function(scope, element, attr) {
  29170. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  29171. // we're adding a temporary, animation-specific class for ng-hide since this way
  29172. // we can control when the element is actually displayed on screen without having
  29173. // to have a global/greedy CSS selector that breaks when other animations are run.
  29174. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  29175. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  29176. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  29177. });
  29178. });
  29179. }
  29180. };
  29181. }];
  29182. /**
  29183. * @ngdoc directive
  29184. * @name ngHide
  29185. * @multiElement
  29186. *
  29187. * @description
  29188. * The `ngHide` directive shows or hides the given HTML element based on the expression provided to
  29189. * the `ngHide` attribute.
  29190. *
  29191. * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element.
  29192. * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an
  29193. * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see
  29194. * {@link ng.directive:ngCsp ngCsp}).
  29195. *
  29196. * ```html
  29197. * <!-- when $scope.myValue is truthy (element is hidden) -->
  29198. * <div ng-hide="myValue" class="ng-hide"></div>
  29199. *
  29200. * <!-- when $scope.myValue is falsy (element is visible) -->
  29201. * <div ng-hide="myValue"></div>
  29202. * ```
  29203. *
  29204. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added
  29205. * to the class attribute on the element causing it to become hidden. When falsy, the `.ng-hide`
  29206. * CSS class is removed from the element causing the element not to appear hidden.
  29207. *
  29208. * ## Why is `!important` used?
  29209. *
  29210. * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the
  29211. * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as
  29212. * simple as changing the display style on a HTML list item would make hidden elements appear
  29213. * visible. This also becomes a bigger issue when dealing with CSS frameworks.
  29214. *
  29215. * By using `!important`, the show and hide behavior will work as expected despite any clash between
  29216. * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a
  29217. * developer chooses to override the styling to change how to hide an element then it is just a
  29218. * matter of using `!important` in their own CSS code.
  29219. *
  29220. * ### Overriding `.ng-hide`
  29221. *
  29222. * By default, the `.ng-hide` class will style the element with `display: none !important`. If you
  29223. * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for
  29224. * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually
  29225. * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added.
  29226. *
  29227. * ```css
  29228. * .ng-hide:not(.ng-hide-animate) {
  29229. * /&#42; These are just alternative ways of hiding an element &#42;/
  29230. * display: block!important;
  29231. * position: absolute;
  29232. * top: -9999px;
  29233. * left: -9999px;
  29234. * }
  29235. * ```
  29236. *
  29237. * By default you don't need to override in CSS anything and the animations will work around the
  29238. * display style.
  29239. *
  29240. * @animations
  29241. * | Animation | Occurs |
  29242. * |-----------------------------------------------------|------------------------------------------------------------------------------------------------------------|
  29243. * | {@link $animate#addClass addClass} `.ng-hide` | After the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden. |
  29244. * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngHide` expression evaluates to a non truthy value and just before contents are set to visible. |
  29245. *
  29246. * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the
  29247. * directive expression is true and false. This system works like the animation system present with
  29248. * `ngClass` except that you must also include the `!important` flag to override the display
  29249. * property so that the elements are not actually hidden during the animation.
  29250. *
  29251. * ```css
  29252. * /&#42; A working example can be found at the bottom of this page. &#42;/
  29253. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  29254. * transition: all 0.5s linear;
  29255. * }
  29256. *
  29257. * .my-element.ng-hide-add { ... }
  29258. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  29259. * .my-element.ng-hide-remove { ... }
  29260. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  29261. * ```
  29262. *
  29263. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property
  29264. * to block during animation states - ngAnimate will automatically handle the style toggling for you.
  29265. *
  29266. * @element ANY
  29267. * @param {expression} ngHide If the {@link guide/expression expression} is truthy/falsy then the
  29268. * element is hidden/shown respectively.
  29269. *
  29270. * @example
  29271. * A simple example, animating the element's opacity:
  29272. *
  29273. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide-simple">
  29274. <file name="index.html">
  29275. Hide: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br />
  29276. <div class="check-element animate-show-hide" ng-hide="checked">
  29277. I hide when your checkbox is checked.
  29278. </div>
  29279. </file>
  29280. <file name="animations.css">
  29281. .animate-show-hide.ng-hide {
  29282. opacity: 0;
  29283. }
  29284. .animate-show-hide.ng-hide-add,
  29285. .animate-show-hide.ng-hide-remove {
  29286. transition: all linear 0.5s;
  29287. }
  29288. .check-element {
  29289. border: 1px solid black;
  29290. opacity: 1;
  29291. padding: 10px;
  29292. }
  29293. </file>
  29294. <file name="protractor.js" type="protractor">
  29295. it('should check ngHide', function() {
  29296. var checkbox = element(by.model('checked'));
  29297. var checkElem = element(by.css('.check-element'));
  29298. expect(checkElem.isDisplayed()).toBe(true);
  29299. checkbox.click();
  29300. expect(checkElem.isDisplayed()).toBe(false);
  29301. });
  29302. </file>
  29303. </example>
  29304. *
  29305. * <hr />
  29306. * @example
  29307. * A more complex example, featuring different show/hide animations:
  29308. *
  29309. <example module="ngAnimate" deps="angular-animate.js" animations="true" name="ng-hide-complex">
  29310. <file name="index.html">
  29311. Hide: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br />
  29312. <div class="check-element funky-show-hide" ng-hide="checked">
  29313. I hide when your checkbox is checked.
  29314. </div>
  29315. </file>
  29316. <file name="animations.css">
  29317. body {
  29318. overflow: hidden;
  29319. perspective: 1000px;
  29320. }
  29321. .funky-show-hide.ng-hide-add {
  29322. transform: rotateZ(0);
  29323. transform-origin: right;
  29324. transition: all 0.5s ease-in-out;
  29325. }
  29326. .funky-show-hide.ng-hide-add.ng-hide-add-active {
  29327. transform: rotateZ(-135deg);
  29328. }
  29329. .funky-show-hide.ng-hide-remove {
  29330. transform: rotateY(90deg);
  29331. transform-origin: left;
  29332. transition: all 0.5s ease;
  29333. }
  29334. .funky-show-hide.ng-hide-remove.ng-hide-remove-active {
  29335. transform: rotateY(0);
  29336. }
  29337. .check-element {
  29338. border: 1px solid black;
  29339. opacity: 1;
  29340. padding: 10px;
  29341. }
  29342. </file>
  29343. <file name="protractor.js" type="protractor">
  29344. it('should check ngHide', function() {
  29345. var checkbox = element(by.model('checked'));
  29346. var checkElem = element(by.css('.check-element'));
  29347. expect(checkElem.isDisplayed()).toBe(true);
  29348. checkbox.click();
  29349. expect(checkElem.isDisplayed()).toBe(false);
  29350. });
  29351. </file>
  29352. </example>
  29353. */
  29354. var ngHideDirective = ['$animate', function($animate) {
  29355. return {
  29356. restrict: 'A',
  29357. multiElement: true,
  29358. link: function(scope, element, attr) {
  29359. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  29360. // The comment inside of the ngShowDirective explains why we add and
  29361. // remove a temporary class for the show/hide animation
  29362. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  29363. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  29364. });
  29365. });
  29366. }
  29367. };
  29368. }];
  29369. /**
  29370. * @ngdoc directive
  29371. * @name ngStyle
  29372. * @restrict AC
  29373. *
  29374. * @description
  29375. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  29376. *
  29377. * @knownIssue
  29378. * You should not use {@link guide/interpolation interpolation} in the value of the `style`
  29379. * attribute, when using the `ngStyle` directive on the same element.
  29380. * See {@link guide/interpolation#known-issues here} for more info.
  29381. *
  29382. * @element ANY
  29383. * @param {expression} ngStyle
  29384. *
  29385. * {@link guide/expression Expression} which evals to an
  29386. * object whose keys are CSS style names and values are corresponding values for those CSS
  29387. * keys.
  29388. *
  29389. * Since some CSS style names are not valid keys for an object, they must be quoted.
  29390. * See the 'background-color' style in the example below.
  29391. *
  29392. * @example
  29393. <example name="ng-style">
  29394. <file name="index.html">
  29395. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  29396. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  29397. <input type="button" value="clear" ng-click="myStyle={}">
  29398. <br/>
  29399. <span ng-style="myStyle">Sample Text</span>
  29400. <pre>myStyle={{myStyle}}</pre>
  29401. </file>
  29402. <file name="style.css">
  29403. span {
  29404. color: black;
  29405. }
  29406. </file>
  29407. <file name="protractor.js" type="protractor">
  29408. var colorSpan = element(by.css('span'));
  29409. it('should check ng-style', function() {
  29410. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  29411. element(by.css('input[value=\'set color\']')).click();
  29412. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  29413. element(by.css('input[value=clear]')).click();
  29414. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  29415. });
  29416. </file>
  29417. </example>
  29418. */
  29419. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  29420. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  29421. if (oldStyles && (newStyles !== oldStyles)) {
  29422. forEach(oldStyles, function(val, style) { element.css(style, '');});
  29423. }
  29424. if (newStyles) element.css(newStyles);
  29425. }, true);
  29426. });
  29427. /**
  29428. * @ngdoc directive
  29429. * @name ngSwitch
  29430. * @restrict EA
  29431. *
  29432. * @description
  29433. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  29434. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  29435. * as specified in the template.
  29436. *
  29437. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  29438. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  29439. * matches the value obtained from the evaluated expression. In other words, you define a container element
  29440. * (where you place the directive), place an expression on the **`on="..."` attribute**
  29441. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  29442. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  29443. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  29444. * attribute is displayed.
  29445. *
  29446. * <div class="alert alert-info">
  29447. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  29448. * as literal string values to match against.
  29449. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  29450. * value of the expression `$scope.someVal`.
  29451. * </div>
  29452. * @animations
  29453. * | Animation | Occurs |
  29454. * |----------------------------------|-------------------------------------|
  29455. * | {@link ng.$animate#enter enter} | after the ngSwitch contents change and the matched child element is placed inside the container |
  29456. * | {@link ng.$animate#leave leave} | after the ngSwitch contents change and just before the former contents are removed from the DOM |
  29457. *
  29458. * @usage
  29459. *
  29460. * ```
  29461. * <ANY ng-switch="expression">
  29462. * <ANY ng-switch-when="matchValue1">...</ANY>
  29463. * <ANY ng-switch-when="matchValue2">...</ANY>
  29464. * <ANY ng-switch-default>...</ANY>
  29465. * </ANY>
  29466. * ```
  29467. *
  29468. *
  29469. * @scope
  29470. * @priority 1200
  29471. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  29472. * On child elements add:
  29473. *
  29474. * * `ngSwitchWhen`: the case statement to match against. If match then this
  29475. * case will be displayed. If the same match appears multiple times, all the
  29476. * elements will be displayed. It is possible to associate multiple values to
  29477. * the same `ngSwitchWhen` by defining the optional attribute
  29478. * `ngSwitchWhenSeparator`. The separator will be used to split the value of
  29479. * the `ngSwitchWhen` attribute into multiple tokens, and the element will show
  29480. * if any of the `ngSwitch` evaluates to any of these tokens.
  29481. * * `ngSwitchDefault`: the default case when no other case match. If there
  29482. * are multiple default cases, all of them will be displayed when no other
  29483. * case match.
  29484. *
  29485. *
  29486. * @example
  29487. <example module="switchExample" deps="angular-animate.js" animations="true" name="ng-switch">
  29488. <file name="index.html">
  29489. <div ng-controller="ExampleController">
  29490. <select ng-model="selection" ng-options="item for item in items">
  29491. </select>
  29492. <code>selection={{selection}}</code>
  29493. <hr/>
  29494. <div class="animate-switch-container"
  29495. ng-switch on="selection">
  29496. <div class="animate-switch" ng-switch-when="settings|options" ng-switch-when-separator="|">Settings Div</div>
  29497. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  29498. <div class="animate-switch" ng-switch-default>default</div>
  29499. </div>
  29500. </div>
  29501. </file>
  29502. <file name="script.js">
  29503. angular.module('switchExample', ['ngAnimate'])
  29504. .controller('ExampleController', ['$scope', function($scope) {
  29505. $scope.items = ['settings', 'home', 'options', 'other'];
  29506. $scope.selection = $scope.items[0];
  29507. }]);
  29508. </file>
  29509. <file name="animations.css">
  29510. .animate-switch-container {
  29511. position:relative;
  29512. background:white;
  29513. border:1px solid black;
  29514. height:40px;
  29515. overflow:hidden;
  29516. }
  29517. .animate-switch {
  29518. padding:10px;
  29519. }
  29520. .animate-switch.ng-animate {
  29521. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  29522. position:absolute;
  29523. top:0;
  29524. left:0;
  29525. right:0;
  29526. bottom:0;
  29527. }
  29528. .animate-switch.ng-leave.ng-leave-active,
  29529. .animate-switch.ng-enter {
  29530. top:-50px;
  29531. }
  29532. .animate-switch.ng-leave,
  29533. .animate-switch.ng-enter.ng-enter-active {
  29534. top:0;
  29535. }
  29536. </file>
  29537. <file name="protractor.js" type="protractor">
  29538. var switchElem = element(by.css('[ng-switch]'));
  29539. var select = element(by.model('selection'));
  29540. it('should start in settings', function() {
  29541. expect(switchElem.getText()).toMatch(/Settings Div/);
  29542. });
  29543. it('should change to home', function() {
  29544. select.all(by.css('option')).get(1).click();
  29545. expect(switchElem.getText()).toMatch(/Home Span/);
  29546. });
  29547. it('should change to settings via "options"', function() {
  29548. select.all(by.css('option')).get(2).click();
  29549. expect(switchElem.getText()).toMatch(/Settings Div/);
  29550. });
  29551. it('should select default', function() {
  29552. select.all(by.css('option')).get(3).click();
  29553. expect(switchElem.getText()).toMatch(/default/);
  29554. });
  29555. </file>
  29556. </example>
  29557. */
  29558. var ngSwitchDirective = ['$animate', '$compile', function($animate, $compile) {
  29559. return {
  29560. require: 'ngSwitch',
  29561. // asks for $scope to fool the BC controller module
  29562. controller: ['$scope', function NgSwitchController() {
  29563. this.cases = {};
  29564. }],
  29565. link: function(scope, element, attr, ngSwitchController) {
  29566. var watchExpr = attr.ngSwitch || attr.on,
  29567. selectedTranscludes = [],
  29568. selectedElements = [],
  29569. previousLeaveAnimations = [],
  29570. selectedScopes = [];
  29571. var spliceFactory = function(array, index) {
  29572. return function(response) {
  29573. if (response !== false) array.splice(index, 1);
  29574. };
  29575. };
  29576. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  29577. var i, ii;
  29578. // Start with the last, in case the array is modified during the loop
  29579. while (previousLeaveAnimations.length) {
  29580. $animate.cancel(previousLeaveAnimations.pop());
  29581. }
  29582. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  29583. var selected = getBlockNodes(selectedElements[i].clone);
  29584. selectedScopes[i].$destroy();
  29585. var runner = previousLeaveAnimations[i] = $animate.leave(selected);
  29586. runner.done(spliceFactory(previousLeaveAnimations, i));
  29587. }
  29588. selectedElements.length = 0;
  29589. selectedScopes.length = 0;
  29590. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  29591. forEach(selectedTranscludes, function(selectedTransclude) {
  29592. selectedTransclude.transclude(function(caseElement, selectedScope) {
  29593. selectedScopes.push(selectedScope);
  29594. var anchor = selectedTransclude.element;
  29595. caseElement[caseElement.length++] = $compile.$$createComment('end ngSwitchWhen');
  29596. var block = { clone: caseElement };
  29597. selectedElements.push(block);
  29598. $animate.enter(caseElement, anchor.parent(), anchor);
  29599. });
  29600. });
  29601. }
  29602. });
  29603. }
  29604. };
  29605. }];
  29606. var ngSwitchWhenDirective = ngDirective({
  29607. transclude: 'element',
  29608. priority: 1200,
  29609. require: '^ngSwitch',
  29610. multiElement: true,
  29611. link: function(scope, element, attrs, ctrl, $transclude) {
  29612. var cases = attrs.ngSwitchWhen.split(attrs.ngSwitchWhenSeparator).sort().filter(
  29613. // Filter duplicate cases
  29614. function(element, index, array) { return array[index - 1] !== element; }
  29615. );
  29616. forEach(cases, function(whenCase) {
  29617. ctrl.cases['!' + whenCase] = (ctrl.cases['!' + whenCase] || []);
  29618. ctrl.cases['!' + whenCase].push({ transclude: $transclude, element: element });
  29619. });
  29620. }
  29621. });
  29622. var ngSwitchDefaultDirective = ngDirective({
  29623. transclude: 'element',
  29624. priority: 1200,
  29625. require: '^ngSwitch',
  29626. multiElement: true,
  29627. link: function(scope, element, attr, ctrl, $transclude) {
  29628. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  29629. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  29630. }
  29631. });
  29632. /**
  29633. * @ngdoc directive
  29634. * @name ngTransclude
  29635. * @restrict EAC
  29636. *
  29637. * @description
  29638. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  29639. *
  29640. * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name
  29641. * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.
  29642. *
  29643. * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing
  29644. * content of this element will be removed before the transcluded content is inserted.
  29645. * If the transcluded content is empty (or only whitespace), the existing content is left intact. This lets you provide fallback
  29646. * content in the case that no transcluded content is provided.
  29647. *
  29648. * @element ANY
  29649. *
  29650. * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty
  29651. * or its value is the same as the name of the attribute then the default slot is used.
  29652. *
  29653. * @example
  29654. * ### Basic transclusion
  29655. * This example demonstrates basic transclusion of content into a component directive.
  29656. * <example name="simpleTranscludeExample" module="transcludeExample">
  29657. * <file name="index.html">
  29658. * <script>
  29659. * angular.module('transcludeExample', [])
  29660. * .directive('pane', function(){
  29661. * return {
  29662. * restrict: 'E',
  29663. * transclude: true,
  29664. * scope: { title:'@' },
  29665. * template: '<div style="border: 1px solid black;">' +
  29666. * '<div style="background-color: gray">{{title}}</div>' +
  29667. * '<ng-transclude></ng-transclude>' +
  29668. * '</div>'
  29669. * };
  29670. * })
  29671. * .controller('ExampleController', ['$scope', function($scope) {
  29672. * $scope.title = 'Lorem Ipsum';
  29673. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  29674. * }]);
  29675. * </script>
  29676. * <div ng-controller="ExampleController">
  29677. * <input ng-model="title" aria-label="title"> <br/>
  29678. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  29679. * <pane title="{{title}}"><span>{{text}}</span></pane>
  29680. * </div>
  29681. * </file>
  29682. * <file name="protractor.js" type="protractor">
  29683. * it('should have transcluded', function() {
  29684. * var titleElement = element(by.model('title'));
  29685. * titleElement.clear();
  29686. * titleElement.sendKeys('TITLE');
  29687. * var textElement = element(by.model('text'));
  29688. * textElement.clear();
  29689. * textElement.sendKeys('TEXT');
  29690. * expect(element(by.binding('title')).getText()).toEqual('TITLE');
  29691. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  29692. * });
  29693. * </file>
  29694. * </example>
  29695. *
  29696. * @example
  29697. * ### Transclude fallback content
  29698. * This example shows how to use `NgTransclude` with fallback content, that
  29699. * is displayed if no transcluded content is provided.
  29700. *
  29701. * <example module="transcludeFallbackContentExample" name="ng-transclude">
  29702. * <file name="index.html">
  29703. * <script>
  29704. * angular.module('transcludeFallbackContentExample', [])
  29705. * .directive('myButton', function(){
  29706. * return {
  29707. * restrict: 'E',
  29708. * transclude: true,
  29709. * scope: true,
  29710. * template: '<button style="cursor: pointer;">' +
  29711. * '<ng-transclude>' +
  29712. * '<b style="color: red;">Button1</b>' +
  29713. * '</ng-transclude>' +
  29714. * '</button>'
  29715. * };
  29716. * });
  29717. * </script>
  29718. * <!-- fallback button content -->
  29719. * <my-button id="fallback"></my-button>
  29720. * <!-- modified button content -->
  29721. * <my-button id="modified">
  29722. * <i style="color: green;">Button2</i>
  29723. * </my-button>
  29724. * </file>
  29725. * <file name="protractor.js" type="protractor">
  29726. * it('should have different transclude element content', function() {
  29727. * expect(element(by.id('fallback')).getText()).toBe('Button1');
  29728. * expect(element(by.id('modified')).getText()).toBe('Button2');
  29729. * });
  29730. * </file>
  29731. * </example>
  29732. *
  29733. * @example
  29734. * ### Multi-slot transclusion
  29735. * This example demonstrates using multi-slot transclusion in a component directive.
  29736. * <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample">
  29737. * <file name="index.html">
  29738. * <style>
  29739. * .title, .footer {
  29740. * background-color: gray
  29741. * }
  29742. * </style>
  29743. * <div ng-controller="ExampleController">
  29744. * <input ng-model="title" aria-label="title"> <br/>
  29745. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  29746. * <pane>
  29747. * <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
  29748. * <pane-body><p>{{text}}</p></pane-body>
  29749. * </pane>
  29750. * </div>
  29751. * </file>
  29752. * <file name="app.js">
  29753. * angular.module('multiSlotTranscludeExample', [])
  29754. * .directive('pane', function() {
  29755. * return {
  29756. * restrict: 'E',
  29757. * transclude: {
  29758. * 'title': '?paneTitle',
  29759. * 'body': 'paneBody',
  29760. * 'footer': '?paneFooter'
  29761. * },
  29762. * template: '<div style="border: 1px solid black;">' +
  29763. * '<div class="title" ng-transclude="title">Fallback Title</div>' +
  29764. * '<div ng-transclude="body"></div>' +
  29765. * '<div class="footer" ng-transclude="footer">Fallback Footer</div>' +
  29766. * '</div>'
  29767. * };
  29768. * })
  29769. * .controller('ExampleController', ['$scope', function($scope) {
  29770. * $scope.title = 'Lorem Ipsum';
  29771. * $scope.link = 'https://google.com';
  29772. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  29773. * }]);
  29774. * </file>
  29775. * <file name="protractor.js" type="protractor">
  29776. * it('should have transcluded the title and the body', function() {
  29777. * var titleElement = element(by.model('title'));
  29778. * titleElement.clear();
  29779. * titleElement.sendKeys('TITLE');
  29780. * var textElement = element(by.model('text'));
  29781. * textElement.clear();
  29782. * textElement.sendKeys('TEXT');
  29783. * expect(element(by.css('.title')).getText()).toEqual('TITLE');
  29784. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  29785. * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer');
  29786. * });
  29787. * </file>
  29788. * </example>
  29789. */
  29790. var ngTranscludeMinErr = minErr('ngTransclude');
  29791. var ngTranscludeDirective = ['$compile', function($compile) {
  29792. return {
  29793. restrict: 'EAC',
  29794. terminal: true,
  29795. compile: function ngTranscludeCompile(tElement) {
  29796. // Remove and cache any original content to act as a fallback
  29797. var fallbackLinkFn = $compile(tElement.contents());
  29798. tElement.empty();
  29799. return function ngTranscludePostLink($scope, $element, $attrs, controller, $transclude) {
  29800. if (!$transclude) {
  29801. throw ngTranscludeMinErr('orphan',
  29802. 'Illegal use of ngTransclude directive in the template! ' +
  29803. 'No parent directive that requires a transclusion found. ' +
  29804. 'Element: {0}',
  29805. startingTag($element));
  29806. }
  29807. // If the attribute is of the form: `ng-transclude="ng-transclude"` then treat it like the default
  29808. if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) {
  29809. $attrs.ngTransclude = '';
  29810. }
  29811. var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot;
  29812. // If the slot is required and no transclusion content is provided then this call will throw an error
  29813. $transclude(ngTranscludeCloneAttachFn, null, slotName);
  29814. // If the slot is optional and no transclusion content is provided then use the fallback content
  29815. if (slotName && !$transclude.isSlotFilled(slotName)) {
  29816. useFallbackContent();
  29817. }
  29818. function ngTranscludeCloneAttachFn(clone, transcludedScope) {
  29819. if (clone.length && notWhitespace(clone)) {
  29820. $element.append(clone);
  29821. } else {
  29822. useFallbackContent();
  29823. // There is nothing linked against the transcluded scope since no content was available,
  29824. // so it should be safe to clean up the generated scope.
  29825. transcludedScope.$destroy();
  29826. }
  29827. }
  29828. function useFallbackContent() {
  29829. // Since this is the fallback content rather than the transcluded content,
  29830. // we link against the scope of this directive rather than the transcluded scope
  29831. fallbackLinkFn($scope, function(clone) {
  29832. $element.append(clone);
  29833. });
  29834. }
  29835. function notWhitespace(nodes) {
  29836. for (var i = 0, ii = nodes.length; i < ii; i++) {
  29837. var node = nodes[i];
  29838. if (node.nodeType !== NODE_TYPE_TEXT || node.nodeValue.trim()) {
  29839. return true;
  29840. }
  29841. }
  29842. }
  29843. };
  29844. }
  29845. };
  29846. }];
  29847. /**
  29848. * @ngdoc directive
  29849. * @name script
  29850. * @restrict E
  29851. *
  29852. * @description
  29853. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  29854. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  29855. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  29856. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  29857. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  29858. *
  29859. * @param {string} type Must be set to `'text/ng-template'`.
  29860. * @param {string} id Cache name of the template.
  29861. *
  29862. * @example
  29863. <example name="script-tag">
  29864. <file name="index.html">
  29865. <script type="text/ng-template" id="/tpl.html">
  29866. Content of the template.
  29867. </script>
  29868. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  29869. <div id="tpl-content" ng-include src="currentTpl"></div>
  29870. </file>
  29871. <file name="protractor.js" type="protractor">
  29872. it('should load template defined inside script tag', function() {
  29873. element(by.css('#tpl-link')).click();
  29874. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  29875. });
  29876. </file>
  29877. </example>
  29878. */
  29879. var scriptDirective = ['$templateCache', function($templateCache) {
  29880. return {
  29881. restrict: 'E',
  29882. terminal: true,
  29883. compile: function(element, attr) {
  29884. if (attr.type === 'text/ng-template') {
  29885. var templateUrl = attr.id,
  29886. text = element[0].text;
  29887. $templateCache.put(templateUrl, text);
  29888. }
  29889. }
  29890. };
  29891. }];
  29892. /* exported selectDirective, optionDirective */
  29893. var noopNgModelController = { $setViewValue: noop, $render: noop };
  29894. function setOptionSelectedStatus(optionEl, value) {
  29895. optionEl.prop('selected', value);
  29896. /**
  29897. * When unselecting an option, setting the property to null / false should be enough
  29898. * However, screenreaders might react to the selected attribute instead, see
  29899. * https://github.com/angular/angular.js/issues/14419
  29900. * Note: "selected" is a boolean attr and will be removed when the "value" arg in attr() is false
  29901. * or null
  29902. */
  29903. optionEl.attr('selected', value);
  29904. }
  29905. /**
  29906. * @ngdoc type
  29907. * @name select.SelectController
  29908. *
  29909. * @description
  29910. * The controller for the {@link ng.select select} directive. The controller exposes
  29911. * a few utility methods that can be used to augment the behavior of a regular or an
  29912. * {@link ng.ngOptions ngOptions} select element.
  29913. *
  29914. * @example
  29915. * ### Set a custom error when the unknown option is selected
  29916. *
  29917. * This example sets a custom error "unknownValue" on the ngModelController
  29918. * when the select element's unknown option is selected, i.e. when the model is set to a value
  29919. * that is not matched by any option.
  29920. *
  29921. * <example name="select-unknown-value-error" module="staticSelect">
  29922. * <file name="index.html">
  29923. * <div ng-controller="ExampleController">
  29924. * <form name="myForm">
  29925. * <label for="testSelect"> Single select: </label><br>
  29926. * <select name="testSelect" ng-model="selected" unknown-value-error>
  29927. * <option value="option-1">Option 1</option>
  29928. * <option value="option-2">Option 2</option>
  29929. * </select><br>
  29930. * <span class="error" ng-if="myForm.testSelect.$error.unknownValue">
  29931. * Error: The current model doesn't match any option</span><br>
  29932. *
  29933. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  29934. * </form>
  29935. * </div>
  29936. * </file>
  29937. * <file name="app.js">
  29938. * angular.module('staticSelect', [])
  29939. * .controller('ExampleController', ['$scope', function($scope) {
  29940. * $scope.selected = null;
  29941. *
  29942. * $scope.forceUnknownOption = function() {
  29943. * $scope.selected = 'nonsense';
  29944. * };
  29945. * }])
  29946. * .directive('unknownValueError', function() {
  29947. * return {
  29948. * require: ['ngModel', 'select'],
  29949. * link: function(scope, element, attrs, ctrls) {
  29950. * var ngModelCtrl = ctrls[0];
  29951. * var selectCtrl = ctrls[1];
  29952. *
  29953. * ngModelCtrl.$validators.unknownValue = function(modelValue, viewValue) {
  29954. * if (selectCtrl.$isUnknownOptionSelected()) {
  29955. * return false;
  29956. * }
  29957. *
  29958. * return true;
  29959. * };
  29960. * }
  29961. *
  29962. * };
  29963. * });
  29964. * </file>
  29965. *</example>
  29966. *
  29967. *
  29968. * @example
  29969. * ### Set the "required" error when the unknown option is selected.
  29970. *
  29971. * By default, the "required" error on the ngModelController is only set on a required select
  29972. * when the empty option is selected. This example adds a custom directive that also sets the
  29973. * error when the unknown option is selected.
  29974. *
  29975. * <example name="select-unknown-value-required" module="staticSelect">
  29976. * <file name="index.html">
  29977. * <div ng-controller="ExampleController">
  29978. * <form name="myForm">
  29979. * <label for="testSelect"> Select: </label><br>
  29980. * <select name="testSelect" ng-model="selected" required unknown-value-required>
  29981. * <option value="option-1">Option 1</option>
  29982. * <option value="option-2">Option 2</option>
  29983. * </select><br>
  29984. * <span class="error" ng-if="myForm.testSelect.$error.required">Error: Please select a value</span><br>
  29985. *
  29986. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  29987. * </form>
  29988. * </div>
  29989. * </file>
  29990. * <file name="app.js">
  29991. * angular.module('staticSelect', [])
  29992. * .controller('ExampleController', ['$scope', function($scope) {
  29993. * $scope.selected = null;
  29994. *
  29995. * $scope.forceUnknownOption = function() {
  29996. * $scope.selected = 'nonsense';
  29997. * };
  29998. * }])
  29999. * .directive('unknownValueRequired', function() {
  30000. * return {
  30001. * priority: 1, // This directive must run after the required directive has added its validator
  30002. * require: ['ngModel', 'select'],
  30003. * link: function(scope, element, attrs, ctrls) {
  30004. * var ngModelCtrl = ctrls[0];
  30005. * var selectCtrl = ctrls[1];
  30006. *
  30007. * var originalRequiredValidator = ngModelCtrl.$validators.required;
  30008. *
  30009. * ngModelCtrl.$validators.required = function() {
  30010. * if (attrs.required && selectCtrl.$isUnknownOptionSelected()) {
  30011. * return false;
  30012. * }
  30013. *
  30014. * return originalRequiredValidator.apply(this, arguments);
  30015. * };
  30016. * }
  30017. * };
  30018. * });
  30019. * </file>
  30020. * <file name="protractor.js" type="protractor">
  30021. * it('should show the error message when the unknown option is selected', function() {
  30022. var error = element(by.className('error'));
  30023. expect(error.getText()).toBe('Error: Please select a value');
  30024. element(by.cssContainingText('option', 'Option 1')).click();
  30025. expect(error.isPresent()).toBe(false);
  30026. element(by.tagName('button')).click();
  30027. expect(error.getText()).toBe('Error: Please select a value');
  30028. });
  30029. * </file>
  30030. *</example>
  30031. *
  30032. *
  30033. */
  30034. var SelectController =
  30035. ['$element', '$scope', /** @this */ function($element, $scope) {
  30036. var self = this,
  30037. optionsMap = new NgMap();
  30038. self.selectValueMap = {}; // Keys are the hashed values, values the original values
  30039. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  30040. self.ngModelCtrl = noopNgModelController;
  30041. self.multiple = false;
  30042. // The "unknown" option is one that is prepended to the list if the viewValue
  30043. // does not match any of the options. When it is rendered the value of the unknown
  30044. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  30045. //
  30046. // Support: IE 9 only
  30047. // We can't just jqLite('<option>') since jqLite is not smart enough
  30048. // to create it in <select> and IE barfs otherwise.
  30049. self.unknownOption = jqLite(window.document.createElement('option'));
  30050. // The empty option is an option with the value '' that the application developer can
  30051. // provide inside the select. It is always selectable and indicates that a "null" selection has
  30052. // been made by the user.
  30053. // If the select has an empty option, and the model of the select is set to "undefined" or "null",
  30054. // the empty option is selected.
  30055. // If the model is set to a different unmatched value, the unknown option is rendered and
  30056. // selected, i.e both are present, because a "null" selection and an unknown value are different.
  30057. self.hasEmptyOption = false;
  30058. self.emptyOption = undefined;
  30059. self.renderUnknownOption = function(val) {
  30060. var unknownVal = self.generateUnknownOptionValue(val);
  30061. self.unknownOption.val(unknownVal);
  30062. $element.prepend(self.unknownOption);
  30063. setOptionSelectedStatus(self.unknownOption, true);
  30064. $element.val(unknownVal);
  30065. };
  30066. self.updateUnknownOption = function(val) {
  30067. var unknownVal = self.generateUnknownOptionValue(val);
  30068. self.unknownOption.val(unknownVal);
  30069. setOptionSelectedStatus(self.unknownOption, true);
  30070. $element.val(unknownVal);
  30071. };
  30072. self.generateUnknownOptionValue = function(val) {
  30073. return '? ' + hashKey(val) + ' ?';
  30074. };
  30075. self.removeUnknownOption = function() {
  30076. if (self.unknownOption.parent()) self.unknownOption.remove();
  30077. };
  30078. self.selectEmptyOption = function() {
  30079. if (self.emptyOption) {
  30080. $element.val('');
  30081. setOptionSelectedStatus(self.emptyOption, true);
  30082. }
  30083. };
  30084. self.unselectEmptyOption = function() {
  30085. if (self.hasEmptyOption) {
  30086. setOptionSelectedStatus(self.emptyOption, false);
  30087. }
  30088. };
  30089. $scope.$on('$destroy', function() {
  30090. // disable unknown option so that we don't do work when the whole select is being destroyed
  30091. self.renderUnknownOption = noop;
  30092. });
  30093. // Read the value of the select control, the implementation of this changes depending
  30094. // upon whether the select can have multiple values and whether ngOptions is at work.
  30095. self.readValue = function readSingleValue() {
  30096. var val = $element.val();
  30097. // ngValue added option values are stored in the selectValueMap, normal interpolations are not
  30098. var realVal = val in self.selectValueMap ? self.selectValueMap[val] : val;
  30099. if (self.hasOption(realVal)) {
  30100. return realVal;
  30101. }
  30102. return null;
  30103. };
  30104. // Write the value to the select control, the implementation of this changes depending
  30105. // upon whether the select can have multiple values and whether ngOptions is at work.
  30106. self.writeValue = function writeSingleValue(value) {
  30107. // Make sure to remove the selected attribute from the previously selected option
  30108. // Otherwise, screen readers might get confused
  30109. var currentlySelectedOption = $element[0].options[$element[0].selectedIndex];
  30110. if (currentlySelectedOption) setOptionSelectedStatus(jqLite(currentlySelectedOption), false);
  30111. if (self.hasOption(value)) {
  30112. self.removeUnknownOption();
  30113. var hashedVal = hashKey(value);
  30114. $element.val(hashedVal in self.selectValueMap ? hashedVal : value);
  30115. // Set selected attribute and property on selected option for screen readers
  30116. var selectedOption = $element[0].options[$element[0].selectedIndex];
  30117. setOptionSelectedStatus(jqLite(selectedOption), true);
  30118. } else {
  30119. self.selectUnknownOrEmptyOption(value);
  30120. }
  30121. };
  30122. // Tell the select control that an option, with the given value, has been added
  30123. self.addOption = function(value, element) {
  30124. // Skip comment nodes, as they only pollute the `optionsMap`
  30125. if (element[0].nodeType === NODE_TYPE_COMMENT) return;
  30126. assertNotHasOwnProperty(value, '"option value"');
  30127. if (value === '') {
  30128. self.hasEmptyOption = true;
  30129. self.emptyOption = element;
  30130. }
  30131. var count = optionsMap.get(value) || 0;
  30132. optionsMap.set(value, count + 1);
  30133. // Only render at the end of a digest. This improves render performance when many options
  30134. // are added during a digest and ensures all relevant options are correctly marked as selected
  30135. scheduleRender();
  30136. };
  30137. // Tell the select control that an option, with the given value, has been removed
  30138. self.removeOption = function(value) {
  30139. var count = optionsMap.get(value);
  30140. if (count) {
  30141. if (count === 1) {
  30142. optionsMap.delete(value);
  30143. if (value === '') {
  30144. self.hasEmptyOption = false;
  30145. self.emptyOption = undefined;
  30146. }
  30147. } else {
  30148. optionsMap.set(value, count - 1);
  30149. }
  30150. }
  30151. };
  30152. // Check whether the select control has an option matching the given value
  30153. self.hasOption = function(value) {
  30154. return !!optionsMap.get(value);
  30155. };
  30156. /**
  30157. * @ngdoc method
  30158. * @name select.SelectController#$hasEmptyOption
  30159. *
  30160. * @description
  30161. *
  30162. * Returns `true` if the select element currently has an empty option
  30163. * element, i.e. an option that signifies that the select is empty / the selection is null.
  30164. *
  30165. */
  30166. self.$hasEmptyOption = function() {
  30167. return self.hasEmptyOption;
  30168. };
  30169. /**
  30170. * @ngdoc method
  30171. * @name select.SelectController#$isUnknownOptionSelected
  30172. *
  30173. * @description
  30174. *
  30175. * Returns `true` if the select element's unknown option is selected. The unknown option is added
  30176. * and automatically selected whenever the select model doesn't match any option.
  30177. *
  30178. */
  30179. self.$isUnknownOptionSelected = function() {
  30180. // Presence of the unknown option means it is selected
  30181. return $element[0].options[0] === self.unknownOption[0];
  30182. };
  30183. /**
  30184. * @ngdoc method
  30185. * @name select.SelectController#$isEmptyOptionSelected
  30186. *
  30187. * @description
  30188. *
  30189. * Returns `true` if the select element has an empty option and this empty option is currently
  30190. * selected. Returns `false` if the select element has no empty option or it is not selected.
  30191. *
  30192. */
  30193. self.$isEmptyOptionSelected = function() {
  30194. return self.hasEmptyOption && $element[0].options[$element[0].selectedIndex] === self.emptyOption[0];
  30195. };
  30196. self.selectUnknownOrEmptyOption = function(value) {
  30197. if (value == null && self.emptyOption) {
  30198. self.removeUnknownOption();
  30199. self.selectEmptyOption();
  30200. } else if (self.unknownOption.parent().length) {
  30201. self.updateUnknownOption(value);
  30202. } else {
  30203. self.renderUnknownOption(value);
  30204. }
  30205. };
  30206. var renderScheduled = false;
  30207. function scheduleRender() {
  30208. if (renderScheduled) return;
  30209. renderScheduled = true;
  30210. $scope.$$postDigest(function() {
  30211. renderScheduled = false;
  30212. self.ngModelCtrl.$render();
  30213. });
  30214. }
  30215. var updateScheduled = false;
  30216. function scheduleViewValueUpdate(renderAfter) {
  30217. if (updateScheduled) return;
  30218. updateScheduled = true;
  30219. $scope.$$postDigest(function() {
  30220. if ($scope.$$destroyed) return;
  30221. updateScheduled = false;
  30222. self.ngModelCtrl.$setViewValue(self.readValue());
  30223. if (renderAfter) self.ngModelCtrl.$render();
  30224. });
  30225. }
  30226. self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
  30227. if (optionAttrs.$attr.ngValue) {
  30228. // The value attribute is set by ngValue
  30229. var oldVal, hashedVal = NaN;
  30230. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  30231. var removal;
  30232. var previouslySelected = optionElement.prop('selected');
  30233. if (isDefined(hashedVal)) {
  30234. self.removeOption(oldVal);
  30235. delete self.selectValueMap[hashedVal];
  30236. removal = true;
  30237. }
  30238. hashedVal = hashKey(newVal);
  30239. oldVal = newVal;
  30240. self.selectValueMap[hashedVal] = newVal;
  30241. self.addOption(newVal, optionElement);
  30242. // Set the attribute directly instead of using optionAttrs.$set - this stops the observer
  30243. // from firing a second time. Other $observers on value will also get the result of the
  30244. // ngValue expression, not the hashed value
  30245. optionElement.attr('value', hashedVal);
  30246. if (removal && previouslySelected) {
  30247. scheduleViewValueUpdate();
  30248. }
  30249. });
  30250. } else if (interpolateValueFn) {
  30251. // The value attribute is interpolated
  30252. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  30253. // This method is overwritten in ngOptions and has side-effects!
  30254. self.readValue();
  30255. var removal;
  30256. var previouslySelected = optionElement.prop('selected');
  30257. if (isDefined(oldVal)) {
  30258. self.removeOption(oldVal);
  30259. removal = true;
  30260. }
  30261. oldVal = newVal;
  30262. self.addOption(newVal, optionElement);
  30263. if (removal && previouslySelected) {
  30264. scheduleViewValueUpdate();
  30265. }
  30266. });
  30267. } else if (interpolateTextFn) {
  30268. // The text content is interpolated
  30269. optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
  30270. optionAttrs.$set('value', newVal);
  30271. var previouslySelected = optionElement.prop('selected');
  30272. if (oldVal !== newVal) {
  30273. self.removeOption(oldVal);
  30274. }
  30275. self.addOption(newVal, optionElement);
  30276. if (oldVal && previouslySelected) {
  30277. scheduleViewValueUpdate();
  30278. }
  30279. });
  30280. } else {
  30281. // The value attribute is static
  30282. self.addOption(optionAttrs.value, optionElement);
  30283. }
  30284. optionAttrs.$observe('disabled', function(newVal) {
  30285. // Since model updates will also select disabled options (like ngOptions),
  30286. // we only have to handle options becoming disabled, not enabled
  30287. if (newVal === 'true' || newVal && optionElement.prop('selected')) {
  30288. if (self.multiple) {
  30289. scheduleViewValueUpdate(true);
  30290. } else {
  30291. self.ngModelCtrl.$setViewValue(null);
  30292. self.ngModelCtrl.$render();
  30293. }
  30294. }
  30295. });
  30296. optionElement.on('$destroy', function() {
  30297. var currentValue = self.readValue();
  30298. var removeValue = optionAttrs.value;
  30299. self.removeOption(removeValue);
  30300. scheduleRender();
  30301. if (self.multiple && currentValue && currentValue.indexOf(removeValue) !== -1 ||
  30302. currentValue === removeValue
  30303. ) {
  30304. // When multiple (selected) options are destroyed at the same time, we don't want
  30305. // to run a model update for each of them. Instead, run a single update in the $$postDigest
  30306. scheduleViewValueUpdate(true);
  30307. }
  30308. });
  30309. };
  30310. }];
  30311. /**
  30312. * @ngdoc directive
  30313. * @name select
  30314. * @restrict E
  30315. *
  30316. * @description
  30317. * HTML `select` element with angular data-binding.
  30318. *
  30319. * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
  30320. * between the scope and the `<select>` control (including setting default values).
  30321. * It also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
  30322. * {@link ngOptions `ngOptions`} directives.
  30323. *
  30324. * When an item in the `<select>` menu is selected, the value of the selected option will be bound
  30325. * to the model identified by the `ngModel` directive. With static or repeated options, this is
  30326. * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
  30327. * Value and textContent can be interpolated.
  30328. *
  30329. * The {@link select.SelectController select controller} exposes utility functions that can be used
  30330. * to manipulate the select's behavior.
  30331. *
  30332. * ## Matching model and option values
  30333. *
  30334. * In general, the match between the model and an option is evaluated by strictly comparing the model
  30335. * value against the value of the available options.
  30336. *
  30337. * If you are setting the option value with the option's `value` attribute, or textContent, the
  30338. * value will always be a `string` which means that the model value must also be a string.
  30339. * Otherwise the `select` directive cannot match them correctly.
  30340. *
  30341. * To bind the model to a non-string value, you can use one of the following strategies:
  30342. * - the {@link ng.ngOptions `ngOptions`} directive
  30343. * ({@link ng.select#using-select-with-ngoptions-and-setting-a-default-value})
  30344. * - the {@link ng.ngValue `ngValue`} directive, which allows arbitrary expressions to be
  30345. * option values ({@link ng.select#using-ngvalue-to-bind-the-model-to-an-array-of-objects Example})
  30346. * - model $parsers / $formatters to convert the string value
  30347. * ({@link ng.select#binding-select-to-a-non-string-value-via-ngmodel-parsing-formatting Example})
  30348. *
  30349. * If the viewValue of `ngModel` does not match any of the options, then the control
  30350. * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
  30351. *
  30352. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  30353. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  30354. * option. See example below for demonstration.
  30355. *
  30356. * ## Choosing between `ngRepeat` and `ngOptions`
  30357. *
  30358. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  30359. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits:
  30360. * - more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  30361. * comprehension expression
  30362. * - reduced memory consumption by not creating a new scope for each repeated instance
  30363. * - increased render speed by creating the options in a documentFragment instead of individually
  30364. *
  30365. * Specifically, select with repeated options slows down significantly starting at 2000 options in
  30366. * Chrome and Internet Explorer / Edge.
  30367. *
  30368. *
  30369. * @param {string} ngModel Assignable angular expression to data-bind to.
  30370. * @param {string=} name Property name of the form under which the control is published.
  30371. * @param {string=} multiple Allows multiple options to be selected. The selected values will be
  30372. * bound to the model as an array.
  30373. * @param {string=} required Sets `required` validation error key if the value is not entered.
  30374. * @param {string=} ngRequired Adds required attribute and required validation constraint to
  30375. * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
  30376. * when you want to data-bind to the required attribute.
  30377. * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
  30378. * interaction with the select element.
  30379. * @param {string=} ngOptions sets the options that the select is populated with and defines what is
  30380. * set on the model on selection. See {@link ngOptions `ngOptions`}.
  30381. * @param {string=} ngAttrSize sets the size of the select element dynamically. Uses the
  30382. * {@link guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes ngAttr} directive.
  30383. *
  30384. *
  30385. * @knownIssue
  30386. *
  30387. * In Firefox, the select model is only updated when the select element is blurred. For example,
  30388. * when switching between options with the keyboard, the select model is only set to the
  30389. * currently selected option when the select is blurred, e.g via tab key or clicking the mouse
  30390. * outside the select.
  30391. *
  30392. * This is due to an ambiguity in the select element specification. See the
  30393. * [issue on the Firefox bug tracker](https://bugzilla.mozilla.org/show_bug.cgi?id=126379)
  30394. * for more information, and this
  30395. * [Github comment for a workaround](https://github.com/angular/angular.js/issues/9134#issuecomment-130800488)
  30396. *
  30397. * @example
  30398. * ### Simple `select` elements with static options
  30399. *
  30400. * <example name="static-select" module="staticSelect">
  30401. * <file name="index.html">
  30402. * <div ng-controller="ExampleController">
  30403. * <form name="myForm">
  30404. * <label for="singleSelect"> Single select: </label><br>
  30405. * <select name="singleSelect" ng-model="data.singleSelect">
  30406. * <option value="option-1">Option 1</option>
  30407. * <option value="option-2">Option 2</option>
  30408. * </select><br>
  30409. *
  30410. * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
  30411. * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
  30412. * <option value="">---Please select---</option> <!-- not selected / blank option -->
  30413. * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
  30414. * <option value="option-2">Option 2</option>
  30415. * </select><br>
  30416. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  30417. * <tt>singleSelect = {{data.singleSelect}}</tt>
  30418. *
  30419. * <hr>
  30420. * <label for="multipleSelect"> Multiple select: </label><br>
  30421. * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
  30422. * <option value="option-1">Option 1</option>
  30423. * <option value="option-2">Option 2</option>
  30424. * <option value="option-3">Option 3</option>
  30425. * </select><br>
  30426. * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
  30427. * </form>
  30428. * </div>
  30429. * </file>
  30430. * <file name="app.js">
  30431. * angular.module('staticSelect', [])
  30432. * .controller('ExampleController', ['$scope', function($scope) {
  30433. * $scope.data = {
  30434. * singleSelect: null,
  30435. * multipleSelect: [],
  30436. * option1: 'option-1'
  30437. * };
  30438. *
  30439. * $scope.forceUnknownOption = function() {
  30440. * $scope.data.singleSelect = 'nonsense';
  30441. * };
  30442. * }]);
  30443. * </file>
  30444. *</example>
  30445. *
  30446. * @example
  30447. * ### Using `ngRepeat` to generate `select` options
  30448. * <example name="select-ngrepeat" module="ngrepeatSelect">
  30449. * <file name="index.html">
  30450. * <div ng-controller="ExampleController">
  30451. * <form name="myForm">
  30452. * <label for="repeatSelect"> Repeat select: </label>
  30453. * <select name="repeatSelect" id="repeatSelect" ng-model="data.model">
  30454. * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
  30455. * </select>
  30456. * </form>
  30457. * <hr>
  30458. * <tt>model = {{data.model}}</tt><br/>
  30459. * </div>
  30460. * </file>
  30461. * <file name="app.js">
  30462. * angular.module('ngrepeatSelect', [])
  30463. * .controller('ExampleController', ['$scope', function($scope) {
  30464. * $scope.data = {
  30465. * model: null,
  30466. * availableOptions: [
  30467. * {id: '1', name: 'Option A'},
  30468. * {id: '2', name: 'Option B'},
  30469. * {id: '3', name: 'Option C'}
  30470. * ]
  30471. * };
  30472. * }]);
  30473. * </file>
  30474. *</example>
  30475. *
  30476. * @example
  30477. * ### Using `ngValue` to bind the model to an array of objects
  30478. * <example name="select-ngvalue" module="ngvalueSelect">
  30479. * <file name="index.html">
  30480. * <div ng-controller="ExampleController">
  30481. * <form name="myForm">
  30482. * <label for="ngvalueselect"> ngvalue select: </label>
  30483. * <select size="6" name="ngvalueselect" ng-model="data.model" multiple>
  30484. * <option ng-repeat="option in data.availableOptions" ng-value="option.value">{{option.name}}</option>
  30485. * </select>
  30486. * </form>
  30487. * <hr>
  30488. * <pre>model = {{data.model | json}}</pre><br/>
  30489. * </div>
  30490. * </file>
  30491. * <file name="app.js">
  30492. * angular.module('ngvalueSelect', [])
  30493. * .controller('ExampleController', ['$scope', function($scope) {
  30494. * $scope.data = {
  30495. * model: null,
  30496. * availableOptions: [
  30497. {value: 'myString', name: 'string'},
  30498. {value: 1, name: 'integer'},
  30499. {value: true, name: 'boolean'},
  30500. {value: null, name: 'null'},
  30501. {value: {prop: 'value'}, name: 'object'},
  30502. {value: ['a'], name: 'array'}
  30503. * ]
  30504. * };
  30505. * }]);
  30506. * </file>
  30507. *</example>
  30508. *
  30509. * @example
  30510. * ### Using `select` with `ngOptions` and setting a default value
  30511. * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
  30512. *
  30513. * <example name="select-with-default-values" module="defaultValueSelect">
  30514. * <file name="index.html">
  30515. * <div ng-controller="ExampleController">
  30516. * <form name="myForm">
  30517. * <label for="mySelect">Make a choice:</label>
  30518. * <select name="mySelect" id="mySelect"
  30519. * ng-options="option.name for option in data.availableOptions track by option.id"
  30520. * ng-model="data.selectedOption"></select>
  30521. * </form>
  30522. * <hr>
  30523. * <tt>option = {{data.selectedOption}}</tt><br/>
  30524. * </div>
  30525. * </file>
  30526. * <file name="app.js">
  30527. * angular.module('defaultValueSelect', [])
  30528. * .controller('ExampleController', ['$scope', function($scope) {
  30529. * $scope.data = {
  30530. * availableOptions: [
  30531. * {id: '1', name: 'Option A'},
  30532. * {id: '2', name: 'Option B'},
  30533. * {id: '3', name: 'Option C'}
  30534. * ],
  30535. * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
  30536. * };
  30537. * }]);
  30538. * </file>
  30539. *</example>
  30540. *
  30541. * @example
  30542. * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
  30543. *
  30544. * <example name="select-with-non-string-options" module="nonStringSelect">
  30545. * <file name="index.html">
  30546. * <select ng-model="model.id" convert-to-number>
  30547. * <option value="0">Zero</option>
  30548. * <option value="1">One</option>
  30549. * <option value="2">Two</option>
  30550. * </select>
  30551. * {{ model }}
  30552. * </file>
  30553. * <file name="app.js">
  30554. * angular.module('nonStringSelect', [])
  30555. * .run(function($rootScope) {
  30556. * $rootScope.model = { id: 2 };
  30557. * })
  30558. * .directive('convertToNumber', function() {
  30559. * return {
  30560. * require: 'ngModel',
  30561. * link: function(scope, element, attrs, ngModel) {
  30562. * ngModel.$parsers.push(function(val) {
  30563. * return parseInt(val, 10);
  30564. * });
  30565. * ngModel.$formatters.push(function(val) {
  30566. * return '' + val;
  30567. * });
  30568. * }
  30569. * };
  30570. * });
  30571. * </file>
  30572. * <file name="protractor.js" type="protractor">
  30573. * it('should initialize to model', function() {
  30574. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  30575. * });
  30576. * </file>
  30577. * </example>
  30578. *
  30579. */
  30580. var selectDirective = function() {
  30581. return {
  30582. restrict: 'E',
  30583. require: ['select', '?ngModel'],
  30584. controller: SelectController,
  30585. priority: 1,
  30586. link: {
  30587. pre: selectPreLink,
  30588. post: selectPostLink
  30589. }
  30590. };
  30591. function selectPreLink(scope, element, attr, ctrls) {
  30592. var selectCtrl = ctrls[0];
  30593. var ngModelCtrl = ctrls[1];
  30594. // if ngModel is not defined, we don't need to do anything but set the registerOption
  30595. // function to noop, so options don't get added internally
  30596. if (!ngModelCtrl) {
  30597. selectCtrl.registerOption = noop;
  30598. return;
  30599. }
  30600. selectCtrl.ngModelCtrl = ngModelCtrl;
  30601. // When the selected item(s) changes we delegate getting the value of the select control
  30602. // to the `readValue` method, which can be changed if the select can have multiple
  30603. // selected values or if the options are being generated by `ngOptions`
  30604. element.on('change', function() {
  30605. selectCtrl.removeUnknownOption();
  30606. scope.$apply(function() {
  30607. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  30608. });
  30609. });
  30610. // If the select allows multiple values then we need to modify how we read and write
  30611. // values from and to the control; also what it means for the value to be empty and
  30612. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  30613. // doesn't trigger rendering if only an item in the array changes.
  30614. if (attr.multiple) {
  30615. selectCtrl.multiple = true;
  30616. // Read value now needs to check each option to see if it is selected
  30617. selectCtrl.readValue = function readMultipleValue() {
  30618. var array = [];
  30619. forEach(element.find('option'), function(option) {
  30620. if (option.selected && !option.disabled) {
  30621. var val = option.value;
  30622. array.push(val in selectCtrl.selectValueMap ? selectCtrl.selectValueMap[val] : val);
  30623. }
  30624. });
  30625. return array;
  30626. };
  30627. // Write value now needs to set the selected property of each matching option
  30628. selectCtrl.writeValue = function writeMultipleValue(value) {
  30629. forEach(element.find('option'), function(option) {
  30630. var shouldBeSelected = !!value && (includes(value, option.value) ||
  30631. includes(value, selectCtrl.selectValueMap[option.value]));
  30632. var currentlySelected = option.selected;
  30633. // Support: IE 9-11 only, Edge 12-15+
  30634. // In IE and Edge adding options to the selection via shift+click/UP/DOWN
  30635. // will de-select already selected options if "selected" on those options was set
  30636. // more than once (i.e. when the options were already selected)
  30637. // So we only modify the selected property if necessary.
  30638. // Note: this behavior cannot be replicated via unit tests because it only shows in the
  30639. // actual user interface.
  30640. if (shouldBeSelected !== currentlySelected) {
  30641. setOptionSelectedStatus(jqLite(option), shouldBeSelected);
  30642. }
  30643. });
  30644. };
  30645. // we have to do it on each watch since ngModel watches reference, but
  30646. // we need to work of an array, so we need to see if anything was inserted/removed
  30647. var lastView, lastViewRef = NaN;
  30648. scope.$watch(function selectMultipleWatch() {
  30649. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  30650. lastView = shallowCopy(ngModelCtrl.$viewValue);
  30651. ngModelCtrl.$render();
  30652. }
  30653. lastViewRef = ngModelCtrl.$viewValue;
  30654. });
  30655. // If we are a multiple select then value is now a collection
  30656. // so the meaning of $isEmpty changes
  30657. ngModelCtrl.$isEmpty = function(value) {
  30658. return !value || value.length === 0;
  30659. };
  30660. }
  30661. }
  30662. function selectPostLink(scope, element, attrs, ctrls) {
  30663. // if ngModel is not defined, we don't need to do anything
  30664. var ngModelCtrl = ctrls[1];
  30665. if (!ngModelCtrl) return;
  30666. var selectCtrl = ctrls[0];
  30667. // We delegate rendering to the `writeValue` method, which can be changed
  30668. // if the select can have multiple selected values or if the options are being
  30669. // generated by `ngOptions`.
  30670. // This must be done in the postLink fn to prevent $render to be called before
  30671. // all nodes have been linked correctly.
  30672. ngModelCtrl.$render = function() {
  30673. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  30674. };
  30675. }
  30676. };
  30677. // The option directive is purely designed to communicate the existence (or lack of)
  30678. // of dynamically created (and destroyed) option elements to their containing select
  30679. // directive via its controller.
  30680. var optionDirective = ['$interpolate', function($interpolate) {
  30681. return {
  30682. restrict: 'E',
  30683. priority: 100,
  30684. compile: function(element, attr) {
  30685. var interpolateValueFn, interpolateTextFn;
  30686. if (isDefined(attr.ngValue)) {
  30687. // Will be handled by registerOption
  30688. } else if (isDefined(attr.value)) {
  30689. // If the value attribute is defined, check if it contains an interpolation
  30690. interpolateValueFn = $interpolate(attr.value, true);
  30691. } else {
  30692. // If the value attribute is not defined then we fall back to the
  30693. // text content of the option element, which may be interpolated
  30694. interpolateTextFn = $interpolate(element.text(), true);
  30695. if (!interpolateTextFn) {
  30696. attr.$set('value', element.text());
  30697. }
  30698. }
  30699. return function(scope, element, attr) {
  30700. // This is an optimization over using ^^ since we don't want to have to search
  30701. // all the way to the root of the DOM for every single option element
  30702. var selectCtrlName = '$selectController',
  30703. parent = element.parent(),
  30704. selectCtrl = parent.data(selectCtrlName) ||
  30705. parent.parent().data(selectCtrlName); // in case we are in optgroup
  30706. if (selectCtrl) {
  30707. selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
  30708. }
  30709. };
  30710. }
  30711. };
  30712. }];
  30713. /**
  30714. * @ngdoc directive
  30715. * @name ngRequired
  30716. * @restrict A
  30717. *
  30718. * @param {expression} ngRequired AngularJS expression. If it evaluates to `true`, it sets the
  30719. * `required` attribute to the element and adds the `required`
  30720. * {@link ngModel.NgModelController#$validators `validator`}.
  30721. *
  30722. * @description
  30723. *
  30724. * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  30725. * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be
  30726. * applied to custom controls.
  30727. *
  30728. * The directive sets the `required` attribute on the element if the Angular expression inside
  30729. * `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we
  30730. * cannot use interpolation inside `required`. See the {@link guide/interpolation interpolation guide}
  30731. * for more info.
  30732. *
  30733. * The validator will set the `required` error key to true if the `required` attribute is set and
  30734. * calling {@link ngModel.NgModelController#$isEmpty `NgModelController.$isEmpty`} with the
  30735. * {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} returns `true`. For example, the
  30736. * `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing
  30737. * custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based.
  30738. *
  30739. * @example
  30740. * <example name="ngRequiredDirective" module="ngRequiredExample">
  30741. * <file name="index.html">
  30742. * <script>
  30743. * angular.module('ngRequiredExample', [])
  30744. * .controller('ExampleController', ['$scope', function($scope) {
  30745. * $scope.required = true;
  30746. * }]);
  30747. * </script>
  30748. * <div ng-controller="ExampleController">
  30749. * <form name="form">
  30750. * <label for="required">Toggle required: </label>
  30751. * <input type="checkbox" ng-model="required" id="required" />
  30752. * <br>
  30753. * <label for="input">This input must be filled if `required` is true: </label>
  30754. * <input type="text" ng-model="model" id="input" name="input" ng-required="required" /><br>
  30755. * <hr>
  30756. * required error set? = <code>{{form.input.$error.required}}</code><br>
  30757. * model = <code>{{model}}</code>
  30758. * </form>
  30759. * </div>
  30760. * </file>
  30761. * <file name="protractor.js" type="protractor">
  30762. var required = element(by.binding('form.input.$error.required'));
  30763. var model = element(by.binding('model'));
  30764. var input = element(by.id('input'));
  30765. it('should set the required error', function() {
  30766. expect(required.getText()).toContain('true');
  30767. input.sendKeys('123');
  30768. expect(required.getText()).not.toContain('true');
  30769. expect(model.getText()).toContain('123');
  30770. });
  30771. * </file>
  30772. * </example>
  30773. */
  30774. var requiredDirective = function() {
  30775. return {
  30776. restrict: 'A',
  30777. require: '?ngModel',
  30778. link: function(scope, elm, attr, ctrl) {
  30779. if (!ctrl) return;
  30780. attr.required = true; // force truthy in case we are on non input element
  30781. ctrl.$validators.required = function(modelValue, viewValue) {
  30782. return !attr.required || !ctrl.$isEmpty(viewValue);
  30783. };
  30784. attr.$observe('required', function() {
  30785. ctrl.$validate();
  30786. });
  30787. }
  30788. };
  30789. };
  30790. /**
  30791. * @ngdoc directive
  30792. * @name ngPattern
  30793. * @restrict A
  30794. *
  30795. * @param {expression|RegExp} ngPattern AngularJS expression that must evaluate to a `RegExp` or a `String`
  30796. * parsable into a `RegExp`, or a `RegExp` literal. See above for
  30797. * more details.
  30798. *
  30799. * @description
  30800. *
  30801. * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  30802. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  30803. *
  30804. * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  30805. * does not match a RegExp which is obtained from the `ngPattern` attribute value:
  30806. * - the value is an AngularJS expression:
  30807. * - If the expression evaluates to a RegExp object, then this is used directly.
  30808. * - If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it
  30809. * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  30810. * - If the value is a RegExp literal, e.g. `ngPattern="/^\d+$/"`, it is used directly.
  30811. *
  30812. * <div class="alert alert-info">
  30813. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  30814. * start at the index of the last search's match, thus not taking the whole input value into
  30815. * account.
  30816. * </div>
  30817. *
  30818. * <div class="alert alert-info">
  30819. * **Note:** This directive is also added when the plain `pattern` attribute is used, with two
  30820. * differences:
  30821. * <ol>
  30822. * <li>
  30823. * `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is
  30824. * not available.
  30825. * </li>
  30826. * <li>
  30827. * The `ngPattern` attribute must be an expression, while the `pattern` value must be
  30828. * interpolated.
  30829. * </li>
  30830. * </ol>
  30831. * </div>
  30832. *
  30833. * @example
  30834. * <example name="ngPatternDirective" module="ngPatternExample">
  30835. * <file name="index.html">
  30836. * <script>
  30837. * angular.module('ngPatternExample', [])
  30838. * .controller('ExampleController', ['$scope', function($scope) {
  30839. * $scope.regex = '\\d+';
  30840. * }]);
  30841. * </script>
  30842. * <div ng-controller="ExampleController">
  30843. * <form name="form">
  30844. * <label for="regex">Set a pattern (regex string): </label>
  30845. * <input type="text" ng-model="regex" id="regex" />
  30846. * <br>
  30847. * <label for="input">This input is restricted by the current pattern: </label>
  30848. * <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
  30849. * <hr>
  30850. * input valid? = <code>{{form.input.$valid}}</code><br>
  30851. * model = <code>{{model}}</code>
  30852. * </form>
  30853. * </div>
  30854. * </file>
  30855. * <file name="protractor.js" type="protractor">
  30856. var model = element(by.binding('model'));
  30857. var input = element(by.id('input'));
  30858. it('should validate the input with the default pattern', function() {
  30859. input.sendKeys('aaa');
  30860. expect(model.getText()).not.toContain('aaa');
  30861. input.clear().then(function() {
  30862. input.sendKeys('123');
  30863. expect(model.getText()).toContain('123');
  30864. });
  30865. });
  30866. * </file>
  30867. * </example>
  30868. */
  30869. var patternDirective = function() {
  30870. return {
  30871. restrict: 'A',
  30872. require: '?ngModel',
  30873. link: function(scope, elm, attr, ctrl) {
  30874. if (!ctrl) return;
  30875. var regexp, patternExp = attr.ngPattern || attr.pattern;
  30876. attr.$observe('pattern', function(regex) {
  30877. if (isString(regex) && regex.length > 0) {
  30878. regex = new RegExp('^' + regex + '$');
  30879. }
  30880. if (regex && !regex.test) {
  30881. throw minErr('ngPattern')('noregexp',
  30882. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  30883. regex, startingTag(elm));
  30884. }
  30885. regexp = regex || undefined;
  30886. ctrl.$validate();
  30887. });
  30888. ctrl.$validators.pattern = function(modelValue, viewValue) {
  30889. // HTML5 pattern constraint validates the input value, so we validate the viewValue
  30890. return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
  30891. };
  30892. }
  30893. };
  30894. };
  30895. /**
  30896. * @ngdoc directive
  30897. * @name ngMaxlength
  30898. * @restrict A
  30899. *
  30900. * @param {expression} ngMaxlength AngularJS expression that must evaluate to a `Number` or `String`
  30901. * parsable into a `Number`. Used as value for the `maxlength`
  30902. * {@link ngModel.NgModelController#$validators validator}.
  30903. *
  30904. * @description
  30905. *
  30906. * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  30907. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  30908. *
  30909. * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  30910. * is longer than the integer obtained by evaluating the Angular expression given in the
  30911. * `ngMaxlength` attribute value.
  30912. *
  30913. * <div class="alert alert-info">
  30914. * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two
  30915. * differences:
  30916. * <ol>
  30917. * <li>
  30918. * `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint
  30919. * validation is not available.
  30920. * </li>
  30921. * <li>
  30922. * The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be
  30923. * interpolated.
  30924. * </li>
  30925. * </ol>
  30926. * </div>
  30927. *
  30928. * @example
  30929. * <example name="ngMaxlengthDirective" module="ngMaxlengthExample">
  30930. * <file name="index.html">
  30931. * <script>
  30932. * angular.module('ngMaxlengthExample', [])
  30933. * .controller('ExampleController', ['$scope', function($scope) {
  30934. * $scope.maxlength = 5;
  30935. * }]);
  30936. * </script>
  30937. * <div ng-controller="ExampleController">
  30938. * <form name="form">
  30939. * <label for="maxlength">Set a maxlength: </label>
  30940. * <input type="number" ng-model="maxlength" id="maxlength" />
  30941. * <br>
  30942. * <label for="input">This input is restricted by the current maxlength: </label>
  30943. * <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br>
  30944. * <hr>
  30945. * input valid? = <code>{{form.input.$valid}}</code><br>
  30946. * model = <code>{{model}}</code>
  30947. * </form>
  30948. * </div>
  30949. * </file>
  30950. * <file name="protractor.js" type="protractor">
  30951. var model = element(by.binding('model'));
  30952. var input = element(by.id('input'));
  30953. it('should validate the input with the default maxlength', function() {
  30954. input.sendKeys('abcdef');
  30955. expect(model.getText()).not.toContain('abcdef');
  30956. input.clear().then(function() {
  30957. input.sendKeys('abcde');
  30958. expect(model.getText()).toContain('abcde');
  30959. });
  30960. });
  30961. * </file>
  30962. * </example>
  30963. */
  30964. var maxlengthDirective = function() {
  30965. return {
  30966. restrict: 'A',
  30967. require: '?ngModel',
  30968. link: function(scope, elm, attr, ctrl) {
  30969. if (!ctrl) return;
  30970. var maxlength = -1;
  30971. attr.$observe('maxlength', function(value) {
  30972. var intVal = toInt(value);
  30973. maxlength = isNumberNaN(intVal) ? -1 : intVal;
  30974. ctrl.$validate();
  30975. });
  30976. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  30977. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  30978. };
  30979. }
  30980. };
  30981. };
  30982. /**
  30983. * @ngdoc directive
  30984. * @name ngMinlength
  30985. * @restrict A
  30986. *
  30987. * @param {expression} ngMinlength AngularJS expression that must evaluate to a `Number` or `String`
  30988. * parsable into a `Number`. Used as value for the `minlength`
  30989. * {@link ngModel.NgModelController#$validators validator}.
  30990. *
  30991. * @description
  30992. *
  30993. * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  30994. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  30995. *
  30996. * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  30997. * is shorter than the integer obtained by evaluating the Angular expression given in the
  30998. * `ngMinlength` attribute value.
  30999. *
  31000. * <div class="alert alert-info">
  31001. * **Note:** This directive is also added when the plain `minlength` attribute is used, with two
  31002. * differences:
  31003. * <ol>
  31004. * <li>
  31005. * `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint
  31006. * validation is not available.
  31007. * </li>
  31008. * <li>
  31009. * The `ngMinlength` value must be an expression, while the `minlength` value must be
  31010. * interpolated.
  31011. * </li>
  31012. * </ol>
  31013. * </div>
  31014. *
  31015. * @example
  31016. * <example name="ngMinlengthDirective" module="ngMinlengthExample">
  31017. * <file name="index.html">
  31018. * <script>
  31019. * angular.module('ngMinlengthExample', [])
  31020. * .controller('ExampleController', ['$scope', function($scope) {
  31021. * $scope.minlength = 3;
  31022. * }]);
  31023. * </script>
  31024. * <div ng-controller="ExampleController">
  31025. * <form name="form">
  31026. * <label for="minlength">Set a minlength: </label>
  31027. * <input type="number" ng-model="minlength" id="minlength" />
  31028. * <br>
  31029. * <label for="input">This input is restricted by the current minlength: </label>
  31030. * <input type="text" ng-model="model" id="input" name="input" ng-minlength="minlength" /><br>
  31031. * <hr>
  31032. * input valid? = <code>{{form.input.$valid}}</code><br>
  31033. * model = <code>{{model}}</code>
  31034. * </form>
  31035. * </div>
  31036. * </file>
  31037. * <file name="protractor.js" type="protractor">
  31038. var model = element(by.binding('model'));
  31039. var input = element(by.id('input'));
  31040. it('should validate the input with the default minlength', function() {
  31041. input.sendKeys('ab');
  31042. expect(model.getText()).not.toContain('ab');
  31043. input.sendKeys('abc');
  31044. expect(model.getText()).toContain('abc');
  31045. });
  31046. * </file>
  31047. * </example>
  31048. */
  31049. var minlengthDirective = function() {
  31050. return {
  31051. restrict: 'A',
  31052. require: '?ngModel',
  31053. link: function(scope, elm, attr, ctrl) {
  31054. if (!ctrl) return;
  31055. var minlength = 0;
  31056. attr.$observe('minlength', function(value) {
  31057. minlength = toInt(value) || 0;
  31058. ctrl.$validate();
  31059. });
  31060. ctrl.$validators.minlength = function(modelValue, viewValue) {
  31061. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  31062. };
  31063. }
  31064. };
  31065. };
  31066. if (window.angular.bootstrap) {
  31067. // AngularJS is already loaded, so we can return here...
  31068. if (window.console) {
  31069. console.log('WARNING: Tried to load angular more than once.');
  31070. }
  31071. return;
  31072. }
  31073. // try to bind to jquery now so that one can write jqLite(fn)
  31074. // but we will rebind on bootstrap again.
  31075. bindJQuery();
  31076. publishExternalAPI(angular);
  31077. angular.module("ngLocale", [], ["$provide", function($provide) {
  31078. var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
  31079. function getDecimals(n) {
  31080. n = n + '';
  31081. var i = n.indexOf('.');
  31082. return (i == -1) ? 0 : n.length - i - 1;
  31083. }
  31084. function getVF(n, opt_precision) {
  31085. var v = opt_precision;
  31086. if (undefined === v) {
  31087. v = Math.min(getDecimals(n), 3);
  31088. }
  31089. var base = Math.pow(10, v);
  31090. var f = ((n * base) | 0) % base;
  31091. return {v: v, f: f};
  31092. }
  31093. $provide.value("$locale", {
  31094. "DATETIME_FORMATS": {
  31095. "AMPMS": [
  31096. "AM",
  31097. "PM"
  31098. ],
  31099. "DAY": [
  31100. "Sunday",
  31101. "Monday",
  31102. "Tuesday",
  31103. "Wednesday",
  31104. "Thursday",
  31105. "Friday",
  31106. "Saturday"
  31107. ],
  31108. "ERANAMES": [
  31109. "Before Christ",
  31110. "Anno Domini"
  31111. ],
  31112. "ERAS": [
  31113. "BC",
  31114. "AD"
  31115. ],
  31116. "FIRSTDAYOFWEEK": 6,
  31117. "MONTH": [
  31118. "January",
  31119. "February",
  31120. "March",
  31121. "April",
  31122. "May",
  31123. "June",
  31124. "July",
  31125. "August",
  31126. "September",
  31127. "October",
  31128. "November",
  31129. "December"
  31130. ],
  31131. "SHORTDAY": [
  31132. "Sun",
  31133. "Mon",
  31134. "Tue",
  31135. "Wed",
  31136. "Thu",
  31137. "Fri",
  31138. "Sat"
  31139. ],
  31140. "SHORTMONTH": [
  31141. "Jan",
  31142. "Feb",
  31143. "Mar",
  31144. "Apr",
  31145. "May",
  31146. "Jun",
  31147. "Jul",
  31148. "Aug",
  31149. "Sep",
  31150. "Oct",
  31151. "Nov",
  31152. "Dec"
  31153. ],
  31154. "STANDALONEMONTH": [
  31155. "January",
  31156. "February",
  31157. "March",
  31158. "April",
  31159. "May",
  31160. "June",
  31161. "July",
  31162. "August",
  31163. "September",
  31164. "October",
  31165. "November",
  31166. "December"
  31167. ],
  31168. "WEEKENDRANGE": [
  31169. 5,
  31170. 6
  31171. ],
  31172. "fullDate": "EEEE, MMMM d, y",
  31173. "longDate": "MMMM d, y",
  31174. "medium": "MMM d, y h:mm:ss a",
  31175. "mediumDate": "MMM d, y",
  31176. "mediumTime": "h:mm:ss a",
  31177. "short": "M/d/yy h:mm a",
  31178. "shortDate": "M/d/yy",
  31179. "shortTime": "h:mm a"
  31180. },
  31181. "NUMBER_FORMATS": {
  31182. "CURRENCY_SYM": "$",
  31183. "DECIMAL_SEP": ".",
  31184. "GROUP_SEP": ",",
  31185. "PATTERNS": [
  31186. {
  31187. "gSize": 3,
  31188. "lgSize": 3,
  31189. "maxFrac": 3,
  31190. "minFrac": 0,
  31191. "minInt": 1,
  31192. "negPre": "-",
  31193. "negSuf": "",
  31194. "posPre": "",
  31195. "posSuf": ""
  31196. },
  31197. {
  31198. "gSize": 3,
  31199. "lgSize": 3,
  31200. "maxFrac": 2,
  31201. "minFrac": 2,
  31202. "minInt": 1,
  31203. "negPre": "-\u00a4",
  31204. "negSuf": "",
  31205. "posPre": "\u00a4",
  31206. "posSuf": ""
  31207. }
  31208. ]
  31209. },
  31210. "id": "en-us",
  31211. "localeID": "en_US",
  31212. "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;}
  31213. });
  31214. }]);
  31215. jqLite(function() {
  31216. angularInit(window.document, bootstrap);
  31217. });
  31218. })(window);
  31219. !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>');