angular.js 1.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691
  1. /* */
  2. "format global";
  3. "exports angular";
  4. /**
  5. * @license AngularJS v1.4.5
  6. * (c) 2010-2015 Google, Inc. http://angularjs.org
  7. * License: MIT
  8. */
  9. (function(window, document, undefined) {'use strict';
  10. /**
  11. * @description
  12. *
  13. * This object provides a utility for producing rich Error messages within
  14. * Angular. It can be called as follows:
  15. *
  16. * var exampleMinErr = minErr('example');
  17. * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
  18. *
  19. * The above creates an instance of minErr in the example namespace. The
  20. * resulting error will have a namespaced error code of example.one. The
  21. * resulting error will replace {0} with the value of foo, and {1} with the
  22. * value of bar. The object is not restricted in the number of arguments it can
  23. * take.
  24. *
  25. * If fewer arguments are specified than necessary for interpolation, the extra
  26. * interpolation markers will be preserved in the final string.
  27. *
  28. * Since data will be parsed statically during a build step, some restrictions
  29. * are applied with respect to how minErr instances are created and called.
  30. * Instances should have names of the form namespaceMinErr for a minErr created
  31. * using minErr('namespace') . Error codes, namespaces and template strings
  32. * should all be static strings, not variables or general expressions.
  33. *
  34. * @param {string} module The namespace to use for the new minErr instance.
  35. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
  36. * error from returned function, for cases when a particular type of error is useful.
  37. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
  38. */
  39. function minErr(module, ErrorConstructor) {
  40. ErrorConstructor = ErrorConstructor || Error;
  41. return function() {
  42. var SKIP_INDEXES = 2;
  43. var templateArgs = arguments,
  44. code = templateArgs[0],
  45. message = '[' + (module ? module + ':' : '') + code + '] ',
  46. template = templateArgs[1],
  47. paramPrefix, i;
  48. message += template.replace(/\{\d+\}/g, function(match) {
  49. var index = +match.slice(1, -1),
  50. shiftedIndex = index + SKIP_INDEXES;
  51. if (shiftedIndex < templateArgs.length) {
  52. return toDebugString(templateArgs[shiftedIndex]);
  53. }
  54. return match;
  55. });
  56. message += '\nhttp://errors.angularjs.org/1.4.5/' +
  57. (module ? module + '/' : '') + code;
  58. for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
  59. message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
  60. encodeURIComponent(toDebugString(templateArgs[i]));
  61. }
  62. return new ErrorConstructor(message);
  63. };
  64. }
  65. /* We need to tell jshint what variables are being exported */
  66. /* global angular: true,
  67. msie: true,
  68. jqLite: true,
  69. jQuery: true,
  70. slice: true,
  71. splice: true,
  72. push: true,
  73. toString: true,
  74. ngMinErr: true,
  75. angularModule: true,
  76. uid: true,
  77. REGEX_STRING_REGEXP: true,
  78. VALIDITY_STATE_PROPERTY: true,
  79. lowercase: true,
  80. uppercase: true,
  81. manualLowercase: true,
  82. manualUppercase: true,
  83. nodeName_: true,
  84. isArrayLike: true,
  85. forEach: true,
  86. forEachSorted: true,
  87. reverseParams: true,
  88. nextUid: true,
  89. setHashKey: true,
  90. extend: true,
  91. toInt: true,
  92. inherit: true,
  93. merge: true,
  94. noop: true,
  95. identity: true,
  96. valueFn: true,
  97. isUndefined: true,
  98. isDefined: true,
  99. isObject: true,
  100. isBlankObject: true,
  101. isString: true,
  102. isNumber: true,
  103. isDate: true,
  104. isArray: true,
  105. isFunction: true,
  106. isRegExp: true,
  107. isWindow: true,
  108. isScope: true,
  109. isFile: true,
  110. isFormData: true,
  111. isBlob: true,
  112. isBoolean: true,
  113. isPromiseLike: true,
  114. trim: true,
  115. escapeForRegexp: true,
  116. isElement: true,
  117. makeMap: true,
  118. includes: true,
  119. arrayRemove: true,
  120. copy: true,
  121. shallowCopy: true,
  122. equals: true,
  123. csp: true,
  124. jq: true,
  125. concat: true,
  126. sliceArgs: true,
  127. bind: true,
  128. toJsonReplacer: true,
  129. toJson: true,
  130. fromJson: true,
  131. convertTimezoneToLocal: true,
  132. timezoneToOffset: true,
  133. startingTag: true,
  134. tryDecodeURIComponent: true,
  135. parseKeyValue: true,
  136. toKeyValue: true,
  137. encodeUriSegment: true,
  138. encodeUriQuery: true,
  139. angularInit: true,
  140. bootstrap: true,
  141. getTestability: true,
  142. snake_case: true,
  143. bindJQuery: true,
  144. assertArg: true,
  145. assertArgFn: true,
  146. assertNotHasOwnProperty: true,
  147. getter: true,
  148. getBlockNodes: true,
  149. hasOwnProperty: true,
  150. createMap: true,
  151. NODE_TYPE_ELEMENT: true,
  152. NODE_TYPE_ATTRIBUTE: true,
  153. NODE_TYPE_TEXT: true,
  154. NODE_TYPE_COMMENT: true,
  155. NODE_TYPE_DOCUMENT: true,
  156. NODE_TYPE_DOCUMENT_FRAGMENT: true,
  157. */
  158. ////////////////////////////////////
  159. /**
  160. * @ngdoc module
  161. * @name ng
  162. * @module ng
  163. * @description
  164. *
  165. * # ng (core module)
  166. * The ng module is loaded by default when an AngularJS application is started. The module itself
  167. * contains the essential components for an AngularJS application to function. The table below
  168. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  169. * components available within this core module.
  170. *
  171. * <div doc-module-components="ng"></div>
  172. */
  173. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  174. // The name of a form control's ValidityState property.
  175. // This is used so that it's possible for internal tests to create mock ValidityStates.
  176. var VALIDITY_STATE_PROPERTY = 'validity';
  177. /**
  178. * @ngdoc function
  179. * @name angular.lowercase
  180. * @module ng
  181. * @kind function
  182. *
  183. * @description Converts the specified string to lowercase.
  184. * @param {string} string String to be converted to lowercase.
  185. * @returns {string} Lowercased string.
  186. */
  187. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  188. var hasOwnProperty = Object.prototype.hasOwnProperty;
  189. /**
  190. * @ngdoc function
  191. * @name angular.uppercase
  192. * @module ng
  193. * @kind function
  194. *
  195. * @description Converts the specified string to uppercase.
  196. * @param {string} string String to be converted to uppercase.
  197. * @returns {string} Uppercased string.
  198. */
  199. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  200. var manualLowercase = function(s) {
  201. /* jshint bitwise: false */
  202. return isString(s)
  203. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  204. : s;
  205. };
  206. var manualUppercase = function(s) {
  207. /* jshint bitwise: false */
  208. return isString(s)
  209. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  210. : s;
  211. };
  212. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  213. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  214. // with correct but slower alternatives.
  215. if ('i' !== 'I'.toLowerCase()) {
  216. lowercase = manualLowercase;
  217. uppercase = manualUppercase;
  218. }
  219. var
  220. msie, // holds major version number for IE, or NaN if UA is not IE.
  221. jqLite, // delay binding since jQuery could be loaded after us.
  222. jQuery, // delay binding
  223. slice = [].slice,
  224. splice = [].splice,
  225. push = [].push,
  226. toString = Object.prototype.toString,
  227. getPrototypeOf = Object.getPrototypeOf,
  228. ngMinErr = minErr('ng'),
  229. /** @name angular */
  230. angular = window.angular || (window.angular = {}),
  231. angularModule,
  232. uid = 0;
  233. /**
  234. * documentMode is an IE-only property
  235. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  236. */
  237. msie = document.documentMode;
  238. /**
  239. * @private
  240. * @param {*} obj
  241. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  242. * String ...)
  243. */
  244. function isArrayLike(obj) {
  245. if (obj == null || isWindow(obj)) {
  246. return false;
  247. }
  248. // Support: iOS 8.2 (not reproducible in simulator)
  249. // "length" in obj used to prevent JIT error (gh-11508)
  250. var length = "length" in Object(obj) && obj.length;
  251. if (obj.nodeType === NODE_TYPE_ELEMENT && length) {
  252. return true;
  253. }
  254. return isString(obj) || isArray(obj) || length === 0 ||
  255. typeof length === 'number' && length > 0 && (length - 1) in obj;
  256. }
  257. /**
  258. * @ngdoc function
  259. * @name angular.forEach
  260. * @module ng
  261. * @kind function
  262. *
  263. * @description
  264. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  265. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  266. * is the value of an object property or an array element, `key` is the object property key or
  267. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  268. *
  269. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  270. * using the `hasOwnProperty` method.
  271. *
  272. * Unlike ES262's
  273. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  274. * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  275. * return the value provided.
  276. *
  277. ```js
  278. var values = {name: 'misko', gender: 'male'};
  279. var log = [];
  280. angular.forEach(values, function(value, key) {
  281. this.push(key + ': ' + value);
  282. }, log);
  283. expect(log).toEqual(['name: misko', 'gender: male']);
  284. ```
  285. *
  286. * @param {Object|Array} obj Object to iterate over.
  287. * @param {Function} iterator Iterator function.
  288. * @param {Object=} context Object to become context (`this`) for the iterator function.
  289. * @returns {Object|Array} Reference to `obj`.
  290. */
  291. function forEach(obj, iterator, context) {
  292. var key, length;
  293. if (obj) {
  294. if (isFunction(obj)) {
  295. for (key in obj) {
  296. // Need to check if hasOwnProperty exists,
  297. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  298. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  299. iterator.call(context, obj[key], key, obj);
  300. }
  301. }
  302. } else if (isArray(obj) || isArrayLike(obj)) {
  303. var isPrimitive = typeof obj !== 'object';
  304. for (key = 0, length = obj.length; key < length; key++) {
  305. if (isPrimitive || key in obj) {
  306. iterator.call(context, obj[key], key, obj);
  307. }
  308. }
  309. } else if (obj.forEach && obj.forEach !== forEach) {
  310. obj.forEach(iterator, context, obj);
  311. } else if (isBlankObject(obj)) {
  312. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  313. for (key in obj) {
  314. iterator.call(context, obj[key], key, obj);
  315. }
  316. } else if (typeof obj.hasOwnProperty === 'function') {
  317. // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
  318. for (key in obj) {
  319. if (obj.hasOwnProperty(key)) {
  320. iterator.call(context, obj[key], key, obj);
  321. }
  322. }
  323. } else {
  324. // Slow path for objects which do not have a method `hasOwnProperty`
  325. for (key in obj) {
  326. if (hasOwnProperty.call(obj, key)) {
  327. iterator.call(context, obj[key], key, obj);
  328. }
  329. }
  330. }
  331. }
  332. return obj;
  333. }
  334. function forEachSorted(obj, iterator, context) {
  335. var keys = Object.keys(obj).sort();
  336. for (var i = 0; i < keys.length; i++) {
  337. iterator.call(context, obj[keys[i]], keys[i]);
  338. }
  339. return keys;
  340. }
  341. /**
  342. * when using forEach the params are value, key, but it is often useful to have key, value.
  343. * @param {function(string, *)} iteratorFn
  344. * @returns {function(*, string)}
  345. */
  346. function reverseParams(iteratorFn) {
  347. return function(value, key) { iteratorFn(key, value); };
  348. }
  349. /**
  350. * A consistent way of creating unique IDs in angular.
  351. *
  352. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  353. * we hit number precision issues in JavaScript.
  354. *
  355. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  356. *
  357. * @returns {number} an unique alpha-numeric string
  358. */
  359. function nextUid() {
  360. return ++uid;
  361. }
  362. /**
  363. * Set or clear the hashkey for an object.
  364. * @param obj object
  365. * @param h the hashkey (!truthy to delete the hashkey)
  366. */
  367. function setHashKey(obj, h) {
  368. if (h) {
  369. obj.$$hashKey = h;
  370. } else {
  371. delete obj.$$hashKey;
  372. }
  373. }
  374. function baseExtend(dst, objs, deep) {
  375. var h = dst.$$hashKey;
  376. for (var i = 0, ii = objs.length; i < ii; ++i) {
  377. var obj = objs[i];
  378. if (!isObject(obj) && !isFunction(obj)) continue;
  379. var keys = Object.keys(obj);
  380. for (var j = 0, jj = keys.length; j < jj; j++) {
  381. var key = keys[j];
  382. var src = obj[key];
  383. if (deep && isObject(src)) {
  384. if (isDate(src)) {
  385. dst[key] = new Date(src.valueOf());
  386. } else if (isRegExp(src)) {
  387. dst[key] = new RegExp(src);
  388. } else {
  389. if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
  390. baseExtend(dst[key], [src], true);
  391. }
  392. } else {
  393. dst[key] = src;
  394. }
  395. }
  396. }
  397. setHashKey(dst, h);
  398. return dst;
  399. }
  400. /**
  401. * @ngdoc function
  402. * @name angular.extend
  403. * @module ng
  404. * @kind function
  405. *
  406. * @description
  407. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  408. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  409. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  410. *
  411. * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
  412. * {@link angular.merge} for this.
  413. *
  414. * @param {Object} dst Destination object.
  415. * @param {...Object} src Source object(s).
  416. * @returns {Object} Reference to `dst`.
  417. */
  418. function extend(dst) {
  419. return baseExtend(dst, slice.call(arguments, 1), false);
  420. }
  421. /**
  422. * @ngdoc function
  423. * @name angular.merge
  424. * @module ng
  425. * @kind function
  426. *
  427. * @description
  428. * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  429. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  430. * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
  431. *
  432. * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
  433. * objects, performing a deep copy.
  434. *
  435. * @param {Object} dst Destination object.
  436. * @param {...Object} src Source object(s).
  437. * @returns {Object} Reference to `dst`.
  438. */
  439. function merge(dst) {
  440. return baseExtend(dst, slice.call(arguments, 1), true);
  441. }
  442. function toInt(str) {
  443. return parseInt(str, 10);
  444. }
  445. function inherit(parent, extra) {
  446. return extend(Object.create(parent), extra);
  447. }
  448. /**
  449. * @ngdoc function
  450. * @name angular.noop
  451. * @module ng
  452. * @kind function
  453. *
  454. * @description
  455. * A function that performs no operations. This function can be useful when writing code in the
  456. * functional style.
  457. ```js
  458. function foo(callback) {
  459. var result = calculateResult();
  460. (callback || angular.noop)(result);
  461. }
  462. ```
  463. */
  464. function noop() {}
  465. noop.$inject = [];
  466. /**
  467. * @ngdoc function
  468. * @name angular.identity
  469. * @module ng
  470. * @kind function
  471. *
  472. * @description
  473. * A function that returns its first argument. This function is useful when writing code in the
  474. * functional style.
  475. *
  476. ```js
  477. function transformer(transformationFn, value) {
  478. return (transformationFn || angular.identity)(value);
  479. };
  480. ```
  481. * @param {*} value to be returned.
  482. * @returns {*} the value passed in.
  483. */
  484. function identity($) {return $;}
  485. identity.$inject = [];
  486. function valueFn(value) {return function() {return value;};}
  487. function hasCustomToString(obj) {
  488. return isFunction(obj.toString) && obj.toString !== Object.prototype.toString;
  489. }
  490. /**
  491. * @ngdoc function
  492. * @name angular.isUndefined
  493. * @module ng
  494. * @kind function
  495. *
  496. * @description
  497. * Determines if a reference is undefined.
  498. *
  499. * @param {*} value Reference to check.
  500. * @returns {boolean} True if `value` is undefined.
  501. */
  502. function isUndefined(value) {return typeof value === 'undefined';}
  503. /**
  504. * @ngdoc function
  505. * @name angular.isDefined
  506. * @module ng
  507. * @kind function
  508. *
  509. * @description
  510. * Determines if a reference is defined.
  511. *
  512. * @param {*} value Reference to check.
  513. * @returns {boolean} True if `value` is defined.
  514. */
  515. function isDefined(value) {return typeof value !== 'undefined';}
  516. /**
  517. * @ngdoc function
  518. * @name angular.isObject
  519. * @module ng
  520. * @kind function
  521. *
  522. * @description
  523. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  524. * considered to be objects. Note that JavaScript arrays are objects.
  525. *
  526. * @param {*} value Reference to check.
  527. * @returns {boolean} True if `value` is an `Object` but not `null`.
  528. */
  529. function isObject(value) {
  530. // http://jsperf.com/isobject4
  531. return value !== null && typeof value === 'object';
  532. }
  533. /**
  534. * Determine if a value is an object with a null prototype
  535. *
  536. * @returns {boolean} True if `value` is an `Object` with a null prototype
  537. */
  538. function isBlankObject(value) {
  539. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  540. }
  541. /**
  542. * @ngdoc function
  543. * @name angular.isString
  544. * @module ng
  545. * @kind function
  546. *
  547. * @description
  548. * Determines if a reference is a `String`.
  549. *
  550. * @param {*} value Reference to check.
  551. * @returns {boolean} True if `value` is a `String`.
  552. */
  553. function isString(value) {return typeof value === 'string';}
  554. /**
  555. * @ngdoc function
  556. * @name angular.isNumber
  557. * @module ng
  558. * @kind function
  559. *
  560. * @description
  561. * Determines if a reference is a `Number`.
  562. *
  563. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  564. *
  565. * If you wish to exclude these then you can use the native
  566. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  567. * method.
  568. *
  569. * @param {*} value Reference to check.
  570. * @returns {boolean} True if `value` is a `Number`.
  571. */
  572. function isNumber(value) {return typeof value === 'number';}
  573. /**
  574. * @ngdoc function
  575. * @name angular.isDate
  576. * @module ng
  577. * @kind function
  578. *
  579. * @description
  580. * Determines if a value is a date.
  581. *
  582. * @param {*} value Reference to check.
  583. * @returns {boolean} True if `value` is a `Date`.
  584. */
  585. function isDate(value) {
  586. return toString.call(value) === '[object Date]';
  587. }
  588. /**
  589. * @ngdoc function
  590. * @name angular.isArray
  591. * @module ng
  592. * @kind function
  593. *
  594. * @description
  595. * Determines if a reference is an `Array`.
  596. *
  597. * @param {*} value Reference to check.
  598. * @returns {boolean} True if `value` is an `Array`.
  599. */
  600. var isArray = Array.isArray;
  601. /**
  602. * @ngdoc function
  603. * @name angular.isFunction
  604. * @module ng
  605. * @kind function
  606. *
  607. * @description
  608. * Determines if a reference is a `Function`.
  609. *
  610. * @param {*} value Reference to check.
  611. * @returns {boolean} True if `value` is a `Function`.
  612. */
  613. function isFunction(value) {return typeof value === 'function';}
  614. /**
  615. * Determines if a value is a regular expression object.
  616. *
  617. * @private
  618. * @param {*} value Reference to check.
  619. * @returns {boolean} True if `value` is a `RegExp`.
  620. */
  621. function isRegExp(value) {
  622. return toString.call(value) === '[object RegExp]';
  623. }
  624. /**
  625. * Checks if `obj` is a window object.
  626. *
  627. * @private
  628. * @param {*} obj Object to check
  629. * @returns {boolean} True if `obj` is a window obj.
  630. */
  631. function isWindow(obj) {
  632. return obj && obj.window === obj;
  633. }
  634. function isScope(obj) {
  635. return obj && obj.$evalAsync && obj.$watch;
  636. }
  637. function isFile(obj) {
  638. return toString.call(obj) === '[object File]';
  639. }
  640. function isFormData(obj) {
  641. return toString.call(obj) === '[object FormData]';
  642. }
  643. function isBlob(obj) {
  644. return toString.call(obj) === '[object Blob]';
  645. }
  646. function isBoolean(value) {
  647. return typeof value === 'boolean';
  648. }
  649. function isPromiseLike(obj) {
  650. return obj && isFunction(obj.then);
  651. }
  652. var TYPED_ARRAY_REGEXP = /^\[object (Uint8(Clamped)?)|(Uint16)|(Uint32)|(Int8)|(Int16)|(Int32)|(Float(32)|(64))Array\]$/;
  653. function isTypedArray(value) {
  654. return TYPED_ARRAY_REGEXP.test(toString.call(value));
  655. }
  656. var trim = function(value) {
  657. return isString(value) ? value.trim() : value;
  658. };
  659. // Copied from:
  660. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  661. // Prereq: s is a string.
  662. var escapeForRegexp = function(s) {
  663. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  664. replace(/\x08/g, '\\x08');
  665. };
  666. /**
  667. * @ngdoc function
  668. * @name angular.isElement
  669. * @module ng
  670. * @kind function
  671. *
  672. * @description
  673. * Determines if a reference is a DOM element (or wrapped jQuery element).
  674. *
  675. * @param {*} value Reference to check.
  676. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  677. */
  678. function isElement(node) {
  679. return !!(node &&
  680. (node.nodeName // we are a direct element
  681. || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
  682. }
  683. /**
  684. * @param str 'key1,key2,...'
  685. * @returns {object} in the form of {key1:true, key2:true, ...}
  686. */
  687. function makeMap(str) {
  688. var obj = {}, items = str.split(","), i;
  689. for (i = 0; i < items.length; i++) {
  690. obj[items[i]] = true;
  691. }
  692. return obj;
  693. }
  694. function nodeName_(element) {
  695. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  696. }
  697. function includes(array, obj) {
  698. return Array.prototype.indexOf.call(array, obj) != -1;
  699. }
  700. function arrayRemove(array, value) {
  701. var index = array.indexOf(value);
  702. if (index >= 0) {
  703. array.splice(index, 1);
  704. }
  705. return index;
  706. }
  707. /**
  708. * @ngdoc function
  709. * @name angular.copy
  710. * @module ng
  711. * @kind function
  712. *
  713. * @description
  714. * Creates a deep copy of `source`, which should be an object or an array.
  715. *
  716. * * If no destination is supplied, a copy of the object or array is created.
  717. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  718. * are deleted and then all elements/properties from the source are copied to it.
  719. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  720. * * If `source` is identical to 'destination' an exception will be thrown.
  721. *
  722. * @param {*} source The source that will be used to make a copy.
  723. * Can be any type, including primitives, `null`, and `undefined`.
  724. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  725. * provided, must be of the same type as `source`.
  726. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  727. *
  728. * @example
  729. <example module="copyExample">
  730. <file name="index.html">
  731. <div ng-controller="ExampleController">
  732. <form novalidate class="simple-form">
  733. Name: <input type="text" ng-model="user.name" /><br />
  734. E-mail: <input type="email" ng-model="user.email" /><br />
  735. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  736. <input type="radio" ng-model="user.gender" value="female" />female<br />
  737. <button ng-click="reset()">RESET</button>
  738. <button ng-click="update(user)">SAVE</button>
  739. </form>
  740. <pre>form = {{user | json}}</pre>
  741. <pre>master = {{master | json}}</pre>
  742. </div>
  743. <script>
  744. angular.module('copyExample', [])
  745. .controller('ExampleController', ['$scope', function($scope) {
  746. $scope.master= {};
  747. $scope.update = function(user) {
  748. // Example with 1 argument
  749. $scope.master= angular.copy(user);
  750. };
  751. $scope.reset = function() {
  752. // Example with 2 arguments
  753. angular.copy($scope.master, $scope.user);
  754. };
  755. $scope.reset();
  756. }]);
  757. </script>
  758. </file>
  759. </example>
  760. */
  761. function copy(source, destination, stackSource, stackDest) {
  762. if (isWindow(source) || isScope(source)) {
  763. throw ngMinErr('cpws',
  764. "Can't copy! Making copies of Window or Scope instances is not supported.");
  765. }
  766. if (isTypedArray(destination)) {
  767. throw ngMinErr('cpta',
  768. "Can't copy! TypedArray destination cannot be mutated.");
  769. }
  770. if (!destination) {
  771. destination = source;
  772. if (isObject(source)) {
  773. var index;
  774. if (stackSource && (index = stackSource.indexOf(source)) !== -1) {
  775. return stackDest[index];
  776. }
  777. // TypedArray, Date and RegExp have specific copy functionality and must be
  778. // pushed onto the stack before returning.
  779. // Array and other objects create the base object and recurse to copy child
  780. // objects. The array/object will be pushed onto the stack when recursed.
  781. if (isArray(source)) {
  782. return copy(source, [], stackSource, stackDest);
  783. } else if (isTypedArray(source)) {
  784. destination = new source.constructor(source);
  785. } else if (isDate(source)) {
  786. destination = new Date(source.getTime());
  787. } else if (isRegExp(source)) {
  788. destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  789. destination.lastIndex = source.lastIndex;
  790. } else {
  791. var emptyObject = Object.create(getPrototypeOf(source));
  792. return copy(source, emptyObject, stackSource, stackDest);
  793. }
  794. if (stackDest) {
  795. stackSource.push(source);
  796. stackDest.push(destination);
  797. }
  798. }
  799. } else {
  800. if (source === destination) throw ngMinErr('cpi',
  801. "Can't copy! Source and destination are identical.");
  802. stackSource = stackSource || [];
  803. stackDest = stackDest || [];
  804. if (isObject(source)) {
  805. stackSource.push(source);
  806. stackDest.push(destination);
  807. }
  808. var result, key;
  809. if (isArray(source)) {
  810. destination.length = 0;
  811. for (var i = 0; i < source.length; i++) {
  812. destination.push(copy(source[i], null, stackSource, stackDest));
  813. }
  814. } else {
  815. var h = destination.$$hashKey;
  816. if (isArray(destination)) {
  817. destination.length = 0;
  818. } else {
  819. forEach(destination, function(value, key) {
  820. delete destination[key];
  821. });
  822. }
  823. if (isBlankObject(source)) {
  824. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  825. for (key in source) {
  826. destination[key] = copy(source[key], null, stackSource, stackDest);
  827. }
  828. } else if (source && typeof source.hasOwnProperty === 'function') {
  829. // Slow path, which must rely on hasOwnProperty
  830. for (key in source) {
  831. if (source.hasOwnProperty(key)) {
  832. destination[key] = copy(source[key], null, stackSource, stackDest);
  833. }
  834. }
  835. } else {
  836. // Slowest path --- hasOwnProperty can't be called as a method
  837. for (key in source) {
  838. if (hasOwnProperty.call(source, key)) {
  839. destination[key] = copy(source[key], null, stackSource, stackDest);
  840. }
  841. }
  842. }
  843. setHashKey(destination,h);
  844. }
  845. }
  846. return destination;
  847. }
  848. /**
  849. * Creates a shallow copy of an object, an array or a primitive.
  850. *
  851. * Assumes that there are no proto properties for objects.
  852. */
  853. function shallowCopy(src, dst) {
  854. if (isArray(src)) {
  855. dst = dst || [];
  856. for (var i = 0, ii = src.length; i < ii; i++) {
  857. dst[i] = src[i];
  858. }
  859. } else if (isObject(src)) {
  860. dst = dst || {};
  861. for (var key in src) {
  862. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  863. dst[key] = src[key];
  864. }
  865. }
  866. }
  867. return dst || src;
  868. }
  869. /**
  870. * @ngdoc function
  871. * @name angular.equals
  872. * @module ng
  873. * @kind function
  874. *
  875. * @description
  876. * Determines if two objects or two values are equivalent. Supports value types, regular
  877. * expressions, arrays and objects.
  878. *
  879. * Two objects or values are considered equivalent if at least one of the following is true:
  880. *
  881. * * Both objects or values pass `===` comparison.
  882. * * Both objects or values are of the same type and all of their properties are equal by
  883. * comparing them with `angular.equals`.
  884. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  885. * * Both values represent the same regular expression (In JavaScript,
  886. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  887. * representation matches).
  888. *
  889. * During a property comparison, properties of `function` type and properties with names
  890. * that begin with `$` are ignored.
  891. *
  892. * Scope and DOMWindow objects are being compared only by identify (`===`).
  893. *
  894. * @param {*} o1 Object or value to compare.
  895. * @param {*} o2 Object or value to compare.
  896. * @returns {boolean} True if arguments are equal.
  897. */
  898. function equals(o1, o2) {
  899. if (o1 === o2) return true;
  900. if (o1 === null || o2 === null) return false;
  901. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  902. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  903. if (t1 == t2) {
  904. if (t1 == 'object') {
  905. if (isArray(o1)) {
  906. if (!isArray(o2)) return false;
  907. if ((length = o1.length) == o2.length) {
  908. for (key = 0; key < length; key++) {
  909. if (!equals(o1[key], o2[key])) return false;
  910. }
  911. return true;
  912. }
  913. } else if (isDate(o1)) {
  914. if (!isDate(o2)) return false;
  915. return equals(o1.getTime(), o2.getTime());
  916. } else if (isRegExp(o1)) {
  917. return isRegExp(o2) ? o1.toString() == o2.toString() : false;
  918. } else {
  919. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  920. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  921. keySet = createMap();
  922. for (key in o1) {
  923. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  924. if (!equals(o1[key], o2[key])) return false;
  925. keySet[key] = true;
  926. }
  927. for (key in o2) {
  928. if (!(key in keySet) &&
  929. key.charAt(0) !== '$' &&
  930. o2[key] !== undefined &&
  931. !isFunction(o2[key])) return false;
  932. }
  933. return true;
  934. }
  935. }
  936. }
  937. return false;
  938. }
  939. var csp = function() {
  940. if (!isDefined(csp.rules)) {
  941. var ngCspElement = (document.querySelector('[ng-csp]') ||
  942. document.querySelector('[data-ng-csp]'));
  943. if (ngCspElement) {
  944. var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
  945. ngCspElement.getAttribute('data-ng-csp');
  946. csp.rules = {
  947. noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
  948. noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
  949. };
  950. } else {
  951. csp.rules = {
  952. noUnsafeEval: noUnsafeEval(),
  953. noInlineStyle: false
  954. };
  955. }
  956. }
  957. return csp.rules;
  958. function noUnsafeEval() {
  959. try {
  960. /* jshint -W031, -W054 */
  961. new Function('');
  962. /* jshint +W031, +W054 */
  963. return false;
  964. } catch (e) {
  965. return true;
  966. }
  967. }
  968. };
  969. /**
  970. * @ngdoc directive
  971. * @module ng
  972. * @name ngJq
  973. *
  974. * @element ANY
  975. * @param {string=} ngJq the name of the library available under `window`
  976. * to be used for angular.element
  977. * @description
  978. * Use this directive to force the angular.element library. This should be
  979. * used to force either jqLite by leaving ng-jq blank or setting the name of
  980. * the jquery variable under window (eg. jQuery).
  981. *
  982. * Since angular looks for this directive when it is loaded (doesn't wait for the
  983. * DOMContentLoaded event), it must be placed on an element that comes before the script
  984. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  985. * others ignored.
  986. *
  987. * @example
  988. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  989. ```html
  990. <!doctype html>
  991. <html ng-app ng-jq>
  992. ...
  993. ...
  994. </html>
  995. ```
  996. * @example
  997. * This example shows how to use a jQuery based library of a different name.
  998. * The library name must be available at the top most 'window'.
  999. ```html
  1000. <!doctype html>
  1001. <html ng-app ng-jq="jQueryLib">
  1002. ...
  1003. ...
  1004. </html>
  1005. ```
  1006. */
  1007. var jq = function() {
  1008. if (isDefined(jq.name_)) return jq.name_;
  1009. var el;
  1010. var i, ii = ngAttrPrefixes.length, prefix, name;
  1011. for (i = 0; i < ii; ++i) {
  1012. prefix = ngAttrPrefixes[i];
  1013. if (el = document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]')) {
  1014. name = el.getAttribute(prefix + 'jq');
  1015. break;
  1016. }
  1017. }
  1018. return (jq.name_ = name);
  1019. };
  1020. function concat(array1, array2, index) {
  1021. return array1.concat(slice.call(array2, index));
  1022. }
  1023. function sliceArgs(args, startIndex) {
  1024. return slice.call(args, startIndex || 0);
  1025. }
  1026. /* jshint -W101 */
  1027. /**
  1028. * @ngdoc function
  1029. * @name angular.bind
  1030. * @module ng
  1031. * @kind function
  1032. *
  1033. * @description
  1034. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  1035. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  1036. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  1037. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  1038. *
  1039. * @param {Object} self Context which `fn` should be evaluated in.
  1040. * @param {function()} fn Function to be bound.
  1041. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  1042. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  1043. */
  1044. /* jshint +W101 */
  1045. function bind(self, fn) {
  1046. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  1047. if (isFunction(fn) && !(fn instanceof RegExp)) {
  1048. return curryArgs.length
  1049. ? function() {
  1050. return arguments.length
  1051. ? fn.apply(self, concat(curryArgs, arguments, 0))
  1052. : fn.apply(self, curryArgs);
  1053. }
  1054. : function() {
  1055. return arguments.length
  1056. ? fn.apply(self, arguments)
  1057. : fn.call(self);
  1058. };
  1059. } else {
  1060. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  1061. return fn;
  1062. }
  1063. }
  1064. function toJsonReplacer(key, value) {
  1065. var val = value;
  1066. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  1067. val = undefined;
  1068. } else if (isWindow(value)) {
  1069. val = '$WINDOW';
  1070. } else if (value && document === value) {
  1071. val = '$DOCUMENT';
  1072. } else if (isScope(value)) {
  1073. val = '$SCOPE';
  1074. }
  1075. return val;
  1076. }
  1077. /**
  1078. * @ngdoc function
  1079. * @name angular.toJson
  1080. * @module ng
  1081. * @kind function
  1082. *
  1083. * @description
  1084. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  1085. * stripped since angular uses this notation internally.
  1086. *
  1087. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  1088. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  1089. * If set to an integer, the JSON output will contain that many spaces per indentation.
  1090. * @returns {string|undefined} JSON-ified string representing `obj`.
  1091. */
  1092. function toJson(obj, pretty) {
  1093. if (typeof obj === 'undefined') return undefined;
  1094. if (!isNumber(pretty)) {
  1095. pretty = pretty ? 2 : null;
  1096. }
  1097. return JSON.stringify(obj, toJsonReplacer, pretty);
  1098. }
  1099. /**
  1100. * @ngdoc function
  1101. * @name angular.fromJson
  1102. * @module ng
  1103. * @kind function
  1104. *
  1105. * @description
  1106. * Deserializes a JSON string.
  1107. *
  1108. * @param {string} json JSON string to deserialize.
  1109. * @returns {Object|Array|string|number} Deserialized JSON string.
  1110. */
  1111. function fromJson(json) {
  1112. return isString(json)
  1113. ? JSON.parse(json)
  1114. : json;
  1115. }
  1116. function timezoneToOffset(timezone, fallback) {
  1117. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  1118. return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  1119. }
  1120. function addDateMinutes(date, minutes) {
  1121. date = new Date(date.getTime());
  1122. date.setMinutes(date.getMinutes() + minutes);
  1123. return date;
  1124. }
  1125. function convertTimezoneToLocal(date, timezone, reverse) {
  1126. reverse = reverse ? -1 : 1;
  1127. var timezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
  1128. return addDateMinutes(date, reverse * (timezoneOffset - date.getTimezoneOffset()));
  1129. }
  1130. /**
  1131. * @returns {string} Returns the string representation of the element.
  1132. */
  1133. function startingTag(element) {
  1134. element = jqLite(element).clone();
  1135. try {
  1136. // turns out IE does not let you set .html() on elements which
  1137. // are not allowed to have children. So we just ignore it.
  1138. element.empty();
  1139. } catch (e) {}
  1140. var elemHtml = jqLite('<div>').append(element).html();
  1141. try {
  1142. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  1143. elemHtml.
  1144. match(/^(<[^>]+>)/)[1].
  1145. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
  1146. } catch (e) {
  1147. return lowercase(elemHtml);
  1148. }
  1149. }
  1150. /////////////////////////////////////////////////
  1151. /**
  1152. * Tries to decode the URI component without throwing an exception.
  1153. *
  1154. * @private
  1155. * @param str value potential URI component to check.
  1156. * @returns {boolean} True if `value` can be decoded
  1157. * with the decodeURIComponent function.
  1158. */
  1159. function tryDecodeURIComponent(value) {
  1160. try {
  1161. return decodeURIComponent(value);
  1162. } catch (e) {
  1163. // Ignore any invalid uri component
  1164. }
  1165. }
  1166. /**
  1167. * Parses an escaped url query string into key-value pairs.
  1168. * @returns {Object.<string,boolean|Array>}
  1169. */
  1170. function parseKeyValue(/**string*/keyValue) {
  1171. var obj = {};
  1172. forEach((keyValue || "").split('&'), function(keyValue) {
  1173. var splitPoint, key, val;
  1174. if (keyValue) {
  1175. key = keyValue = keyValue.replace(/\+/g,'%20');
  1176. splitPoint = keyValue.indexOf('=');
  1177. if (splitPoint !== -1) {
  1178. key = keyValue.substring(0, splitPoint);
  1179. val = keyValue.substring(splitPoint + 1);
  1180. }
  1181. key = tryDecodeURIComponent(key);
  1182. if (isDefined(key)) {
  1183. val = isDefined(val) ? tryDecodeURIComponent(val) : true;
  1184. if (!hasOwnProperty.call(obj, key)) {
  1185. obj[key] = val;
  1186. } else if (isArray(obj[key])) {
  1187. obj[key].push(val);
  1188. } else {
  1189. obj[key] = [obj[key],val];
  1190. }
  1191. }
  1192. }
  1193. });
  1194. return obj;
  1195. }
  1196. function toKeyValue(obj) {
  1197. var parts = [];
  1198. forEach(obj, function(value, key) {
  1199. if (isArray(value)) {
  1200. forEach(value, function(arrayValue) {
  1201. parts.push(encodeUriQuery(key, true) +
  1202. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1203. });
  1204. } else {
  1205. parts.push(encodeUriQuery(key, true) +
  1206. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1207. }
  1208. });
  1209. return parts.length ? parts.join('&') : '';
  1210. }
  1211. /**
  1212. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1213. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1214. * segments:
  1215. * segment = *pchar
  1216. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1217. * pct-encoded = "%" HEXDIG HEXDIG
  1218. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1219. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1220. * / "*" / "+" / "," / ";" / "="
  1221. */
  1222. function encodeUriSegment(val) {
  1223. return encodeUriQuery(val, true).
  1224. replace(/%26/gi, '&').
  1225. replace(/%3D/gi, '=').
  1226. replace(/%2B/gi, '+');
  1227. }
  1228. /**
  1229. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1230. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1231. * encoded per http://tools.ietf.org/html/rfc3986:
  1232. * query = *( pchar / "/" / "?" )
  1233. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1234. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1235. * pct-encoded = "%" HEXDIG HEXDIG
  1236. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1237. * / "*" / "+" / "," / ";" / "="
  1238. */
  1239. function encodeUriQuery(val, pctEncodeSpaces) {
  1240. return encodeURIComponent(val).
  1241. replace(/%40/gi, '@').
  1242. replace(/%3A/gi, ':').
  1243. replace(/%24/g, '$').
  1244. replace(/%2C/gi, ',').
  1245. replace(/%3B/gi, ';').
  1246. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1247. }
  1248. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1249. function getNgAttribute(element, ngAttr) {
  1250. var attr, i, ii = ngAttrPrefixes.length;
  1251. for (i = 0; i < ii; ++i) {
  1252. attr = ngAttrPrefixes[i] + ngAttr;
  1253. if (isString(attr = element.getAttribute(attr))) {
  1254. return attr;
  1255. }
  1256. }
  1257. return null;
  1258. }
  1259. /**
  1260. * @ngdoc directive
  1261. * @name ngApp
  1262. * @module ng
  1263. *
  1264. * @element ANY
  1265. * @param {angular.Module} ngApp an optional application
  1266. * {@link angular.module module} name to load.
  1267. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1268. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1269. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1270. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1271. * tracking down the root of these bugs.
  1272. *
  1273. * @description
  1274. *
  1275. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1276. * designates the **root element** of the application and is typically placed near the root element
  1277. * of the page - e.g. on the `<body>` or `<html>` tags.
  1278. *
  1279. * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1280. * found in the document will be used to define the root element to auto-bootstrap as an
  1281. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1282. * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
  1283. *
  1284. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1285. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1286. * should contain the application code needed or have dependencies on other modules that will
  1287. * contain the code. See {@link angular.module} for more information.
  1288. *
  1289. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1290. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1291. * would not be resolved to `3`.
  1292. *
  1293. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1294. *
  1295. <example module="ngAppDemo">
  1296. <file name="index.html">
  1297. <div ng-controller="ngAppDemoController">
  1298. I can add: {{a}} + {{b}} = {{ a+b }}
  1299. </div>
  1300. </file>
  1301. <file name="script.js">
  1302. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1303. $scope.a = 1;
  1304. $scope.b = 2;
  1305. });
  1306. </file>
  1307. </example>
  1308. *
  1309. * Using `ngStrictDi`, you would see something like this:
  1310. *
  1311. <example ng-app-included="true">
  1312. <file name="index.html">
  1313. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1314. <div ng-controller="GoodController1">
  1315. I can add: {{a}} + {{b}} = {{ a+b }}
  1316. <p>This renders because the controller does not fail to
  1317. instantiate, by using explicit annotation style (see
  1318. script.js for details)
  1319. </p>
  1320. </div>
  1321. <div ng-controller="GoodController2">
  1322. Name: <input ng-model="name"><br />
  1323. Hello, {{name}}!
  1324. <p>This renders because the controller does not fail to
  1325. instantiate, by using explicit annotation style
  1326. (see script.js for details)
  1327. </p>
  1328. </div>
  1329. <div ng-controller="BadController">
  1330. I can add: {{a}} + {{b}} = {{ a+b }}
  1331. <p>The controller could not be instantiated, due to relying
  1332. on automatic function annotations (which are disabled in
  1333. strict mode). As such, the content of this section is not
  1334. interpolated, and there should be an error in your web console.
  1335. </p>
  1336. </div>
  1337. </div>
  1338. </file>
  1339. <file name="script.js">
  1340. angular.module('ngAppStrictDemo', [])
  1341. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1342. // rather than an explicit annotation
  1343. .controller('BadController', function($scope) {
  1344. $scope.a = 1;
  1345. $scope.b = 2;
  1346. })
  1347. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1348. // due to using explicit annotations using the array style and $inject property, respectively.
  1349. .controller('GoodController1', ['$scope', function($scope) {
  1350. $scope.a = 1;
  1351. $scope.b = 2;
  1352. }])
  1353. .controller('GoodController2', GoodController2);
  1354. function GoodController2($scope) {
  1355. $scope.name = "World";
  1356. }
  1357. GoodController2.$inject = ['$scope'];
  1358. </file>
  1359. <file name="style.css">
  1360. div[ng-controller] {
  1361. margin-bottom: 1em;
  1362. -webkit-border-radius: 4px;
  1363. border-radius: 4px;
  1364. border: 1px solid;
  1365. padding: .5em;
  1366. }
  1367. div[ng-controller^=Good] {
  1368. border-color: #d6e9c6;
  1369. background-color: #dff0d8;
  1370. color: #3c763d;
  1371. }
  1372. div[ng-controller^=Bad] {
  1373. border-color: #ebccd1;
  1374. background-color: #f2dede;
  1375. color: #a94442;
  1376. margin-bottom: 0;
  1377. }
  1378. </file>
  1379. </example>
  1380. */
  1381. function angularInit(element, bootstrap) {
  1382. var appElement,
  1383. module,
  1384. config = {};
  1385. // The element `element` has priority over any other element
  1386. forEach(ngAttrPrefixes, function(prefix) {
  1387. var name = prefix + 'app';
  1388. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1389. appElement = element;
  1390. module = element.getAttribute(name);
  1391. }
  1392. });
  1393. forEach(ngAttrPrefixes, function(prefix) {
  1394. var name = prefix + 'app';
  1395. var candidate;
  1396. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1397. appElement = candidate;
  1398. module = candidate.getAttribute(name);
  1399. }
  1400. });
  1401. if (appElement) {
  1402. config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
  1403. bootstrap(appElement, module ? [module] : [], config);
  1404. }
  1405. }
  1406. /**
  1407. * @ngdoc function
  1408. * @name angular.bootstrap
  1409. * @module ng
  1410. * @description
  1411. * Use this function to manually start up angular application.
  1412. *
  1413. * See: {@link guide/bootstrap Bootstrap}
  1414. *
  1415. * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1416. * They must use {@link ng.directive:ngApp ngApp}.
  1417. *
  1418. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1419. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1420. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1421. * multiple instances of Angular try to work on the DOM.
  1422. *
  1423. * ```html
  1424. * <!doctype html>
  1425. * <html>
  1426. * <body>
  1427. * <div ng-controller="WelcomeController">
  1428. * {{greeting}}
  1429. * </div>
  1430. *
  1431. * <script src="angular.js"></script>
  1432. * <script>
  1433. * var app = angular.module('demo', [])
  1434. * .controller('WelcomeController', function($scope) {
  1435. * $scope.greeting = 'Welcome!';
  1436. * });
  1437. * angular.bootstrap(document, ['demo']);
  1438. * </script>
  1439. * </body>
  1440. * </html>
  1441. * ```
  1442. *
  1443. * @param {DOMElement} element DOM element which is the root of angular application.
  1444. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1445. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1446. * function that will be invoked by the injector as a `config` block.
  1447. * See: {@link angular.module modules}
  1448. * @param {Object=} config an object for defining configuration options for the application. The
  1449. * following keys are supported:
  1450. *
  1451. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1452. * assist in finding bugs which break minified code. Defaults to `false`.
  1453. *
  1454. * @returns {auto.$injector} Returns the newly created injector for this app.
  1455. */
  1456. function bootstrap(element, modules, config) {
  1457. if (!isObject(config)) config = {};
  1458. var defaultConfig = {
  1459. strictDi: false
  1460. };
  1461. config = extend(defaultConfig, config);
  1462. var doBootstrap = function() {
  1463. element = jqLite(element);
  1464. if (element.injector()) {
  1465. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1466. //Encode angle brackets to prevent input from being sanitized to empty string #8683
  1467. throw ngMinErr(
  1468. 'btstrpd',
  1469. "App Already Bootstrapped with this Element '{0}'",
  1470. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1471. }
  1472. modules = modules || [];
  1473. modules.unshift(['$provide', function($provide) {
  1474. $provide.value('$rootElement', element);
  1475. }]);
  1476. if (config.debugInfoEnabled) {
  1477. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1478. modules.push(['$compileProvider', function($compileProvider) {
  1479. $compileProvider.debugInfoEnabled(true);
  1480. }]);
  1481. }
  1482. modules.unshift('ng');
  1483. var injector = createInjector(modules, config.strictDi);
  1484. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1485. function bootstrapApply(scope, element, compile, injector) {
  1486. scope.$apply(function() {
  1487. element.data('$injector', injector);
  1488. compile(element)(scope);
  1489. });
  1490. }]
  1491. );
  1492. return injector;
  1493. };
  1494. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1495. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1496. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1497. config.debugInfoEnabled = true;
  1498. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1499. }
  1500. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1501. return doBootstrap();
  1502. }
  1503. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1504. angular.resumeBootstrap = function(extraModules) {
  1505. forEach(extraModules, function(module) {
  1506. modules.push(module);
  1507. });
  1508. return doBootstrap();
  1509. };
  1510. if (isFunction(angular.resumeDeferredBootstrap)) {
  1511. angular.resumeDeferredBootstrap();
  1512. }
  1513. }
  1514. /**
  1515. * @ngdoc function
  1516. * @name angular.reloadWithDebugInfo
  1517. * @module ng
  1518. * @description
  1519. * Use this function to reload the current application with debug information turned on.
  1520. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1521. *
  1522. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1523. */
  1524. function reloadWithDebugInfo() {
  1525. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1526. window.location.reload();
  1527. }
  1528. /**
  1529. * @name angular.getTestability
  1530. * @module ng
  1531. * @description
  1532. * Get the testability service for the instance of Angular on the given
  1533. * element.
  1534. * @param {DOMElement} element DOM element which is the root of angular application.
  1535. */
  1536. function getTestability(rootElement) {
  1537. var injector = angular.element(rootElement).injector();
  1538. if (!injector) {
  1539. throw ngMinErr('test',
  1540. 'no injector found for element argument to getTestability');
  1541. }
  1542. return injector.get('$$testability');
  1543. }
  1544. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1545. function snake_case(name, separator) {
  1546. separator = separator || '_';
  1547. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1548. return (pos ? separator : '') + letter.toLowerCase();
  1549. });
  1550. }
  1551. var bindJQueryFired = false;
  1552. var skipDestroyOnNextJQueryCleanData;
  1553. function bindJQuery() {
  1554. var originalCleanData;
  1555. if (bindJQueryFired) {
  1556. return;
  1557. }
  1558. // bind to jQuery if present;
  1559. var jqName = jq();
  1560. jQuery = window.jQuery; // use default jQuery.
  1561. if (isDefined(jqName)) { // `ngJq` present
  1562. jQuery = jqName === null ? undefined : window[jqName]; // if empty; use jqLite. if not empty, use jQuery specified by `ngJq`.
  1563. }
  1564. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1565. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1566. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1567. // versions. It will not work for sure with jQuery <1.7, though.
  1568. if (jQuery && jQuery.fn.on) {
  1569. jqLite = jQuery;
  1570. extend(jQuery.fn, {
  1571. scope: JQLitePrototype.scope,
  1572. isolateScope: JQLitePrototype.isolateScope,
  1573. controller: JQLitePrototype.controller,
  1574. injector: JQLitePrototype.injector,
  1575. inheritedData: JQLitePrototype.inheritedData
  1576. });
  1577. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1578. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1579. // the $destroy event on all removed nodes.
  1580. originalCleanData = jQuery.cleanData;
  1581. jQuery.cleanData = function(elems) {
  1582. var events;
  1583. if (!skipDestroyOnNextJQueryCleanData) {
  1584. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1585. events = jQuery._data(elem, "events");
  1586. if (events && events.$destroy) {
  1587. jQuery(elem).triggerHandler('$destroy');
  1588. }
  1589. }
  1590. } else {
  1591. skipDestroyOnNextJQueryCleanData = false;
  1592. }
  1593. originalCleanData(elems);
  1594. };
  1595. } else {
  1596. jqLite = JQLite;
  1597. }
  1598. angular.element = jqLite;
  1599. // Prevent double-proxying.
  1600. bindJQueryFired = true;
  1601. }
  1602. /**
  1603. * throw error if the argument is falsy.
  1604. */
  1605. function assertArg(arg, name, reason) {
  1606. if (!arg) {
  1607. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1608. }
  1609. return arg;
  1610. }
  1611. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1612. if (acceptArrayAnnotation && isArray(arg)) {
  1613. arg = arg[arg.length - 1];
  1614. }
  1615. assertArg(isFunction(arg), name, 'not a function, got ' +
  1616. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1617. return arg;
  1618. }
  1619. /**
  1620. * throw error if the name given is hasOwnProperty
  1621. * @param {String} name the name to test
  1622. * @param {String} context the context in which the name is used, such as module or directive
  1623. */
  1624. function assertNotHasOwnProperty(name, context) {
  1625. if (name === 'hasOwnProperty') {
  1626. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1627. }
  1628. }
  1629. /**
  1630. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1631. * @param {Object} obj starting object
  1632. * @param {String} path path to traverse
  1633. * @param {boolean} [bindFnToScope=true]
  1634. * @returns {Object} value as accessible by path
  1635. */
  1636. //TODO(misko): this function needs to be removed
  1637. function getter(obj, path, bindFnToScope) {
  1638. if (!path) return obj;
  1639. var keys = path.split('.');
  1640. var key;
  1641. var lastInstance = obj;
  1642. var len = keys.length;
  1643. for (var i = 0; i < len; i++) {
  1644. key = keys[i];
  1645. if (obj) {
  1646. obj = (lastInstance = obj)[key];
  1647. }
  1648. }
  1649. if (!bindFnToScope && isFunction(obj)) {
  1650. return bind(lastInstance, obj);
  1651. }
  1652. return obj;
  1653. }
  1654. /**
  1655. * Return the DOM siblings between the first and last node in the given array.
  1656. * @param {Array} array like object
  1657. * @returns {jqLite} jqLite collection containing the nodes
  1658. */
  1659. function getBlockNodes(nodes) {
  1660. // TODO(perf): just check if all items in `nodes` are siblings and if they are return the original
  1661. // collection, otherwise update the original collection.
  1662. var node = nodes[0];
  1663. var endNode = nodes[nodes.length - 1];
  1664. var blockNodes = [node];
  1665. do {
  1666. node = node.nextSibling;
  1667. if (!node) break;
  1668. blockNodes.push(node);
  1669. } while (node !== endNode);
  1670. return jqLite(blockNodes);
  1671. }
  1672. /**
  1673. * Creates a new object without a prototype. This object is useful for lookup without having to
  1674. * guard against prototypically inherited properties via hasOwnProperty.
  1675. *
  1676. * Related micro-benchmarks:
  1677. * - http://jsperf.com/object-create2
  1678. * - http://jsperf.com/proto-map-lookup/2
  1679. * - http://jsperf.com/for-in-vs-object-keys2
  1680. *
  1681. * @returns {Object}
  1682. */
  1683. function createMap() {
  1684. return Object.create(null);
  1685. }
  1686. var NODE_TYPE_ELEMENT = 1;
  1687. var NODE_TYPE_ATTRIBUTE = 2;
  1688. var NODE_TYPE_TEXT = 3;
  1689. var NODE_TYPE_COMMENT = 8;
  1690. var NODE_TYPE_DOCUMENT = 9;
  1691. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1692. /**
  1693. * @ngdoc type
  1694. * @name angular.Module
  1695. * @module ng
  1696. * @description
  1697. *
  1698. * Interface for configuring angular {@link angular.module modules}.
  1699. */
  1700. function setupModuleLoader(window) {
  1701. var $injectorMinErr = minErr('$injector');
  1702. var ngMinErr = minErr('ng');
  1703. function ensure(obj, name, factory) {
  1704. return obj[name] || (obj[name] = factory());
  1705. }
  1706. var angular = ensure(window, 'angular', Object);
  1707. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1708. angular.$$minErr = angular.$$minErr || minErr;
  1709. return ensure(angular, 'module', function() {
  1710. /** @type {Object.<string, angular.Module>} */
  1711. var modules = {};
  1712. /**
  1713. * @ngdoc function
  1714. * @name angular.module
  1715. * @module ng
  1716. * @description
  1717. *
  1718. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1719. * modules.
  1720. * All modules (angular core or 3rd party) that should be available to an application must be
  1721. * registered using this mechanism.
  1722. *
  1723. * Passing one argument retrieves an existing {@link angular.Module},
  1724. * whereas passing more than one argument creates a new {@link angular.Module}
  1725. *
  1726. *
  1727. * # Module
  1728. *
  1729. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1730. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1731. *
  1732. * ```js
  1733. * // Create a new module
  1734. * var myModule = angular.module('myModule', []);
  1735. *
  1736. * // register a new service
  1737. * myModule.value('appName', 'MyCoolApp');
  1738. *
  1739. * // configure existing services inside initialization blocks.
  1740. * myModule.config(['$locationProvider', function($locationProvider) {
  1741. * // Configure existing providers
  1742. * $locationProvider.hashPrefix('!');
  1743. * }]);
  1744. * ```
  1745. *
  1746. * Then you can create an injector and load your modules like this:
  1747. *
  1748. * ```js
  1749. * var injector = angular.injector(['ng', 'myModule'])
  1750. * ```
  1751. *
  1752. * However it's more likely that you'll just use
  1753. * {@link ng.directive:ngApp ngApp} or
  1754. * {@link angular.bootstrap} to simplify this process for you.
  1755. *
  1756. * @param {!string} name The name of the module to create or retrieve.
  1757. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1758. * unspecified then the module is being retrieved for further configuration.
  1759. * @param {Function=} configFn Optional configuration function for the module. Same as
  1760. * {@link angular.Module#config Module#config()}.
  1761. * @returns {module} new module with the {@link angular.Module} api.
  1762. */
  1763. return function module(name, requires, configFn) {
  1764. var assertNotHasOwnProperty = function(name, context) {
  1765. if (name === 'hasOwnProperty') {
  1766. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1767. }
  1768. };
  1769. assertNotHasOwnProperty(name, 'module');
  1770. if (requires && modules.hasOwnProperty(name)) {
  1771. modules[name] = null;
  1772. }
  1773. return ensure(modules, name, function() {
  1774. if (!requires) {
  1775. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1776. "the module name or forgot to load it. If registering a module ensure that you " +
  1777. "specify the dependencies as the second argument.", name);
  1778. }
  1779. /** @type {!Array.<Array.<*>>} */
  1780. var invokeQueue = [];
  1781. /** @type {!Array.<Function>} */
  1782. var configBlocks = [];
  1783. /** @type {!Array.<Function>} */
  1784. var runBlocks = [];
  1785. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  1786. /** @type {angular.Module} */
  1787. var moduleInstance = {
  1788. // Private state
  1789. _invokeQueue: invokeQueue,
  1790. _configBlocks: configBlocks,
  1791. _runBlocks: runBlocks,
  1792. /**
  1793. * @ngdoc property
  1794. * @name angular.Module#requires
  1795. * @module ng
  1796. *
  1797. * @description
  1798. * Holds the list of modules which the injector will load before the current module is
  1799. * loaded.
  1800. */
  1801. requires: requires,
  1802. /**
  1803. * @ngdoc property
  1804. * @name angular.Module#name
  1805. * @module ng
  1806. *
  1807. * @description
  1808. * Name of the module.
  1809. */
  1810. name: name,
  1811. /**
  1812. * @ngdoc method
  1813. * @name angular.Module#provider
  1814. * @module ng
  1815. * @param {string} name service name
  1816. * @param {Function} providerType Construction function for creating new instance of the
  1817. * service.
  1818. * @description
  1819. * See {@link auto.$provide#provider $provide.provider()}.
  1820. */
  1821. provider: invokeLaterAndSetModuleName('$provide', 'provider'),
  1822. /**
  1823. * @ngdoc method
  1824. * @name angular.Module#factory
  1825. * @module ng
  1826. * @param {string} name service name
  1827. * @param {Function} providerFunction Function for creating new instance of the service.
  1828. * @description
  1829. * See {@link auto.$provide#factory $provide.factory()}.
  1830. */
  1831. factory: invokeLaterAndSetModuleName('$provide', 'factory'),
  1832. /**
  1833. * @ngdoc method
  1834. * @name angular.Module#service
  1835. * @module ng
  1836. * @param {string} name service name
  1837. * @param {Function} constructor A constructor function that will be instantiated.
  1838. * @description
  1839. * See {@link auto.$provide#service $provide.service()}.
  1840. */
  1841. service: invokeLaterAndSetModuleName('$provide', 'service'),
  1842. /**
  1843. * @ngdoc method
  1844. * @name angular.Module#value
  1845. * @module ng
  1846. * @param {string} name service name
  1847. * @param {*} object Service instance object.
  1848. * @description
  1849. * See {@link auto.$provide#value $provide.value()}.
  1850. */
  1851. value: invokeLater('$provide', 'value'),
  1852. /**
  1853. * @ngdoc method
  1854. * @name angular.Module#constant
  1855. * @module ng
  1856. * @param {string} name constant name
  1857. * @param {*} object Constant value.
  1858. * @description
  1859. * Because the constant are fixed, they get applied before other provide methods.
  1860. * See {@link auto.$provide#constant $provide.constant()}.
  1861. */
  1862. constant: invokeLater('$provide', 'constant', 'unshift'),
  1863. /**
  1864. * @ngdoc method
  1865. * @name angular.Module#decorator
  1866. * @module ng
  1867. * @param {string} The name of the service to decorate.
  1868. * @param {Function} This function will be invoked when the service needs to be
  1869. * instantiated and should return the decorated service instance.
  1870. * @description
  1871. * See {@link auto.$provide#decorator $provide.decorator()}.
  1872. */
  1873. decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
  1874. /**
  1875. * @ngdoc method
  1876. * @name angular.Module#animation
  1877. * @module ng
  1878. * @param {string} name animation name
  1879. * @param {Function} animationFactory Factory function for creating new instance of an
  1880. * animation.
  1881. * @description
  1882. *
  1883. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1884. *
  1885. *
  1886. * Defines an animation hook that can be later used with
  1887. * {@link $animate $animate} service and directives that use this service.
  1888. *
  1889. * ```js
  1890. * module.animation('.animation-name', function($inject1, $inject2) {
  1891. * return {
  1892. * eventName : function(element, done) {
  1893. * //code to run the animation
  1894. * //once complete, then run done()
  1895. * return function cancellationFunction(element) {
  1896. * //code to cancel the animation
  1897. * }
  1898. * }
  1899. * }
  1900. * })
  1901. * ```
  1902. *
  1903. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  1904. * {@link ngAnimate ngAnimate module} for more information.
  1905. */
  1906. animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
  1907. /**
  1908. * @ngdoc method
  1909. * @name angular.Module#filter
  1910. * @module ng
  1911. * @param {string} name Filter name - this must be a valid angular expression identifier
  1912. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1913. * @description
  1914. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1915. *
  1916. * <div class="alert alert-warning">
  1917. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  1918. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  1919. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  1920. * (`myapp_subsection_filterx`).
  1921. * </div>
  1922. */
  1923. filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
  1924. /**
  1925. * @ngdoc method
  1926. * @name angular.Module#controller
  1927. * @module ng
  1928. * @param {string|Object} name Controller name, or an object map of controllers where the
  1929. * keys are the names and the values are the constructors.
  1930. * @param {Function} constructor Controller constructor function.
  1931. * @description
  1932. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1933. */
  1934. controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
  1935. /**
  1936. * @ngdoc method
  1937. * @name angular.Module#directive
  1938. * @module ng
  1939. * @param {string|Object} name Directive name, or an object map of directives where the
  1940. * keys are the names and the values are the factories.
  1941. * @param {Function} directiveFactory Factory function for creating new instance of
  1942. * directives.
  1943. * @description
  1944. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  1945. */
  1946. directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
  1947. /**
  1948. * @ngdoc method
  1949. * @name angular.Module#config
  1950. * @module ng
  1951. * @param {Function} configFn Execute this function on module load. Useful for service
  1952. * configuration.
  1953. * @description
  1954. * Use this method to register work which needs to be performed on module loading.
  1955. * For more about how to configure services, see
  1956. * {@link providers#provider-recipe Provider Recipe}.
  1957. */
  1958. config: config,
  1959. /**
  1960. * @ngdoc method
  1961. * @name angular.Module#run
  1962. * @module ng
  1963. * @param {Function} initializationFn Execute this function after injector creation.
  1964. * Useful for application initialization.
  1965. * @description
  1966. * Use this method to register work which should be performed when the injector is done
  1967. * loading all modules.
  1968. */
  1969. run: function(block) {
  1970. runBlocks.push(block);
  1971. return this;
  1972. }
  1973. };
  1974. if (configFn) {
  1975. config(configFn);
  1976. }
  1977. return moduleInstance;
  1978. /**
  1979. * @param {string} provider
  1980. * @param {string} method
  1981. * @param {String=} insertMethod
  1982. * @returns {angular.Module}
  1983. */
  1984. function invokeLater(provider, method, insertMethod, queue) {
  1985. if (!queue) queue = invokeQueue;
  1986. return function() {
  1987. queue[insertMethod || 'push']([provider, method, arguments]);
  1988. return moduleInstance;
  1989. };
  1990. }
  1991. /**
  1992. * @param {string} provider
  1993. * @param {string} method
  1994. * @returns {angular.Module}
  1995. */
  1996. function invokeLaterAndSetModuleName(provider, method) {
  1997. return function(recipeName, factoryFunction) {
  1998. if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
  1999. invokeQueue.push([provider, method, arguments]);
  2000. return moduleInstance;
  2001. };
  2002. }
  2003. });
  2004. };
  2005. });
  2006. }
  2007. /* global: toDebugString: true */
  2008. function serializeObject(obj) {
  2009. var seen = [];
  2010. return JSON.stringify(obj, function(key, val) {
  2011. val = toJsonReplacer(key, val);
  2012. if (isObject(val)) {
  2013. if (seen.indexOf(val) >= 0) return '<<already seen>>';
  2014. seen.push(val);
  2015. }
  2016. return val;
  2017. });
  2018. }
  2019. function toDebugString(obj) {
  2020. if (typeof obj === 'function') {
  2021. return obj.toString().replace(/ \{[\s\S]*$/, '');
  2022. } else if (typeof obj === 'undefined') {
  2023. return 'undefined';
  2024. } else if (typeof obj !== 'string') {
  2025. return serializeObject(obj);
  2026. }
  2027. return obj;
  2028. }
  2029. /* global angularModule: true,
  2030. version: true,
  2031. $CompileProvider,
  2032. htmlAnchorDirective,
  2033. inputDirective,
  2034. inputDirective,
  2035. formDirective,
  2036. scriptDirective,
  2037. selectDirective,
  2038. styleDirective,
  2039. optionDirective,
  2040. ngBindDirective,
  2041. ngBindHtmlDirective,
  2042. ngBindTemplateDirective,
  2043. ngClassDirective,
  2044. ngClassEvenDirective,
  2045. ngClassOddDirective,
  2046. ngCloakDirective,
  2047. ngControllerDirective,
  2048. ngFormDirective,
  2049. ngHideDirective,
  2050. ngIfDirective,
  2051. ngIncludeDirective,
  2052. ngIncludeFillContentDirective,
  2053. ngInitDirective,
  2054. ngNonBindableDirective,
  2055. ngPluralizeDirective,
  2056. ngRepeatDirective,
  2057. ngShowDirective,
  2058. ngStyleDirective,
  2059. ngSwitchDirective,
  2060. ngSwitchWhenDirective,
  2061. ngSwitchDefaultDirective,
  2062. ngOptionsDirective,
  2063. ngTranscludeDirective,
  2064. ngModelDirective,
  2065. ngListDirective,
  2066. ngChangeDirective,
  2067. patternDirective,
  2068. patternDirective,
  2069. requiredDirective,
  2070. requiredDirective,
  2071. minlengthDirective,
  2072. minlengthDirective,
  2073. maxlengthDirective,
  2074. maxlengthDirective,
  2075. ngValueDirective,
  2076. ngModelOptionsDirective,
  2077. ngAttributeAliasDirectives,
  2078. ngEventDirectives,
  2079. $AnchorScrollProvider,
  2080. $AnimateProvider,
  2081. $CoreAnimateCssProvider,
  2082. $$CoreAnimateQueueProvider,
  2083. $$CoreAnimateRunnerProvider,
  2084. $BrowserProvider,
  2085. $CacheFactoryProvider,
  2086. $ControllerProvider,
  2087. $DocumentProvider,
  2088. $ExceptionHandlerProvider,
  2089. $FilterProvider,
  2090. $$ForceReflowProvider,
  2091. $InterpolateProvider,
  2092. $IntervalProvider,
  2093. $$HashMapProvider,
  2094. $HttpProvider,
  2095. $HttpParamSerializerProvider,
  2096. $HttpParamSerializerJQLikeProvider,
  2097. $HttpBackendProvider,
  2098. $LocationProvider,
  2099. $LogProvider,
  2100. $ParseProvider,
  2101. $RootScopeProvider,
  2102. $QProvider,
  2103. $$QProvider,
  2104. $$SanitizeUriProvider,
  2105. $SceProvider,
  2106. $SceDelegateProvider,
  2107. $SnifferProvider,
  2108. $TemplateCacheProvider,
  2109. $TemplateRequestProvider,
  2110. $$TestabilityProvider,
  2111. $TimeoutProvider,
  2112. $$RAFProvider,
  2113. $WindowProvider,
  2114. $$jqLiteProvider,
  2115. $$CookieReaderProvider
  2116. */
  2117. /**
  2118. * @ngdoc object
  2119. * @name angular.version
  2120. * @module ng
  2121. * @description
  2122. * An object that contains information about the current AngularJS version. This object has the
  2123. * following properties:
  2124. *
  2125. * - `full` – `{string}` – Full version string, such as "0.9.18".
  2126. * - `major` – `{number}` – Major version number, such as "0".
  2127. * - `minor` – `{number}` – Minor version number, such as "9".
  2128. * - `dot` – `{number}` – Dot version number, such as "18".
  2129. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  2130. */
  2131. var version = {
  2132. full: '1.4.5', // all of these placeholder strings will be replaced by grunt's
  2133. major: 1, // package task
  2134. minor: 4,
  2135. dot: 5,
  2136. codeName: 'permanent-internship'
  2137. };
  2138. function publishExternalAPI(angular) {
  2139. extend(angular, {
  2140. 'bootstrap': bootstrap,
  2141. 'copy': copy,
  2142. 'extend': extend,
  2143. 'merge': merge,
  2144. 'equals': equals,
  2145. 'element': jqLite,
  2146. 'forEach': forEach,
  2147. 'injector': createInjector,
  2148. 'noop': noop,
  2149. 'bind': bind,
  2150. 'toJson': toJson,
  2151. 'fromJson': fromJson,
  2152. 'identity': identity,
  2153. 'isUndefined': isUndefined,
  2154. 'isDefined': isDefined,
  2155. 'isString': isString,
  2156. 'isFunction': isFunction,
  2157. 'isObject': isObject,
  2158. 'isNumber': isNumber,
  2159. 'isElement': isElement,
  2160. 'isArray': isArray,
  2161. 'version': version,
  2162. 'isDate': isDate,
  2163. 'lowercase': lowercase,
  2164. 'uppercase': uppercase,
  2165. 'callbacks': {counter: 0},
  2166. 'getTestability': getTestability,
  2167. '$$minErr': minErr,
  2168. '$$csp': csp,
  2169. 'reloadWithDebugInfo': reloadWithDebugInfo
  2170. });
  2171. angularModule = setupModuleLoader(window);
  2172. angularModule('ng', ['ngLocale'], ['$provide',
  2173. function ngModule($provide) {
  2174. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  2175. $provide.provider({
  2176. $$sanitizeUri: $$SanitizeUriProvider
  2177. });
  2178. $provide.provider('$compile', $CompileProvider).
  2179. directive({
  2180. a: htmlAnchorDirective,
  2181. input: inputDirective,
  2182. textarea: inputDirective,
  2183. form: formDirective,
  2184. script: scriptDirective,
  2185. select: selectDirective,
  2186. style: styleDirective,
  2187. option: optionDirective,
  2188. ngBind: ngBindDirective,
  2189. ngBindHtml: ngBindHtmlDirective,
  2190. ngBindTemplate: ngBindTemplateDirective,
  2191. ngClass: ngClassDirective,
  2192. ngClassEven: ngClassEvenDirective,
  2193. ngClassOdd: ngClassOddDirective,
  2194. ngCloak: ngCloakDirective,
  2195. ngController: ngControllerDirective,
  2196. ngForm: ngFormDirective,
  2197. ngHide: ngHideDirective,
  2198. ngIf: ngIfDirective,
  2199. ngInclude: ngIncludeDirective,
  2200. ngInit: ngInitDirective,
  2201. ngNonBindable: ngNonBindableDirective,
  2202. ngPluralize: ngPluralizeDirective,
  2203. ngRepeat: ngRepeatDirective,
  2204. ngShow: ngShowDirective,
  2205. ngStyle: ngStyleDirective,
  2206. ngSwitch: ngSwitchDirective,
  2207. ngSwitchWhen: ngSwitchWhenDirective,
  2208. ngSwitchDefault: ngSwitchDefaultDirective,
  2209. ngOptions: ngOptionsDirective,
  2210. ngTransclude: ngTranscludeDirective,
  2211. ngModel: ngModelDirective,
  2212. ngList: ngListDirective,
  2213. ngChange: ngChangeDirective,
  2214. pattern: patternDirective,
  2215. ngPattern: patternDirective,
  2216. required: requiredDirective,
  2217. ngRequired: requiredDirective,
  2218. minlength: minlengthDirective,
  2219. ngMinlength: minlengthDirective,
  2220. maxlength: maxlengthDirective,
  2221. ngMaxlength: maxlengthDirective,
  2222. ngValue: ngValueDirective,
  2223. ngModelOptions: ngModelOptionsDirective
  2224. }).
  2225. directive({
  2226. ngInclude: ngIncludeFillContentDirective
  2227. }).
  2228. directive(ngAttributeAliasDirectives).
  2229. directive(ngEventDirectives);
  2230. $provide.provider({
  2231. $anchorScroll: $AnchorScrollProvider,
  2232. $animate: $AnimateProvider,
  2233. $animateCss: $CoreAnimateCssProvider,
  2234. $$animateQueue: $$CoreAnimateQueueProvider,
  2235. $$AnimateRunner: $$CoreAnimateRunnerProvider,
  2236. $browser: $BrowserProvider,
  2237. $cacheFactory: $CacheFactoryProvider,
  2238. $controller: $ControllerProvider,
  2239. $document: $DocumentProvider,
  2240. $exceptionHandler: $ExceptionHandlerProvider,
  2241. $filter: $FilterProvider,
  2242. $$forceReflow: $$ForceReflowProvider,
  2243. $interpolate: $InterpolateProvider,
  2244. $interval: $IntervalProvider,
  2245. $http: $HttpProvider,
  2246. $httpParamSerializer: $HttpParamSerializerProvider,
  2247. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  2248. $httpBackend: $HttpBackendProvider,
  2249. $location: $LocationProvider,
  2250. $log: $LogProvider,
  2251. $parse: $ParseProvider,
  2252. $rootScope: $RootScopeProvider,
  2253. $q: $QProvider,
  2254. $$q: $$QProvider,
  2255. $sce: $SceProvider,
  2256. $sceDelegate: $SceDelegateProvider,
  2257. $sniffer: $SnifferProvider,
  2258. $templateCache: $TemplateCacheProvider,
  2259. $templateRequest: $TemplateRequestProvider,
  2260. $$testability: $$TestabilityProvider,
  2261. $timeout: $TimeoutProvider,
  2262. $window: $WindowProvider,
  2263. $$rAF: $$RAFProvider,
  2264. $$jqLite: $$jqLiteProvider,
  2265. $$HashMap: $$HashMapProvider,
  2266. $$cookieReader: $$CookieReaderProvider
  2267. });
  2268. }
  2269. ]);
  2270. }
  2271. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2272. * Any commits to this file should be reviewed with security in mind. *
  2273. * Changes to this file can potentially create security vulnerabilities. *
  2274. * An approval from 2 Core members with history of modifying *
  2275. * this file is required. *
  2276. * *
  2277. * Does the change somehow allow for arbitrary javascript to be executed? *
  2278. * Or allows for someone to change the prototype of built-in objects? *
  2279. * Or gives undesired access to variables likes document or window? *
  2280. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2281. /* global JQLitePrototype: true,
  2282. addEventListenerFn: true,
  2283. removeEventListenerFn: true,
  2284. BOOLEAN_ATTR: true,
  2285. ALIASED_ATTR: true,
  2286. */
  2287. //////////////////////////////////
  2288. //JQLite
  2289. //////////////////////////////////
  2290. /**
  2291. * @ngdoc function
  2292. * @name angular.element
  2293. * @module ng
  2294. * @kind function
  2295. *
  2296. * @description
  2297. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2298. *
  2299. * If jQuery is available, `angular.element` is an alias for the
  2300. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2301. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
  2302. *
  2303. * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
  2304. * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
  2305. * commonly needed functionality with the goal of having a very small footprint.</div>
  2306. *
  2307. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file.
  2308. *
  2309. * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
  2310. * jqLite; they are never raw DOM references.</div>
  2311. *
  2312. * ## Angular's jqLite
  2313. * jqLite provides only the following jQuery methods:
  2314. *
  2315. * - [`addClass()`](http://api.jquery.com/addClass/)
  2316. * - [`after()`](http://api.jquery.com/after/)
  2317. * - [`append()`](http://api.jquery.com/append/)
  2318. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2319. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  2320. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2321. * - [`clone()`](http://api.jquery.com/clone/)
  2322. * - [`contents()`](http://api.jquery.com/contents/)
  2323. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`. As a setter, does not convert numbers to strings or append 'px'.
  2324. * - [`data()`](http://api.jquery.com/data/)
  2325. * - [`detach()`](http://api.jquery.com/detach/)
  2326. * - [`empty()`](http://api.jquery.com/empty/)
  2327. * - [`eq()`](http://api.jquery.com/eq/)
  2328. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2329. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2330. * - [`html()`](http://api.jquery.com/html/)
  2331. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2332. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2333. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
  2334. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2335. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2336. * - [`prepend()`](http://api.jquery.com/prepend/)
  2337. * - [`prop()`](http://api.jquery.com/prop/)
  2338. * - [`ready()`](http://api.jquery.com/ready/)
  2339. * - [`remove()`](http://api.jquery.com/remove/)
  2340. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  2341. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  2342. * - [`removeData()`](http://api.jquery.com/removeData/)
  2343. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2344. * - [`text()`](http://api.jquery.com/text/)
  2345. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  2346. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  2347. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces or event object as parameter
  2348. * - [`val()`](http://api.jquery.com/val/)
  2349. * - [`wrap()`](http://api.jquery.com/wrap/)
  2350. *
  2351. * ## jQuery/jqLite Extras
  2352. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2353. *
  2354. * ### Events
  2355. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2356. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2357. * element before it is removed.
  2358. *
  2359. * ### Methods
  2360. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2361. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2362. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2363. * `'ngModel'`).
  2364. * - `injector()` - retrieves the injector of the current element or its parent.
  2365. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2366. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2367. * be enabled.
  2368. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2369. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2370. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2371. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2372. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2373. * parent element is reached.
  2374. *
  2375. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2376. * @returns {Object} jQuery object.
  2377. */
  2378. JQLite.expando = 'ng339';
  2379. var jqCache = JQLite.cache = {},
  2380. jqId = 1,
  2381. addEventListenerFn = function(element, type, fn) {
  2382. element.addEventListener(type, fn, false);
  2383. },
  2384. removeEventListenerFn = function(element, type, fn) {
  2385. element.removeEventListener(type, fn, false);
  2386. };
  2387. /*
  2388. * !!! This is an undocumented "private" function !!!
  2389. */
  2390. JQLite._data = function(node) {
  2391. //jQuery always returns an object on cache miss
  2392. return this.cache[node[this.expando]] || {};
  2393. };
  2394. function jqNextId() { return ++jqId; }
  2395. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  2396. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  2397. var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
  2398. var jqLiteMinErr = minErr('jqLite');
  2399. /**
  2400. * Converts snake_case to camelCase.
  2401. * Also there is special case for Moz prefix starting with upper case letter.
  2402. * @param name Name to normalize
  2403. */
  2404. function camelCase(name) {
  2405. return name.
  2406. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2407. return offset ? letter.toUpperCase() : letter;
  2408. }).
  2409. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2410. }
  2411. var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
  2412. var HTML_REGEXP = /<|&#?\w+;/;
  2413. var TAG_NAME_REGEXP = /<([\w:]+)/;
  2414. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
  2415. var wrapMap = {
  2416. 'option': [1, '<select multiple="multiple">', '</select>'],
  2417. 'thead': [1, '<table>', '</table>'],
  2418. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2419. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2420. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2421. '_default': [0, "", ""]
  2422. };
  2423. wrapMap.optgroup = wrapMap.option;
  2424. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2425. wrapMap.th = wrapMap.td;
  2426. function jqLiteIsTextNode(html) {
  2427. return !HTML_REGEXP.test(html);
  2428. }
  2429. function jqLiteAcceptsData(node) {
  2430. // The window object can accept data but has no nodeType
  2431. // Otherwise we are only interested in elements (1) and documents (9)
  2432. var nodeType = node.nodeType;
  2433. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2434. }
  2435. function jqLiteHasData(node) {
  2436. for (var key in jqCache[node.ng339]) {
  2437. return true;
  2438. }
  2439. return false;
  2440. }
  2441. function jqLiteBuildFragment(html, context) {
  2442. var tmp, tag, wrap,
  2443. fragment = context.createDocumentFragment(),
  2444. nodes = [], i;
  2445. if (jqLiteIsTextNode(html)) {
  2446. // Convert non-html into a text node
  2447. nodes.push(context.createTextNode(html));
  2448. } else {
  2449. // Convert html into DOM nodes
  2450. tmp = tmp || fragment.appendChild(context.createElement("div"));
  2451. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2452. wrap = wrapMap[tag] || wrapMap._default;
  2453. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2454. // Descend through wrappers to the right content
  2455. i = wrap[0];
  2456. while (i--) {
  2457. tmp = tmp.lastChild;
  2458. }
  2459. nodes = concat(nodes, tmp.childNodes);
  2460. tmp = fragment.firstChild;
  2461. tmp.textContent = "";
  2462. }
  2463. // Remove wrapper from fragment
  2464. fragment.textContent = "";
  2465. fragment.innerHTML = ""; // Clear inner HTML
  2466. forEach(nodes, function(node) {
  2467. fragment.appendChild(node);
  2468. });
  2469. return fragment;
  2470. }
  2471. function jqLiteParseHTML(html, context) {
  2472. context = context || document;
  2473. var parsed;
  2474. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2475. return [context.createElement(parsed[1])];
  2476. }
  2477. if ((parsed = jqLiteBuildFragment(html, context))) {
  2478. return parsed.childNodes;
  2479. }
  2480. return [];
  2481. }
  2482. /////////////////////////////////////////////
  2483. function JQLite(element) {
  2484. if (element instanceof JQLite) {
  2485. return element;
  2486. }
  2487. var argIsString;
  2488. if (isString(element)) {
  2489. element = trim(element);
  2490. argIsString = true;
  2491. }
  2492. if (!(this instanceof JQLite)) {
  2493. if (argIsString && element.charAt(0) != '<') {
  2494. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2495. }
  2496. return new JQLite(element);
  2497. }
  2498. if (argIsString) {
  2499. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2500. } else {
  2501. jqLiteAddNodes(this, element);
  2502. }
  2503. }
  2504. function jqLiteClone(element) {
  2505. return element.cloneNode(true);
  2506. }
  2507. function jqLiteDealoc(element, onlyDescendants) {
  2508. if (!onlyDescendants) jqLiteRemoveData(element);
  2509. if (element.querySelectorAll) {
  2510. var descendants = element.querySelectorAll('*');
  2511. for (var i = 0, l = descendants.length; i < l; i++) {
  2512. jqLiteRemoveData(descendants[i]);
  2513. }
  2514. }
  2515. }
  2516. function jqLiteOff(element, type, fn, unsupported) {
  2517. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2518. var expandoStore = jqLiteExpandoStore(element);
  2519. var events = expandoStore && expandoStore.events;
  2520. var handle = expandoStore && expandoStore.handle;
  2521. if (!handle) return; //no listeners registered
  2522. if (!type) {
  2523. for (type in events) {
  2524. if (type !== '$destroy') {
  2525. removeEventListenerFn(element, type, handle);
  2526. }
  2527. delete events[type];
  2528. }
  2529. } else {
  2530. forEach(type.split(' '), function(type) {
  2531. if (isDefined(fn)) {
  2532. var listenerFns = events[type];
  2533. arrayRemove(listenerFns || [], fn);
  2534. if (listenerFns && listenerFns.length > 0) {
  2535. return;
  2536. }
  2537. }
  2538. removeEventListenerFn(element, type, handle);
  2539. delete events[type];
  2540. });
  2541. }
  2542. }
  2543. function jqLiteRemoveData(element, name) {
  2544. var expandoId = element.ng339;
  2545. var expandoStore = expandoId && jqCache[expandoId];
  2546. if (expandoStore) {
  2547. if (name) {
  2548. delete expandoStore.data[name];
  2549. return;
  2550. }
  2551. if (expandoStore.handle) {
  2552. if (expandoStore.events.$destroy) {
  2553. expandoStore.handle({}, '$destroy');
  2554. }
  2555. jqLiteOff(element);
  2556. }
  2557. delete jqCache[expandoId];
  2558. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2559. }
  2560. }
  2561. function jqLiteExpandoStore(element, createIfNecessary) {
  2562. var expandoId = element.ng339,
  2563. expandoStore = expandoId && jqCache[expandoId];
  2564. if (createIfNecessary && !expandoStore) {
  2565. element.ng339 = expandoId = jqNextId();
  2566. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2567. }
  2568. return expandoStore;
  2569. }
  2570. function jqLiteData(element, key, value) {
  2571. if (jqLiteAcceptsData(element)) {
  2572. var isSimpleSetter = isDefined(value);
  2573. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2574. var massGetter = !key;
  2575. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2576. var data = expandoStore && expandoStore.data;
  2577. if (isSimpleSetter) { // data('key', value)
  2578. data[key] = value;
  2579. } else {
  2580. if (massGetter) { // data()
  2581. return data;
  2582. } else {
  2583. if (isSimpleGetter) { // data('key')
  2584. // don't force creation of expandoStore if it doesn't exist yet
  2585. return data && data[key];
  2586. } else { // mass-setter: data({key1: val1, key2: val2})
  2587. extend(data, key);
  2588. }
  2589. }
  2590. }
  2591. }
  2592. }
  2593. function jqLiteHasClass(element, selector) {
  2594. if (!element.getAttribute) return false;
  2595. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2596. indexOf(" " + selector + " ") > -1);
  2597. }
  2598. function jqLiteRemoveClass(element, cssClasses) {
  2599. if (cssClasses && element.setAttribute) {
  2600. forEach(cssClasses.split(' '), function(cssClass) {
  2601. element.setAttribute('class', trim(
  2602. (" " + (element.getAttribute('class') || '') + " ")
  2603. .replace(/[\n\t]/g, " ")
  2604. .replace(" " + trim(cssClass) + " ", " "))
  2605. );
  2606. });
  2607. }
  2608. }
  2609. function jqLiteAddClass(element, cssClasses) {
  2610. if (cssClasses && element.setAttribute) {
  2611. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2612. .replace(/[\n\t]/g, " ");
  2613. forEach(cssClasses.split(' '), function(cssClass) {
  2614. cssClass = trim(cssClass);
  2615. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2616. existingClasses += cssClass + ' ';
  2617. }
  2618. });
  2619. element.setAttribute('class', trim(existingClasses));
  2620. }
  2621. }
  2622. function jqLiteAddNodes(root, elements) {
  2623. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2624. if (elements) {
  2625. // if a Node (the most common case)
  2626. if (elements.nodeType) {
  2627. root[root.length++] = elements;
  2628. } else {
  2629. var length = elements.length;
  2630. // if an Array or NodeList and not a Window
  2631. if (typeof length === 'number' && elements.window !== elements) {
  2632. if (length) {
  2633. for (var i = 0; i < length; i++) {
  2634. root[root.length++] = elements[i];
  2635. }
  2636. }
  2637. } else {
  2638. root[root.length++] = elements;
  2639. }
  2640. }
  2641. }
  2642. }
  2643. function jqLiteController(element, name) {
  2644. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  2645. }
  2646. function jqLiteInheritedData(element, name, value) {
  2647. // if element is the document object work with the html element instead
  2648. // this makes $(document).scope() possible
  2649. if (element.nodeType == NODE_TYPE_DOCUMENT) {
  2650. element = element.documentElement;
  2651. }
  2652. var names = isArray(name) ? name : [name];
  2653. while (element) {
  2654. for (var i = 0, ii = names.length; i < ii; i++) {
  2655. if ((value = jqLite.data(element, names[i])) !== undefined) return value;
  2656. }
  2657. // If dealing with a document fragment node with a host element, and no parent, use the host
  2658. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2659. // to lookup parent controllers.
  2660. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  2661. }
  2662. }
  2663. function jqLiteEmpty(element) {
  2664. jqLiteDealoc(element, true);
  2665. while (element.firstChild) {
  2666. element.removeChild(element.firstChild);
  2667. }
  2668. }
  2669. function jqLiteRemove(element, keepData) {
  2670. if (!keepData) jqLiteDealoc(element);
  2671. var parent = element.parentNode;
  2672. if (parent) parent.removeChild(element);
  2673. }
  2674. function jqLiteDocumentLoaded(action, win) {
  2675. win = win || window;
  2676. if (win.document.readyState === 'complete') {
  2677. // Force the action to be run async for consistent behaviour
  2678. // from the action's point of view
  2679. // i.e. it will definitely not be in a $apply
  2680. win.setTimeout(action);
  2681. } else {
  2682. // No need to unbind this handler as load is only ever called once
  2683. jqLite(win).on('load', action);
  2684. }
  2685. }
  2686. //////////////////////////////////////////
  2687. // Functions which are declared directly.
  2688. //////////////////////////////////////////
  2689. var JQLitePrototype = JQLite.prototype = {
  2690. ready: function(fn) {
  2691. var fired = false;
  2692. function trigger() {
  2693. if (fired) return;
  2694. fired = true;
  2695. fn();
  2696. }
  2697. // check if document is already loaded
  2698. if (document.readyState === 'complete') {
  2699. setTimeout(trigger);
  2700. } else {
  2701. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2702. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2703. // jshint -W064
  2704. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2705. // jshint +W064
  2706. }
  2707. },
  2708. toString: function() {
  2709. var value = [];
  2710. forEach(this, function(e) { value.push('' + e);});
  2711. return '[' + value.join(', ') + ']';
  2712. },
  2713. eq: function(index) {
  2714. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2715. },
  2716. length: 0,
  2717. push: push,
  2718. sort: [].sort,
  2719. splice: [].splice
  2720. };
  2721. //////////////////////////////////////////
  2722. // Functions iterating getter/setters.
  2723. // these functions return self on setter and
  2724. // value on get.
  2725. //////////////////////////////////////////
  2726. var BOOLEAN_ATTR = {};
  2727. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2728. BOOLEAN_ATTR[lowercase(value)] = value;
  2729. });
  2730. var BOOLEAN_ELEMENTS = {};
  2731. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2732. BOOLEAN_ELEMENTS[value] = true;
  2733. });
  2734. var ALIASED_ATTR = {
  2735. 'ngMinlength': 'minlength',
  2736. 'ngMaxlength': 'maxlength',
  2737. 'ngMin': 'min',
  2738. 'ngMax': 'max',
  2739. 'ngPattern': 'pattern'
  2740. };
  2741. function getBooleanAttrName(element, name) {
  2742. // check dom last since we will most likely fail on name
  2743. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2744. // booleanAttr is here twice to minimize DOM access
  2745. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  2746. }
  2747. function getAliasedAttrName(element, name) {
  2748. var nodeName = element.nodeName;
  2749. return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name];
  2750. }
  2751. forEach({
  2752. data: jqLiteData,
  2753. removeData: jqLiteRemoveData,
  2754. hasData: jqLiteHasData
  2755. }, function(fn, name) {
  2756. JQLite[name] = fn;
  2757. });
  2758. forEach({
  2759. data: jqLiteData,
  2760. inheritedData: jqLiteInheritedData,
  2761. scope: function(element) {
  2762. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2763. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2764. },
  2765. isolateScope: function(element) {
  2766. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2767. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  2768. },
  2769. controller: jqLiteController,
  2770. injector: function(element) {
  2771. return jqLiteInheritedData(element, '$injector');
  2772. },
  2773. removeAttr: function(element, name) {
  2774. element.removeAttribute(name);
  2775. },
  2776. hasClass: jqLiteHasClass,
  2777. css: function(element, name, value) {
  2778. name = camelCase(name);
  2779. if (isDefined(value)) {
  2780. element.style[name] = value;
  2781. } else {
  2782. return element.style[name];
  2783. }
  2784. },
  2785. attr: function(element, name, value) {
  2786. var nodeType = element.nodeType;
  2787. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
  2788. return;
  2789. }
  2790. var lowercasedName = lowercase(name);
  2791. if (BOOLEAN_ATTR[lowercasedName]) {
  2792. if (isDefined(value)) {
  2793. if (!!value) {
  2794. element[name] = true;
  2795. element.setAttribute(name, lowercasedName);
  2796. } else {
  2797. element[name] = false;
  2798. element.removeAttribute(lowercasedName);
  2799. }
  2800. } else {
  2801. return (element[name] ||
  2802. (element.attributes.getNamedItem(name) || noop).specified)
  2803. ? lowercasedName
  2804. : undefined;
  2805. }
  2806. } else if (isDefined(value)) {
  2807. element.setAttribute(name, value);
  2808. } else if (element.getAttribute) {
  2809. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2810. // some elements (e.g. Document) don't have get attribute, so return undefined
  2811. var ret = element.getAttribute(name, 2);
  2812. // normalize non-existing attributes to undefined (as jQuery)
  2813. return ret === null ? undefined : ret;
  2814. }
  2815. },
  2816. prop: function(element, name, value) {
  2817. if (isDefined(value)) {
  2818. element[name] = value;
  2819. } else {
  2820. return element[name];
  2821. }
  2822. },
  2823. text: (function() {
  2824. getText.$dv = '';
  2825. return getText;
  2826. function getText(element, value) {
  2827. if (isUndefined(value)) {
  2828. var nodeType = element.nodeType;
  2829. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  2830. }
  2831. element.textContent = value;
  2832. }
  2833. })(),
  2834. val: function(element, value) {
  2835. if (isUndefined(value)) {
  2836. if (element.multiple && nodeName_(element) === 'select') {
  2837. var result = [];
  2838. forEach(element.options, function(option) {
  2839. if (option.selected) {
  2840. result.push(option.value || option.text);
  2841. }
  2842. });
  2843. return result.length === 0 ? null : result;
  2844. }
  2845. return element.value;
  2846. }
  2847. element.value = value;
  2848. },
  2849. html: function(element, value) {
  2850. if (isUndefined(value)) {
  2851. return element.innerHTML;
  2852. }
  2853. jqLiteDealoc(element, true);
  2854. element.innerHTML = value;
  2855. },
  2856. empty: jqLiteEmpty
  2857. }, function(fn, name) {
  2858. /**
  2859. * Properties: writes return selection, reads return first value
  2860. */
  2861. JQLite.prototype[name] = function(arg1, arg2) {
  2862. var i, key;
  2863. var nodeCount = this.length;
  2864. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  2865. // in a way that survives minification.
  2866. // jqLiteEmpty takes no arguments but is a setter.
  2867. if (fn !== jqLiteEmpty &&
  2868. (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
  2869. if (isObject(arg1)) {
  2870. // we are a write, but the object properties are the key/values
  2871. for (i = 0; i < nodeCount; i++) {
  2872. if (fn === jqLiteData) {
  2873. // data() takes the whole object in jQuery
  2874. fn(this[i], arg1);
  2875. } else {
  2876. for (key in arg1) {
  2877. fn(this[i], key, arg1[key]);
  2878. }
  2879. }
  2880. }
  2881. // return self for chaining
  2882. return this;
  2883. } else {
  2884. // we are a read, so read the first child.
  2885. // TODO: do we still need this?
  2886. var value = fn.$dv;
  2887. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  2888. var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;
  2889. for (var j = 0; j < jj; j++) {
  2890. var nodeValue = fn(this[j], arg1, arg2);
  2891. value = value ? value + nodeValue : nodeValue;
  2892. }
  2893. return value;
  2894. }
  2895. } else {
  2896. // we are a write, so apply to all children
  2897. for (i = 0; i < nodeCount; i++) {
  2898. fn(this[i], arg1, arg2);
  2899. }
  2900. // return self for chaining
  2901. return this;
  2902. }
  2903. };
  2904. });
  2905. function createEventHandler(element, events) {
  2906. var eventHandler = function(event, type) {
  2907. // jQuery specific api
  2908. event.isDefaultPrevented = function() {
  2909. return event.defaultPrevented;
  2910. };
  2911. var eventFns = events[type || event.type];
  2912. var eventFnsLength = eventFns ? eventFns.length : 0;
  2913. if (!eventFnsLength) return;
  2914. if (isUndefined(event.immediatePropagationStopped)) {
  2915. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  2916. event.stopImmediatePropagation = function() {
  2917. event.immediatePropagationStopped = true;
  2918. if (event.stopPropagation) {
  2919. event.stopPropagation();
  2920. }
  2921. if (originalStopImmediatePropagation) {
  2922. originalStopImmediatePropagation.call(event);
  2923. }
  2924. };
  2925. }
  2926. event.isImmediatePropagationStopped = function() {
  2927. return event.immediatePropagationStopped === true;
  2928. };
  2929. // Copy event handlers in case event handlers array is modified during execution.
  2930. if ((eventFnsLength > 1)) {
  2931. eventFns = shallowCopy(eventFns);
  2932. }
  2933. for (var i = 0; i < eventFnsLength; i++) {
  2934. if (!event.isImmediatePropagationStopped()) {
  2935. eventFns[i].call(element, event);
  2936. }
  2937. }
  2938. };
  2939. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  2940. // events on `element`
  2941. eventHandler.elem = element;
  2942. return eventHandler;
  2943. }
  2944. //////////////////////////////////////////
  2945. // Functions iterating traversal.
  2946. // These functions chain results into a single
  2947. // selector.
  2948. //////////////////////////////////////////
  2949. forEach({
  2950. removeData: jqLiteRemoveData,
  2951. on: function jqLiteOn(element, type, fn, unsupported) {
  2952. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  2953. // Do not add event handlers to non-elements because they will not be cleaned up.
  2954. if (!jqLiteAcceptsData(element)) {
  2955. return;
  2956. }
  2957. var expandoStore = jqLiteExpandoStore(element, true);
  2958. var events = expandoStore.events;
  2959. var handle = expandoStore.handle;
  2960. if (!handle) {
  2961. handle = expandoStore.handle = createEventHandler(element, events);
  2962. }
  2963. // http://jsperf.com/string-indexof-vs-split
  2964. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  2965. var i = types.length;
  2966. while (i--) {
  2967. type = types[i];
  2968. var eventFns = events[type];
  2969. if (!eventFns) {
  2970. events[type] = [];
  2971. if (type === 'mouseenter' || type === 'mouseleave') {
  2972. // Refer to jQuery's implementation of mouseenter & mouseleave
  2973. // Read about mouseenter and mouseleave:
  2974. // http://www.quirksmode.org/js/events_mouse.html#link8
  2975. jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) {
  2976. var target = this, related = event.relatedTarget;
  2977. // For mousenter/leave call the handler if related is outside the target.
  2978. // NB: No relatedTarget if the mouse left/entered the browser window
  2979. if (!related || (related !== target && !target.contains(related))) {
  2980. handle(event, type);
  2981. }
  2982. });
  2983. } else {
  2984. if (type !== '$destroy') {
  2985. addEventListenerFn(element, type, handle);
  2986. }
  2987. }
  2988. eventFns = events[type];
  2989. }
  2990. eventFns.push(fn);
  2991. }
  2992. },
  2993. off: jqLiteOff,
  2994. one: function(element, type, fn) {
  2995. element = jqLite(element);
  2996. //add the listener twice so that when it is called
  2997. //you can remove the original function and still be
  2998. //able to call element.off(ev, fn) normally
  2999. element.on(type, function onFn() {
  3000. element.off(type, fn);
  3001. element.off(type, onFn);
  3002. });
  3003. element.on(type, fn);
  3004. },
  3005. replaceWith: function(element, replaceNode) {
  3006. var index, parent = element.parentNode;
  3007. jqLiteDealoc(element);
  3008. forEach(new JQLite(replaceNode), function(node) {
  3009. if (index) {
  3010. parent.insertBefore(node, index.nextSibling);
  3011. } else {
  3012. parent.replaceChild(node, element);
  3013. }
  3014. index = node;
  3015. });
  3016. },
  3017. children: function(element) {
  3018. var children = [];
  3019. forEach(element.childNodes, function(element) {
  3020. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3021. children.push(element);
  3022. }
  3023. });
  3024. return children;
  3025. },
  3026. contents: function(element) {
  3027. return element.contentDocument || element.childNodes || [];
  3028. },
  3029. append: function(element, node) {
  3030. var nodeType = element.nodeType;
  3031. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  3032. node = new JQLite(node);
  3033. for (var i = 0, ii = node.length; i < ii; i++) {
  3034. var child = node[i];
  3035. element.appendChild(child);
  3036. }
  3037. },
  3038. prepend: function(element, node) {
  3039. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3040. var index = element.firstChild;
  3041. forEach(new JQLite(node), function(child) {
  3042. element.insertBefore(child, index);
  3043. });
  3044. }
  3045. },
  3046. wrap: function(element, wrapNode) {
  3047. wrapNode = jqLite(wrapNode).eq(0).clone()[0];
  3048. var parent = element.parentNode;
  3049. if (parent) {
  3050. parent.replaceChild(wrapNode, element);
  3051. }
  3052. wrapNode.appendChild(element);
  3053. },
  3054. remove: jqLiteRemove,
  3055. detach: function(element) {
  3056. jqLiteRemove(element, true);
  3057. },
  3058. after: function(element, newElement) {
  3059. var index = element, parent = element.parentNode;
  3060. newElement = new JQLite(newElement);
  3061. for (var i = 0, ii = newElement.length; i < ii; i++) {
  3062. var node = newElement[i];
  3063. parent.insertBefore(node, index.nextSibling);
  3064. index = node;
  3065. }
  3066. },
  3067. addClass: jqLiteAddClass,
  3068. removeClass: jqLiteRemoveClass,
  3069. toggleClass: function(element, selector, condition) {
  3070. if (selector) {
  3071. forEach(selector.split(' '), function(className) {
  3072. var classCondition = condition;
  3073. if (isUndefined(classCondition)) {
  3074. classCondition = !jqLiteHasClass(element, className);
  3075. }
  3076. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  3077. });
  3078. }
  3079. },
  3080. parent: function(element) {
  3081. var parent = element.parentNode;
  3082. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  3083. },
  3084. next: function(element) {
  3085. return element.nextElementSibling;
  3086. },
  3087. find: function(element, selector) {
  3088. if (element.getElementsByTagName) {
  3089. return element.getElementsByTagName(selector);
  3090. } else {
  3091. return [];
  3092. }
  3093. },
  3094. clone: jqLiteClone,
  3095. triggerHandler: function(element, event, extraParameters) {
  3096. var dummyEvent, eventFnsCopy, handlerArgs;
  3097. var eventName = event.type || event;
  3098. var expandoStore = jqLiteExpandoStore(element);
  3099. var events = expandoStore && expandoStore.events;
  3100. var eventFns = events && events[eventName];
  3101. if (eventFns) {
  3102. // Create a dummy event to pass to the handlers
  3103. dummyEvent = {
  3104. preventDefault: function() { this.defaultPrevented = true; },
  3105. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  3106. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  3107. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  3108. stopPropagation: noop,
  3109. type: eventName,
  3110. target: element
  3111. };
  3112. // If a custom event was provided then extend our dummy event with it
  3113. if (event.type) {
  3114. dummyEvent = extend(dummyEvent, event);
  3115. }
  3116. // Copy event handlers in case event handlers array is modified during execution.
  3117. eventFnsCopy = shallowCopy(eventFns);
  3118. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  3119. forEach(eventFnsCopy, function(fn) {
  3120. if (!dummyEvent.isImmediatePropagationStopped()) {
  3121. fn.apply(element, handlerArgs);
  3122. }
  3123. });
  3124. }
  3125. }
  3126. }, function(fn, name) {
  3127. /**
  3128. * chaining functions
  3129. */
  3130. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  3131. var value;
  3132. for (var i = 0, ii = this.length; i < ii; i++) {
  3133. if (isUndefined(value)) {
  3134. value = fn(this[i], arg1, arg2, arg3);
  3135. if (isDefined(value)) {
  3136. // any function which returns a value needs to be wrapped
  3137. value = jqLite(value);
  3138. }
  3139. } else {
  3140. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  3141. }
  3142. }
  3143. return isDefined(value) ? value : this;
  3144. };
  3145. // bind legacy bind/unbind to on/off
  3146. JQLite.prototype.bind = JQLite.prototype.on;
  3147. JQLite.prototype.unbind = JQLite.prototype.off;
  3148. });
  3149. // Provider for private $$jqLite service
  3150. function $$jqLiteProvider() {
  3151. this.$get = function $$jqLite() {
  3152. return extend(JQLite, {
  3153. hasClass: function(node, classes) {
  3154. if (node.attr) node = node[0];
  3155. return jqLiteHasClass(node, classes);
  3156. },
  3157. addClass: function(node, classes) {
  3158. if (node.attr) node = node[0];
  3159. return jqLiteAddClass(node, classes);
  3160. },
  3161. removeClass: function(node, classes) {
  3162. if (node.attr) node = node[0];
  3163. return jqLiteRemoveClass(node, classes);
  3164. }
  3165. });
  3166. };
  3167. }
  3168. /**
  3169. * Computes a hash of an 'obj'.
  3170. * Hash of a:
  3171. * string is string
  3172. * number is number as string
  3173. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  3174. * that is also assigned to the $$hashKey property of the object.
  3175. *
  3176. * @param obj
  3177. * @returns {string} hash string such that the same input will have the same hash string.
  3178. * The resulting string key is in 'type:hashKey' format.
  3179. */
  3180. function hashKey(obj, nextUidFn) {
  3181. var key = obj && obj.$$hashKey;
  3182. if (key) {
  3183. if (typeof key === 'function') {
  3184. key = obj.$$hashKey();
  3185. }
  3186. return key;
  3187. }
  3188. var objType = typeof obj;
  3189. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  3190. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  3191. } else {
  3192. key = objType + ':' + obj;
  3193. }
  3194. return key;
  3195. }
  3196. /**
  3197. * HashMap which can use objects as keys
  3198. */
  3199. function HashMap(array, isolatedUid) {
  3200. if (isolatedUid) {
  3201. var uid = 0;
  3202. this.nextUid = function() {
  3203. return ++uid;
  3204. };
  3205. }
  3206. forEach(array, this.put, this);
  3207. }
  3208. HashMap.prototype = {
  3209. /**
  3210. * Store key value pair
  3211. * @param key key to store can be any type
  3212. * @param value value to store can be any type
  3213. */
  3214. put: function(key, value) {
  3215. this[hashKey(key, this.nextUid)] = value;
  3216. },
  3217. /**
  3218. * @param key
  3219. * @returns {Object} the value for the key
  3220. */
  3221. get: function(key) {
  3222. return this[hashKey(key, this.nextUid)];
  3223. },
  3224. /**
  3225. * Remove the key/value pair
  3226. * @param key
  3227. */
  3228. remove: function(key) {
  3229. var value = this[key = hashKey(key, this.nextUid)];
  3230. delete this[key];
  3231. return value;
  3232. }
  3233. };
  3234. var $$HashMapProvider = [function() {
  3235. this.$get = [function() {
  3236. return HashMap;
  3237. }];
  3238. }];
  3239. /**
  3240. * @ngdoc function
  3241. * @module ng
  3242. * @name angular.injector
  3243. * @kind function
  3244. *
  3245. * @description
  3246. * Creates an injector object that can be used for retrieving services as well as for
  3247. * dependency injection (see {@link guide/di dependency injection}).
  3248. *
  3249. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3250. * {@link angular.module}. The `ng` module must be explicitly added.
  3251. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3252. * disallows argument name annotation inference.
  3253. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3254. *
  3255. * @example
  3256. * Typical usage
  3257. * ```js
  3258. * // create an injector
  3259. * var $injector = angular.injector(['ng']);
  3260. *
  3261. * // use the injector to kick off your application
  3262. * // use the type inference to auto inject arguments, or use implicit injection
  3263. * $injector.invoke(function($rootScope, $compile, $document) {
  3264. * $compile($document)($rootScope);
  3265. * $rootScope.$digest();
  3266. * });
  3267. * ```
  3268. *
  3269. * Sometimes you want to get access to the injector of a currently running Angular app
  3270. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  3271. * application has been bootstrapped. You can do this using the extra `injector()` added
  3272. * to JQuery/jqLite elements. See {@link angular.element}.
  3273. *
  3274. * *This is fairly rare but could be the case if a third party library is injecting the
  3275. * markup.*
  3276. *
  3277. * In the following example a new block of HTML containing a `ng-controller`
  3278. * directive is added to the end of the document body by JQuery. We then compile and link
  3279. * it into the current AngularJS scope.
  3280. *
  3281. * ```js
  3282. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3283. * $(document.body).append($div);
  3284. *
  3285. * angular.element(document).injector().invoke(function($compile) {
  3286. * var scope = angular.element($div).scope();
  3287. * $compile($div)(scope);
  3288. * });
  3289. * ```
  3290. */
  3291. /**
  3292. * @ngdoc module
  3293. * @name auto
  3294. * @description
  3295. *
  3296. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3297. */
  3298. var FN_ARGS = /^[^\(]*\(\s*([^\)]*)\)/m;
  3299. var FN_ARG_SPLIT = /,/;
  3300. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3301. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3302. var $injectorMinErr = minErr('$injector');
  3303. function anonFn(fn) {
  3304. // For anonymous functions, showing at the very least the function signature can help in
  3305. // debugging.
  3306. var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
  3307. args = fnText.match(FN_ARGS);
  3308. if (args) {
  3309. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3310. }
  3311. return 'fn';
  3312. }
  3313. function annotate(fn, strictDi, name) {
  3314. var $inject,
  3315. fnText,
  3316. argDecl,
  3317. last;
  3318. if (typeof fn === 'function') {
  3319. if (!($inject = fn.$inject)) {
  3320. $inject = [];
  3321. if (fn.length) {
  3322. if (strictDi) {
  3323. if (!isString(name) || !name) {
  3324. name = fn.name || anonFn(fn);
  3325. }
  3326. throw $injectorMinErr('strictdi',
  3327. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3328. }
  3329. fnText = fn.toString().replace(STRIP_COMMENTS, '');
  3330. argDecl = fnText.match(FN_ARGS);
  3331. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3332. arg.replace(FN_ARG, function(all, underscore, name) {
  3333. $inject.push(name);
  3334. });
  3335. });
  3336. }
  3337. fn.$inject = $inject;
  3338. }
  3339. } else if (isArray(fn)) {
  3340. last = fn.length - 1;
  3341. assertArgFn(fn[last], 'fn');
  3342. $inject = fn.slice(0, last);
  3343. } else {
  3344. assertArgFn(fn, 'fn', true);
  3345. }
  3346. return $inject;
  3347. }
  3348. ///////////////////////////////////////
  3349. /**
  3350. * @ngdoc service
  3351. * @name $injector
  3352. *
  3353. * @description
  3354. *
  3355. * `$injector` is used to retrieve object instances as defined by
  3356. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3357. * and load modules.
  3358. *
  3359. * The following always holds true:
  3360. *
  3361. * ```js
  3362. * var $injector = angular.injector();
  3363. * expect($injector.get('$injector')).toBe($injector);
  3364. * expect($injector.invoke(function($injector) {
  3365. * return $injector;
  3366. * })).toBe($injector);
  3367. * ```
  3368. *
  3369. * # Injection Function Annotation
  3370. *
  3371. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3372. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3373. *
  3374. * ```js
  3375. * // inferred (only works if code not minified/obfuscated)
  3376. * $injector.invoke(function(serviceA){});
  3377. *
  3378. * // annotated
  3379. * function explicit(serviceA) {};
  3380. * explicit.$inject = ['serviceA'];
  3381. * $injector.invoke(explicit);
  3382. *
  3383. * // inline
  3384. * $injector.invoke(['serviceA', function(serviceA){}]);
  3385. * ```
  3386. *
  3387. * ## Inference
  3388. *
  3389. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3390. * can then be parsed and the function arguments can be extracted. This method of discovering
  3391. * annotations is disallowed when the injector is in strict mode.
  3392. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3393. * argument names.
  3394. *
  3395. * ## `$inject` Annotation
  3396. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3397. *
  3398. * ## Inline
  3399. * As an array of injection names, where the last item in the array is the function to call.
  3400. */
  3401. /**
  3402. * @ngdoc method
  3403. * @name $injector#get
  3404. *
  3405. * @description
  3406. * Return an instance of the service.
  3407. *
  3408. * @param {string} name The name of the instance to retrieve.
  3409. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  3410. * @return {*} The instance.
  3411. */
  3412. /**
  3413. * @ngdoc method
  3414. * @name $injector#invoke
  3415. *
  3416. * @description
  3417. * Invoke the method and supply the method arguments from the `$injector`.
  3418. *
  3419. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  3420. * injected according to the {@link guide/di $inject Annotation} rules.
  3421. * @param {Object=} self The `this` for the invoked method.
  3422. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3423. * object first, before the `$injector` is consulted.
  3424. * @returns {*} the value returned by the invoked `fn` function.
  3425. */
  3426. /**
  3427. * @ngdoc method
  3428. * @name $injector#has
  3429. *
  3430. * @description
  3431. * Allows the user to query if the particular service exists.
  3432. *
  3433. * @param {string} name Name of the service to query.
  3434. * @returns {boolean} `true` if injector has given service.
  3435. */
  3436. /**
  3437. * @ngdoc method
  3438. * @name $injector#instantiate
  3439. * @description
  3440. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3441. * operator, and supplies all of the arguments to the constructor function as specified by the
  3442. * constructor annotation.
  3443. *
  3444. * @param {Function} Type Annotated constructor function.
  3445. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3446. * object first, before the `$injector` is consulted.
  3447. * @returns {Object} new instance of `Type`.
  3448. */
  3449. /**
  3450. * @ngdoc method
  3451. * @name $injector#annotate
  3452. *
  3453. * @description
  3454. * Returns an array of service names which the function is requesting for injection. This API is
  3455. * used by the injector to determine which services need to be injected into the function when the
  3456. * function is invoked. There are three ways in which the function can be annotated with the needed
  3457. * dependencies.
  3458. *
  3459. * # Argument names
  3460. *
  3461. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3462. * by converting the function into a string using `toString()` method and extracting the argument
  3463. * names.
  3464. * ```js
  3465. * // Given
  3466. * function MyController($scope, $route) {
  3467. * // ...
  3468. * }
  3469. *
  3470. * // Then
  3471. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3472. * ```
  3473. *
  3474. * You can disallow this method by using strict injection mode.
  3475. *
  3476. * This method does not work with code minification / obfuscation. For this reason the following
  3477. * annotation strategies are supported.
  3478. *
  3479. * # The `$inject` property
  3480. *
  3481. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3482. * represent names of services to be injected into the function.
  3483. * ```js
  3484. * // Given
  3485. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3486. * // ...
  3487. * }
  3488. * // Define function dependencies
  3489. * MyController['$inject'] = ['$scope', '$route'];
  3490. *
  3491. * // Then
  3492. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3493. * ```
  3494. *
  3495. * # The array notation
  3496. *
  3497. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3498. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3499. * a way that survives minification is a better choice:
  3500. *
  3501. * ```js
  3502. * // We wish to write this (not minification / obfuscation safe)
  3503. * injector.invoke(function($compile, $rootScope) {
  3504. * // ...
  3505. * });
  3506. *
  3507. * // We are forced to write break inlining
  3508. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3509. * // ...
  3510. * };
  3511. * tmpFn.$inject = ['$compile', '$rootScope'];
  3512. * injector.invoke(tmpFn);
  3513. *
  3514. * // To better support inline function the inline annotation is supported
  3515. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3516. * // ...
  3517. * }]);
  3518. *
  3519. * // Therefore
  3520. * expect(injector.annotate(
  3521. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3522. * ).toEqual(['$compile', '$rootScope']);
  3523. * ```
  3524. *
  3525. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3526. * be retrieved as described above.
  3527. *
  3528. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3529. *
  3530. * @returns {Array.<string>} The names of the services which the function requires.
  3531. */
  3532. /**
  3533. * @ngdoc service
  3534. * @name $provide
  3535. *
  3536. * @description
  3537. *
  3538. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3539. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3540. * {@link angular.Module}.
  3541. *
  3542. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3543. * factories** are functions which, in turn, are created by a **service provider**.
  3544. * The **service providers** are constructor functions. When instantiated they must contain a
  3545. * property called `$get`, which holds the **service factory** function.
  3546. *
  3547. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3548. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3549. * function to get the instance of the **service**.
  3550. *
  3551. * Often services have no configuration options and there is no need to add methods to the service
  3552. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3553. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3554. * services without specifying a provider.
  3555. *
  3556. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  3557. * {@link auto.$injector $injector}
  3558. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  3559. * providers and services.
  3560. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  3561. * services, not providers.
  3562. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  3563. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3564. * given factory function.
  3565. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  3566. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3567. * a new object using the given constructor function.
  3568. *
  3569. * See the individual methods for more information and examples.
  3570. */
  3571. /**
  3572. * @ngdoc method
  3573. * @name $provide#provider
  3574. * @description
  3575. *
  3576. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3577. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3578. * service.
  3579. *
  3580. * Service provider names start with the name of the service they provide followed by `Provider`.
  3581. * For example, the {@link ng.$log $log} service has a provider called
  3582. * {@link ng.$logProvider $logProvider}.
  3583. *
  3584. * Service provider objects can have additional methods which allow configuration of the provider
  3585. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3586. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3587. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3588. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3589. * console or not.
  3590. *
  3591. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3592. 'Provider'` key.
  3593. * @param {(Object|function())} provider If the provider is:
  3594. *
  3595. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3596. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3597. * - `Constructor`: a new instance of the provider will be created using
  3598. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3599. *
  3600. * @returns {Object} registered provider instance
  3601. * @example
  3602. *
  3603. * The following example shows how to create a simple event tracking service and register it using
  3604. * {@link auto.$provide#provider $provide.provider()}.
  3605. *
  3606. * ```js
  3607. * // Define the eventTracker provider
  3608. * function EventTrackerProvider() {
  3609. * var trackingUrl = '/track';
  3610. *
  3611. * // A provider method for configuring where the tracked events should been saved
  3612. * this.setTrackingUrl = function(url) {
  3613. * trackingUrl = url;
  3614. * };
  3615. *
  3616. * // The service factory function
  3617. * this.$get = ['$http', function($http) {
  3618. * var trackedEvents = {};
  3619. * return {
  3620. * // Call this to track an event
  3621. * event: function(event) {
  3622. * var count = trackedEvents[event] || 0;
  3623. * count += 1;
  3624. * trackedEvents[event] = count;
  3625. * return count;
  3626. * },
  3627. * // Call this to save the tracked events to the trackingUrl
  3628. * save: function() {
  3629. * $http.post(trackingUrl, trackedEvents);
  3630. * }
  3631. * };
  3632. * }];
  3633. * }
  3634. *
  3635. * describe('eventTracker', function() {
  3636. * var postSpy;
  3637. *
  3638. * beforeEach(module(function($provide) {
  3639. * // Register the eventTracker provider
  3640. * $provide.provider('eventTracker', EventTrackerProvider);
  3641. * }));
  3642. *
  3643. * beforeEach(module(function(eventTrackerProvider) {
  3644. * // Configure eventTracker provider
  3645. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3646. * }));
  3647. *
  3648. * it('tracks events', inject(function(eventTracker) {
  3649. * expect(eventTracker.event('login')).toEqual(1);
  3650. * expect(eventTracker.event('login')).toEqual(2);
  3651. * }));
  3652. *
  3653. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3654. * postSpy = spyOn($http, 'post');
  3655. * eventTracker.event('login');
  3656. * eventTracker.save();
  3657. * expect(postSpy).toHaveBeenCalled();
  3658. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3659. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3660. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3661. * }));
  3662. * });
  3663. * ```
  3664. */
  3665. /**
  3666. * @ngdoc method
  3667. * @name $provide#factory
  3668. * @description
  3669. *
  3670. * Register a **service factory**, which will be called to return the service instance.
  3671. * This is short for registering a service where its provider consists of only a `$get` property,
  3672. * which is the given service factory function.
  3673. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3674. * configure your service in a provider.
  3675. *
  3676. * @param {string} name The name of the instance.
  3677. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  3678. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  3679. * @returns {Object} registered provider instance
  3680. *
  3681. * @example
  3682. * Here is an example of registering a service
  3683. * ```js
  3684. * $provide.factory('ping', ['$http', function($http) {
  3685. * return function ping() {
  3686. * return $http.send('/ping');
  3687. * };
  3688. * }]);
  3689. * ```
  3690. * You would then inject and use this service like this:
  3691. * ```js
  3692. * someModule.controller('Ctrl', ['ping', function(ping) {
  3693. * ping();
  3694. * }]);
  3695. * ```
  3696. */
  3697. /**
  3698. * @ngdoc method
  3699. * @name $provide#service
  3700. * @description
  3701. *
  3702. * Register a **service constructor**, which will be invoked with `new` to create the service
  3703. * instance.
  3704. * This is short for registering a service where its provider's `$get` property is the service
  3705. * constructor function that will be used to instantiate the service instance.
  3706. *
  3707. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3708. * as a type/class.
  3709. *
  3710. * @param {string} name The name of the instance.
  3711. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  3712. * that will be instantiated.
  3713. * @returns {Object} registered provider instance
  3714. *
  3715. * @example
  3716. * Here is an example of registering a service using
  3717. * {@link auto.$provide#service $provide.service(class)}.
  3718. * ```js
  3719. * var Ping = function($http) {
  3720. * this.$http = $http;
  3721. * };
  3722. *
  3723. * Ping.$inject = ['$http'];
  3724. *
  3725. * Ping.prototype.send = function() {
  3726. * return this.$http.get('/ping');
  3727. * };
  3728. * $provide.service('ping', Ping);
  3729. * ```
  3730. * You would then inject and use this service like this:
  3731. * ```js
  3732. * someModule.controller('Ctrl', ['ping', function(ping) {
  3733. * ping.send();
  3734. * }]);
  3735. * ```
  3736. */
  3737. /**
  3738. * @ngdoc method
  3739. * @name $provide#value
  3740. * @description
  3741. *
  3742. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3743. * number, an array, an object or a function. This is short for registering a service where its
  3744. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3745. * service**.
  3746. *
  3747. * Value services are similar to constant services, except that they cannot be injected into a
  3748. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3749. * an Angular
  3750. * {@link auto.$provide#decorator decorator}.
  3751. *
  3752. * @param {string} name The name of the instance.
  3753. * @param {*} value The value.
  3754. * @returns {Object} registered provider instance
  3755. *
  3756. * @example
  3757. * Here are some examples of creating value services.
  3758. * ```js
  3759. * $provide.value('ADMIN_USER', 'admin');
  3760. *
  3761. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3762. *
  3763. * $provide.value('halfOf', function(value) {
  3764. * return value / 2;
  3765. * });
  3766. * ```
  3767. */
  3768. /**
  3769. * @ngdoc method
  3770. * @name $provide#constant
  3771. * @description
  3772. *
  3773. * Register a **constant service**, such as a string, a number, an array, an object or a function,
  3774. * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
  3775. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3776. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3777. *
  3778. * @param {string} name The name of the constant.
  3779. * @param {*} value The constant value.
  3780. * @returns {Object} registered instance
  3781. *
  3782. * @example
  3783. * Here a some examples of creating constants:
  3784. * ```js
  3785. * $provide.constant('SHARD_HEIGHT', 306);
  3786. *
  3787. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3788. *
  3789. * $provide.constant('double', function(value) {
  3790. * return value * 2;
  3791. * });
  3792. * ```
  3793. */
  3794. /**
  3795. * @ngdoc method
  3796. * @name $provide#decorator
  3797. * @description
  3798. *
  3799. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  3800. * intercepts the creation of a service, allowing it to override or modify the behaviour of the
  3801. * service. The object returned by the decorator may be the original service, or a new service
  3802. * object which replaces or wraps and delegates to the original service.
  3803. *
  3804. * @param {string} name The name of the service to decorate.
  3805. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  3806. * instantiated and should return the decorated service instance. The function is called using
  3807. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3808. * Local injection arguments:
  3809. *
  3810. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3811. * decorated or delegated to.
  3812. *
  3813. * @example
  3814. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3815. * calls to {@link ng.$log#error $log.warn()}.
  3816. * ```js
  3817. * $provide.decorator('$log', ['$delegate', function($delegate) {
  3818. * $delegate.warn = $delegate.error;
  3819. * return $delegate;
  3820. * }]);
  3821. * ```
  3822. */
  3823. function createInjector(modulesToLoad, strictDi) {
  3824. strictDi = (strictDi === true);
  3825. var INSTANTIATING = {},
  3826. providerSuffix = 'Provider',
  3827. path = [],
  3828. loadedModules = new HashMap([], true),
  3829. providerCache = {
  3830. $provide: {
  3831. provider: supportObject(provider),
  3832. factory: supportObject(factory),
  3833. service: supportObject(service),
  3834. value: supportObject(value),
  3835. constant: supportObject(constant),
  3836. decorator: decorator
  3837. }
  3838. },
  3839. providerInjector = (providerCache.$injector =
  3840. createInternalInjector(providerCache, function(serviceName, caller) {
  3841. if (angular.isString(caller)) {
  3842. path.push(caller);
  3843. }
  3844. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  3845. })),
  3846. instanceCache = {},
  3847. instanceInjector = (instanceCache.$injector =
  3848. createInternalInjector(instanceCache, function(serviceName, caller) {
  3849. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  3850. return instanceInjector.invoke(provider.$get, provider, undefined, serviceName);
  3851. }));
  3852. forEach(loadModules(modulesToLoad), function(fn) { if (fn) instanceInjector.invoke(fn); });
  3853. return instanceInjector;
  3854. ////////////////////////////////////
  3855. // $provider
  3856. ////////////////////////////////////
  3857. function supportObject(delegate) {
  3858. return function(key, value) {
  3859. if (isObject(key)) {
  3860. forEach(key, reverseParams(delegate));
  3861. } else {
  3862. return delegate(key, value);
  3863. }
  3864. };
  3865. }
  3866. function provider(name, provider_) {
  3867. assertNotHasOwnProperty(name, 'service');
  3868. if (isFunction(provider_) || isArray(provider_)) {
  3869. provider_ = providerInjector.instantiate(provider_);
  3870. }
  3871. if (!provider_.$get) {
  3872. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  3873. }
  3874. return providerCache[name + providerSuffix] = provider_;
  3875. }
  3876. function enforceReturnValue(name, factory) {
  3877. return function enforcedReturnValue() {
  3878. var result = instanceInjector.invoke(factory, this);
  3879. if (isUndefined(result)) {
  3880. throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
  3881. }
  3882. return result;
  3883. };
  3884. }
  3885. function factory(name, factoryFn, enforce) {
  3886. return provider(name, {
  3887. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  3888. });
  3889. }
  3890. function service(name, constructor) {
  3891. return factory(name, ['$injector', function($injector) {
  3892. return $injector.instantiate(constructor);
  3893. }]);
  3894. }
  3895. function value(name, val) { return factory(name, valueFn(val), false); }
  3896. function constant(name, value) {
  3897. assertNotHasOwnProperty(name, 'constant');
  3898. providerCache[name] = value;
  3899. instanceCache[name] = value;
  3900. }
  3901. function decorator(serviceName, decorFn) {
  3902. var origProvider = providerInjector.get(serviceName + providerSuffix),
  3903. orig$get = origProvider.$get;
  3904. origProvider.$get = function() {
  3905. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  3906. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  3907. };
  3908. }
  3909. ////////////////////////////////////
  3910. // Module Loading
  3911. ////////////////////////////////////
  3912. function loadModules(modulesToLoad) {
  3913. assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
  3914. var runBlocks = [], moduleFn;
  3915. forEach(modulesToLoad, function(module) {
  3916. if (loadedModules.get(module)) return;
  3917. loadedModules.put(module, true);
  3918. function runInvokeQueue(queue) {
  3919. var i, ii;
  3920. for (i = 0, ii = queue.length; i < ii; i++) {
  3921. var invokeArgs = queue[i],
  3922. provider = providerInjector.get(invokeArgs[0]);
  3923. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  3924. }
  3925. }
  3926. try {
  3927. if (isString(module)) {
  3928. moduleFn = angularModule(module);
  3929. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  3930. runInvokeQueue(moduleFn._invokeQueue);
  3931. runInvokeQueue(moduleFn._configBlocks);
  3932. } else if (isFunction(module)) {
  3933. runBlocks.push(providerInjector.invoke(module));
  3934. } else if (isArray(module)) {
  3935. runBlocks.push(providerInjector.invoke(module));
  3936. } else {
  3937. assertArgFn(module, 'module');
  3938. }
  3939. } catch (e) {
  3940. if (isArray(module)) {
  3941. module = module[module.length - 1];
  3942. }
  3943. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  3944. // Safari & FF's stack traces don't contain error.message content
  3945. // unlike those of Chrome and IE
  3946. // So if stack doesn't contain message, we create a new string that contains both.
  3947. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  3948. /* jshint -W022 */
  3949. e = e.message + '\n' + e.stack;
  3950. }
  3951. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  3952. module, e.stack || e.message || e);
  3953. }
  3954. });
  3955. return runBlocks;
  3956. }
  3957. ////////////////////////////////////
  3958. // internal Injector
  3959. ////////////////////////////////////
  3960. function createInternalInjector(cache, factory) {
  3961. function getService(serviceName, caller) {
  3962. if (cache.hasOwnProperty(serviceName)) {
  3963. if (cache[serviceName] === INSTANTIATING) {
  3964. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  3965. serviceName + ' <- ' + path.join(' <- '));
  3966. }
  3967. return cache[serviceName];
  3968. } else {
  3969. try {
  3970. path.unshift(serviceName);
  3971. cache[serviceName] = INSTANTIATING;
  3972. return cache[serviceName] = factory(serviceName, caller);
  3973. } catch (err) {
  3974. if (cache[serviceName] === INSTANTIATING) {
  3975. delete cache[serviceName];
  3976. }
  3977. throw err;
  3978. } finally {
  3979. path.shift();
  3980. }
  3981. }
  3982. }
  3983. function invoke(fn, self, locals, serviceName) {
  3984. if (typeof locals === 'string') {
  3985. serviceName = locals;
  3986. locals = null;
  3987. }
  3988. var args = [],
  3989. $inject = createInjector.$$annotate(fn, strictDi, serviceName),
  3990. length, i,
  3991. key;
  3992. for (i = 0, length = $inject.length; i < length; i++) {
  3993. key = $inject[i];
  3994. if (typeof key !== 'string') {
  3995. throw $injectorMinErr('itkn',
  3996. 'Incorrect injection token! Expected service name as string, got {0}', key);
  3997. }
  3998. args.push(
  3999. locals && locals.hasOwnProperty(key)
  4000. ? locals[key]
  4001. : getService(key, serviceName)
  4002. );
  4003. }
  4004. if (isArray(fn)) {
  4005. fn = fn[length];
  4006. }
  4007. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  4008. // #5388
  4009. return fn.apply(self, args);
  4010. }
  4011. function instantiate(Type, locals, serviceName) {
  4012. // Check if Type is annotated and use just the given function at n-1 as parameter
  4013. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  4014. // Object creation: http://jsperf.com/create-constructor/2
  4015. var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);
  4016. var returnedValue = invoke(Type, instance, locals, serviceName);
  4017. return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
  4018. }
  4019. return {
  4020. invoke: invoke,
  4021. instantiate: instantiate,
  4022. get: getService,
  4023. annotate: createInjector.$$annotate,
  4024. has: function(name) {
  4025. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  4026. }
  4027. };
  4028. }
  4029. }
  4030. createInjector.$$annotate = annotate;
  4031. /**
  4032. * @ngdoc provider
  4033. * @name $anchorScrollProvider
  4034. *
  4035. * @description
  4036. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  4037. * {@link ng.$location#hash $location.hash()} changes.
  4038. */
  4039. function $AnchorScrollProvider() {
  4040. var autoScrollingEnabled = true;
  4041. /**
  4042. * @ngdoc method
  4043. * @name $anchorScrollProvider#disableAutoScrolling
  4044. *
  4045. * @description
  4046. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  4047. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  4048. * Use this method to disable automatic scrolling.
  4049. *
  4050. * If automatic scrolling is disabled, one must explicitly call
  4051. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  4052. * current hash.
  4053. */
  4054. this.disableAutoScrolling = function() {
  4055. autoScrollingEnabled = false;
  4056. };
  4057. /**
  4058. * @ngdoc service
  4059. * @name $anchorScroll
  4060. * @kind function
  4061. * @requires $window
  4062. * @requires $location
  4063. * @requires $rootScope
  4064. *
  4065. * @description
  4066. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  4067. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  4068. * in the
  4069. * [HTML5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).
  4070. *
  4071. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  4072. * match any anchor whenever it changes. This can be disabled by calling
  4073. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  4074. *
  4075. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  4076. * vertical scroll-offset (either fixed or dynamic).
  4077. *
  4078. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  4079. * {@link ng.$location#hash $location.hash()} will be used.
  4080. *
  4081. * @property {(number|function|jqLite)} yOffset
  4082. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  4083. * positioned elements at the top of the page, such as navbars, headers etc.
  4084. *
  4085. * `yOffset` can be specified in various ways:
  4086. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  4087. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  4088. * a number representing the offset (in pixels).<br /><br />
  4089. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  4090. * the top of the page to the element's bottom will be used as offset.<br />
  4091. * **Note**: The element will be taken into account only as long as its `position` is set to
  4092. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  4093. * their height and/or positioning according to the viewport's size.
  4094. *
  4095. * <br />
  4096. * <div class="alert alert-warning">
  4097. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  4098. * not some child element.
  4099. * </div>
  4100. *
  4101. * @example
  4102. <example module="anchorScrollExample">
  4103. <file name="index.html">
  4104. <div id="scrollArea" ng-controller="ScrollController">
  4105. <a ng-click="gotoBottom()">Go to bottom</a>
  4106. <a id="bottom"></a> You're at the bottom!
  4107. </div>
  4108. </file>
  4109. <file name="script.js">
  4110. angular.module('anchorScrollExample', [])
  4111. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  4112. function ($scope, $location, $anchorScroll) {
  4113. $scope.gotoBottom = function() {
  4114. // set the location.hash to the id of
  4115. // the element you wish to scroll to.
  4116. $location.hash('bottom');
  4117. // call $anchorScroll()
  4118. $anchorScroll();
  4119. };
  4120. }]);
  4121. </file>
  4122. <file name="style.css">
  4123. #scrollArea {
  4124. height: 280px;
  4125. overflow: auto;
  4126. }
  4127. #bottom {
  4128. display: block;
  4129. margin-top: 2000px;
  4130. }
  4131. </file>
  4132. </example>
  4133. *
  4134. * <hr />
  4135. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  4136. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  4137. *
  4138. * @example
  4139. <example module="anchorScrollOffsetExample">
  4140. <file name="index.html">
  4141. <div class="fixed-header" ng-controller="headerCtrl">
  4142. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  4143. Go to anchor {{x}}
  4144. </a>
  4145. </div>
  4146. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  4147. Anchor {{x}} of 5
  4148. </div>
  4149. </file>
  4150. <file name="script.js">
  4151. angular.module('anchorScrollOffsetExample', [])
  4152. .run(['$anchorScroll', function($anchorScroll) {
  4153. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  4154. }])
  4155. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  4156. function ($anchorScroll, $location, $scope) {
  4157. $scope.gotoAnchor = function(x) {
  4158. var newHash = 'anchor' + x;
  4159. if ($location.hash() !== newHash) {
  4160. // set the $location.hash to `newHash` and
  4161. // $anchorScroll will automatically scroll to it
  4162. $location.hash('anchor' + x);
  4163. } else {
  4164. // call $anchorScroll() explicitly,
  4165. // since $location.hash hasn't changed
  4166. $anchorScroll();
  4167. }
  4168. };
  4169. }
  4170. ]);
  4171. </file>
  4172. <file name="style.css">
  4173. body {
  4174. padding-top: 50px;
  4175. }
  4176. .anchor {
  4177. border: 2px dashed DarkOrchid;
  4178. padding: 10px 10px 200px 10px;
  4179. }
  4180. .fixed-header {
  4181. background-color: rgba(0, 0, 0, 0.2);
  4182. height: 50px;
  4183. position: fixed;
  4184. top: 0; left: 0; right: 0;
  4185. }
  4186. .fixed-header > a {
  4187. display: inline-block;
  4188. margin: 5px 15px;
  4189. }
  4190. </file>
  4191. </example>
  4192. */
  4193. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  4194. var document = $window.document;
  4195. // Helper function to get first anchor from a NodeList
  4196. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  4197. // and working in all supported browsers.)
  4198. function getFirstAnchor(list) {
  4199. var result = null;
  4200. Array.prototype.some.call(list, function(element) {
  4201. if (nodeName_(element) === 'a') {
  4202. result = element;
  4203. return true;
  4204. }
  4205. });
  4206. return result;
  4207. }
  4208. function getYOffset() {
  4209. var offset = scroll.yOffset;
  4210. if (isFunction(offset)) {
  4211. offset = offset();
  4212. } else if (isElement(offset)) {
  4213. var elem = offset[0];
  4214. var style = $window.getComputedStyle(elem);
  4215. if (style.position !== 'fixed') {
  4216. offset = 0;
  4217. } else {
  4218. offset = elem.getBoundingClientRect().bottom;
  4219. }
  4220. } else if (!isNumber(offset)) {
  4221. offset = 0;
  4222. }
  4223. return offset;
  4224. }
  4225. function scrollTo(elem) {
  4226. if (elem) {
  4227. elem.scrollIntoView();
  4228. var offset = getYOffset();
  4229. if (offset) {
  4230. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  4231. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  4232. // top of the viewport.
  4233. //
  4234. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  4235. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  4236. // way down the page.
  4237. //
  4238. // This is often the case for elements near the bottom of the page.
  4239. //
  4240. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  4241. // the top of the element and the offset, which is enough to align the top of `elem` at the
  4242. // desired position.
  4243. var elemTop = elem.getBoundingClientRect().top;
  4244. $window.scrollBy(0, elemTop - offset);
  4245. }
  4246. } else {
  4247. $window.scrollTo(0, 0);
  4248. }
  4249. }
  4250. function scroll(hash) {
  4251. hash = isString(hash) ? hash : $location.hash();
  4252. var elm;
  4253. // empty hash, scroll to the top of the page
  4254. if (!hash) scrollTo(null);
  4255. // element with given id
  4256. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4257. // first anchor with given name :-D
  4258. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4259. // no element and hash == 'top', scroll to the top of the page
  4260. else if (hash === 'top') scrollTo(null);
  4261. }
  4262. // does not scroll when user clicks on anchor link that is currently on
  4263. // (no url change, no $location.hash() change), browser native does scroll
  4264. if (autoScrollingEnabled) {
  4265. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4266. function autoScrollWatchAction(newVal, oldVal) {
  4267. // skip the initial scroll if $location.hash is empty
  4268. if (newVal === oldVal && newVal === '') return;
  4269. jqLiteDocumentLoaded(function() {
  4270. $rootScope.$evalAsync(scroll);
  4271. });
  4272. });
  4273. }
  4274. return scroll;
  4275. }];
  4276. }
  4277. var $animateMinErr = minErr('$animate');
  4278. var ELEMENT_NODE = 1;
  4279. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  4280. function mergeClasses(a,b) {
  4281. if (!a && !b) return '';
  4282. if (!a) return b;
  4283. if (!b) return a;
  4284. if (isArray(a)) a = a.join(' ');
  4285. if (isArray(b)) b = b.join(' ');
  4286. return a + ' ' + b;
  4287. }
  4288. function extractElementNode(element) {
  4289. for (var i = 0; i < element.length; i++) {
  4290. var elm = element[i];
  4291. if (elm.nodeType === ELEMENT_NODE) {
  4292. return elm;
  4293. }
  4294. }
  4295. }
  4296. function splitClasses(classes) {
  4297. if (isString(classes)) {
  4298. classes = classes.split(' ');
  4299. }
  4300. // Use createMap() to prevent class assumptions involving property names in
  4301. // Object.prototype
  4302. var obj = createMap();
  4303. forEach(classes, function(klass) {
  4304. // sometimes the split leaves empty string values
  4305. // incase extra spaces were applied to the options
  4306. if (klass.length) {
  4307. obj[klass] = true;
  4308. }
  4309. });
  4310. return obj;
  4311. }
  4312. // if any other type of options value besides an Object value is
  4313. // passed into the $animate.method() animation then this helper code
  4314. // will be run which will ignore it. While this patch is not the
  4315. // greatest solution to this, a lot of existing plugins depend on
  4316. // $animate to either call the callback (< 1.2) or return a promise
  4317. // that can be changed. This helper function ensures that the options
  4318. // are wiped clean incase a callback function is provided.
  4319. function prepareAnimateOptions(options) {
  4320. return isObject(options)
  4321. ? options
  4322. : {};
  4323. }
  4324. var $$CoreAnimateRunnerProvider = function() {
  4325. this.$get = ['$q', '$$rAF', function($q, $$rAF) {
  4326. function AnimateRunner() {}
  4327. AnimateRunner.all = noop;
  4328. AnimateRunner.chain = noop;
  4329. AnimateRunner.prototype = {
  4330. end: noop,
  4331. cancel: noop,
  4332. resume: noop,
  4333. pause: noop,
  4334. complete: noop,
  4335. then: function(pass, fail) {
  4336. return $q(function(resolve) {
  4337. $$rAF(function() {
  4338. resolve();
  4339. });
  4340. }).then(pass, fail);
  4341. }
  4342. };
  4343. return AnimateRunner;
  4344. }];
  4345. };
  4346. // this is prefixed with Core since it conflicts with
  4347. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  4348. var $$CoreAnimateQueueProvider = function() {
  4349. var postDigestQueue = new HashMap();
  4350. var postDigestElements = [];
  4351. this.$get = ['$$AnimateRunner', '$rootScope',
  4352. function($$AnimateRunner, $rootScope) {
  4353. return {
  4354. enabled: noop,
  4355. on: noop,
  4356. off: noop,
  4357. pin: noop,
  4358. push: function(element, event, options, domOperation) {
  4359. domOperation && domOperation();
  4360. options = options || {};
  4361. options.from && element.css(options.from);
  4362. options.to && element.css(options.to);
  4363. if (options.addClass || options.removeClass) {
  4364. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  4365. }
  4366. return new $$AnimateRunner(); // jshint ignore:line
  4367. }
  4368. };
  4369. function addRemoveClassesPostDigest(element, add, remove) {
  4370. var classVal, data = postDigestQueue.get(element);
  4371. if (!data) {
  4372. postDigestQueue.put(element, data = {});
  4373. postDigestElements.push(element);
  4374. }
  4375. var updateData = function(classes, value) {
  4376. var changed = false;
  4377. if (classes) {
  4378. classes = isString(classes) ? classes.split(' ') :
  4379. isArray(classes) ? classes : [];
  4380. forEach(classes, function(className) {
  4381. if (className) {
  4382. changed = true;
  4383. data[className] = value;
  4384. }
  4385. });
  4386. }
  4387. return changed;
  4388. };
  4389. var classesAdded = updateData(add, true);
  4390. var classesRemoved = updateData(remove, false);
  4391. if ((!classesAdded && !classesRemoved) || postDigestElements.length > 1) return;
  4392. $rootScope.$$postDigest(function() {
  4393. forEach(postDigestElements, function(element) {
  4394. var data = postDigestQueue.get(element);
  4395. if (data) {
  4396. var existing = splitClasses(element.attr('class'));
  4397. var toAdd = '';
  4398. var toRemove = '';
  4399. forEach(data, function(status, className) {
  4400. var hasClass = !!existing[className];
  4401. if (status !== hasClass) {
  4402. if (status) {
  4403. toAdd += (toAdd.length ? ' ' : '') + className;
  4404. } else {
  4405. toRemove += (toRemove.length ? ' ' : '') + className;
  4406. }
  4407. }
  4408. });
  4409. forEach(element, function(elm) {
  4410. toAdd && jqLiteAddClass(elm, toAdd);
  4411. toRemove && jqLiteRemoveClass(elm, toRemove);
  4412. });
  4413. postDigestQueue.remove(element);
  4414. }
  4415. });
  4416. postDigestElements.length = 0;
  4417. });
  4418. }
  4419. }];
  4420. };
  4421. /**
  4422. * @ngdoc provider
  4423. * @name $animateProvider
  4424. *
  4425. * @description
  4426. * Default implementation of $animate that doesn't perform any animations, instead just
  4427. * synchronously performs DOM updates and resolves the returned runner promise.
  4428. *
  4429. * In order to enable animations the `ngAnimate` module has to be loaded.
  4430. *
  4431. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  4432. */
  4433. var $AnimateProvider = ['$provide', function($provide) {
  4434. var provider = this;
  4435. this.$$registeredAnimations = Object.create(null);
  4436. /**
  4437. * @ngdoc method
  4438. * @name $animateProvider#register
  4439. *
  4440. * @description
  4441. * Registers a new injectable animation factory function. The factory function produces the
  4442. * animation object which contains callback functions for each event that is expected to be
  4443. * animated.
  4444. *
  4445. * * `eventFn`: `function(element, ... , doneFunction, options)`
  4446. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  4447. * on the type of animation additional arguments will be injected into the animation function. The
  4448. * list below explains the function signatures for the different animation methods:
  4449. *
  4450. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  4451. * - addClass: function(element, addedClasses, doneFunction, options)
  4452. * - removeClass: function(element, removedClasses, doneFunction, options)
  4453. * - enter, leave, move: function(element, doneFunction, options)
  4454. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  4455. *
  4456. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  4457. *
  4458. * ```js
  4459. * return {
  4460. * //enter, leave, move signature
  4461. * eventFn : function(element, done, options) {
  4462. * //code to run the animation
  4463. * //once complete, then run done()
  4464. * return function endFunction(wasCancelled) {
  4465. * //code to cancel the animation
  4466. * }
  4467. * }
  4468. * }
  4469. * ```
  4470. *
  4471. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  4472. * @param {Function} factory The factory function that will be executed to return the animation
  4473. * object.
  4474. */
  4475. this.register = function(name, factory) {
  4476. if (name && name.charAt(0) !== '.') {
  4477. throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name);
  4478. }
  4479. var key = name + '-animation';
  4480. provider.$$registeredAnimations[name.substr(1)] = key;
  4481. $provide.factory(key, factory);
  4482. };
  4483. /**
  4484. * @ngdoc method
  4485. * @name $animateProvider#classNameFilter
  4486. *
  4487. * @description
  4488. * Sets and/or returns the CSS class regular expression that is checked when performing
  4489. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4490. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  4491. * When setting the `classNameFilter` value, animations will only be performed on elements
  4492. * that successfully match the filter expression. This in turn can boost performance
  4493. * for low-powered devices as well as applications containing a lot of structural operations.
  4494. * @param {RegExp=} expression The className expression which will be checked against all animations
  4495. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4496. */
  4497. this.classNameFilter = function(expression) {
  4498. if (arguments.length === 1) {
  4499. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  4500. if (this.$$classNameFilter) {
  4501. var reservedRegex = new RegExp("(\\s+|\\/)" + NG_ANIMATE_CLASSNAME + "(\\s+|\\/)");
  4502. if (reservedRegex.test(this.$$classNameFilter.toString())) {
  4503. throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  4504. }
  4505. }
  4506. }
  4507. return this.$$classNameFilter;
  4508. };
  4509. this.$get = ['$$animateQueue', function($$animateQueue) {
  4510. function domInsert(element, parentElement, afterElement) {
  4511. // if for some reason the previous element was removed
  4512. // from the dom sometime before this code runs then let's
  4513. // just stick to using the parent element as the anchor
  4514. if (afterElement) {
  4515. var afterNode = extractElementNode(afterElement);
  4516. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  4517. afterElement = null;
  4518. }
  4519. }
  4520. afterElement ? afterElement.after(element) : parentElement.prepend(element);
  4521. }
  4522. /**
  4523. * @ngdoc service
  4524. * @name $animate
  4525. * @description The $animate service exposes a series of DOM utility methods that provide support
  4526. * for animation hooks. The default behavior is the application of DOM operations, however,
  4527. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  4528. * to ensure that animation runs with the triggered DOM operation.
  4529. *
  4530. * By default $animate doesn't trigger an animations. This is because the `ngAnimate` module isn't
  4531. * included and only when it is active then the animation hooks that `$animate` triggers will be
  4532. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  4533. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  4534. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  4535. *
  4536. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  4537. *
  4538. * To learn more about enabling animation support, click here to visit the
  4539. * {@link ngAnimate ngAnimate module page}.
  4540. */
  4541. return {
  4542. // we don't call it directly since non-existant arguments may
  4543. // be interpreted as null within the sub enabled function
  4544. /**
  4545. *
  4546. * @ngdoc method
  4547. * @name $animate#on
  4548. * @kind function
  4549. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  4550. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  4551. * is fired with the following params:
  4552. *
  4553. * ```js
  4554. * $animate.on('enter', container,
  4555. * function callback(element, phase) {
  4556. * // cool we detected an enter animation within the container
  4557. * }
  4558. * );
  4559. * ```
  4560. *
  4561. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  4562. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  4563. * as well as among its children
  4564. * @param {Function} callback the callback function that will be fired when the listener is triggered
  4565. *
  4566. * The arguments present in the callback function are:
  4567. * * `element` - The captured DOM element that the animation was fired on.
  4568. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  4569. */
  4570. on: $$animateQueue.on,
  4571. /**
  4572. *
  4573. * @ngdoc method
  4574. * @name $animate#off
  4575. * @kind function
  4576. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  4577. * can be used in three different ways depending on the arguments:
  4578. *
  4579. * ```js
  4580. * // remove all the animation event listeners listening for `enter`
  4581. * $animate.off('enter');
  4582. *
  4583. * // remove all the animation event listeners listening for `enter` on the given element and its children
  4584. * $animate.off('enter', container);
  4585. *
  4586. * // remove the event listener function provided by `listenerFn` that is set
  4587. * // to listen for `enter` on the given `element` as well as its children
  4588. * $animate.off('enter', container, callback);
  4589. * ```
  4590. *
  4591. * @param {string} event the animation event (e.g. enter, leave, move, addClass, removeClass, etc...)
  4592. * @param {DOMElement=} container the container element the event listener was placed on
  4593. * @param {Function=} callback the callback function that was registered as the listener
  4594. */
  4595. off: $$animateQueue.off,
  4596. /**
  4597. * @ngdoc method
  4598. * @name $animate#pin
  4599. * @kind function
  4600. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  4601. * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
  4602. * element despite being outside the realm of the application or within another application. Say for example if the application
  4603. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  4604. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  4605. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  4606. *
  4607. * Note that this feature is only active when the `ngAnimate` module is used.
  4608. *
  4609. * @param {DOMElement} element the external element that will be pinned
  4610. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  4611. */
  4612. pin: $$animateQueue.pin,
  4613. /**
  4614. *
  4615. * @ngdoc method
  4616. * @name $animate#enabled
  4617. * @kind function
  4618. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  4619. * function can be called in four ways:
  4620. *
  4621. * ```js
  4622. * // returns true or false
  4623. * $animate.enabled();
  4624. *
  4625. * // changes the enabled state for all animations
  4626. * $animate.enabled(false);
  4627. * $animate.enabled(true);
  4628. *
  4629. * // returns true or false if animations are enabled for an element
  4630. * $animate.enabled(element);
  4631. *
  4632. * // changes the enabled state for an element and its children
  4633. * $animate.enabled(element, true);
  4634. * $animate.enabled(element, false);
  4635. * ```
  4636. *
  4637. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  4638. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  4639. *
  4640. * @return {boolean} whether or not animations are enabled
  4641. */
  4642. enabled: $$animateQueue.enabled,
  4643. /**
  4644. * @ngdoc method
  4645. * @name $animate#cancel
  4646. * @kind function
  4647. * @description Cancels the provided animation.
  4648. *
  4649. * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
  4650. */
  4651. cancel: function(runner) {
  4652. runner.end && runner.end();
  4653. },
  4654. /**
  4655. *
  4656. * @ngdoc method
  4657. * @name $animate#enter
  4658. * @kind function
  4659. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  4660. * as the first child within the `parent` element and then triggers an animation.
  4661. * A promise is returned that will be resolved during the next digest once the animation
  4662. * has completed.
  4663. *
  4664. * @param {DOMElement} element the element which will be inserted into the DOM
  4665. * @param {DOMElement} parent the parent element which will append the element as
  4666. * a child (so long as the after element is not present)
  4667. * @param {DOMElement=} after the sibling element after which the element will be appended
  4668. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4669. *
  4670. * @return {Promise} the animation callback promise
  4671. */
  4672. enter: function(element, parent, after, options) {
  4673. parent = parent && jqLite(parent);
  4674. after = after && jqLite(after);
  4675. parent = parent || after.parent();
  4676. domInsert(element, parent, after);
  4677. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  4678. },
  4679. /**
  4680. *
  4681. * @ngdoc method
  4682. * @name $animate#move
  4683. * @kind function
  4684. * @description Inserts (moves) the element into its new position in the DOM either after
  4685. * the `after` element (if provided) or as the first child within the `parent` element
  4686. * and then triggers an animation. A promise is returned that will be resolved
  4687. * during the next digest once the animation has completed.
  4688. *
  4689. * @param {DOMElement} element the element which will be moved into the new DOM position
  4690. * @param {DOMElement} parent the parent element which will append the element as
  4691. * a child (so long as the after element is not present)
  4692. * @param {DOMElement=} after the sibling element after which the element will be appended
  4693. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4694. *
  4695. * @return {Promise} the animation callback promise
  4696. */
  4697. move: function(element, parent, after, options) {
  4698. parent = parent && jqLite(parent);
  4699. after = after && jqLite(after);
  4700. parent = parent || after.parent();
  4701. domInsert(element, parent, after);
  4702. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  4703. },
  4704. /**
  4705. * @ngdoc method
  4706. * @name $animate#leave
  4707. * @kind function
  4708. * @description Triggers an animation and then removes the element from the DOM.
  4709. * When the function is called a promise is returned that will be resolved during the next
  4710. * digest once the animation has completed.
  4711. *
  4712. * @param {DOMElement} element the element which will be removed from the DOM
  4713. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4714. *
  4715. * @return {Promise} the animation callback promise
  4716. */
  4717. leave: function(element, options) {
  4718. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  4719. element.remove();
  4720. });
  4721. },
  4722. /**
  4723. * @ngdoc method
  4724. * @name $animate#addClass
  4725. * @kind function
  4726. *
  4727. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  4728. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  4729. * animation if element already contains the CSS class or if the class is removed at a later step.
  4730. * Note that class-based animations are treated differently compared to structural animations
  4731. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4732. * depending if CSS or JavaScript animations are used.
  4733. *
  4734. * @param {DOMElement} element the element which the CSS classes will be applied to
  4735. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  4736. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4737. *
  4738. * @return {Promise} the animation callback promise
  4739. */
  4740. addClass: function(element, className, options) {
  4741. options = prepareAnimateOptions(options);
  4742. options.addClass = mergeClasses(options.addclass, className);
  4743. return $$animateQueue.push(element, 'addClass', options);
  4744. },
  4745. /**
  4746. * @ngdoc method
  4747. * @name $animate#removeClass
  4748. * @kind function
  4749. *
  4750. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  4751. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  4752. * animation if element does not contain the CSS class or if the class is added at a later step.
  4753. * Note that class-based animations are treated differently compared to structural animations
  4754. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4755. * depending if CSS or JavaScript animations are used.
  4756. *
  4757. * @param {DOMElement} element the element which the CSS classes will be applied to
  4758. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  4759. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4760. *
  4761. * @return {Promise} the animation callback promise
  4762. */
  4763. removeClass: function(element, className, options) {
  4764. options = prepareAnimateOptions(options);
  4765. options.removeClass = mergeClasses(options.removeClass, className);
  4766. return $$animateQueue.push(element, 'removeClass', options);
  4767. },
  4768. /**
  4769. * @ngdoc method
  4770. * @name $animate#setClass
  4771. * @kind function
  4772. *
  4773. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  4774. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  4775. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  4776. * passed. Note that class-based animations are treated differently compared to structural animations
  4777. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4778. * depending if CSS or JavaScript animations are used.
  4779. *
  4780. * @param {DOMElement} element the element which the CSS classes will be applied to
  4781. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  4782. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  4783. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4784. *
  4785. * @return {Promise} the animation callback promise
  4786. */
  4787. setClass: function(element, add, remove, options) {
  4788. options = prepareAnimateOptions(options);
  4789. options.addClass = mergeClasses(options.addClass, add);
  4790. options.removeClass = mergeClasses(options.removeClass, remove);
  4791. return $$animateQueue.push(element, 'setClass', options);
  4792. },
  4793. /**
  4794. * @ngdoc method
  4795. * @name $animate#animate
  4796. * @kind function
  4797. *
  4798. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  4799. * If any detected CSS transition, keyframe or JavaScript matches the provided className value then the animation will take
  4800. * on the provided styles. For example, if a transition animation is set for the given className then the provided from and
  4801. * to styles will be applied alongside the given transition. If a JavaScript animation is detected then the provided styles
  4802. * will be given in as function paramters into the `animate` method (or as apart of the `options` parameter).
  4803. *
  4804. * @param {DOMElement} element the element which the CSS styles will be applied to
  4805. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  4806. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  4807. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  4808. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  4809. * (Note that if no animation is detected then this value will not be appplied to the element.)
  4810. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4811. *
  4812. * @return {Promise} the animation callback promise
  4813. */
  4814. animate: function(element, from, to, className, options) {
  4815. options = prepareAnimateOptions(options);
  4816. options.from = options.from ? extend(options.from, from) : from;
  4817. options.to = options.to ? extend(options.to, to) : to;
  4818. className = className || 'ng-inline-animate';
  4819. options.tempClasses = mergeClasses(options.tempClasses, className);
  4820. return $$animateQueue.push(element, 'animate', options);
  4821. }
  4822. };
  4823. }];
  4824. }];
  4825. /**
  4826. * @ngdoc service
  4827. * @name $animateCss
  4828. * @kind object
  4829. *
  4830. * @description
  4831. * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
  4832. * then the `$animateCss` service will actually perform animations.
  4833. *
  4834. * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
  4835. */
  4836. var $CoreAnimateCssProvider = function() {
  4837. this.$get = ['$$rAF', '$q', function($$rAF, $q) {
  4838. var RAFPromise = function() {};
  4839. RAFPromise.prototype = {
  4840. done: function(cancel) {
  4841. this.defer && this.defer[cancel === true ? 'reject' : 'resolve']();
  4842. },
  4843. end: function() {
  4844. this.done();
  4845. },
  4846. cancel: function() {
  4847. this.done(true);
  4848. },
  4849. getPromise: function() {
  4850. if (!this.defer) {
  4851. this.defer = $q.defer();
  4852. }
  4853. return this.defer.promise;
  4854. },
  4855. then: function(f1,f2) {
  4856. return this.getPromise().then(f1,f2);
  4857. },
  4858. 'catch': function(f1) {
  4859. return this.getPromise()['catch'](f1);
  4860. },
  4861. 'finally': function(f1) {
  4862. return this.getPromise()['finally'](f1);
  4863. }
  4864. };
  4865. return function(element, options) {
  4866. if (options.from) {
  4867. element.css(options.from);
  4868. options.from = null;
  4869. }
  4870. var closed, runner = new RAFPromise();
  4871. return {
  4872. start: run,
  4873. end: run
  4874. };
  4875. function run() {
  4876. $$rAF(function() {
  4877. close();
  4878. if (!closed) {
  4879. runner.done();
  4880. }
  4881. closed = true;
  4882. });
  4883. return runner;
  4884. }
  4885. function close() {
  4886. if (options.addClass) {
  4887. element.addClass(options.addClass);
  4888. options.addClass = null;
  4889. }
  4890. if (options.removeClass) {
  4891. element.removeClass(options.removeClass);
  4892. options.removeClass = null;
  4893. }
  4894. if (options.to) {
  4895. element.css(options.to);
  4896. options.to = null;
  4897. }
  4898. }
  4899. };
  4900. }];
  4901. };
  4902. /* global stripHash: true */
  4903. /**
  4904. * ! This is a private undocumented service !
  4905. *
  4906. * @name $browser
  4907. * @requires $log
  4908. * @description
  4909. * This object has two goals:
  4910. *
  4911. * - hide all the global state in the browser caused by the window object
  4912. * - abstract away all the browser specific features and inconsistencies
  4913. *
  4914. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  4915. * service, which can be used for convenient testing of the application without the interaction with
  4916. * the real browser apis.
  4917. */
  4918. /**
  4919. * @param {object} window The global window object.
  4920. * @param {object} document jQuery wrapped document.
  4921. * @param {object} $log window.console or an object with the same interface.
  4922. * @param {object} $sniffer $sniffer service
  4923. */
  4924. function Browser(window, document, $log, $sniffer) {
  4925. var self = this,
  4926. rawDocument = document[0],
  4927. location = window.location,
  4928. history = window.history,
  4929. setTimeout = window.setTimeout,
  4930. clearTimeout = window.clearTimeout,
  4931. pendingDeferIds = {};
  4932. self.isMock = false;
  4933. var outstandingRequestCount = 0;
  4934. var outstandingRequestCallbacks = [];
  4935. // TODO(vojta): remove this temporary api
  4936. self.$$completeOutstandingRequest = completeOutstandingRequest;
  4937. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  4938. /**
  4939. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  4940. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  4941. */
  4942. function completeOutstandingRequest(fn) {
  4943. try {
  4944. fn.apply(null, sliceArgs(arguments, 1));
  4945. } finally {
  4946. outstandingRequestCount--;
  4947. if (outstandingRequestCount === 0) {
  4948. while (outstandingRequestCallbacks.length) {
  4949. try {
  4950. outstandingRequestCallbacks.pop()();
  4951. } catch (e) {
  4952. $log.error(e);
  4953. }
  4954. }
  4955. }
  4956. }
  4957. }
  4958. function getHash(url) {
  4959. var index = url.indexOf('#');
  4960. return index === -1 ? '' : url.substr(index);
  4961. }
  4962. /**
  4963. * @private
  4964. * Note: this method is used only by scenario runner
  4965. * TODO(vojta): prefix this method with $$ ?
  4966. * @param {function()} callback Function that will be called when no outstanding request
  4967. */
  4968. self.notifyWhenNoOutstandingRequests = function(callback) {
  4969. if (outstandingRequestCount === 0) {
  4970. callback();
  4971. } else {
  4972. outstandingRequestCallbacks.push(callback);
  4973. }
  4974. };
  4975. //////////////////////////////////////////////////////////////
  4976. // URL API
  4977. //////////////////////////////////////////////////////////////
  4978. var cachedState, lastHistoryState,
  4979. lastBrowserUrl = location.href,
  4980. baseElement = document.find('base'),
  4981. reloadLocation = null;
  4982. cacheState();
  4983. lastHistoryState = cachedState;
  4984. /**
  4985. * @name $browser#url
  4986. *
  4987. * @description
  4988. * GETTER:
  4989. * Without any argument, this method just returns current value of location.href.
  4990. *
  4991. * SETTER:
  4992. * With at least one argument, this method sets url to new value.
  4993. * If html5 history api supported, pushState/replaceState is used, otherwise
  4994. * location.href/location.replace is used.
  4995. * Returns its own instance to allow chaining
  4996. *
  4997. * NOTE: this api is intended for use only by the $location service. Please use the
  4998. * {@link ng.$location $location service} to change url.
  4999. *
  5000. * @param {string} url New url (when used as setter)
  5001. * @param {boolean=} replace Should new url replace current history record?
  5002. * @param {object=} state object to use with pushState/replaceState
  5003. */
  5004. self.url = function(url, replace, state) {
  5005. // In modern browsers `history.state` is `null` by default; treating it separately
  5006. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  5007. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  5008. if (isUndefined(state)) {
  5009. state = null;
  5010. }
  5011. // Android Browser BFCache causes location, history reference to become stale.
  5012. if (location !== window.location) location = window.location;
  5013. if (history !== window.history) history = window.history;
  5014. // setter
  5015. if (url) {
  5016. var sameState = lastHistoryState === state;
  5017. // Don't change anything if previous and current URLs and states match. This also prevents
  5018. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  5019. // See https://github.com/angular/angular.js/commit/ffb2701
  5020. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  5021. return self;
  5022. }
  5023. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  5024. lastBrowserUrl = url;
  5025. lastHistoryState = state;
  5026. // Don't use history API if only the hash changed
  5027. // due to a bug in IE10/IE11 which leads
  5028. // to not firing a `hashchange` nor `popstate` event
  5029. // in some cases (see #9143).
  5030. if ($sniffer.history && (!sameBase || !sameState)) {
  5031. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  5032. cacheState();
  5033. // Do the assignment again so that those two variables are referentially identical.
  5034. lastHistoryState = cachedState;
  5035. } else {
  5036. if (!sameBase || reloadLocation) {
  5037. reloadLocation = url;
  5038. }
  5039. if (replace) {
  5040. location.replace(url);
  5041. } else if (!sameBase) {
  5042. location.href = url;
  5043. } else {
  5044. location.hash = getHash(url);
  5045. }
  5046. }
  5047. return self;
  5048. // getter
  5049. } else {
  5050. // - reloadLocation is needed as browsers don't allow to read out
  5051. // the new location.href if a reload happened.
  5052. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  5053. return reloadLocation || location.href.replace(/%27/g,"'");
  5054. }
  5055. };
  5056. /**
  5057. * @name $browser#state
  5058. *
  5059. * @description
  5060. * This method is a getter.
  5061. *
  5062. * Return history.state or null if history.state is undefined.
  5063. *
  5064. * @returns {object} state
  5065. */
  5066. self.state = function() {
  5067. return cachedState;
  5068. };
  5069. var urlChangeListeners = [],
  5070. urlChangeInit = false;
  5071. function cacheStateAndFireUrlChange() {
  5072. cacheState();
  5073. fireUrlChange();
  5074. }
  5075. function getCurrentState() {
  5076. try {
  5077. return history.state;
  5078. } catch (e) {
  5079. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  5080. }
  5081. }
  5082. // This variable should be used *only* inside the cacheState function.
  5083. var lastCachedState = null;
  5084. function cacheState() {
  5085. // This should be the only place in $browser where `history.state` is read.
  5086. cachedState = getCurrentState();
  5087. cachedState = isUndefined(cachedState) ? null : cachedState;
  5088. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  5089. if (equals(cachedState, lastCachedState)) {
  5090. cachedState = lastCachedState;
  5091. }
  5092. lastCachedState = cachedState;
  5093. }
  5094. function fireUrlChange() {
  5095. if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
  5096. return;
  5097. }
  5098. lastBrowserUrl = self.url();
  5099. lastHistoryState = cachedState;
  5100. forEach(urlChangeListeners, function(listener) {
  5101. listener(self.url(), cachedState);
  5102. });
  5103. }
  5104. /**
  5105. * @name $browser#onUrlChange
  5106. *
  5107. * @description
  5108. * Register callback function that will be called, when url changes.
  5109. *
  5110. * It's only called when the url is changed from outside of angular:
  5111. * - user types different url into address bar
  5112. * - user clicks on history (forward/back) button
  5113. * - user clicks on a link
  5114. *
  5115. * It's not called when url is changed by $browser.url() method
  5116. *
  5117. * The listener gets called with new url as parameter.
  5118. *
  5119. * NOTE: this api is intended for use only by the $location service. Please use the
  5120. * {@link ng.$location $location service} to monitor url changes in angular apps.
  5121. *
  5122. * @param {function(string)} listener Listener function to be called when url changes.
  5123. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  5124. */
  5125. self.onUrlChange = function(callback) {
  5126. // TODO(vojta): refactor to use node's syntax for events
  5127. if (!urlChangeInit) {
  5128. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  5129. // don't fire popstate when user change the address bar and don't fire hashchange when url
  5130. // changed by push/replaceState
  5131. // html5 history api - popstate event
  5132. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  5133. // hashchange event
  5134. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  5135. urlChangeInit = true;
  5136. }
  5137. urlChangeListeners.push(callback);
  5138. return callback;
  5139. };
  5140. /**
  5141. * @private
  5142. * Remove popstate and hashchange handler from window.
  5143. *
  5144. * NOTE: this api is intended for use only by $rootScope.
  5145. */
  5146. self.$$applicationDestroyed = function() {
  5147. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  5148. };
  5149. /**
  5150. * Checks whether the url has changed outside of Angular.
  5151. * Needs to be exported to be able to check for changes that have been done in sync,
  5152. * as hashchange/popstate events fire in async.
  5153. */
  5154. self.$$checkUrlChange = fireUrlChange;
  5155. //////////////////////////////////////////////////////////////
  5156. // Misc API
  5157. //////////////////////////////////////////////////////////////
  5158. /**
  5159. * @name $browser#baseHref
  5160. *
  5161. * @description
  5162. * Returns current <base href>
  5163. * (always relative - without domain)
  5164. *
  5165. * @returns {string} The current base href
  5166. */
  5167. self.baseHref = function() {
  5168. var href = baseElement.attr('href');
  5169. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  5170. };
  5171. /**
  5172. * @name $browser#defer
  5173. * @param {function()} fn A function, who's execution should be deferred.
  5174. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  5175. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  5176. *
  5177. * @description
  5178. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  5179. *
  5180. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  5181. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  5182. * via `$browser.defer.flush()`.
  5183. *
  5184. */
  5185. self.defer = function(fn, delay) {
  5186. var timeoutId;
  5187. outstandingRequestCount++;
  5188. timeoutId = setTimeout(function() {
  5189. delete pendingDeferIds[timeoutId];
  5190. completeOutstandingRequest(fn);
  5191. }, delay || 0);
  5192. pendingDeferIds[timeoutId] = true;
  5193. return timeoutId;
  5194. };
  5195. /**
  5196. * @name $browser#defer.cancel
  5197. *
  5198. * @description
  5199. * Cancels a deferred task identified with `deferId`.
  5200. *
  5201. * @param {*} deferId Token returned by the `$browser.defer` function.
  5202. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  5203. * canceled.
  5204. */
  5205. self.defer.cancel = function(deferId) {
  5206. if (pendingDeferIds[deferId]) {
  5207. delete pendingDeferIds[deferId];
  5208. clearTimeout(deferId);
  5209. completeOutstandingRequest(noop);
  5210. return true;
  5211. }
  5212. return false;
  5213. };
  5214. }
  5215. function $BrowserProvider() {
  5216. this.$get = ['$window', '$log', '$sniffer', '$document',
  5217. function($window, $log, $sniffer, $document) {
  5218. return new Browser($window, $document, $log, $sniffer);
  5219. }];
  5220. }
  5221. /**
  5222. * @ngdoc service
  5223. * @name $cacheFactory
  5224. *
  5225. * @description
  5226. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  5227. * them.
  5228. *
  5229. * ```js
  5230. *
  5231. * var cache = $cacheFactory('cacheId');
  5232. * expect($cacheFactory.get('cacheId')).toBe(cache);
  5233. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  5234. *
  5235. * cache.put("key", "value");
  5236. * cache.put("another key", "another value");
  5237. *
  5238. * // We've specified no options on creation
  5239. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  5240. *
  5241. * ```
  5242. *
  5243. *
  5244. * @param {string} cacheId Name or id of the newly created cache.
  5245. * @param {object=} options Options object that specifies the cache behavior. Properties:
  5246. *
  5247. * - `{number=}` `capacity` — turns the cache into LRU cache.
  5248. *
  5249. * @returns {object} Newly created cache object with the following set of methods:
  5250. *
  5251. * - `{object}` `info()` — Returns id, size, and options of cache.
  5252. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  5253. * it.
  5254. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  5255. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  5256. * - `{void}` `removeAll()` — Removes all cached values.
  5257. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  5258. *
  5259. * @example
  5260. <example module="cacheExampleApp">
  5261. <file name="index.html">
  5262. <div ng-controller="CacheController">
  5263. <input ng-model="newCacheKey" placeholder="Key">
  5264. <input ng-model="newCacheValue" placeholder="Value">
  5265. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  5266. <p ng-if="keys.length">Cached Values</p>
  5267. <div ng-repeat="key in keys">
  5268. <span ng-bind="key"></span>
  5269. <span>: </span>
  5270. <b ng-bind="cache.get(key)"></b>
  5271. </div>
  5272. <p>Cache Info</p>
  5273. <div ng-repeat="(key, value) in cache.info()">
  5274. <span ng-bind="key"></span>
  5275. <span>: </span>
  5276. <b ng-bind="value"></b>
  5277. </div>
  5278. </div>
  5279. </file>
  5280. <file name="script.js">
  5281. angular.module('cacheExampleApp', []).
  5282. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  5283. $scope.keys = [];
  5284. $scope.cache = $cacheFactory('cacheId');
  5285. $scope.put = function(key, value) {
  5286. if ($scope.cache.get(key) === undefined) {
  5287. $scope.keys.push(key);
  5288. }
  5289. $scope.cache.put(key, value === undefined ? null : value);
  5290. };
  5291. }]);
  5292. </file>
  5293. <file name="style.css">
  5294. p {
  5295. margin: 10px 0 3px;
  5296. }
  5297. </file>
  5298. </example>
  5299. */
  5300. function $CacheFactoryProvider() {
  5301. this.$get = function() {
  5302. var caches = {};
  5303. function cacheFactory(cacheId, options) {
  5304. if (cacheId in caches) {
  5305. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  5306. }
  5307. var size = 0,
  5308. stats = extend({}, options, {id: cacheId}),
  5309. data = {},
  5310. capacity = (options && options.capacity) || Number.MAX_VALUE,
  5311. lruHash = {},
  5312. freshEnd = null,
  5313. staleEnd = null;
  5314. /**
  5315. * @ngdoc type
  5316. * @name $cacheFactory.Cache
  5317. *
  5318. * @description
  5319. * A cache object used to store and retrieve data, primarily used by
  5320. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  5321. * templates and other data.
  5322. *
  5323. * ```js
  5324. * angular.module('superCache')
  5325. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  5326. * return $cacheFactory('super-cache');
  5327. * }]);
  5328. * ```
  5329. *
  5330. * Example test:
  5331. *
  5332. * ```js
  5333. * it('should behave like a cache', inject(function(superCache) {
  5334. * superCache.put('key', 'value');
  5335. * superCache.put('another key', 'another value');
  5336. *
  5337. * expect(superCache.info()).toEqual({
  5338. * id: 'super-cache',
  5339. * size: 2
  5340. * });
  5341. *
  5342. * superCache.remove('another key');
  5343. * expect(superCache.get('another key')).toBeUndefined();
  5344. *
  5345. * superCache.removeAll();
  5346. * expect(superCache.info()).toEqual({
  5347. * id: 'super-cache',
  5348. * size: 0
  5349. * });
  5350. * }));
  5351. * ```
  5352. */
  5353. return caches[cacheId] = {
  5354. /**
  5355. * @ngdoc method
  5356. * @name $cacheFactory.Cache#put
  5357. * @kind function
  5358. *
  5359. * @description
  5360. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  5361. * retrieved later, and incrementing the size of the cache if the key was not already
  5362. * present in the cache. If behaving like an LRU cache, it will also remove stale
  5363. * entries from the set.
  5364. *
  5365. * It will not insert undefined values into the cache.
  5366. *
  5367. * @param {string} key the key under which the cached data is stored.
  5368. * @param {*} value the value to store alongside the key. If it is undefined, the key
  5369. * will not be stored.
  5370. * @returns {*} the value stored.
  5371. */
  5372. put: function(key, value) {
  5373. if (isUndefined(value)) return;
  5374. if (capacity < Number.MAX_VALUE) {
  5375. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  5376. refresh(lruEntry);
  5377. }
  5378. if (!(key in data)) size++;
  5379. data[key] = value;
  5380. if (size > capacity) {
  5381. this.remove(staleEnd.key);
  5382. }
  5383. return value;
  5384. },
  5385. /**
  5386. * @ngdoc method
  5387. * @name $cacheFactory.Cache#get
  5388. * @kind function
  5389. *
  5390. * @description
  5391. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  5392. *
  5393. * @param {string} key the key of the data to be retrieved
  5394. * @returns {*} the value stored.
  5395. */
  5396. get: function(key) {
  5397. if (capacity < Number.MAX_VALUE) {
  5398. var lruEntry = lruHash[key];
  5399. if (!lruEntry) return;
  5400. refresh(lruEntry);
  5401. }
  5402. return data[key];
  5403. },
  5404. /**
  5405. * @ngdoc method
  5406. * @name $cacheFactory.Cache#remove
  5407. * @kind function
  5408. *
  5409. * @description
  5410. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  5411. *
  5412. * @param {string} key the key of the entry to be removed
  5413. */
  5414. remove: function(key) {
  5415. if (capacity < Number.MAX_VALUE) {
  5416. var lruEntry = lruHash[key];
  5417. if (!lruEntry) return;
  5418. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  5419. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  5420. link(lruEntry.n,lruEntry.p);
  5421. delete lruHash[key];
  5422. }
  5423. delete data[key];
  5424. size--;
  5425. },
  5426. /**
  5427. * @ngdoc method
  5428. * @name $cacheFactory.Cache#removeAll
  5429. * @kind function
  5430. *
  5431. * @description
  5432. * Clears the cache object of any entries.
  5433. */
  5434. removeAll: function() {
  5435. data = {};
  5436. size = 0;
  5437. lruHash = {};
  5438. freshEnd = staleEnd = null;
  5439. },
  5440. /**
  5441. * @ngdoc method
  5442. * @name $cacheFactory.Cache#destroy
  5443. * @kind function
  5444. *
  5445. * @description
  5446. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  5447. * removing it from the {@link $cacheFactory $cacheFactory} set.
  5448. */
  5449. destroy: function() {
  5450. data = null;
  5451. stats = null;
  5452. lruHash = null;
  5453. delete caches[cacheId];
  5454. },
  5455. /**
  5456. * @ngdoc method
  5457. * @name $cacheFactory.Cache#info
  5458. * @kind function
  5459. *
  5460. * @description
  5461. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  5462. *
  5463. * @returns {object} an object with the following properties:
  5464. * <ul>
  5465. * <li>**id**: the id of the cache instance</li>
  5466. * <li>**size**: the number of entries kept in the cache instance</li>
  5467. * <li>**...**: any additional properties from the options object when creating the
  5468. * cache.</li>
  5469. * </ul>
  5470. */
  5471. info: function() {
  5472. return extend({}, stats, {size: size});
  5473. }
  5474. };
  5475. /**
  5476. * makes the `entry` the freshEnd of the LRU linked list
  5477. */
  5478. function refresh(entry) {
  5479. if (entry != freshEnd) {
  5480. if (!staleEnd) {
  5481. staleEnd = entry;
  5482. } else if (staleEnd == entry) {
  5483. staleEnd = entry.n;
  5484. }
  5485. link(entry.n, entry.p);
  5486. link(entry, freshEnd);
  5487. freshEnd = entry;
  5488. freshEnd.n = null;
  5489. }
  5490. }
  5491. /**
  5492. * bidirectionally links two entries of the LRU linked list
  5493. */
  5494. function link(nextEntry, prevEntry) {
  5495. if (nextEntry != prevEntry) {
  5496. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  5497. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  5498. }
  5499. }
  5500. }
  5501. /**
  5502. * @ngdoc method
  5503. * @name $cacheFactory#info
  5504. *
  5505. * @description
  5506. * Get information about all the caches that have been created
  5507. *
  5508. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  5509. */
  5510. cacheFactory.info = function() {
  5511. var info = {};
  5512. forEach(caches, function(cache, cacheId) {
  5513. info[cacheId] = cache.info();
  5514. });
  5515. return info;
  5516. };
  5517. /**
  5518. * @ngdoc method
  5519. * @name $cacheFactory#get
  5520. *
  5521. * @description
  5522. * Get access to a cache object by the `cacheId` used when it was created.
  5523. *
  5524. * @param {string} cacheId Name or id of a cache to access.
  5525. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  5526. */
  5527. cacheFactory.get = function(cacheId) {
  5528. return caches[cacheId];
  5529. };
  5530. return cacheFactory;
  5531. };
  5532. }
  5533. /**
  5534. * @ngdoc service
  5535. * @name $templateCache
  5536. *
  5537. * @description
  5538. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  5539. * can load templates directly into the cache in a `script` tag, or by consuming the
  5540. * `$templateCache` service directly.
  5541. *
  5542. * Adding via the `script` tag:
  5543. *
  5544. * ```html
  5545. * <script type="text/ng-template" id="templateId.html">
  5546. * <p>This is the content of the template</p>
  5547. * </script>
  5548. * ```
  5549. *
  5550. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  5551. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  5552. * element with ng-app attribute), otherwise the template will be ignored.
  5553. *
  5554. * Adding via the `$templateCache` service:
  5555. *
  5556. * ```js
  5557. * var myApp = angular.module('myApp', []);
  5558. * myApp.run(function($templateCache) {
  5559. * $templateCache.put('templateId.html', 'This is the content of the template');
  5560. * });
  5561. * ```
  5562. *
  5563. * To retrieve the template later, simply use it in your HTML:
  5564. * ```html
  5565. * <div ng-include=" 'templateId.html' "></div>
  5566. * ```
  5567. *
  5568. * or get it via Javascript:
  5569. * ```js
  5570. * $templateCache.get('templateId.html')
  5571. * ```
  5572. *
  5573. * See {@link ng.$cacheFactory $cacheFactory}.
  5574. *
  5575. */
  5576. function $TemplateCacheProvider() {
  5577. this.$get = ['$cacheFactory', function($cacheFactory) {
  5578. return $cacheFactory('templates');
  5579. }];
  5580. }
  5581. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  5582. * Any commits to this file should be reviewed with security in mind. *
  5583. * Changes to this file can potentially create security vulnerabilities. *
  5584. * An approval from 2 Core members with history of modifying *
  5585. * this file is required. *
  5586. * *
  5587. * Does the change somehow allow for arbitrary javascript to be executed? *
  5588. * Or allows for someone to change the prototype of built-in objects? *
  5589. * Or gives undesired access to variables likes document or window? *
  5590. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  5591. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  5592. *
  5593. * DOM-related variables:
  5594. *
  5595. * - "node" - DOM Node
  5596. * - "element" - DOM Element or Node
  5597. * - "$node" or "$element" - jqLite-wrapped node or element
  5598. *
  5599. *
  5600. * Compiler related stuff:
  5601. *
  5602. * - "linkFn" - linking fn of a single directive
  5603. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  5604. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  5605. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  5606. */
  5607. /**
  5608. * @ngdoc service
  5609. * @name $compile
  5610. * @kind function
  5611. *
  5612. * @description
  5613. * Compiles an HTML string or DOM into a template and produces a template function, which
  5614. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  5615. *
  5616. * The compilation is a process of walking the DOM tree and matching DOM elements to
  5617. * {@link ng.$compileProvider#directive directives}.
  5618. *
  5619. * <div class="alert alert-warning">
  5620. * **Note:** This document is an in-depth reference of all directive options.
  5621. * For a gentle introduction to directives with examples of common use cases,
  5622. * see the {@link guide/directive directive guide}.
  5623. * </div>
  5624. *
  5625. * ## Comprehensive Directive API
  5626. *
  5627. * There are many different options for a directive.
  5628. *
  5629. * The difference resides in the return value of the factory function.
  5630. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  5631. * or just the `postLink` function (all other properties will have the default values).
  5632. *
  5633. * <div class="alert alert-success">
  5634. * **Best Practice:** It's recommended to use the "directive definition object" form.
  5635. * </div>
  5636. *
  5637. * Here's an example directive declared with a Directive Definition Object:
  5638. *
  5639. * ```js
  5640. * var myModule = angular.module(...);
  5641. *
  5642. * myModule.directive('directiveName', function factory(injectables) {
  5643. * var directiveDefinitionObject = {
  5644. * priority: 0,
  5645. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  5646. * // or
  5647. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  5648. * transclude: false,
  5649. * restrict: 'A',
  5650. * templateNamespace: 'html',
  5651. * scope: false,
  5652. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  5653. * controllerAs: 'stringIdentifier',
  5654. * bindToController: false,
  5655. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  5656. * compile: function compile(tElement, tAttrs, transclude) {
  5657. * return {
  5658. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5659. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5660. * }
  5661. * // or
  5662. * // return function postLink( ... ) { ... }
  5663. * },
  5664. * // or
  5665. * // link: {
  5666. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5667. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5668. * // }
  5669. * // or
  5670. * // link: function postLink( ... ) { ... }
  5671. * };
  5672. * return directiveDefinitionObject;
  5673. * });
  5674. * ```
  5675. *
  5676. * <div class="alert alert-warning">
  5677. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  5678. * </div>
  5679. *
  5680. * Therefore the above can be simplified as:
  5681. *
  5682. * ```js
  5683. * var myModule = angular.module(...);
  5684. *
  5685. * myModule.directive('directiveName', function factory(injectables) {
  5686. * var directiveDefinitionObject = {
  5687. * link: function postLink(scope, iElement, iAttrs) { ... }
  5688. * };
  5689. * return directiveDefinitionObject;
  5690. * // or
  5691. * // return function postLink(scope, iElement, iAttrs) { ... }
  5692. * });
  5693. * ```
  5694. *
  5695. *
  5696. *
  5697. * ### Directive Definition Object
  5698. *
  5699. * The directive definition object provides instructions to the {@link ng.$compile
  5700. * compiler}. The attributes are:
  5701. *
  5702. * #### `multiElement`
  5703. * When this property is set to true, the HTML compiler will collect DOM nodes between
  5704. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  5705. * together as the directive elements. It is recommended that this feature be used on directives
  5706. * which are not strictly behavioural (such as {@link ngClick}), and which
  5707. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  5708. *
  5709. * #### `priority`
  5710. * When there are multiple directives defined on a single DOM element, sometimes it
  5711. * is necessary to specify the order in which the directives are applied. The `priority` is used
  5712. * to sort the directives before their `compile` functions get called. Priority is defined as a
  5713. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  5714. * are also run in priority order, but post-link functions are run in reverse order. The order
  5715. * of directives with the same priority is undefined. The default priority is `0`.
  5716. *
  5717. * #### `terminal`
  5718. * If set to true then the current `priority` will be the last set of directives
  5719. * which will execute (any directives at the current priority will still execute
  5720. * as the order of execution on same `priority` is undefined). Note that expressions
  5721. * and other directives used in the directive's template will also be excluded from execution.
  5722. *
  5723. * #### `scope`
  5724. * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
  5725. * same element request a new scope, only one new scope is created. The new scope rule does not
  5726. * apply for the root of the template since the root of the template always gets a new scope.
  5727. *
  5728. * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
  5729. * normal scope in that it does not prototypically inherit from the parent scope. This is useful
  5730. * when creating reusable components, which should not accidentally read or modify data in the
  5731. * parent scope.
  5732. *
  5733. * The 'isolate' scope takes an object hash which defines a set of local scope properties
  5734. * derived from the parent scope. These local properties are useful for aliasing values for
  5735. * templates. Locals definition is a hash of local scope property to its source:
  5736. *
  5737. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  5738. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  5739. * attribute name is assumed to be the same as the local name.
  5740. * Given `<widget my-attr="hello {{name}}">` and widget definition
  5741. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  5742. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  5743. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  5744. * component scope).
  5745. *
  5746. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  5747. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  5748. * name is specified then the attribute name is assumed to be the same as the local name.
  5749. * Given `<widget my-attr="parentModel">` and widget definition of
  5750. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  5751. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  5752. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  5753. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  5754. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If
  5755. * you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use
  5756. * `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).
  5757. *
  5758. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  5759. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  5760. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  5761. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  5762. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  5763. * pass data from the isolated scope via an expression to the parent scope, this can be
  5764. * done by passing a map of local variable names and values into the expression wrapper fn.
  5765. * For example, if the expression is `increment(amount)` then we can specify the amount value
  5766. * by calling the `localFn` as `localFn({amount: 22})`.
  5767. *
  5768. *
  5769. * #### `bindToController`
  5770. * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will
  5771. * allow a component to have its properties bound to the controller, rather than to scope. When the controller
  5772. * is instantiated, the initial values of the isolate scope bindings are already available.
  5773. *
  5774. * #### `controller`
  5775. * Controller constructor function. The controller is instantiated before the
  5776. * pre-linking phase and it is shared with other directives (see
  5777. * `require` attribute). This allows the directives to communicate with each other and augment
  5778. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  5779. *
  5780. * * `$scope` - Current scope associated with the element
  5781. * * `$element` - Current element
  5782. * * `$attrs` - Current attributes object for the element
  5783. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  5784. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5785. * * `scope`: optional argument to override the scope.
  5786. * * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.
  5787. * * `futureParentElement`:
  5788. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  5789. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  5790. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  5791. * and when the `cloneLinkinFn` is passed,
  5792. * as those elements need to created and cloned in a special way when they are defined outside their
  5793. * usual containers (e.g. like `<svg>`).
  5794. * * See also the `directive.templateNamespace` property.
  5795. *
  5796. *
  5797. * #### `require`
  5798. * Require another directive and inject its controller as the fourth argument to the linking function. The
  5799. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  5800. * injected argument will be an array in corresponding order. If no such directive can be
  5801. * found, or if the directive does not have a controller, then an error is raised (unless no link function
  5802. * is specified, in which case error checking is skipped). The name can be prefixed with:
  5803. *
  5804. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  5805. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  5806. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  5807. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  5808. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  5809. * `null` to the `link` fn if not found.
  5810. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  5811. * `null` to the `link` fn if not found.
  5812. *
  5813. *
  5814. * #### `controllerAs`
  5815. * Identifier name for a reference to the controller in the directive's scope.
  5816. * This allows the controller to be referenced from the directive template. The directive
  5817. * needs to define a scope for this configuration to be used. Useful in the case when
  5818. * directive is used as component.
  5819. *
  5820. *
  5821. * #### `restrict`
  5822. * String of subset of `EACM` which restricts the directive to a specific directive
  5823. * declaration style. If omitted, the defaults (elements and attributes) are used.
  5824. *
  5825. * * `E` - Element name (default): `<my-directive></my-directive>`
  5826. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  5827. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  5828. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  5829. *
  5830. *
  5831. * #### `templateNamespace`
  5832. * String representing the document type used by the markup in the template.
  5833. * AngularJS needs this information as those elements need to be created and cloned
  5834. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  5835. *
  5836. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  5837. * top-level elements such as `<svg>` or `<math>`.
  5838. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  5839. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  5840. *
  5841. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  5842. *
  5843. * #### `template`
  5844. * HTML markup that may:
  5845. * * Replace the contents of the directive's element (default).
  5846. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  5847. * * Wrap the contents of the directive's element (if `transclude` is true).
  5848. *
  5849. * Value may be:
  5850. *
  5851. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  5852. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  5853. * function api below) and returns a string value.
  5854. *
  5855. *
  5856. * #### `templateUrl`
  5857. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  5858. *
  5859. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  5860. * for later when the template has been resolved. In the meantime it will continue to compile and link
  5861. * sibling and parent elements as though this element had not contained any directives.
  5862. *
  5863. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  5864. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  5865. * case when only one deeply nested directive has `templateUrl`.
  5866. *
  5867. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  5868. *
  5869. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  5870. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  5871. * a string value representing the url. In either case, the template URL is passed through {@link
  5872. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  5873. *
  5874. *
  5875. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  5876. * specify what the template should replace. Defaults to `false`.
  5877. *
  5878. * * `true` - the template will replace the directive's element.
  5879. * * `false` - the template will replace the contents of the directive's element.
  5880. *
  5881. * The replacement process migrates all of the attributes / classes from the old element to the new
  5882. * one. See the {@link guide/directive#template-expanding-directive
  5883. * Directives Guide} for an example.
  5884. *
  5885. * There are very few scenarios where element replacement is required for the application function,
  5886. * the main one being reusable custom components that are used within SVG contexts
  5887. * (because SVG doesn't work with custom elements in the DOM tree).
  5888. *
  5889. * #### `transclude`
  5890. * Extract the contents of the element where the directive appears and make it available to the directive.
  5891. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  5892. * {@link $compile#transclusion Transclusion} section below.
  5893. *
  5894. * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
  5895. * directive's element or the entire element:
  5896. *
  5897. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  5898. * * `'element'` - transclude the whole of the directive's element including any directives on this
  5899. * element that defined at a lower priority than this directive. When used, the `template`
  5900. * property is ignored.
  5901. *
  5902. *
  5903. * #### `compile`
  5904. *
  5905. * ```js
  5906. * function compile(tElement, tAttrs, transclude) { ... }
  5907. * ```
  5908. *
  5909. * The compile function deals with transforming the template DOM. Since most directives do not do
  5910. * template transformation, it is not used often. The compile function takes the following arguments:
  5911. *
  5912. * * `tElement` - template element - The element where the directive has been declared. It is
  5913. * safe to do template transformation on the element and child elements only.
  5914. *
  5915. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  5916. * between all directive compile functions.
  5917. *
  5918. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  5919. *
  5920. * <div class="alert alert-warning">
  5921. * **Note:** The template instance and the link instance may be different objects if the template has
  5922. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  5923. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  5924. * should be done in a linking function rather than in a compile function.
  5925. * </div>
  5926. * <div class="alert alert-warning">
  5927. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  5928. * own templates or compile functions. Compiling these directives results in an infinite loop and a
  5929. * stack overflow errors.
  5930. *
  5931. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  5932. * a directive's template instead of relying on automatic template compilation via `template` or
  5933. * `templateUrl` declaration or manual compilation inside the compile function.
  5934. * </div>
  5935. *
  5936. * <div class="alert alert-danger">
  5937. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  5938. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  5939. * to the link function instead.
  5940. * </div>
  5941. * A compile function can have a return value which can be either a function or an object.
  5942. *
  5943. * * returning a (post-link) function - is equivalent to registering the linking function via the
  5944. * `link` property of the config object when the compile function is empty.
  5945. *
  5946. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  5947. * control when a linking function should be called during the linking phase. See info about
  5948. * pre-linking and post-linking functions below.
  5949. *
  5950. *
  5951. * #### `link`
  5952. * This property is used only if the `compile` property is not defined.
  5953. *
  5954. * ```js
  5955. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  5956. * ```
  5957. *
  5958. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  5959. * executed after the template has been cloned. This is where most of the directive logic will be
  5960. * put.
  5961. *
  5962. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  5963. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  5964. *
  5965. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  5966. * manipulate the children of the element only in `postLink` function since the children have
  5967. * already been linked.
  5968. *
  5969. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  5970. * between all directive linking functions.
  5971. *
  5972. * * `controller` - the directive's required controller instance(s) - Instances are shared
  5973. * among all directives, which allows the directives to use the controllers as a communication
  5974. * channel. The exact value depends on the directive's `require` property:
  5975. * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
  5976. * * `string`: the controller instance
  5977. * * `array`: array of controller instances
  5978. *
  5979. * If a required controller cannot be found, and it is optional, the instance is `null`,
  5980. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  5981. *
  5982. * Note that you can also require the directive's own controller - it will be made available like
  5983. * any other controller.
  5984. *
  5985. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  5986. * This is the same as the `$transclude`
  5987. * parameter of directive controllers, see there for details.
  5988. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5989. *
  5990. * #### Pre-linking function
  5991. *
  5992. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  5993. * compiler linking function will fail to locate the correct elements for linking.
  5994. *
  5995. * #### Post-linking function
  5996. *
  5997. * Executed after the child elements are linked.
  5998. *
  5999. * Note that child elements that contain `templateUrl` directives will not have been compiled
  6000. * and linked since they are waiting for their template to load asynchronously and their own
  6001. * compilation and linking has been suspended until that occurs.
  6002. *
  6003. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  6004. * for their async templates to be resolved.
  6005. *
  6006. *
  6007. * ### Transclusion
  6008. *
  6009. * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
  6010. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  6011. * scope from where they were taken.
  6012. *
  6013. * Transclusion is used (often with {@link ngTransclude}) to insert the
  6014. * original contents of a directive's element into a specified place in the template of the directive.
  6015. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  6016. * content has access to the properties on the scope from which it was taken, even if the directive
  6017. * has isolated scope.
  6018. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  6019. *
  6020. * This makes it possible for the widget to have private state for its template, while the transcluded
  6021. * content has access to its originating scope.
  6022. *
  6023. * <div class="alert alert-warning">
  6024. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  6025. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  6026. * Testing Transclusion Directives}.
  6027. * </div>
  6028. *
  6029. * #### Transclusion Functions
  6030. *
  6031. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  6032. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  6033. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  6034. *
  6035. * <div class="alert alert-info">
  6036. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  6037. * ngTransclude will deal with it for us.
  6038. * </div>
  6039. *
  6040. * If you want to manually control the insertion and removal of the transcluded content in your directive
  6041. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  6042. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  6043. *
  6044. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  6045. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  6046. * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
  6047. *
  6048. * <div class="alert alert-info">
  6049. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
  6050. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  6051. * </div>
  6052. *
  6053. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  6054. * attach function**:
  6055. *
  6056. * ```js
  6057. * var transcludedContent, transclusionScope;
  6058. *
  6059. * $transclude(function(clone, scope) {
  6060. * element.append(clone);
  6061. * transcludedContent = clone;
  6062. * transclusionScope = scope;
  6063. * });
  6064. * ```
  6065. *
  6066. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  6067. * associated transclusion scope:
  6068. *
  6069. * ```js
  6070. * transcludedContent.remove();
  6071. * transclusionScope.$destroy();
  6072. * ```
  6073. *
  6074. * <div class="alert alert-info">
  6075. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  6076. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  6077. * then you are also responsible for calling `$destroy` on the transclusion scope.
  6078. * </div>
  6079. *
  6080. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  6081. * automatically destroy their transluded clones as necessary so you do not need to worry about this if
  6082. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  6083. *
  6084. *
  6085. * #### Transclusion Scopes
  6086. *
  6087. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  6088. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  6089. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  6090. * was taken.
  6091. *
  6092. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  6093. * like this:
  6094. *
  6095. * ```html
  6096. * <div ng-app>
  6097. * <div isolate>
  6098. * <div transclusion>
  6099. * </div>
  6100. * </div>
  6101. * </div>
  6102. * ```
  6103. *
  6104. * The `$parent` scope hierarchy will look like this:
  6105. *
  6106. * ```
  6107. * - $rootScope
  6108. * - isolate
  6109. * - transclusion
  6110. * ```
  6111. *
  6112. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  6113. *
  6114. * ```
  6115. * - $rootScope
  6116. * - transclusion
  6117. * - isolate
  6118. * ```
  6119. *
  6120. *
  6121. * ### Attributes
  6122. *
  6123. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  6124. * `link()` or `compile()` functions. It has a variety of uses.
  6125. *
  6126. * accessing *Normalized attribute names:*
  6127. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  6128. * the attributes object allows for normalized access to
  6129. * the attributes.
  6130. *
  6131. * * *Directive inter-communication:* All directives share the same instance of the attributes
  6132. * object which allows the directives to use the attributes object as inter directive
  6133. * communication.
  6134. *
  6135. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  6136. * allowing other directives to read the interpolated value.
  6137. *
  6138. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  6139. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  6140. * the only way to easily get the actual value because during the linking phase the interpolation
  6141. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  6142. *
  6143. * ```js
  6144. * function linkingFn(scope, elm, attrs, ctrl) {
  6145. * // get the attribute value
  6146. * console.log(attrs.ngModel);
  6147. *
  6148. * // change the attribute
  6149. * attrs.$set('ngModel', 'new value');
  6150. *
  6151. * // observe changes to interpolated attribute
  6152. * attrs.$observe('ngModel', function(value) {
  6153. * console.log('ngModel has changed value to ' + value);
  6154. * });
  6155. * }
  6156. * ```
  6157. *
  6158. * ## Example
  6159. *
  6160. * <div class="alert alert-warning">
  6161. * **Note**: Typically directives are registered with `module.directive`. The example below is
  6162. * to illustrate how `$compile` works.
  6163. * </div>
  6164. *
  6165. <example module="compileExample">
  6166. <file name="index.html">
  6167. <script>
  6168. angular.module('compileExample', [], function($compileProvider) {
  6169. // configure new 'compile' directive by passing a directive
  6170. // factory function. The factory function injects the '$compile'
  6171. $compileProvider.directive('compile', function($compile) {
  6172. // directive factory creates a link function
  6173. return function(scope, element, attrs) {
  6174. scope.$watch(
  6175. function(scope) {
  6176. // watch the 'compile' expression for changes
  6177. return scope.$eval(attrs.compile);
  6178. },
  6179. function(value) {
  6180. // when the 'compile' expression changes
  6181. // assign it into the current DOM
  6182. element.html(value);
  6183. // compile the new DOM and link it to the current
  6184. // scope.
  6185. // NOTE: we only compile .childNodes so that
  6186. // we don't get into infinite loop compiling ourselves
  6187. $compile(element.contents())(scope);
  6188. }
  6189. );
  6190. };
  6191. });
  6192. })
  6193. .controller('GreeterController', ['$scope', function($scope) {
  6194. $scope.name = 'Angular';
  6195. $scope.html = 'Hello {{name}}';
  6196. }]);
  6197. </script>
  6198. <div ng-controller="GreeterController">
  6199. <input ng-model="name"> <br/>
  6200. <textarea ng-model="html"></textarea> <br/>
  6201. <div compile="html"></div>
  6202. </div>
  6203. </file>
  6204. <file name="protractor.js" type="protractor">
  6205. it('should auto compile', function() {
  6206. var textarea = $('textarea');
  6207. var output = $('div[compile]');
  6208. // The initial state reads 'Hello Angular'.
  6209. expect(output.getText()).toBe('Hello Angular');
  6210. textarea.clear();
  6211. textarea.sendKeys('{{name}}!');
  6212. expect(output.getText()).toBe('Angular!');
  6213. });
  6214. </file>
  6215. </example>
  6216. *
  6217. *
  6218. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  6219. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  6220. *
  6221. * <div class="alert alert-danger">
  6222. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  6223. * e.g. will not use the right outer scope. Please pass the transclude function as a
  6224. * `parentBoundTranscludeFn` to the link function instead.
  6225. * </div>
  6226. *
  6227. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  6228. * root element(s), not their children)
  6229. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  6230. * (a DOM element/tree) to a scope. Where:
  6231. *
  6232. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  6233. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  6234. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  6235. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  6236. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  6237. *
  6238. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  6239. * * `scope` - is the current scope with which the linking function is working with.
  6240. *
  6241. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  6242. * keys may be used to control linking behavior:
  6243. *
  6244. * * `parentBoundTranscludeFn` - the transclude function made available to
  6245. * directives; if given, it will be passed through to the link functions of
  6246. * directives found in `element` during compilation.
  6247. * * `transcludeControllers` - an object hash with keys that map controller names
  6248. * to controller instances; if given, it will make the controllers
  6249. * available to directives.
  6250. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  6251. * the cloned elements; only needed for transcludes that are allowed to contain non html
  6252. * elements (e.g. SVG elements). See also the directive.controller property.
  6253. *
  6254. * Calling the linking function returns the element of the template. It is either the original
  6255. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  6256. *
  6257. * After linking the view is not updated until after a call to $digest which typically is done by
  6258. * Angular automatically.
  6259. *
  6260. * If you need access to the bound view, there are two ways to do it:
  6261. *
  6262. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  6263. * before you send them to the compiler and keep this reference around.
  6264. * ```js
  6265. * var element = $compile('<p>{{total}}</p>')(scope);
  6266. * ```
  6267. *
  6268. * - if on the other hand, you need the element to be cloned, the view reference from the original
  6269. * example would not point to the clone, but rather to the original template that was cloned. In
  6270. * this case, you can access the clone via the cloneAttachFn:
  6271. * ```js
  6272. * var templateElement = angular.element('<p>{{total}}</p>'),
  6273. * scope = ....;
  6274. *
  6275. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  6276. * //attach the clone to DOM document at the right place
  6277. * });
  6278. *
  6279. * //now we have reference to the cloned DOM via `clonedElement`
  6280. * ```
  6281. *
  6282. *
  6283. * For information on how the compiler works, see the
  6284. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  6285. */
  6286. var $compileMinErr = minErr('$compile');
  6287. /**
  6288. * @ngdoc provider
  6289. * @name $compileProvider
  6290. *
  6291. * @description
  6292. */
  6293. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  6294. function $CompileProvider($provide, $$sanitizeUriProvider) {
  6295. var hasDirectives = {},
  6296. Suffix = 'Directive',
  6297. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
  6298. CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
  6299. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  6300. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  6301. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  6302. // The assumption is that future DOM event attribute names will begin with
  6303. // 'on' and be composed of only English letters.
  6304. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  6305. function parseIsolateBindings(scope, directiveName, isController) {
  6306. var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;
  6307. var bindings = {};
  6308. forEach(scope, function(definition, scopeName) {
  6309. var match = definition.match(LOCAL_REGEXP);
  6310. if (!match) {
  6311. throw $compileMinErr('iscp',
  6312. "Invalid {3} for directive '{0}'." +
  6313. " Definition: {... {1}: '{2}' ...}",
  6314. directiveName, scopeName, definition,
  6315. (isController ? "controller bindings definition" :
  6316. "isolate scope definition"));
  6317. }
  6318. bindings[scopeName] = {
  6319. mode: match[1][0],
  6320. collection: match[2] === '*',
  6321. optional: match[3] === '?',
  6322. attrName: match[4] || scopeName
  6323. };
  6324. });
  6325. return bindings;
  6326. }
  6327. function parseDirectiveBindings(directive, directiveName) {
  6328. var bindings = {
  6329. isolateScope: null,
  6330. bindToController: null
  6331. };
  6332. if (isObject(directive.scope)) {
  6333. if (directive.bindToController === true) {
  6334. bindings.bindToController = parseIsolateBindings(directive.scope,
  6335. directiveName, true);
  6336. bindings.isolateScope = {};
  6337. } else {
  6338. bindings.isolateScope = parseIsolateBindings(directive.scope,
  6339. directiveName, false);
  6340. }
  6341. }
  6342. if (isObject(directive.bindToController)) {
  6343. bindings.bindToController =
  6344. parseIsolateBindings(directive.bindToController, directiveName, true);
  6345. }
  6346. if (isObject(bindings.bindToController)) {
  6347. var controller = directive.controller;
  6348. var controllerAs = directive.controllerAs;
  6349. if (!controller) {
  6350. // There is no controller, there may or may not be a controllerAs property
  6351. throw $compileMinErr('noctrl',
  6352. "Cannot bind to controller without directive '{0}'s controller.",
  6353. directiveName);
  6354. } else if (!identifierForController(controller, controllerAs)) {
  6355. // There is a controller, but no identifier or controllerAs property
  6356. throw $compileMinErr('noident',
  6357. "Cannot bind to controller without identifier for directive '{0}'.",
  6358. directiveName);
  6359. }
  6360. }
  6361. return bindings;
  6362. }
  6363. function assertValidDirectiveName(name) {
  6364. var letter = name.charAt(0);
  6365. if (!letter || letter !== lowercase(letter)) {
  6366. throw $compileMinErr('baddir', "Directive name '{0}' is invalid. The first character must be a lowercase letter", name);
  6367. }
  6368. if (name !== name.trim()) {
  6369. throw $compileMinErr('baddir',
  6370. "Directive name '{0}' is invalid. The name should not contain leading or trailing whitespaces",
  6371. name);
  6372. }
  6373. }
  6374. /**
  6375. * @ngdoc method
  6376. * @name $compileProvider#directive
  6377. * @kind function
  6378. *
  6379. * @description
  6380. * Register a new directive with the compiler.
  6381. *
  6382. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  6383. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  6384. * names and the values are the factories.
  6385. * @param {Function|Array} directiveFactory An injectable directive factory function. See
  6386. * {@link guide/directive} for more info.
  6387. * @returns {ng.$compileProvider} Self for chaining.
  6388. */
  6389. this.directive = function registerDirective(name, directiveFactory) {
  6390. assertNotHasOwnProperty(name, 'directive');
  6391. if (isString(name)) {
  6392. assertValidDirectiveName(name);
  6393. assertArg(directiveFactory, 'directiveFactory');
  6394. if (!hasDirectives.hasOwnProperty(name)) {
  6395. hasDirectives[name] = [];
  6396. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  6397. function($injector, $exceptionHandler) {
  6398. var directives = [];
  6399. forEach(hasDirectives[name], function(directiveFactory, index) {
  6400. try {
  6401. var directive = $injector.invoke(directiveFactory);
  6402. if (isFunction(directive)) {
  6403. directive = { compile: valueFn(directive) };
  6404. } else if (!directive.compile && directive.link) {
  6405. directive.compile = valueFn(directive.link);
  6406. }
  6407. directive.priority = directive.priority || 0;
  6408. directive.index = index;
  6409. directive.name = directive.name || name;
  6410. directive.require = directive.require || (directive.controller && directive.name);
  6411. directive.restrict = directive.restrict || 'EA';
  6412. var bindings = directive.$$bindings =
  6413. parseDirectiveBindings(directive, directive.name);
  6414. if (isObject(bindings.isolateScope)) {
  6415. directive.$$isolateBindings = bindings.isolateScope;
  6416. }
  6417. directive.$$moduleName = directiveFactory.$$moduleName;
  6418. directives.push(directive);
  6419. } catch (e) {
  6420. $exceptionHandler(e);
  6421. }
  6422. });
  6423. return directives;
  6424. }]);
  6425. }
  6426. hasDirectives[name].push(directiveFactory);
  6427. } else {
  6428. forEach(name, reverseParams(registerDirective));
  6429. }
  6430. return this;
  6431. };
  6432. /**
  6433. * @ngdoc method
  6434. * @name $compileProvider#aHrefSanitizationWhitelist
  6435. * @kind function
  6436. *
  6437. * @description
  6438. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  6439. * urls during a[href] sanitization.
  6440. *
  6441. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  6442. *
  6443. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  6444. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  6445. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  6446. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  6447. *
  6448. * @param {RegExp=} regexp New regexp to whitelist urls with.
  6449. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  6450. * chaining otherwise.
  6451. */
  6452. this.aHrefSanitizationWhitelist = function(regexp) {
  6453. if (isDefined(regexp)) {
  6454. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  6455. return this;
  6456. } else {
  6457. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  6458. }
  6459. };
  6460. /**
  6461. * @ngdoc method
  6462. * @name $compileProvider#imgSrcSanitizationWhitelist
  6463. * @kind function
  6464. *
  6465. * @description
  6466. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  6467. * urls during img[src] sanitization.
  6468. *
  6469. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  6470. *
  6471. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  6472. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  6473. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  6474. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  6475. *
  6476. * @param {RegExp=} regexp New regexp to whitelist urls with.
  6477. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  6478. * chaining otherwise.
  6479. */
  6480. this.imgSrcSanitizationWhitelist = function(regexp) {
  6481. if (isDefined(regexp)) {
  6482. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  6483. return this;
  6484. } else {
  6485. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  6486. }
  6487. };
  6488. /**
  6489. * @ngdoc method
  6490. * @name $compileProvider#debugInfoEnabled
  6491. *
  6492. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  6493. * current debugInfoEnabled state
  6494. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  6495. *
  6496. * @kind function
  6497. *
  6498. * @description
  6499. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  6500. * binding information and a reference to the current scope on to DOM elements.
  6501. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  6502. * * `ng-binding` CSS class
  6503. * * `$binding` data property containing an array of the binding expressions
  6504. *
  6505. * You may want to disable this in production for a significant performance boost. See
  6506. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  6507. *
  6508. * The default value is true.
  6509. */
  6510. var debugInfoEnabled = true;
  6511. this.debugInfoEnabled = function(enabled) {
  6512. if (isDefined(enabled)) {
  6513. debugInfoEnabled = enabled;
  6514. return this;
  6515. }
  6516. return debugInfoEnabled;
  6517. };
  6518. this.$get = [
  6519. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  6520. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  6521. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  6522. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  6523. var Attributes = function(element, attributesToCopy) {
  6524. if (attributesToCopy) {
  6525. var keys = Object.keys(attributesToCopy);
  6526. var i, l, key;
  6527. for (i = 0, l = keys.length; i < l; i++) {
  6528. key = keys[i];
  6529. this[key] = attributesToCopy[key];
  6530. }
  6531. } else {
  6532. this.$attr = {};
  6533. }
  6534. this.$$element = element;
  6535. };
  6536. Attributes.prototype = {
  6537. /**
  6538. * @ngdoc method
  6539. * @name $compile.directive.Attributes#$normalize
  6540. * @kind function
  6541. *
  6542. * @description
  6543. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  6544. * `data-`) to its normalized, camelCase form.
  6545. *
  6546. * Also there is special case for Moz prefix starting with upper case letter.
  6547. *
  6548. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  6549. *
  6550. * @param {string} name Name to normalize
  6551. */
  6552. $normalize: directiveNormalize,
  6553. /**
  6554. * @ngdoc method
  6555. * @name $compile.directive.Attributes#$addClass
  6556. * @kind function
  6557. *
  6558. * @description
  6559. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  6560. * are enabled then an animation will be triggered for the class addition.
  6561. *
  6562. * @param {string} classVal The className value that will be added to the element
  6563. */
  6564. $addClass: function(classVal) {
  6565. if (classVal && classVal.length > 0) {
  6566. $animate.addClass(this.$$element, classVal);
  6567. }
  6568. },
  6569. /**
  6570. * @ngdoc method
  6571. * @name $compile.directive.Attributes#$removeClass
  6572. * @kind function
  6573. *
  6574. * @description
  6575. * Removes the CSS class value specified by the classVal parameter from the element. If
  6576. * animations are enabled then an animation will be triggered for the class removal.
  6577. *
  6578. * @param {string} classVal The className value that will be removed from the element
  6579. */
  6580. $removeClass: function(classVal) {
  6581. if (classVal && classVal.length > 0) {
  6582. $animate.removeClass(this.$$element, classVal);
  6583. }
  6584. },
  6585. /**
  6586. * @ngdoc method
  6587. * @name $compile.directive.Attributes#$updateClass
  6588. * @kind function
  6589. *
  6590. * @description
  6591. * Adds and removes the appropriate CSS class values to the element based on the difference
  6592. * between the new and old CSS class values (specified as newClasses and oldClasses).
  6593. *
  6594. * @param {string} newClasses The current CSS className value
  6595. * @param {string} oldClasses The former CSS className value
  6596. */
  6597. $updateClass: function(newClasses, oldClasses) {
  6598. var toAdd = tokenDifference(newClasses, oldClasses);
  6599. if (toAdd && toAdd.length) {
  6600. $animate.addClass(this.$$element, toAdd);
  6601. }
  6602. var toRemove = tokenDifference(oldClasses, newClasses);
  6603. if (toRemove && toRemove.length) {
  6604. $animate.removeClass(this.$$element, toRemove);
  6605. }
  6606. },
  6607. /**
  6608. * Set a normalized attribute on the element in a way such that all directives
  6609. * can share the attribute. This function properly handles boolean attributes.
  6610. * @param {string} key Normalized key. (ie ngAttribute)
  6611. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  6612. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  6613. * Defaults to true.
  6614. * @param {string=} attrName Optional none normalized name. Defaults to key.
  6615. */
  6616. $set: function(key, value, writeAttr, attrName) {
  6617. // TODO: decide whether or not to throw an error if "class"
  6618. //is set through this function since it may cause $updateClass to
  6619. //become unstable.
  6620. var node = this.$$element[0],
  6621. booleanKey = getBooleanAttrName(node, key),
  6622. aliasedKey = getAliasedAttrName(node, key),
  6623. observer = key,
  6624. nodeName;
  6625. if (booleanKey) {
  6626. this.$$element.prop(key, value);
  6627. attrName = booleanKey;
  6628. } else if (aliasedKey) {
  6629. this[aliasedKey] = value;
  6630. observer = aliasedKey;
  6631. }
  6632. this[key] = value;
  6633. // translate normalized key to actual key
  6634. if (attrName) {
  6635. this.$attr[key] = attrName;
  6636. } else {
  6637. attrName = this.$attr[key];
  6638. if (!attrName) {
  6639. this.$attr[key] = attrName = snake_case(key, '-');
  6640. }
  6641. }
  6642. nodeName = nodeName_(this.$$element);
  6643. if ((nodeName === 'a' && key === 'href') ||
  6644. (nodeName === 'img' && key === 'src')) {
  6645. // sanitize a[href] and img[src] values
  6646. this[key] = value = $$sanitizeUri(value, key === 'src');
  6647. } else if (nodeName === 'img' && key === 'srcset') {
  6648. // sanitize img[srcset] values
  6649. var result = "";
  6650. // first check if there are spaces because it's not the same pattern
  6651. var trimmedSrcset = trim(value);
  6652. // ( 999x ,| 999w ,| ,|, )
  6653. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  6654. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  6655. // split srcset into tuple of uri and descriptor except for the last item
  6656. var rawUris = trimmedSrcset.split(pattern);
  6657. // for each tuples
  6658. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  6659. for (var i = 0; i < nbrUrisWith2parts; i++) {
  6660. var innerIdx = i * 2;
  6661. // sanitize the uri
  6662. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  6663. // add the descriptor
  6664. result += (" " + trim(rawUris[innerIdx + 1]));
  6665. }
  6666. // split the last item into uri and descriptor
  6667. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  6668. // sanitize the last uri
  6669. result += $$sanitizeUri(trim(lastTuple[0]), true);
  6670. // and add the last descriptor if any
  6671. if (lastTuple.length === 2) {
  6672. result += (" " + trim(lastTuple[1]));
  6673. }
  6674. this[key] = value = result;
  6675. }
  6676. if (writeAttr !== false) {
  6677. if (value === null || value === undefined) {
  6678. this.$$element.removeAttr(attrName);
  6679. } else {
  6680. this.$$element.attr(attrName, value);
  6681. }
  6682. }
  6683. // fire observers
  6684. var $$observers = this.$$observers;
  6685. $$observers && forEach($$observers[observer], function(fn) {
  6686. try {
  6687. fn(value);
  6688. } catch (e) {
  6689. $exceptionHandler(e);
  6690. }
  6691. });
  6692. },
  6693. /**
  6694. * @ngdoc method
  6695. * @name $compile.directive.Attributes#$observe
  6696. * @kind function
  6697. *
  6698. * @description
  6699. * Observes an interpolated attribute.
  6700. *
  6701. * The observer function will be invoked once during the next `$digest` following
  6702. * compilation. The observer is then invoked whenever the interpolated value
  6703. * changes.
  6704. *
  6705. * @param {string} key Normalized key. (ie ngAttribute) .
  6706. * @param {function(interpolatedValue)} fn Function that will be called whenever
  6707. the interpolated value of the attribute changes.
  6708. * See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.
  6709. * @returns {function()} Returns a deregistration function for this observer.
  6710. */
  6711. $observe: function(key, fn) {
  6712. var attrs = this,
  6713. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  6714. listeners = ($$observers[key] || ($$observers[key] = []));
  6715. listeners.push(fn);
  6716. $rootScope.$evalAsync(function() {
  6717. if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
  6718. // no one registered attribute interpolation function, so lets call it manually
  6719. fn(attrs[key]);
  6720. }
  6721. });
  6722. return function() {
  6723. arrayRemove(listeners, fn);
  6724. };
  6725. }
  6726. };
  6727. function safeAddClass($element, className) {
  6728. try {
  6729. $element.addClass(className);
  6730. } catch (e) {
  6731. // ignore, since it means that we are trying to set class on
  6732. // SVG element, where class name is read-only.
  6733. }
  6734. }
  6735. var startSymbol = $interpolate.startSymbol(),
  6736. endSymbol = $interpolate.endSymbol(),
  6737. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  6738. ? identity
  6739. : function denormalizeTemplate(template) {
  6740. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  6741. },
  6742. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  6743. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  6744. var bindings = $element.data('$binding') || [];
  6745. if (isArray(binding)) {
  6746. bindings = bindings.concat(binding);
  6747. } else {
  6748. bindings.push(binding);
  6749. }
  6750. $element.data('$binding', bindings);
  6751. } : noop;
  6752. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  6753. safeAddClass($element, 'ng-binding');
  6754. } : noop;
  6755. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  6756. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  6757. $element.data(dataName, scope);
  6758. } : noop;
  6759. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  6760. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  6761. } : noop;
  6762. return compile;
  6763. //================================
  6764. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  6765. previousCompileContext) {
  6766. if (!($compileNodes instanceof jqLite)) {
  6767. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  6768. // modify it.
  6769. $compileNodes = jqLite($compileNodes);
  6770. }
  6771. // We can not compile top level text elements since text nodes can be merged and we will
  6772. // not be able to attach scope data to them, so we will wrap them in <span>
  6773. forEach($compileNodes, function(node, index) {
  6774. if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  6775. $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
  6776. }
  6777. });
  6778. var compositeLinkFn =
  6779. compileNodes($compileNodes, transcludeFn, $compileNodes,
  6780. maxPriority, ignoreDirective, previousCompileContext);
  6781. compile.$$addScopeClass($compileNodes);
  6782. var namespace = null;
  6783. return function publicLinkFn(scope, cloneConnectFn, options) {
  6784. assertArg(scope, 'scope');
  6785. options = options || {};
  6786. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  6787. transcludeControllers = options.transcludeControllers,
  6788. futureParentElement = options.futureParentElement;
  6789. // When `parentBoundTranscludeFn` is passed, it is a
  6790. // `controllersBoundTransclude` function (it was previously passed
  6791. // as `transclude` to directive.link) so we must unwrap it to get
  6792. // its `boundTranscludeFn`
  6793. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  6794. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  6795. }
  6796. if (!namespace) {
  6797. namespace = detectNamespaceForChildElements(futureParentElement);
  6798. }
  6799. var $linkNode;
  6800. if (namespace !== 'html') {
  6801. // When using a directive with replace:true and templateUrl the $compileNodes
  6802. // (or a child element inside of them)
  6803. // might change, so we need to recreate the namespace adapted compileNodes
  6804. // for call to the link function.
  6805. // Note: This will already clone the nodes...
  6806. $linkNode = jqLite(
  6807. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  6808. );
  6809. } else if (cloneConnectFn) {
  6810. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  6811. // and sometimes changes the structure of the DOM.
  6812. $linkNode = JQLitePrototype.clone.call($compileNodes);
  6813. } else {
  6814. $linkNode = $compileNodes;
  6815. }
  6816. if (transcludeControllers) {
  6817. for (var controllerName in transcludeControllers) {
  6818. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  6819. }
  6820. }
  6821. compile.$$addScopeInfo($linkNode, scope);
  6822. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  6823. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  6824. return $linkNode;
  6825. };
  6826. }
  6827. function detectNamespaceForChildElements(parentElement) {
  6828. // TODO: Make this detect MathML as well...
  6829. var node = parentElement && parentElement[0];
  6830. if (!node) {
  6831. return 'html';
  6832. } else {
  6833. return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';
  6834. }
  6835. }
  6836. /**
  6837. * Compile function matches each node in nodeList against the directives. Once all directives
  6838. * for a particular node are collected their compile functions are executed. The compile
  6839. * functions return values - the linking functions - are combined into a composite linking
  6840. * function, which is the a linking function for the node.
  6841. *
  6842. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  6843. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  6844. * scope argument is auto-generated to the new child of the transcluded parent scope.
  6845. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  6846. * the rootElement must be set the jqLite collection of the compile root. This is
  6847. * needed so that the jqLite collection items can be replaced with widgets.
  6848. * @param {number=} maxPriority Max directive priority.
  6849. * @returns {Function} A composite linking function of all of the matched directives or null.
  6850. */
  6851. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  6852. previousCompileContext) {
  6853. var linkFns = [],
  6854. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  6855. for (var i = 0; i < nodeList.length; i++) {
  6856. attrs = new Attributes();
  6857. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  6858. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  6859. ignoreDirective);
  6860. nodeLinkFn = (directives.length)
  6861. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  6862. null, [], [], previousCompileContext)
  6863. : null;
  6864. if (nodeLinkFn && nodeLinkFn.scope) {
  6865. compile.$$addScopeClass(attrs.$$element);
  6866. }
  6867. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  6868. !(childNodes = nodeList[i].childNodes) ||
  6869. !childNodes.length)
  6870. ? null
  6871. : compileNodes(childNodes,
  6872. nodeLinkFn ? (
  6873. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  6874. && nodeLinkFn.transclude) : transcludeFn);
  6875. if (nodeLinkFn || childLinkFn) {
  6876. linkFns.push(i, nodeLinkFn, childLinkFn);
  6877. linkFnFound = true;
  6878. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  6879. }
  6880. //use the previous context only for the first element in the virtual group
  6881. previousCompileContext = null;
  6882. }
  6883. // return a linking function if we have found anything, null otherwise
  6884. return linkFnFound ? compositeLinkFn : null;
  6885. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  6886. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  6887. var stableNodeList;
  6888. if (nodeLinkFnFound) {
  6889. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  6890. // offsets don't get screwed up
  6891. var nodeListLength = nodeList.length;
  6892. stableNodeList = new Array(nodeListLength);
  6893. // create a sparse array by only copying the elements which have a linkFn
  6894. for (i = 0; i < linkFns.length; i+=3) {
  6895. idx = linkFns[i];
  6896. stableNodeList[idx] = nodeList[idx];
  6897. }
  6898. } else {
  6899. stableNodeList = nodeList;
  6900. }
  6901. for (i = 0, ii = linkFns.length; i < ii;) {
  6902. node = stableNodeList[linkFns[i++]];
  6903. nodeLinkFn = linkFns[i++];
  6904. childLinkFn = linkFns[i++];
  6905. if (nodeLinkFn) {
  6906. if (nodeLinkFn.scope) {
  6907. childScope = scope.$new();
  6908. compile.$$addScopeInfo(jqLite(node), childScope);
  6909. var destroyBindings = nodeLinkFn.$$destroyBindings;
  6910. if (destroyBindings) {
  6911. nodeLinkFn.$$destroyBindings = null;
  6912. childScope.$on('$destroyed', destroyBindings);
  6913. }
  6914. } else {
  6915. childScope = scope;
  6916. }
  6917. if (nodeLinkFn.transcludeOnThisElement) {
  6918. childBoundTranscludeFn = createBoundTranscludeFn(
  6919. scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  6920. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  6921. childBoundTranscludeFn = parentBoundTranscludeFn;
  6922. } else if (!parentBoundTranscludeFn && transcludeFn) {
  6923. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  6924. } else {
  6925. childBoundTranscludeFn = null;
  6926. }
  6927. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn,
  6928. nodeLinkFn);
  6929. } else if (childLinkFn) {
  6930. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  6931. }
  6932. }
  6933. }
  6934. }
  6935. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  6936. var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  6937. if (!transcludedScope) {
  6938. transcludedScope = scope.$new(false, containingScope);
  6939. transcludedScope.$$transcluded = true;
  6940. }
  6941. return transcludeFn(transcludedScope, cloneFn, {
  6942. parentBoundTranscludeFn: previousBoundTranscludeFn,
  6943. transcludeControllers: controllers,
  6944. futureParentElement: futureParentElement
  6945. });
  6946. };
  6947. return boundTranscludeFn;
  6948. }
  6949. /**
  6950. * Looks for directives on the given node and adds them to the directive collection which is
  6951. * sorted.
  6952. *
  6953. * @param node Node to search.
  6954. * @param directives An array to which the directives are added to. This array is sorted before
  6955. * the function returns.
  6956. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  6957. * @param {number=} maxPriority Max directive priority.
  6958. */
  6959. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  6960. var nodeType = node.nodeType,
  6961. attrsMap = attrs.$attr,
  6962. match,
  6963. className;
  6964. switch (nodeType) {
  6965. case NODE_TYPE_ELEMENT: /* Element */
  6966. // use the node name: <directive>
  6967. addDirective(directives,
  6968. directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
  6969. // iterate over the attributes
  6970. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  6971. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  6972. var attrStartName = false;
  6973. var attrEndName = false;
  6974. attr = nAttrs[j];
  6975. name = attr.name;
  6976. value = trim(attr.value);
  6977. // support ngAttr attribute binding
  6978. ngAttrName = directiveNormalize(name);
  6979. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  6980. name = name.replace(PREFIX_REGEXP, '')
  6981. .substr(8).replace(/_(.)/g, function(match, letter) {
  6982. return letter.toUpperCase();
  6983. });
  6984. }
  6985. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  6986. if (directiveIsMultiElement(directiveNName)) {
  6987. if (ngAttrName === directiveNName + 'Start') {
  6988. attrStartName = name;
  6989. attrEndName = name.substr(0, name.length - 5) + 'end';
  6990. name = name.substr(0, name.length - 6);
  6991. }
  6992. }
  6993. nName = directiveNormalize(name.toLowerCase());
  6994. attrsMap[nName] = name;
  6995. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  6996. attrs[nName] = value;
  6997. if (getBooleanAttrName(node, nName)) {
  6998. attrs[nName] = true; // presence means true
  6999. }
  7000. }
  7001. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  7002. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  7003. attrEndName);
  7004. }
  7005. // use class as directive
  7006. className = node.className;
  7007. if (isObject(className)) {
  7008. // Maybe SVGAnimatedString
  7009. className = className.animVal;
  7010. }
  7011. if (isString(className) && className !== '') {
  7012. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  7013. nName = directiveNormalize(match[2]);
  7014. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  7015. attrs[nName] = trim(match[3]);
  7016. }
  7017. className = className.substr(match.index + match[0].length);
  7018. }
  7019. }
  7020. break;
  7021. case NODE_TYPE_TEXT: /* Text Node */
  7022. if (msie === 11) {
  7023. // Workaround for #11781
  7024. while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {
  7025. node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
  7026. node.parentNode.removeChild(node.nextSibling);
  7027. }
  7028. }
  7029. addTextInterpolateDirective(directives, node.nodeValue);
  7030. break;
  7031. case NODE_TYPE_COMMENT: /* Comment */
  7032. try {
  7033. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  7034. if (match) {
  7035. nName = directiveNormalize(match[1]);
  7036. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  7037. attrs[nName] = trim(match[2]);
  7038. }
  7039. }
  7040. } catch (e) {
  7041. // turns out that under some circumstances IE9 throws errors when one attempts to read
  7042. // comment's node value.
  7043. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  7044. }
  7045. break;
  7046. }
  7047. directives.sort(byPriority);
  7048. return directives;
  7049. }
  7050. /**
  7051. * Given a node with an directive-start it collects all of the siblings until it finds
  7052. * directive-end.
  7053. * @param node
  7054. * @param attrStart
  7055. * @param attrEnd
  7056. * @returns {*}
  7057. */
  7058. function groupScan(node, attrStart, attrEnd) {
  7059. var nodes = [];
  7060. var depth = 0;
  7061. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  7062. do {
  7063. if (!node) {
  7064. throw $compileMinErr('uterdir',
  7065. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  7066. attrStart, attrEnd);
  7067. }
  7068. if (node.nodeType == NODE_TYPE_ELEMENT) {
  7069. if (node.hasAttribute(attrStart)) depth++;
  7070. if (node.hasAttribute(attrEnd)) depth--;
  7071. }
  7072. nodes.push(node);
  7073. node = node.nextSibling;
  7074. } while (depth > 0);
  7075. } else {
  7076. nodes.push(node);
  7077. }
  7078. return jqLite(nodes);
  7079. }
  7080. /**
  7081. * Wrapper for linking function which converts normal linking function into a grouped
  7082. * linking function.
  7083. * @param linkFn
  7084. * @param attrStart
  7085. * @param attrEnd
  7086. * @returns {Function}
  7087. */
  7088. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  7089. return function(scope, element, attrs, controllers, transcludeFn) {
  7090. element = groupScan(element[0], attrStart, attrEnd);
  7091. return linkFn(scope, element, attrs, controllers, transcludeFn);
  7092. };
  7093. }
  7094. /**
  7095. * Once the directives have been collected, their compile functions are executed. This method
  7096. * is responsible for inlining directive templates as well as terminating the application
  7097. * of the directives if the terminal directive has been reached.
  7098. *
  7099. * @param {Array} directives Array of collected directives to execute their compile function.
  7100. * this needs to be pre-sorted by priority order.
  7101. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  7102. * @param {Object} templateAttrs The shared attribute function
  7103. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  7104. * scope argument is auto-generated to the new
  7105. * child of the transcluded parent scope.
  7106. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  7107. * argument has the root jqLite array so that we can replace nodes
  7108. * on it.
  7109. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  7110. * compiling the transclusion.
  7111. * @param {Array.<Function>} preLinkFns
  7112. * @param {Array.<Function>} postLinkFns
  7113. * @param {Object} previousCompileContext Context used for previous compilation of the current
  7114. * node
  7115. * @returns {Function} linkFn
  7116. */
  7117. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  7118. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  7119. previousCompileContext) {
  7120. previousCompileContext = previousCompileContext || {};
  7121. var terminalPriority = -Number.MAX_VALUE,
  7122. newScopeDirective = previousCompileContext.newScopeDirective,
  7123. controllerDirectives = previousCompileContext.controllerDirectives,
  7124. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  7125. templateDirective = previousCompileContext.templateDirective,
  7126. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  7127. hasTranscludeDirective = false,
  7128. hasTemplate = false,
  7129. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  7130. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  7131. directive,
  7132. directiveName,
  7133. $template,
  7134. replaceDirective = originalReplaceDirective,
  7135. childTranscludeFn = transcludeFn,
  7136. linkFn,
  7137. directiveValue;
  7138. // executes all directives on the current element
  7139. for (var i = 0, ii = directives.length; i < ii; i++) {
  7140. directive = directives[i];
  7141. var attrStart = directive.$$start;
  7142. var attrEnd = directive.$$end;
  7143. // collect multiblock sections
  7144. if (attrStart) {
  7145. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  7146. }
  7147. $template = undefined;
  7148. if (terminalPriority > directive.priority) {
  7149. break; // prevent further processing of directives
  7150. }
  7151. if (directiveValue = directive.scope) {
  7152. // skip the check for directives with async templates, we'll check the derived sync
  7153. // directive when the template arrives
  7154. if (!directive.templateUrl) {
  7155. if (isObject(directiveValue)) {
  7156. // This directive is trying to add an isolated scope.
  7157. // Check that there is no scope of any kind already
  7158. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  7159. directive, $compileNode);
  7160. newIsolateScopeDirective = directive;
  7161. } else {
  7162. // This directive is trying to add a child scope.
  7163. // Check that there is no isolated scope already
  7164. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  7165. $compileNode);
  7166. }
  7167. }
  7168. newScopeDirective = newScopeDirective || directive;
  7169. }
  7170. directiveName = directive.name;
  7171. if (!directive.templateUrl && directive.controller) {
  7172. directiveValue = directive.controller;
  7173. controllerDirectives = controllerDirectives || createMap();
  7174. assertNoDuplicate("'" + directiveName + "' controller",
  7175. controllerDirectives[directiveName], directive, $compileNode);
  7176. controllerDirectives[directiveName] = directive;
  7177. }
  7178. if (directiveValue = directive.transclude) {
  7179. hasTranscludeDirective = true;
  7180. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  7181. // This option should only be used by directives that know how to safely handle element transclusion,
  7182. // where the transcluded nodes are added or replaced after linking.
  7183. if (!directive.$$tlb) {
  7184. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  7185. nonTlbTranscludeDirective = directive;
  7186. }
  7187. if (directiveValue == 'element') {
  7188. hasElementTranscludeDirective = true;
  7189. terminalPriority = directive.priority;
  7190. $template = $compileNode;
  7191. $compileNode = templateAttrs.$$element =
  7192. jqLite(document.createComment(' ' + directiveName + ': ' +
  7193. templateAttrs[directiveName] + ' '));
  7194. compileNode = $compileNode[0];
  7195. replaceWith(jqCollection, sliceArgs($template), compileNode);
  7196. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  7197. replaceDirective && replaceDirective.name, {
  7198. // Don't pass in:
  7199. // - controllerDirectives - otherwise we'll create duplicates controllers
  7200. // - newIsolateScopeDirective or templateDirective - combining templates with
  7201. // element transclusion doesn't make sense.
  7202. //
  7203. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  7204. // on the same element more than once.
  7205. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  7206. });
  7207. } else {
  7208. $template = jqLite(jqLiteClone(compileNode)).contents();
  7209. $compileNode.empty(); // clear contents
  7210. childTranscludeFn = compile($template, transcludeFn);
  7211. }
  7212. }
  7213. if (directive.template) {
  7214. hasTemplate = true;
  7215. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  7216. templateDirective = directive;
  7217. directiveValue = (isFunction(directive.template))
  7218. ? directive.template($compileNode, templateAttrs)
  7219. : directive.template;
  7220. directiveValue = denormalizeTemplate(directiveValue);
  7221. if (directive.replace) {
  7222. replaceDirective = directive;
  7223. if (jqLiteIsTextNode(directiveValue)) {
  7224. $template = [];
  7225. } else {
  7226. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  7227. }
  7228. compileNode = $template[0];
  7229. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7230. throw $compileMinErr('tplrt',
  7231. "Template for directive '{0}' must have exactly one root element. {1}",
  7232. directiveName, '');
  7233. }
  7234. replaceWith(jqCollection, $compileNode, compileNode);
  7235. var newTemplateAttrs = {$attr: {}};
  7236. // combine directives from the original node and from the template:
  7237. // - take the array of directives for this element
  7238. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  7239. // - collect directives from the template and sort them by priority
  7240. // - combine directives as: processed + template + unprocessed
  7241. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  7242. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  7243. if (newIsolateScopeDirective) {
  7244. markDirectivesAsIsolate(templateDirectives);
  7245. }
  7246. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  7247. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  7248. ii = directives.length;
  7249. } else {
  7250. $compileNode.html(directiveValue);
  7251. }
  7252. }
  7253. if (directive.templateUrl) {
  7254. hasTemplate = true;
  7255. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  7256. templateDirective = directive;
  7257. if (directive.replace) {
  7258. replaceDirective = directive;
  7259. }
  7260. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  7261. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  7262. controllerDirectives: controllerDirectives,
  7263. newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
  7264. newIsolateScopeDirective: newIsolateScopeDirective,
  7265. templateDirective: templateDirective,
  7266. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  7267. });
  7268. ii = directives.length;
  7269. } else if (directive.compile) {
  7270. try {
  7271. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  7272. if (isFunction(linkFn)) {
  7273. addLinkFns(null, linkFn, attrStart, attrEnd);
  7274. } else if (linkFn) {
  7275. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  7276. }
  7277. } catch (e) {
  7278. $exceptionHandler(e, startingTag($compileNode));
  7279. }
  7280. }
  7281. if (directive.terminal) {
  7282. nodeLinkFn.terminal = true;
  7283. terminalPriority = Math.max(terminalPriority, directive.priority);
  7284. }
  7285. }
  7286. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  7287. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  7288. nodeLinkFn.templateOnThisElement = hasTemplate;
  7289. nodeLinkFn.transclude = childTranscludeFn;
  7290. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  7291. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  7292. return nodeLinkFn;
  7293. ////////////////////
  7294. function addLinkFns(pre, post, attrStart, attrEnd) {
  7295. if (pre) {
  7296. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  7297. pre.require = directive.require;
  7298. pre.directiveName = directiveName;
  7299. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  7300. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  7301. }
  7302. preLinkFns.push(pre);
  7303. }
  7304. if (post) {
  7305. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  7306. post.require = directive.require;
  7307. post.directiveName = directiveName;
  7308. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  7309. post = cloneAndAnnotateFn(post, {isolateScope: true});
  7310. }
  7311. postLinkFns.push(post);
  7312. }
  7313. }
  7314. function getControllers(directiveName, require, $element, elementControllers) {
  7315. var value;
  7316. if (isString(require)) {
  7317. var match = require.match(REQUIRE_PREFIX_REGEXP);
  7318. var name = require.substring(match[0].length);
  7319. var inheritType = match[1] || match[3];
  7320. var optional = match[2] === '?';
  7321. //If only parents then start at the parent element
  7322. if (inheritType === '^^') {
  7323. $element = $element.parent();
  7324. //Otherwise attempt getting the controller from elementControllers in case
  7325. //the element is transcluded (and has no data) and to avoid .data if possible
  7326. } else {
  7327. value = elementControllers && elementControllers[name];
  7328. value = value && value.instance;
  7329. }
  7330. if (!value) {
  7331. var dataName = '$' + name + 'Controller';
  7332. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  7333. }
  7334. if (!value && !optional) {
  7335. throw $compileMinErr('ctreq',
  7336. "Controller '{0}', required by directive '{1}', can't be found!",
  7337. name, directiveName);
  7338. }
  7339. } else if (isArray(require)) {
  7340. value = [];
  7341. for (var i = 0, ii = require.length; i < ii; i++) {
  7342. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  7343. }
  7344. }
  7345. return value || null;
  7346. }
  7347. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
  7348. var elementControllers = createMap();
  7349. for (var controllerKey in controllerDirectives) {
  7350. var directive = controllerDirectives[controllerKey];
  7351. var locals = {
  7352. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  7353. $element: $element,
  7354. $attrs: attrs,
  7355. $transclude: transcludeFn
  7356. };
  7357. var controller = directive.controller;
  7358. if (controller == '@') {
  7359. controller = attrs[directive.name];
  7360. }
  7361. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  7362. // For directives with element transclusion the element is a comment,
  7363. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  7364. // clean up (http://bugs.jquery.com/ticket/8335).
  7365. // Instead, we save the controllers for the element in a local hash and attach to .data
  7366. // later, once we have the actual element.
  7367. elementControllers[directive.name] = controllerInstance;
  7368. if (!hasElementTranscludeDirective) {
  7369. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  7370. }
  7371. }
  7372. return elementControllers;
  7373. }
  7374. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn,
  7375. thisLinkFn) {
  7376. var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element,
  7377. attrs;
  7378. if (compileNode === linkNode) {
  7379. attrs = templateAttrs;
  7380. $element = templateAttrs.$$element;
  7381. } else {
  7382. $element = jqLite(linkNode);
  7383. attrs = new Attributes($element, templateAttrs);
  7384. }
  7385. if (newIsolateScopeDirective) {
  7386. isolateScope = scope.$new(true);
  7387. }
  7388. if (boundTranscludeFn) {
  7389. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  7390. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  7391. transcludeFn = controllersBoundTransclude;
  7392. transcludeFn.$$boundTransclude = boundTranscludeFn;
  7393. }
  7394. if (controllerDirectives) {
  7395. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope);
  7396. }
  7397. if (newIsolateScopeDirective) {
  7398. // Initialize isolate scope bindings for new isolate scope directive.
  7399. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  7400. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  7401. compile.$$addScopeClass($element, true);
  7402. isolateScope.$$isolateBindings =
  7403. newIsolateScopeDirective.$$isolateBindings;
  7404. initializeDirectiveBindings(scope, attrs, isolateScope,
  7405. isolateScope.$$isolateBindings,
  7406. newIsolateScopeDirective, isolateScope);
  7407. }
  7408. if (elementControllers) {
  7409. // Initialize bindToController bindings for new/isolate scopes
  7410. var scopeDirective = newIsolateScopeDirective || newScopeDirective;
  7411. var bindings;
  7412. var controllerForBindings;
  7413. if (scopeDirective && elementControllers[scopeDirective.name]) {
  7414. bindings = scopeDirective.$$bindings.bindToController;
  7415. controller = elementControllers[scopeDirective.name];
  7416. if (controller && controller.identifier && bindings) {
  7417. controllerForBindings = controller;
  7418. thisLinkFn.$$destroyBindings =
  7419. initializeDirectiveBindings(scope, attrs, controller.instance,
  7420. bindings, scopeDirective);
  7421. }
  7422. }
  7423. for (i in elementControllers) {
  7424. controller = elementControllers[i];
  7425. var controllerResult = controller();
  7426. if (controllerResult !== controller.instance) {
  7427. // If the controller constructor has a return value, overwrite the instance
  7428. // from setupControllers and update the element data
  7429. controller.instance = controllerResult;
  7430. $element.data('$' + i + 'Controller', controllerResult);
  7431. if (controller === controllerForBindings) {
  7432. // Remove and re-install bindToController bindings
  7433. thisLinkFn.$$destroyBindings();
  7434. thisLinkFn.$$destroyBindings =
  7435. initializeDirectiveBindings(scope, attrs, controllerResult, bindings, scopeDirective);
  7436. }
  7437. }
  7438. }
  7439. }
  7440. // PRELINKING
  7441. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  7442. linkFn = preLinkFns[i];
  7443. invokeLinkFn(linkFn,
  7444. linkFn.isolateScope ? isolateScope : scope,
  7445. $element,
  7446. attrs,
  7447. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  7448. transcludeFn
  7449. );
  7450. }
  7451. // RECURSION
  7452. // We only pass the isolate scope, if the isolate directive has a template,
  7453. // otherwise the child elements do not belong to the isolate directive.
  7454. var scopeToChild = scope;
  7455. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  7456. scopeToChild = isolateScope;
  7457. }
  7458. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  7459. // POSTLINKING
  7460. for (i = postLinkFns.length - 1; i >= 0; i--) {
  7461. linkFn = postLinkFns[i];
  7462. invokeLinkFn(linkFn,
  7463. linkFn.isolateScope ? isolateScope : scope,
  7464. $element,
  7465. attrs,
  7466. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  7467. transcludeFn
  7468. );
  7469. }
  7470. // This is the function that is injected as `$transclude`.
  7471. // Note: all arguments are optional!
  7472. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {
  7473. var transcludeControllers;
  7474. // No scope passed in:
  7475. if (!isScope(scope)) {
  7476. futureParentElement = cloneAttachFn;
  7477. cloneAttachFn = scope;
  7478. scope = undefined;
  7479. }
  7480. if (hasElementTranscludeDirective) {
  7481. transcludeControllers = elementControllers;
  7482. }
  7483. if (!futureParentElement) {
  7484. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  7485. }
  7486. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  7487. }
  7488. }
  7489. }
  7490. function markDirectivesAsIsolate(directives) {
  7491. // mark all directives as needing isolate scope.
  7492. for (var j = 0, jj = directives.length; j < jj; j++) {
  7493. directives[j] = inherit(directives[j], {$$isolateScope: true});
  7494. }
  7495. }
  7496. /**
  7497. * looks up the directive and decorates it with exception handling and proper parameters. We
  7498. * call this the boundDirective.
  7499. *
  7500. * @param {string} name name of the directive to look up.
  7501. * @param {string} location The directive must be found in specific format.
  7502. * String containing any of theses characters:
  7503. *
  7504. * * `E`: element name
  7505. * * `A': attribute
  7506. * * `C`: class
  7507. * * `M`: comment
  7508. * @returns {boolean} true if directive was added.
  7509. */
  7510. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  7511. endAttrName) {
  7512. if (name === ignoreDirective) return null;
  7513. var match = null;
  7514. if (hasDirectives.hasOwnProperty(name)) {
  7515. for (var directive, directives = $injector.get(name + Suffix),
  7516. i = 0, ii = directives.length; i < ii; i++) {
  7517. try {
  7518. directive = directives[i];
  7519. if ((maxPriority === undefined || maxPriority > directive.priority) &&
  7520. directive.restrict.indexOf(location) != -1) {
  7521. if (startAttrName) {
  7522. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  7523. }
  7524. tDirectives.push(directive);
  7525. match = directive;
  7526. }
  7527. } catch (e) { $exceptionHandler(e); }
  7528. }
  7529. }
  7530. return match;
  7531. }
  7532. /**
  7533. * looks up the directive and returns true if it is a multi-element directive,
  7534. * and therefore requires DOM nodes between -start and -end markers to be grouped
  7535. * together.
  7536. *
  7537. * @param {string} name name of the directive to look up.
  7538. * @returns true if directive was registered as multi-element.
  7539. */
  7540. function directiveIsMultiElement(name) {
  7541. if (hasDirectives.hasOwnProperty(name)) {
  7542. for (var directive, directives = $injector.get(name + Suffix),
  7543. i = 0, ii = directives.length; i < ii; i++) {
  7544. directive = directives[i];
  7545. if (directive.multiElement) {
  7546. return true;
  7547. }
  7548. }
  7549. }
  7550. return false;
  7551. }
  7552. /**
  7553. * When the element is replaced with HTML template then the new attributes
  7554. * on the template need to be merged with the existing attributes in the DOM.
  7555. * The desired effect is to have both of the attributes present.
  7556. *
  7557. * @param {object} dst destination attributes (original DOM)
  7558. * @param {object} src source attributes (from the directive template)
  7559. */
  7560. function mergeTemplateAttributes(dst, src) {
  7561. var srcAttr = src.$attr,
  7562. dstAttr = dst.$attr,
  7563. $element = dst.$$element;
  7564. // reapply the old attributes to the new element
  7565. forEach(dst, function(value, key) {
  7566. if (key.charAt(0) != '$') {
  7567. if (src[key] && src[key] !== value) {
  7568. value += (key === 'style' ? ';' : ' ') + src[key];
  7569. }
  7570. dst.$set(key, value, true, srcAttr[key]);
  7571. }
  7572. });
  7573. // copy the new attributes on the old attrs object
  7574. forEach(src, function(value, key) {
  7575. if (key == 'class') {
  7576. safeAddClass($element, value);
  7577. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  7578. } else if (key == 'style') {
  7579. $element.attr('style', $element.attr('style') + ';' + value);
  7580. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  7581. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  7582. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  7583. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  7584. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  7585. dst[key] = value;
  7586. dstAttr[key] = srcAttr[key];
  7587. }
  7588. });
  7589. }
  7590. function compileTemplateUrl(directives, $compileNode, tAttrs,
  7591. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  7592. var linkQueue = [],
  7593. afterTemplateNodeLinkFn,
  7594. afterTemplateChildLinkFn,
  7595. beforeTemplateCompileNode = $compileNode[0],
  7596. origAsyncDirective = directives.shift(),
  7597. derivedSyncDirective = inherit(origAsyncDirective, {
  7598. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  7599. }),
  7600. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  7601. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  7602. : origAsyncDirective.templateUrl,
  7603. templateNamespace = origAsyncDirective.templateNamespace;
  7604. $compileNode.empty();
  7605. $templateRequest(templateUrl)
  7606. .then(function(content) {
  7607. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  7608. content = denormalizeTemplate(content);
  7609. if (origAsyncDirective.replace) {
  7610. if (jqLiteIsTextNode(content)) {
  7611. $template = [];
  7612. } else {
  7613. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  7614. }
  7615. compileNode = $template[0];
  7616. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7617. throw $compileMinErr('tplrt',
  7618. "Template for directive '{0}' must have exactly one root element. {1}",
  7619. origAsyncDirective.name, templateUrl);
  7620. }
  7621. tempTemplateAttrs = {$attr: {}};
  7622. replaceWith($rootElement, $compileNode, compileNode);
  7623. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  7624. if (isObject(origAsyncDirective.scope)) {
  7625. markDirectivesAsIsolate(templateDirectives);
  7626. }
  7627. directives = templateDirectives.concat(directives);
  7628. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  7629. } else {
  7630. compileNode = beforeTemplateCompileNode;
  7631. $compileNode.html(content);
  7632. }
  7633. directives.unshift(derivedSyncDirective);
  7634. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  7635. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  7636. previousCompileContext);
  7637. forEach($rootElement, function(node, i) {
  7638. if (node == compileNode) {
  7639. $rootElement[i] = $compileNode[0];
  7640. }
  7641. });
  7642. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  7643. while (linkQueue.length) {
  7644. var scope = linkQueue.shift(),
  7645. beforeTemplateLinkNode = linkQueue.shift(),
  7646. linkRootElement = linkQueue.shift(),
  7647. boundTranscludeFn = linkQueue.shift(),
  7648. linkNode = $compileNode[0];
  7649. if (scope.$$destroyed) continue;
  7650. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  7651. var oldClasses = beforeTemplateLinkNode.className;
  7652. if (!(previousCompileContext.hasElementTranscludeDirective &&
  7653. origAsyncDirective.replace)) {
  7654. // it was cloned therefore we have to clone as well.
  7655. linkNode = jqLiteClone(compileNode);
  7656. }
  7657. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  7658. // Copy in CSS classes from original node
  7659. safeAddClass(jqLite(linkNode), oldClasses);
  7660. }
  7661. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7662. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7663. } else {
  7664. childBoundTranscludeFn = boundTranscludeFn;
  7665. }
  7666. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  7667. childBoundTranscludeFn, afterTemplateNodeLinkFn);
  7668. }
  7669. linkQueue = null;
  7670. });
  7671. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  7672. var childBoundTranscludeFn = boundTranscludeFn;
  7673. if (scope.$$destroyed) return;
  7674. if (linkQueue) {
  7675. linkQueue.push(scope,
  7676. node,
  7677. rootElement,
  7678. childBoundTranscludeFn);
  7679. } else {
  7680. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7681. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7682. }
  7683. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn,
  7684. afterTemplateNodeLinkFn);
  7685. }
  7686. };
  7687. }
  7688. /**
  7689. * Sorting function for bound directives.
  7690. */
  7691. function byPriority(a, b) {
  7692. var diff = b.priority - a.priority;
  7693. if (diff !== 0) return diff;
  7694. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  7695. return a.index - b.index;
  7696. }
  7697. function assertNoDuplicate(what, previousDirective, directive, element) {
  7698. function wrapModuleNameIfDefined(moduleName) {
  7699. return moduleName ?
  7700. (' (module: ' + moduleName + ')') :
  7701. '';
  7702. }
  7703. if (previousDirective) {
  7704. throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
  7705. previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
  7706. directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
  7707. }
  7708. }
  7709. function addTextInterpolateDirective(directives, text) {
  7710. var interpolateFn = $interpolate(text, true);
  7711. if (interpolateFn) {
  7712. directives.push({
  7713. priority: 0,
  7714. compile: function textInterpolateCompileFn(templateNode) {
  7715. var templateNodeParent = templateNode.parent(),
  7716. hasCompileParent = !!templateNodeParent.length;
  7717. // When transcluding a template that has bindings in the root
  7718. // we don't have a parent and thus need to add the class during linking fn.
  7719. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  7720. return function textInterpolateLinkFn(scope, node) {
  7721. var parent = node.parent();
  7722. if (!hasCompileParent) compile.$$addBindingClass(parent);
  7723. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  7724. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  7725. node[0].nodeValue = value;
  7726. });
  7727. };
  7728. }
  7729. });
  7730. }
  7731. }
  7732. function wrapTemplate(type, template) {
  7733. type = lowercase(type || 'html');
  7734. switch (type) {
  7735. case 'svg':
  7736. case 'math':
  7737. var wrapper = document.createElement('div');
  7738. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  7739. return wrapper.childNodes[0].childNodes;
  7740. default:
  7741. return template;
  7742. }
  7743. }
  7744. function getTrustedContext(node, attrNormalizedName) {
  7745. if (attrNormalizedName == "srcdoc") {
  7746. return $sce.HTML;
  7747. }
  7748. var tag = nodeName_(node);
  7749. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  7750. if (attrNormalizedName == "xlinkHref" ||
  7751. (tag == "form" && attrNormalizedName == "action") ||
  7752. (tag != "img" && (attrNormalizedName == "src" ||
  7753. attrNormalizedName == "ngSrc"))) {
  7754. return $sce.RESOURCE_URL;
  7755. }
  7756. }
  7757. function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  7758. var trustedContext = getTrustedContext(node, name);
  7759. allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
  7760. var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
  7761. // no interpolation found -> ignore
  7762. if (!interpolateFn) return;
  7763. if (name === "multiple" && nodeName_(node) === "select") {
  7764. throw $compileMinErr("selmulti",
  7765. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  7766. startingTag(node));
  7767. }
  7768. directives.push({
  7769. priority: 100,
  7770. compile: function() {
  7771. return {
  7772. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  7773. var $$observers = (attr.$$observers || (attr.$$observers = {}));
  7774. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  7775. throw $compileMinErr('nodomevents',
  7776. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  7777. "ng- versions (such as ng-click instead of onclick) instead.");
  7778. }
  7779. // If the attribute has changed since last $interpolate()ed
  7780. var newValue = attr[name];
  7781. if (newValue !== value) {
  7782. // we need to interpolate again since the attribute value has been updated
  7783. // (e.g. by another directive's compile function)
  7784. // ensure unset/empty values make interpolateFn falsy
  7785. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  7786. value = newValue;
  7787. }
  7788. // if attribute was updated so that there is no interpolation going on we don't want to
  7789. // register any observers
  7790. if (!interpolateFn) return;
  7791. // initialize attr object so that it's ready in case we need the value for isolate
  7792. // scope initialization, otherwise the value would not be available from isolate
  7793. // directive's linking fn during linking phase
  7794. attr[name] = interpolateFn(scope);
  7795. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  7796. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  7797. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  7798. //special case for class attribute addition + removal
  7799. //so that class changes can tap into the animation
  7800. //hooks provided by the $animate service. Be sure to
  7801. //skip animations when the first digest occurs (when
  7802. //both the new and the old values are the same) since
  7803. //the CSS classes are the non-interpolated values
  7804. if (name === 'class' && newValue != oldValue) {
  7805. attr.$updateClass(newValue, oldValue);
  7806. } else {
  7807. attr.$set(name, newValue);
  7808. }
  7809. });
  7810. }
  7811. };
  7812. }
  7813. });
  7814. }
  7815. /**
  7816. * This is a special jqLite.replaceWith, which can replace items which
  7817. * have no parents, provided that the containing jqLite collection is provided.
  7818. *
  7819. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  7820. * in the root of the tree.
  7821. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  7822. * the shell, but replace its DOM node reference.
  7823. * @param {Node} newNode The new DOM node.
  7824. */
  7825. function replaceWith($rootElement, elementsToRemove, newNode) {
  7826. var firstElementToRemove = elementsToRemove[0],
  7827. removeCount = elementsToRemove.length,
  7828. parent = firstElementToRemove.parentNode,
  7829. i, ii;
  7830. if ($rootElement) {
  7831. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  7832. if ($rootElement[i] == firstElementToRemove) {
  7833. $rootElement[i++] = newNode;
  7834. for (var j = i, j2 = j + removeCount - 1,
  7835. jj = $rootElement.length;
  7836. j < jj; j++, j2++) {
  7837. if (j2 < jj) {
  7838. $rootElement[j] = $rootElement[j2];
  7839. } else {
  7840. delete $rootElement[j];
  7841. }
  7842. }
  7843. $rootElement.length -= removeCount - 1;
  7844. // If the replaced element is also the jQuery .context then replace it
  7845. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  7846. // http://api.jquery.com/context/
  7847. if ($rootElement.context === firstElementToRemove) {
  7848. $rootElement.context = newNode;
  7849. }
  7850. break;
  7851. }
  7852. }
  7853. }
  7854. if (parent) {
  7855. parent.replaceChild(newNode, firstElementToRemove);
  7856. }
  7857. // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?
  7858. var fragment = document.createDocumentFragment();
  7859. fragment.appendChild(firstElementToRemove);
  7860. if (jqLite.hasData(firstElementToRemove)) {
  7861. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  7862. // data here because there's no public interface in jQuery to do that and copying over
  7863. // event listeners (which is the main use of private data) wouldn't work anyway.
  7864. jqLite(newNode).data(jqLite(firstElementToRemove).data());
  7865. // Remove data of the replaced element. We cannot just call .remove()
  7866. // on the element it since that would deallocate scope that is needed
  7867. // for the new node. Instead, remove the data "manually".
  7868. if (!jQuery) {
  7869. delete jqLite.cache[firstElementToRemove[jqLite.expando]];
  7870. } else {
  7871. // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after
  7872. // the replaced element. The cleanData version monkey-patched by Angular would cause
  7873. // the scope to be trashed and we do need the very same scope to work with the new
  7874. // element. However, we cannot just cache the non-patched version and use it here as
  7875. // that would break if another library patches the method after Angular does (one
  7876. // example is jQuery UI). Instead, set a flag indicating scope destroying should be
  7877. // skipped this one time.
  7878. skipDestroyOnNextJQueryCleanData = true;
  7879. jQuery.cleanData([firstElementToRemove]);
  7880. }
  7881. }
  7882. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  7883. var element = elementsToRemove[k];
  7884. jqLite(element).remove(); // must do this way to clean up expando
  7885. fragment.appendChild(element);
  7886. delete elementsToRemove[k];
  7887. }
  7888. elementsToRemove[0] = newNode;
  7889. elementsToRemove.length = 1;
  7890. }
  7891. function cloneAndAnnotateFn(fn, annotation) {
  7892. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  7893. }
  7894. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  7895. try {
  7896. linkFn(scope, $element, attrs, controllers, transcludeFn);
  7897. } catch (e) {
  7898. $exceptionHandler(e, startingTag($element));
  7899. }
  7900. }
  7901. // Set up $watches for isolate scope and controller bindings. This process
  7902. // only occurs for isolate scopes and new scopes with controllerAs.
  7903. function initializeDirectiveBindings(scope, attrs, destination, bindings,
  7904. directive, newScope) {
  7905. var onNewScopeDestroyed;
  7906. forEach(bindings, function(definition, scopeName) {
  7907. var attrName = definition.attrName,
  7908. optional = definition.optional,
  7909. mode = definition.mode, // @, =, or &
  7910. lastValue,
  7911. parentGet, parentSet, compare;
  7912. switch (mode) {
  7913. case '@':
  7914. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  7915. destination[scopeName] = attrs[attrName] = void 0;
  7916. }
  7917. attrs.$observe(attrName, function(value) {
  7918. if (isString(value)) {
  7919. destination[scopeName] = value;
  7920. }
  7921. });
  7922. attrs.$$observers[attrName].$$scope = scope;
  7923. if (isString(attrs[attrName])) {
  7924. // If the attribute has been provided then we trigger an interpolation to ensure
  7925. // the value is there for use in the link fn
  7926. destination[scopeName] = $interpolate(attrs[attrName])(scope);
  7927. }
  7928. break;
  7929. case '=':
  7930. if (!hasOwnProperty.call(attrs, attrName)) {
  7931. if (optional) break;
  7932. attrs[attrName] = void 0;
  7933. }
  7934. if (optional && !attrs[attrName]) break;
  7935. parentGet = $parse(attrs[attrName]);
  7936. if (parentGet.literal) {
  7937. compare = equals;
  7938. } else {
  7939. compare = function(a, b) { return a === b || (a !== a && b !== b); };
  7940. }
  7941. parentSet = parentGet.assign || function() {
  7942. // reset the change, or we will throw this exception on every $digest
  7943. lastValue = destination[scopeName] = parentGet(scope);
  7944. throw $compileMinErr('nonassign',
  7945. "Expression '{0}' used with directive '{1}' is non-assignable!",
  7946. attrs[attrName], directive.name);
  7947. };
  7948. lastValue = destination[scopeName] = parentGet(scope);
  7949. var parentValueWatch = function parentValueWatch(parentValue) {
  7950. if (!compare(parentValue, destination[scopeName])) {
  7951. // we are out of sync and need to copy
  7952. if (!compare(parentValue, lastValue)) {
  7953. // parent changed and it has precedence
  7954. destination[scopeName] = parentValue;
  7955. } else {
  7956. // if the parent can be assigned then do so
  7957. parentSet(scope, parentValue = destination[scopeName]);
  7958. }
  7959. }
  7960. return lastValue = parentValue;
  7961. };
  7962. parentValueWatch.$stateful = true;
  7963. var unwatch;
  7964. if (definition.collection) {
  7965. unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  7966. } else {
  7967. unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  7968. }
  7969. onNewScopeDestroyed = (onNewScopeDestroyed || []);
  7970. onNewScopeDestroyed.push(unwatch);
  7971. break;
  7972. case '&':
  7973. // Don't assign Object.prototype method to scope
  7974. parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
  7975. // Don't assign noop to destination if expression is not valid
  7976. if (parentGet === noop && optional) break;
  7977. destination[scopeName] = function(locals) {
  7978. return parentGet(scope, locals);
  7979. };
  7980. break;
  7981. }
  7982. });
  7983. var destroyBindings = onNewScopeDestroyed ? function destroyBindings() {
  7984. for (var i = 0, ii = onNewScopeDestroyed.length; i < ii; ++i) {
  7985. onNewScopeDestroyed[i]();
  7986. }
  7987. } : noop;
  7988. if (newScope && destroyBindings !== noop) {
  7989. newScope.$on('$destroy', destroyBindings);
  7990. return noop;
  7991. }
  7992. return destroyBindings;
  7993. }
  7994. }];
  7995. }
  7996. var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
  7997. /**
  7998. * Converts all accepted directives format into proper directive name.
  7999. * @param name Name to normalize
  8000. */
  8001. function directiveNormalize(name) {
  8002. return camelCase(name.replace(PREFIX_REGEXP, ''));
  8003. }
  8004. /**
  8005. * @ngdoc type
  8006. * @name $compile.directive.Attributes
  8007. *
  8008. * @description
  8009. * A shared object between directive compile / linking functions which contains normalized DOM
  8010. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  8011. * needed since all of these are treated as equivalent in Angular:
  8012. *
  8013. * ```
  8014. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  8015. * ```
  8016. */
  8017. /**
  8018. * @ngdoc property
  8019. * @name $compile.directive.Attributes#$attr
  8020. *
  8021. * @description
  8022. * A map of DOM element attribute names to the normalized name. This is
  8023. * needed to do reverse lookup from normalized name back to actual name.
  8024. */
  8025. /**
  8026. * @ngdoc method
  8027. * @name $compile.directive.Attributes#$set
  8028. * @kind function
  8029. *
  8030. * @description
  8031. * Set DOM element attribute value.
  8032. *
  8033. *
  8034. * @param {string} name Normalized element attribute name of the property to modify. The name is
  8035. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  8036. * property to the original name.
  8037. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  8038. */
  8039. /**
  8040. * Closure compiler type information
  8041. */
  8042. function nodesetLinkingFn(
  8043. /* angular.Scope */ scope,
  8044. /* NodeList */ nodeList,
  8045. /* Element */ rootElement,
  8046. /* function(Function) */ boundTranscludeFn
  8047. ) {}
  8048. function directiveLinkingFn(
  8049. /* nodesetLinkingFn */ nodesetLinkingFn,
  8050. /* angular.Scope */ scope,
  8051. /* Node */ node,
  8052. /* Element */ rootElement,
  8053. /* function(Function) */ boundTranscludeFn
  8054. ) {}
  8055. function tokenDifference(str1, str2) {
  8056. var values = '',
  8057. tokens1 = str1.split(/\s+/),
  8058. tokens2 = str2.split(/\s+/);
  8059. outer:
  8060. for (var i = 0; i < tokens1.length; i++) {
  8061. var token = tokens1[i];
  8062. for (var j = 0; j < tokens2.length; j++) {
  8063. if (token == tokens2[j]) continue outer;
  8064. }
  8065. values += (values.length > 0 ? ' ' : '') + token;
  8066. }
  8067. return values;
  8068. }
  8069. function removeComments(jqNodes) {
  8070. jqNodes = jqLite(jqNodes);
  8071. var i = jqNodes.length;
  8072. if (i <= 1) {
  8073. return jqNodes;
  8074. }
  8075. while (i--) {
  8076. var node = jqNodes[i];
  8077. if (node.nodeType === NODE_TYPE_COMMENT) {
  8078. splice.call(jqNodes, i, 1);
  8079. }
  8080. }
  8081. return jqNodes;
  8082. }
  8083. var $controllerMinErr = minErr('$controller');
  8084. var CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
  8085. function identifierForController(controller, ident) {
  8086. if (ident && isString(ident)) return ident;
  8087. if (isString(controller)) {
  8088. var match = CNTRL_REG.exec(controller);
  8089. if (match) return match[3];
  8090. }
  8091. }
  8092. /**
  8093. * @ngdoc provider
  8094. * @name $controllerProvider
  8095. * @description
  8096. * The {@link ng.$controller $controller service} is used by Angular to create new
  8097. * controllers.
  8098. *
  8099. * This provider allows controller registration via the
  8100. * {@link ng.$controllerProvider#register register} method.
  8101. */
  8102. function $ControllerProvider() {
  8103. var controllers = {},
  8104. globals = false;
  8105. /**
  8106. * @ngdoc method
  8107. * @name $controllerProvider#register
  8108. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  8109. * the names and the values are the constructors.
  8110. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  8111. * annotations in the array notation).
  8112. */
  8113. this.register = function(name, constructor) {
  8114. assertNotHasOwnProperty(name, 'controller');
  8115. if (isObject(name)) {
  8116. extend(controllers, name);
  8117. } else {
  8118. controllers[name] = constructor;
  8119. }
  8120. };
  8121. /**
  8122. * @ngdoc method
  8123. * @name $controllerProvider#allowGlobals
  8124. * @description If called, allows `$controller` to find controller constructors on `window`
  8125. */
  8126. this.allowGlobals = function() {
  8127. globals = true;
  8128. };
  8129. this.$get = ['$injector', '$window', function($injector, $window) {
  8130. /**
  8131. * @ngdoc service
  8132. * @name $controller
  8133. * @requires $injector
  8134. *
  8135. * @param {Function|string} constructor If called with a function then it's considered to be the
  8136. * controller constructor function. Otherwise it's considered to be a string which is used
  8137. * to retrieve the controller constructor using the following steps:
  8138. *
  8139. * * check if a controller with given name is registered via `$controllerProvider`
  8140. * * check if evaluating the string on the current scope returns a constructor
  8141. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  8142. * `window` object (not recommended)
  8143. *
  8144. * The string can use the `controller as property` syntax, where the controller instance is published
  8145. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  8146. * to work correctly.
  8147. *
  8148. * @param {Object} locals Injection locals for Controller.
  8149. * @return {Object} Instance of given controller.
  8150. *
  8151. * @description
  8152. * `$controller` service is responsible for instantiating controllers.
  8153. *
  8154. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  8155. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  8156. */
  8157. return function(expression, locals, later, ident) {
  8158. // PRIVATE API:
  8159. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  8160. // If true, $controller will allocate the object with the correct
  8161. // prototype chain, but will not invoke the controller until a returned
  8162. // callback is invoked.
  8163. // param `ident` --- An optional label which overrides the label parsed from the controller
  8164. // expression, if any.
  8165. var instance, match, constructor, identifier;
  8166. later = later === true;
  8167. if (ident && isString(ident)) {
  8168. identifier = ident;
  8169. }
  8170. if (isString(expression)) {
  8171. match = expression.match(CNTRL_REG);
  8172. if (!match) {
  8173. throw $controllerMinErr('ctrlfmt',
  8174. "Badly formed controller string '{0}'. " +
  8175. "Must match `__name__ as __id__` or `__name__`.", expression);
  8176. }
  8177. constructor = match[1],
  8178. identifier = identifier || match[3];
  8179. expression = controllers.hasOwnProperty(constructor)
  8180. ? controllers[constructor]
  8181. : getter(locals.$scope, constructor, true) ||
  8182. (globals ? getter($window, constructor, true) : undefined);
  8183. assertArgFn(expression, constructor, true);
  8184. }
  8185. if (later) {
  8186. // Instantiate controller later:
  8187. // This machinery is used to create an instance of the object before calling the
  8188. // controller's constructor itself.
  8189. //
  8190. // This allows properties to be added to the controller before the constructor is
  8191. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  8192. //
  8193. // This feature is not intended for use by applications, and is thus not documented
  8194. // publicly.
  8195. // Object creation: http://jsperf.com/create-constructor/2
  8196. var controllerPrototype = (isArray(expression) ?
  8197. expression[expression.length - 1] : expression).prototype;
  8198. instance = Object.create(controllerPrototype || null);
  8199. if (identifier) {
  8200. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8201. }
  8202. var instantiate;
  8203. return instantiate = extend(function() {
  8204. var result = $injector.invoke(expression, instance, locals, constructor);
  8205. if (result !== instance && (isObject(result) || isFunction(result))) {
  8206. instance = result;
  8207. if (identifier) {
  8208. // If result changed, re-assign controllerAs value to scope.
  8209. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8210. }
  8211. }
  8212. return instance;
  8213. }, {
  8214. instance: instance,
  8215. identifier: identifier
  8216. });
  8217. }
  8218. instance = $injector.instantiate(expression, locals, constructor);
  8219. if (identifier) {
  8220. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8221. }
  8222. return instance;
  8223. };
  8224. function addIdentifier(locals, identifier, instance, name) {
  8225. if (!(locals && isObject(locals.$scope))) {
  8226. throw minErr('$controller')('noscp',
  8227. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  8228. name, identifier);
  8229. }
  8230. locals.$scope[identifier] = instance;
  8231. }
  8232. }];
  8233. }
  8234. /**
  8235. * @ngdoc service
  8236. * @name $document
  8237. * @requires $window
  8238. *
  8239. * @description
  8240. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  8241. *
  8242. * @example
  8243. <example module="documentExample">
  8244. <file name="index.html">
  8245. <div ng-controller="ExampleController">
  8246. <p>$document title: <b ng-bind="title"></b></p>
  8247. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  8248. </div>
  8249. </file>
  8250. <file name="script.js">
  8251. angular.module('documentExample', [])
  8252. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  8253. $scope.title = $document[0].title;
  8254. $scope.windowTitle = angular.element(window.document)[0].title;
  8255. }]);
  8256. </file>
  8257. </example>
  8258. */
  8259. function $DocumentProvider() {
  8260. this.$get = ['$window', function(window) {
  8261. return jqLite(window.document);
  8262. }];
  8263. }
  8264. /**
  8265. * @ngdoc service
  8266. * @name $exceptionHandler
  8267. * @requires ng.$log
  8268. *
  8269. * @description
  8270. * Any uncaught exception in angular expressions is delegated to this service.
  8271. * The default implementation simply delegates to `$log.error` which logs it into
  8272. * the browser console.
  8273. *
  8274. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  8275. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  8276. *
  8277. * ## Example:
  8278. *
  8279. * ```js
  8280. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
  8281. * return function(exception, cause) {
  8282. * exception.message += ' (caused by "' + cause + '")';
  8283. * throw exception;
  8284. * };
  8285. * });
  8286. * ```
  8287. *
  8288. * This example will override the normal action of `$exceptionHandler`, to make angular
  8289. * exceptions fail hard when they happen, instead of just logging to the console.
  8290. *
  8291. * <hr />
  8292. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  8293. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  8294. * (unless executed during a digest).
  8295. *
  8296. * If you wish, you can manually delegate exceptions, e.g.
  8297. * `try { ... } catch(e) { $exceptionHandler(e); }`
  8298. *
  8299. * @param {Error} exception Exception associated with the error.
  8300. * @param {string=} cause optional information about the context in which
  8301. * the error was thrown.
  8302. *
  8303. */
  8304. function $ExceptionHandlerProvider() {
  8305. this.$get = ['$log', function($log) {
  8306. return function(exception, cause) {
  8307. $log.error.apply($log, arguments);
  8308. };
  8309. }];
  8310. }
  8311. var $$ForceReflowProvider = function() {
  8312. this.$get = ['$document', function($document) {
  8313. return function(domNode) {
  8314. //the line below will force the browser to perform a repaint so
  8315. //that all the animated elements within the animation frame will
  8316. //be properly updated and drawn on screen. This is required to
  8317. //ensure that the preparation animation is properly flushed so that
  8318. //the active state picks up from there. DO NOT REMOVE THIS LINE.
  8319. //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
  8320. //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
  8321. //WILL TAKE YEARS AWAY FROM YOUR LIFE.
  8322. if (domNode) {
  8323. if (!domNode.nodeType && domNode instanceof jqLite) {
  8324. domNode = domNode[0];
  8325. }
  8326. } else {
  8327. domNode = $document[0].body;
  8328. }
  8329. return domNode.offsetWidth + 1;
  8330. };
  8331. }];
  8332. };
  8333. var APPLICATION_JSON = 'application/json';
  8334. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  8335. var JSON_START = /^\[|^\{(?!\{)/;
  8336. var JSON_ENDS = {
  8337. '[': /]$/,
  8338. '{': /}$/
  8339. };
  8340. var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
  8341. var $httpMinErr = minErr('$http');
  8342. var $httpMinErrLegacyFn = function(method) {
  8343. return function() {
  8344. throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method);
  8345. };
  8346. };
  8347. function serializeValue(v) {
  8348. if (isObject(v)) {
  8349. return isDate(v) ? v.toISOString() : toJson(v);
  8350. }
  8351. return v;
  8352. }
  8353. function $HttpParamSerializerProvider() {
  8354. /**
  8355. * @ngdoc service
  8356. * @name $httpParamSerializer
  8357. * @description
  8358. *
  8359. * Default {@link $http `$http`} params serializer that converts objects to strings
  8360. * according to the following rules:
  8361. *
  8362. * * `{'foo': 'bar'}` results in `foo=bar`
  8363. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  8364. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  8365. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
  8366. *
  8367. * Note that serializer will sort the request parameters alphabetically.
  8368. * */
  8369. this.$get = function() {
  8370. return function ngParamSerializer(params) {
  8371. if (!params) return '';
  8372. var parts = [];
  8373. forEachSorted(params, function(value, key) {
  8374. if (value === null || isUndefined(value)) return;
  8375. if (isArray(value)) {
  8376. forEach(value, function(v, k) {
  8377. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  8378. });
  8379. } else {
  8380. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  8381. }
  8382. });
  8383. return parts.join('&');
  8384. };
  8385. };
  8386. }
  8387. function $HttpParamSerializerJQLikeProvider() {
  8388. /**
  8389. * @ngdoc service
  8390. * @name $httpParamSerializerJQLike
  8391. * @description
  8392. *
  8393. * Alternative {@link $http `$http`} params serializer that follows
  8394. * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  8395. * The serializer will also sort the params alphabetically.
  8396. *
  8397. * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
  8398. *
  8399. * ```js
  8400. * $http({
  8401. * url: myUrl,
  8402. * method: 'GET',
  8403. * params: myParams,
  8404. * paramSerializer: '$httpParamSerializerJQLike'
  8405. * });
  8406. * ```
  8407. *
  8408. * It is also possible to set it as the default `paramSerializer` in the
  8409. * {@link $httpProvider#defaults `$httpProvider`}.
  8410. *
  8411. * Additionally, you can inject the serializer and use it explicitly, for example to serialize
  8412. * form data for submission:
  8413. *
  8414. * ```js
  8415. * .controller(function($http, $httpParamSerializerJQLike) {
  8416. * //...
  8417. *
  8418. * $http({
  8419. * url: myUrl,
  8420. * method: 'POST',
  8421. * data: $httpParamSerializerJQLike(myData),
  8422. * headers: {
  8423. * 'Content-Type': 'application/x-www-form-urlencoded'
  8424. * }
  8425. * });
  8426. *
  8427. * });
  8428. * ```
  8429. *
  8430. * */
  8431. this.$get = function() {
  8432. return function jQueryLikeParamSerializer(params) {
  8433. if (!params) return '';
  8434. var parts = [];
  8435. serialize(params, '', true);
  8436. return parts.join('&');
  8437. function serialize(toSerialize, prefix, topLevel) {
  8438. if (toSerialize === null || isUndefined(toSerialize)) return;
  8439. if (isArray(toSerialize)) {
  8440. forEach(toSerialize, function(value, index) {
  8441. serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
  8442. });
  8443. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  8444. forEachSorted(toSerialize, function(value, key) {
  8445. serialize(value, prefix +
  8446. (topLevel ? '' : '[') +
  8447. key +
  8448. (topLevel ? '' : ']'));
  8449. });
  8450. } else {
  8451. parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
  8452. }
  8453. }
  8454. };
  8455. };
  8456. }
  8457. function defaultHttpResponseTransform(data, headers) {
  8458. if (isString(data)) {
  8459. // Strip json vulnerability protection prefix and trim whitespace
  8460. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  8461. if (tempData) {
  8462. var contentType = headers('Content-Type');
  8463. if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
  8464. data = fromJson(tempData);
  8465. }
  8466. }
  8467. }
  8468. return data;
  8469. }
  8470. function isJsonLike(str) {
  8471. var jsonStart = str.match(JSON_START);
  8472. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  8473. }
  8474. /**
  8475. * Parse headers into key value object
  8476. *
  8477. * @param {string} headers Raw headers as a string
  8478. * @returns {Object} Parsed headers as key value object
  8479. */
  8480. function parseHeaders(headers) {
  8481. var parsed = createMap(), i;
  8482. function fillInParsed(key, val) {
  8483. if (key) {
  8484. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  8485. }
  8486. }
  8487. if (isString(headers)) {
  8488. forEach(headers.split('\n'), function(line) {
  8489. i = line.indexOf(':');
  8490. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  8491. });
  8492. } else if (isObject(headers)) {
  8493. forEach(headers, function(headerVal, headerKey) {
  8494. fillInParsed(lowercase(headerKey), trim(headerVal));
  8495. });
  8496. }
  8497. return parsed;
  8498. }
  8499. /**
  8500. * Returns a function that provides access to parsed headers.
  8501. *
  8502. * Headers are lazy parsed when first requested.
  8503. * @see parseHeaders
  8504. *
  8505. * @param {(string|Object)} headers Headers to provide access to.
  8506. * @returns {function(string=)} Returns a getter function which if called with:
  8507. *
  8508. * - if called with single an argument returns a single header value or null
  8509. * - if called with no arguments returns an object containing all headers.
  8510. */
  8511. function headersGetter(headers) {
  8512. var headersObj;
  8513. return function(name) {
  8514. if (!headersObj) headersObj = parseHeaders(headers);
  8515. if (name) {
  8516. var value = headersObj[lowercase(name)];
  8517. if (value === void 0) {
  8518. value = null;
  8519. }
  8520. return value;
  8521. }
  8522. return headersObj;
  8523. };
  8524. }
  8525. /**
  8526. * Chain all given functions
  8527. *
  8528. * This function is used for both request and response transforming
  8529. *
  8530. * @param {*} data Data to transform.
  8531. * @param {function(string=)} headers HTTP headers getter fn.
  8532. * @param {number} status HTTP status code of the response.
  8533. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  8534. * @returns {*} Transformed data.
  8535. */
  8536. function transformData(data, headers, status, fns) {
  8537. if (isFunction(fns)) {
  8538. return fns(data, headers, status);
  8539. }
  8540. forEach(fns, function(fn) {
  8541. data = fn(data, headers, status);
  8542. });
  8543. return data;
  8544. }
  8545. function isSuccess(status) {
  8546. return 200 <= status && status < 300;
  8547. }
  8548. /**
  8549. * @ngdoc provider
  8550. * @name $httpProvider
  8551. * @description
  8552. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  8553. * */
  8554. function $HttpProvider() {
  8555. /**
  8556. * @ngdoc property
  8557. * @name $httpProvider#defaults
  8558. * @description
  8559. *
  8560. * Object containing default values for all {@link ng.$http $http} requests.
  8561. *
  8562. * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
  8563. * that will provide the cache for all requests who set their `cache` property to `true`.
  8564. * If you set the `defaults.cache = false` then only requests that specify their own custom
  8565. * cache object will be cached. See {@link $http#caching $http Caching} for more information.
  8566. *
  8567. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  8568. * Defaults value is `'XSRF-TOKEN'`.
  8569. *
  8570. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  8571. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  8572. *
  8573. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  8574. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  8575. * setting default headers.
  8576. * - **`defaults.headers.common`**
  8577. * - **`defaults.headers.post`**
  8578. * - **`defaults.headers.put`**
  8579. * - **`defaults.headers.patch`**
  8580. *
  8581. *
  8582. * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
  8583. * used to the prepare string representation of request parameters (specified as an object).
  8584. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  8585. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  8586. *
  8587. **/
  8588. var defaults = this.defaults = {
  8589. // transform incoming response data
  8590. transformResponse: [defaultHttpResponseTransform],
  8591. // transform outgoing request data
  8592. transformRequest: [function(d) {
  8593. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  8594. }],
  8595. // default headers
  8596. headers: {
  8597. common: {
  8598. 'Accept': 'application/json, text/plain, */*'
  8599. },
  8600. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  8601. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  8602. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  8603. },
  8604. xsrfCookieName: 'XSRF-TOKEN',
  8605. xsrfHeaderName: 'X-XSRF-TOKEN',
  8606. paramSerializer: '$httpParamSerializer'
  8607. };
  8608. var useApplyAsync = false;
  8609. /**
  8610. * @ngdoc method
  8611. * @name $httpProvider#useApplyAsync
  8612. * @description
  8613. *
  8614. * Configure $http service to combine processing of multiple http responses received at around
  8615. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  8616. * significant performance improvement for bigger applications that make many HTTP requests
  8617. * concurrently (common during application bootstrap).
  8618. *
  8619. * Defaults to false. If no value is specified, returns the current configured value.
  8620. *
  8621. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  8622. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  8623. * to load and share the same digest cycle.
  8624. *
  8625. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  8626. * otherwise, returns the current configured value.
  8627. **/
  8628. this.useApplyAsync = function(value) {
  8629. if (isDefined(value)) {
  8630. useApplyAsync = !!value;
  8631. return this;
  8632. }
  8633. return useApplyAsync;
  8634. };
  8635. var useLegacyPromise = true;
  8636. /**
  8637. * @ngdoc method
  8638. * @name $httpProvider#useLegacyPromiseExtensions
  8639. * @description
  8640. *
  8641. * Configure `$http` service to return promises without the shorthand methods `success` and `error`.
  8642. * This should be used to make sure that applications work without these methods.
  8643. *
  8644. * Defaults to false. If no value is specified, returns the current configured value.
  8645. *
  8646. * @param {boolean=} value If true, `$http` will return a normal promise without the `success` and `error` methods.
  8647. *
  8648. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  8649. * otherwise, returns the current configured value.
  8650. **/
  8651. this.useLegacyPromiseExtensions = function(value) {
  8652. if (isDefined(value)) {
  8653. useLegacyPromise = !!value;
  8654. return this;
  8655. }
  8656. return useLegacyPromise;
  8657. };
  8658. /**
  8659. * @ngdoc property
  8660. * @name $httpProvider#interceptors
  8661. * @description
  8662. *
  8663. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  8664. * pre-processing of request or postprocessing of responses.
  8665. *
  8666. * These service factories are ordered by request, i.e. they are applied in the same order as the
  8667. * array, on request, but reverse order, on response.
  8668. *
  8669. * {@link ng.$http#interceptors Interceptors detailed info}
  8670. **/
  8671. var interceptorFactories = this.interceptors = [];
  8672. this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
  8673. function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
  8674. var defaultCache = $cacheFactory('$http');
  8675. /**
  8676. * Make sure that default param serializer is exposed as a function
  8677. */
  8678. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  8679. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  8680. /**
  8681. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  8682. * The reversal is needed so that we can build up the interception chain around the
  8683. * server request.
  8684. */
  8685. var reversedInterceptors = [];
  8686. forEach(interceptorFactories, function(interceptorFactory) {
  8687. reversedInterceptors.unshift(isString(interceptorFactory)
  8688. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  8689. });
  8690. /**
  8691. * @ngdoc service
  8692. * @kind function
  8693. * @name $http
  8694. * @requires ng.$httpBackend
  8695. * @requires $cacheFactory
  8696. * @requires $rootScope
  8697. * @requires $q
  8698. * @requires $injector
  8699. *
  8700. * @description
  8701. * The `$http` service is a core Angular service that facilitates communication with the remote
  8702. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  8703. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  8704. *
  8705. * For unit testing applications that use `$http` service, see
  8706. * {@link ngMock.$httpBackend $httpBackend mock}.
  8707. *
  8708. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  8709. * $resource} service.
  8710. *
  8711. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  8712. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  8713. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  8714. *
  8715. *
  8716. * ## General usage
  8717. * The `$http` service is a function which takes a single argument — a configuration object —
  8718. * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
  8719. *
  8720. * ```js
  8721. * // Simple GET request example :
  8722. * $http.get('/someUrl').
  8723. * then(function(response) {
  8724. * // this callback will be called asynchronously
  8725. * // when the response is available
  8726. * }, function(response) {
  8727. * // called asynchronously if an error occurs
  8728. * // or server returns response with an error status.
  8729. * });
  8730. * ```
  8731. *
  8732. * ```js
  8733. * // Simple POST request example (passing data) :
  8734. * $http.post('/someUrl', {msg:'hello word!'}).
  8735. * then(function(response) {
  8736. * // this callback will be called asynchronously
  8737. * // when the response is available
  8738. * }, function(response) {
  8739. * // called asynchronously if an error occurs
  8740. * // or server returns response with an error status.
  8741. * });
  8742. * ```
  8743. *
  8744. * The response object has these properties:
  8745. *
  8746. * - **data** – `{string|Object}` – The response body transformed with the transform
  8747. * functions.
  8748. * - **status** – `{number}` – HTTP status code of the response.
  8749. * - **headers** – `{function([headerName])}` – Header getter function.
  8750. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  8751. * - **statusText** – `{string}` – HTTP status text of the response.
  8752. *
  8753. * A response status code between 200 and 299 is considered a success status and
  8754. * will result in the success callback being called. Note that if the response is a redirect,
  8755. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  8756. * called for such responses.
  8757. *
  8758. * ## Writing Unit Tests that use $http
  8759. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  8760. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  8761. * request using trained responses.
  8762. *
  8763. * ```
  8764. * $httpBackend.expectGET(...);
  8765. * $http.get(...);
  8766. * $httpBackend.flush();
  8767. * ```
  8768. *
  8769. * ## Shortcut methods
  8770. *
  8771. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  8772. * request data must be passed in for POST/PUT requests.
  8773. *
  8774. * ```js
  8775. * $http.get('/someUrl').then(successCallback);
  8776. * $http.post('/someUrl', data).then(successCallback);
  8777. * ```
  8778. *
  8779. * Complete list of shortcut methods:
  8780. *
  8781. * - {@link ng.$http#get $http.get}
  8782. * - {@link ng.$http#head $http.head}
  8783. * - {@link ng.$http#post $http.post}
  8784. * - {@link ng.$http#put $http.put}
  8785. * - {@link ng.$http#delete $http.delete}
  8786. * - {@link ng.$http#jsonp $http.jsonp}
  8787. * - {@link ng.$http#patch $http.patch}
  8788. *
  8789. *
  8790. * ## Deprecation Notice
  8791. * <div class="alert alert-danger">
  8792. * The `$http` legacy promise methods `success` and `error` have been deprecated.
  8793. * Use the standard `then` method instead.
  8794. * If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to
  8795. * `false` then these methods will throw {@link $http:legacy `$http/legacy`} error.
  8796. * </div>
  8797. *
  8798. * ## Setting HTTP Headers
  8799. *
  8800. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  8801. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  8802. * object, which currently contains this default configuration:
  8803. *
  8804. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  8805. * - `Accept: application/json, text/plain, * / *`
  8806. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  8807. * - `Content-Type: application/json`
  8808. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  8809. * - `Content-Type: application/json`
  8810. *
  8811. * To add or overwrite these defaults, simply add or remove a property from these configuration
  8812. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  8813. * with the lowercased HTTP method name as the key, e.g.
  8814. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  8815. *
  8816. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  8817. * fashion. For example:
  8818. *
  8819. * ```
  8820. * module.run(function($http) {
  8821. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
  8822. * });
  8823. * ```
  8824. *
  8825. * In addition, you can supply a `headers` property in the config object passed when
  8826. * calling `$http(config)`, which overrides the defaults without changing them globally.
  8827. *
  8828. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  8829. * Use the `headers` property, setting the desired header to `undefined`. For example:
  8830. *
  8831. * ```js
  8832. * var req = {
  8833. * method: 'POST',
  8834. * url: 'http://example.com',
  8835. * headers: {
  8836. * 'Content-Type': undefined
  8837. * },
  8838. * data: { test: 'test' }
  8839. * }
  8840. *
  8841. * $http(req).then(function(){...}, function(){...});
  8842. * ```
  8843. *
  8844. * ## Transforming Requests and Responses
  8845. *
  8846. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  8847. * and `transformResponse`. These properties can be a single function that returns
  8848. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  8849. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  8850. *
  8851. * ### Default Transformations
  8852. *
  8853. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  8854. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  8855. * then these will be applied.
  8856. *
  8857. * You can augment or replace the default transformations by modifying these properties by adding to or
  8858. * replacing the array.
  8859. *
  8860. * Angular provides the following default transformations:
  8861. *
  8862. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  8863. *
  8864. * - If the `data` property of the request configuration object contains an object, serialize it
  8865. * into JSON format.
  8866. *
  8867. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  8868. *
  8869. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  8870. * - If JSON response is detected, deserialize it using a JSON parser.
  8871. *
  8872. *
  8873. * ### Overriding the Default Transformations Per Request
  8874. *
  8875. * If you wish override the request/response transformations only for a single request then provide
  8876. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  8877. * into `$http`.
  8878. *
  8879. * Note that if you provide these properties on the config object the default transformations will be
  8880. * overwritten. If you wish to augment the default transformations then you must include them in your
  8881. * local transformation array.
  8882. *
  8883. * The following code demonstrates adding a new response transformation to be run after the default response
  8884. * transformations have been run.
  8885. *
  8886. * ```js
  8887. * function appendTransform(defaults, transform) {
  8888. *
  8889. * // We can't guarantee that the default transformation is an array
  8890. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  8891. *
  8892. * // Append the new transformation to the defaults
  8893. * return defaults.concat(transform);
  8894. * }
  8895. *
  8896. * $http({
  8897. * url: '...',
  8898. * method: 'GET',
  8899. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  8900. * return doTransform(value);
  8901. * })
  8902. * });
  8903. * ```
  8904. *
  8905. *
  8906. * ## Caching
  8907. *
  8908. * To enable caching, set the request configuration `cache` property to `true` (to use default
  8909. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  8910. * When the cache is enabled, `$http` stores the response from the server in the specified
  8911. * cache. The next time the same request is made, the response is served from the cache without
  8912. * sending a request to the server.
  8913. *
  8914. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  8915. * the same way that real requests are.
  8916. *
  8917. * If there are multiple GET requests for the same URL that should be cached using the same
  8918. * cache, but the cache is not populated yet, only one request to the server will be made and
  8919. * the remaining requests will be fulfilled using the response from the first request.
  8920. *
  8921. * You can change the default cache to a new object (built with
  8922. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  8923. * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
  8924. * their `cache` property to `true` will now use this cache object.
  8925. *
  8926. * If you set the default cache to `false` then only requests that specify their own custom
  8927. * cache object will be cached.
  8928. *
  8929. * ## Interceptors
  8930. *
  8931. * Before you start creating interceptors, be sure to understand the
  8932. * {@link ng.$q $q and deferred/promise APIs}.
  8933. *
  8934. * For purposes of global error handling, authentication, or any kind of synchronous or
  8935. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  8936. * able to intercept requests before they are handed to the server and
  8937. * responses before they are handed over to the application code that
  8938. * initiated these requests. The interceptors leverage the {@link ng.$q
  8939. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  8940. *
  8941. * The interceptors are service factories that are registered with the `$httpProvider` by
  8942. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  8943. * injected with dependencies (if specified) and returns the interceptor.
  8944. *
  8945. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  8946. *
  8947. * * `request`: interceptors get called with a http `config` object. The function is free to
  8948. * modify the `config` object or create a new one. The function needs to return the `config`
  8949. * object directly, or a promise containing the `config` or a new `config` object.
  8950. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  8951. * resolved with a rejection.
  8952. * * `response`: interceptors get called with http `response` object. The function is free to
  8953. * modify the `response` object or create a new one. The function needs to return the `response`
  8954. * object directly, or as a promise containing the `response` or a new `response` object.
  8955. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  8956. * resolved with a rejection.
  8957. *
  8958. *
  8959. * ```js
  8960. * // register the interceptor as a service
  8961. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  8962. * return {
  8963. * // optional method
  8964. * 'request': function(config) {
  8965. * // do something on success
  8966. * return config;
  8967. * },
  8968. *
  8969. * // optional method
  8970. * 'requestError': function(rejection) {
  8971. * // do something on error
  8972. * if (canRecover(rejection)) {
  8973. * return responseOrNewPromise
  8974. * }
  8975. * return $q.reject(rejection);
  8976. * },
  8977. *
  8978. *
  8979. *
  8980. * // optional method
  8981. * 'response': function(response) {
  8982. * // do something on success
  8983. * return response;
  8984. * },
  8985. *
  8986. * // optional method
  8987. * 'responseError': function(rejection) {
  8988. * // do something on error
  8989. * if (canRecover(rejection)) {
  8990. * return responseOrNewPromise
  8991. * }
  8992. * return $q.reject(rejection);
  8993. * }
  8994. * };
  8995. * });
  8996. *
  8997. * $httpProvider.interceptors.push('myHttpInterceptor');
  8998. *
  8999. *
  9000. * // alternatively, register the interceptor via an anonymous factory
  9001. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  9002. * return {
  9003. * 'request': function(config) {
  9004. * // same as above
  9005. * },
  9006. *
  9007. * 'response': function(response) {
  9008. * // same as above
  9009. * }
  9010. * };
  9011. * });
  9012. * ```
  9013. *
  9014. * ## Security Considerations
  9015. *
  9016. * When designing web applications, consider security threats from:
  9017. *
  9018. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  9019. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  9020. *
  9021. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  9022. * pre-configured with strategies that address these issues, but for this to work backend server
  9023. * cooperation is required.
  9024. *
  9025. * ### JSON Vulnerability Protection
  9026. *
  9027. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  9028. * allows third party website to turn your JSON resource URL into
  9029. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  9030. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  9031. * Angular will automatically strip the prefix before processing it as JSON.
  9032. *
  9033. * For example if your server needs to return:
  9034. * ```js
  9035. * ['one','two']
  9036. * ```
  9037. *
  9038. * which is vulnerable to attack, your server can return:
  9039. * ```js
  9040. * )]}',
  9041. * ['one','two']
  9042. * ```
  9043. *
  9044. * Angular will strip the prefix, before processing the JSON.
  9045. *
  9046. *
  9047. * ### Cross Site Request Forgery (XSRF) Protection
  9048. *
  9049. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
  9050. * an unauthorized site can gain your user's private data. Angular provides a mechanism
  9051. * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
  9052. * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
  9053. * JavaScript that runs on your domain could read the cookie, your server can be assured that
  9054. * the XHR came from JavaScript running on your domain. The header will not be set for
  9055. * cross-domain requests.
  9056. *
  9057. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  9058. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  9059. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  9060. * that only JavaScript running on your domain could have sent the request. The token must be
  9061. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  9062. * making up its own tokens). We recommend that the token is a digest of your site's
  9063. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  9064. * for added security.
  9065. *
  9066. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  9067. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  9068. * or the per-request config object.
  9069. *
  9070. * In order to prevent collisions in environments where multiple Angular apps share the
  9071. * same domain or subdomain, we recommend that each application uses unique cookie name.
  9072. *
  9073. * @param {object} config Object describing the request to be made and how it should be
  9074. * processed. The object has following properties:
  9075. *
  9076. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  9077. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  9078. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
  9079. * with the `paramSerializer` and appended as GET parameters.
  9080. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  9081. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  9082. * HTTP headers to send to the server. If the return value of a function is null, the
  9083. * header will not be sent. Functions accept a config object as an argument.
  9084. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  9085. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  9086. * - **transformRequest** –
  9087. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  9088. * transform function or an array of such functions. The transform function takes the http
  9089. * request body and headers and returns its transformed (typically serialized) version.
  9090. * See {@link ng.$http#overriding-the-default-transformations-per-request
  9091. * Overriding the Default Transformations}
  9092. * - **transformResponse** –
  9093. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  9094. * transform function or an array of such functions. The transform function takes the http
  9095. * response body, headers and status and returns its transformed (typically deserialized) version.
  9096. * See {@link ng.$http#overriding-the-default-transformations-per-request
  9097. * Overriding the Default TransformationjqLiks}
  9098. * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
  9099. * prepare the string representation of request parameters (specified as an object).
  9100. * If specified as string, it is interpreted as function registered with the
  9101. * {@link $injector $injector}, which means you can create your own serializer
  9102. * by registering it as a {@link auto.$provide#service service}.
  9103. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
  9104. * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
  9105. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  9106. * GET request, otherwise if a cache instance built with
  9107. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  9108. * caching.
  9109. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  9110. * that should abort the request when resolved.
  9111. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  9112. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  9113. * for more information.
  9114. * - **responseType** - `{string}` - see
  9115. * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
  9116. *
  9117. * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
  9118. * when the request succeeds or fails.
  9119. *
  9120. *
  9121. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  9122. * requests. This is primarily meant to be used for debugging purposes.
  9123. *
  9124. *
  9125. * @example
  9126. <example module="httpExample">
  9127. <file name="index.html">
  9128. <div ng-controller="FetchController">
  9129. <select ng-model="method" aria-label="Request method">
  9130. <option>GET</option>
  9131. <option>JSONP</option>
  9132. </select>
  9133. <input type="text" ng-model="url" size="80" aria-label="URL" />
  9134. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  9135. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  9136. <button id="samplejsonpbtn"
  9137. ng-click="updateModel('JSONP',
  9138. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  9139. Sample JSONP
  9140. </button>
  9141. <button id="invalidjsonpbtn"
  9142. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  9143. Invalid JSONP
  9144. </button>
  9145. <pre>http status code: {{status}}</pre>
  9146. <pre>http response data: {{data}}</pre>
  9147. </div>
  9148. </file>
  9149. <file name="script.js">
  9150. angular.module('httpExample', [])
  9151. .controller('FetchController', ['$scope', '$http', '$templateCache',
  9152. function($scope, $http, $templateCache) {
  9153. $scope.method = 'GET';
  9154. $scope.url = 'http-hello.html';
  9155. $scope.fetch = function() {
  9156. $scope.code = null;
  9157. $scope.response = null;
  9158. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  9159. then(function(response) {
  9160. $scope.status = response.status;
  9161. $scope.data = response.data;
  9162. }, function(response) {
  9163. $scope.data = response.data || "Request failed";
  9164. $scope.status = response.status;
  9165. });
  9166. };
  9167. $scope.updateModel = function(method, url) {
  9168. $scope.method = method;
  9169. $scope.url = url;
  9170. };
  9171. }]);
  9172. </file>
  9173. <file name="http-hello.html">
  9174. Hello, $http!
  9175. </file>
  9176. <file name="protractor.js" type="protractor">
  9177. var status = element(by.binding('status'));
  9178. var data = element(by.binding('data'));
  9179. var fetchBtn = element(by.id('fetchbtn'));
  9180. var sampleGetBtn = element(by.id('samplegetbtn'));
  9181. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  9182. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  9183. it('should make an xhr GET request', function() {
  9184. sampleGetBtn.click();
  9185. fetchBtn.click();
  9186. expect(status.getText()).toMatch('200');
  9187. expect(data.getText()).toMatch(/Hello, \$http!/);
  9188. });
  9189. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  9190. // it('should make a JSONP request to angularjs.org', function() {
  9191. // sampleJsonpBtn.click();
  9192. // fetchBtn.click();
  9193. // expect(status.getText()).toMatch('200');
  9194. // expect(data.getText()).toMatch(/Super Hero!/);
  9195. // });
  9196. it('should make JSONP request to invalid URL and invoke the error handler',
  9197. function() {
  9198. invalidJsonpBtn.click();
  9199. fetchBtn.click();
  9200. expect(status.getText()).toMatch('0');
  9201. expect(data.getText()).toMatch('Request failed');
  9202. });
  9203. </file>
  9204. </example>
  9205. */
  9206. function $http(requestConfig) {
  9207. if (!angular.isObject(requestConfig)) {
  9208. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  9209. }
  9210. var config = extend({
  9211. method: 'get',
  9212. transformRequest: defaults.transformRequest,
  9213. transformResponse: defaults.transformResponse,
  9214. paramSerializer: defaults.paramSerializer
  9215. }, requestConfig);
  9216. config.headers = mergeHeaders(requestConfig);
  9217. config.method = uppercase(config.method);
  9218. config.paramSerializer = isString(config.paramSerializer) ?
  9219. $injector.get(config.paramSerializer) : config.paramSerializer;
  9220. var serverRequest = function(config) {
  9221. var headers = config.headers;
  9222. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  9223. // strip content-type if data is undefined
  9224. if (isUndefined(reqData)) {
  9225. forEach(headers, function(value, header) {
  9226. if (lowercase(header) === 'content-type') {
  9227. delete headers[header];
  9228. }
  9229. });
  9230. }
  9231. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  9232. config.withCredentials = defaults.withCredentials;
  9233. }
  9234. // send request
  9235. return sendReq(config, reqData).then(transformResponse, transformResponse);
  9236. };
  9237. var chain = [serverRequest, undefined];
  9238. var promise = $q.when(config);
  9239. // apply interceptors
  9240. forEach(reversedInterceptors, function(interceptor) {
  9241. if (interceptor.request || interceptor.requestError) {
  9242. chain.unshift(interceptor.request, interceptor.requestError);
  9243. }
  9244. if (interceptor.response || interceptor.responseError) {
  9245. chain.push(interceptor.response, interceptor.responseError);
  9246. }
  9247. });
  9248. while (chain.length) {
  9249. var thenFn = chain.shift();
  9250. var rejectFn = chain.shift();
  9251. promise = promise.then(thenFn, rejectFn);
  9252. }
  9253. if (useLegacyPromise) {
  9254. promise.success = function(fn) {
  9255. assertArgFn(fn, 'fn');
  9256. promise.then(function(response) {
  9257. fn(response.data, response.status, response.headers, config);
  9258. });
  9259. return promise;
  9260. };
  9261. promise.error = function(fn) {
  9262. assertArgFn(fn, 'fn');
  9263. promise.then(null, function(response) {
  9264. fn(response.data, response.status, response.headers, config);
  9265. });
  9266. return promise;
  9267. };
  9268. } else {
  9269. promise.success = $httpMinErrLegacyFn('success');
  9270. promise.error = $httpMinErrLegacyFn('error');
  9271. }
  9272. return promise;
  9273. function transformResponse(response) {
  9274. // make a copy since the response must be cacheable
  9275. var resp = extend({}, response);
  9276. if (!response.data) {
  9277. resp.data = response.data;
  9278. } else {
  9279. resp.data = transformData(response.data, response.headers, response.status, config.transformResponse);
  9280. }
  9281. return (isSuccess(response.status))
  9282. ? resp
  9283. : $q.reject(resp);
  9284. }
  9285. function executeHeaderFns(headers, config) {
  9286. var headerContent, processedHeaders = {};
  9287. forEach(headers, function(headerFn, header) {
  9288. if (isFunction(headerFn)) {
  9289. headerContent = headerFn(config);
  9290. if (headerContent != null) {
  9291. processedHeaders[header] = headerContent;
  9292. }
  9293. } else {
  9294. processedHeaders[header] = headerFn;
  9295. }
  9296. });
  9297. return processedHeaders;
  9298. }
  9299. function mergeHeaders(config) {
  9300. var defHeaders = defaults.headers,
  9301. reqHeaders = extend({}, config.headers),
  9302. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  9303. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  9304. // using for-in instead of forEach to avoid unecessary iteration after header has been found
  9305. defaultHeadersIteration:
  9306. for (defHeaderName in defHeaders) {
  9307. lowercaseDefHeaderName = lowercase(defHeaderName);
  9308. for (reqHeaderName in reqHeaders) {
  9309. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  9310. continue defaultHeadersIteration;
  9311. }
  9312. }
  9313. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  9314. }
  9315. // execute if header value is a function for merged headers
  9316. return executeHeaderFns(reqHeaders, shallowCopy(config));
  9317. }
  9318. }
  9319. $http.pendingRequests = [];
  9320. /**
  9321. * @ngdoc method
  9322. * @name $http#get
  9323. *
  9324. * @description
  9325. * Shortcut method to perform `GET` request.
  9326. *
  9327. * @param {string} url Relative or absolute URL specifying the destination of the request
  9328. * @param {Object=} config Optional configuration object
  9329. * @returns {HttpPromise} Future object
  9330. */
  9331. /**
  9332. * @ngdoc method
  9333. * @name $http#delete
  9334. *
  9335. * @description
  9336. * Shortcut method to perform `DELETE` request.
  9337. *
  9338. * @param {string} url Relative or absolute URL specifying the destination of the request
  9339. * @param {Object=} config Optional configuration object
  9340. * @returns {HttpPromise} Future object
  9341. */
  9342. /**
  9343. * @ngdoc method
  9344. * @name $http#head
  9345. *
  9346. * @description
  9347. * Shortcut method to perform `HEAD` request.
  9348. *
  9349. * @param {string} url Relative or absolute URL specifying the destination of the request
  9350. * @param {Object=} config Optional configuration object
  9351. * @returns {HttpPromise} Future object
  9352. */
  9353. /**
  9354. * @ngdoc method
  9355. * @name $http#jsonp
  9356. *
  9357. * @description
  9358. * Shortcut method to perform `JSONP` request.
  9359. *
  9360. * @param {string} url Relative or absolute URL specifying the destination of the request.
  9361. * The name of the callback should be the string `JSON_CALLBACK`.
  9362. * @param {Object=} config Optional configuration object
  9363. * @returns {HttpPromise} Future object
  9364. */
  9365. createShortMethods('get', 'delete', 'head', 'jsonp');
  9366. /**
  9367. * @ngdoc method
  9368. * @name $http#post
  9369. *
  9370. * @description
  9371. * Shortcut method to perform `POST` request.
  9372. *
  9373. * @param {string} url Relative or absolute URL specifying the destination of the request
  9374. * @param {*} data Request content
  9375. * @param {Object=} config Optional configuration object
  9376. * @returns {HttpPromise} Future object
  9377. */
  9378. /**
  9379. * @ngdoc method
  9380. * @name $http#put
  9381. *
  9382. * @description
  9383. * Shortcut method to perform `PUT` request.
  9384. *
  9385. * @param {string} url Relative or absolute URL specifying the destination of the request
  9386. * @param {*} data Request content
  9387. * @param {Object=} config Optional configuration object
  9388. * @returns {HttpPromise} Future object
  9389. */
  9390. /**
  9391. * @ngdoc method
  9392. * @name $http#patch
  9393. *
  9394. * @description
  9395. * Shortcut method to perform `PATCH` request.
  9396. *
  9397. * @param {string} url Relative or absolute URL specifying the destination of the request
  9398. * @param {*} data Request content
  9399. * @param {Object=} config Optional configuration object
  9400. * @returns {HttpPromise} Future object
  9401. */
  9402. createShortMethodsWithData('post', 'put', 'patch');
  9403. /**
  9404. * @ngdoc property
  9405. * @name $http#defaults
  9406. *
  9407. * @description
  9408. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  9409. * default headers, withCredentials as well as request and response transformations.
  9410. *
  9411. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  9412. */
  9413. $http.defaults = defaults;
  9414. return $http;
  9415. function createShortMethods(names) {
  9416. forEach(arguments, function(name) {
  9417. $http[name] = function(url, config) {
  9418. return $http(extend({}, config || {}, {
  9419. method: name,
  9420. url: url
  9421. }));
  9422. };
  9423. });
  9424. }
  9425. function createShortMethodsWithData(name) {
  9426. forEach(arguments, function(name) {
  9427. $http[name] = function(url, data, config) {
  9428. return $http(extend({}, config || {}, {
  9429. method: name,
  9430. url: url,
  9431. data: data
  9432. }));
  9433. };
  9434. });
  9435. }
  9436. /**
  9437. * Makes the request.
  9438. *
  9439. * !!! ACCESSES CLOSURE VARS:
  9440. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  9441. */
  9442. function sendReq(config, reqData) {
  9443. var deferred = $q.defer(),
  9444. promise = deferred.promise,
  9445. cache,
  9446. cachedResp,
  9447. reqHeaders = config.headers,
  9448. url = buildUrl(config.url, config.paramSerializer(config.params));
  9449. $http.pendingRequests.push(config);
  9450. promise.then(removePendingReq, removePendingReq);
  9451. if ((config.cache || defaults.cache) && config.cache !== false &&
  9452. (config.method === 'GET' || config.method === 'JSONP')) {
  9453. cache = isObject(config.cache) ? config.cache
  9454. : isObject(defaults.cache) ? defaults.cache
  9455. : defaultCache;
  9456. }
  9457. if (cache) {
  9458. cachedResp = cache.get(url);
  9459. if (isDefined(cachedResp)) {
  9460. if (isPromiseLike(cachedResp)) {
  9461. // cached request has already been sent, but there is no response yet
  9462. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  9463. } else {
  9464. // serving from cache
  9465. if (isArray(cachedResp)) {
  9466. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  9467. } else {
  9468. resolvePromise(cachedResp, 200, {}, 'OK');
  9469. }
  9470. }
  9471. } else {
  9472. // put the promise for the non-transformed response into cache as a placeholder
  9473. cache.put(url, promise);
  9474. }
  9475. }
  9476. // if we won't have the response in cache, set the xsrf headers and
  9477. // send the request to the backend
  9478. if (isUndefined(cachedResp)) {
  9479. var xsrfValue = urlIsSameOrigin(config.url)
  9480. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  9481. : undefined;
  9482. if (xsrfValue) {
  9483. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  9484. }
  9485. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  9486. config.withCredentials, config.responseType);
  9487. }
  9488. return promise;
  9489. /**
  9490. * Callback registered to $httpBackend():
  9491. * - caches the response if desired
  9492. * - resolves the raw $http promise
  9493. * - calls $apply
  9494. */
  9495. function done(status, response, headersString, statusText) {
  9496. if (cache) {
  9497. if (isSuccess(status)) {
  9498. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  9499. } else {
  9500. // remove promise from the cache
  9501. cache.remove(url);
  9502. }
  9503. }
  9504. function resolveHttpPromise() {
  9505. resolvePromise(response, status, headersString, statusText);
  9506. }
  9507. if (useApplyAsync) {
  9508. $rootScope.$applyAsync(resolveHttpPromise);
  9509. } else {
  9510. resolveHttpPromise();
  9511. if (!$rootScope.$$phase) $rootScope.$apply();
  9512. }
  9513. }
  9514. /**
  9515. * Resolves the raw $http promise.
  9516. */
  9517. function resolvePromise(response, status, headers, statusText) {
  9518. // normalize internal statuses to 0
  9519. status = Math.max(status, 0);
  9520. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  9521. data: response,
  9522. status: status,
  9523. headers: headersGetter(headers),
  9524. config: config,
  9525. statusText: statusText
  9526. });
  9527. }
  9528. function resolvePromiseWithResult(result) {
  9529. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
  9530. }
  9531. function removePendingReq() {
  9532. var idx = $http.pendingRequests.indexOf(config);
  9533. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  9534. }
  9535. }
  9536. function buildUrl(url, serializedParams) {
  9537. if (serializedParams.length > 0) {
  9538. url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
  9539. }
  9540. return url;
  9541. }
  9542. }];
  9543. }
  9544. function createXhr() {
  9545. return new window.XMLHttpRequest();
  9546. }
  9547. /**
  9548. * @ngdoc service
  9549. * @name $httpBackend
  9550. * @requires $window
  9551. * @requires $document
  9552. *
  9553. * @description
  9554. * HTTP backend used by the {@link ng.$http service} that delegates to
  9555. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  9556. *
  9557. * You should never need to use this service directly, instead use the higher-level abstractions:
  9558. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  9559. *
  9560. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  9561. * $httpBackend} which can be trained with responses.
  9562. */
  9563. function $HttpBackendProvider() {
  9564. this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
  9565. return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
  9566. }];
  9567. }
  9568. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  9569. // TODO(vojta): fix the signature
  9570. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  9571. $browser.$$incOutstandingRequestCount();
  9572. url = url || $browser.url();
  9573. if (lowercase(method) == 'jsonp') {
  9574. var callbackId = '_' + (callbacks.counter++).toString(36);
  9575. callbacks[callbackId] = function(data) {
  9576. callbacks[callbackId].data = data;
  9577. callbacks[callbackId].called = true;
  9578. };
  9579. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  9580. callbackId, function(status, text) {
  9581. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  9582. callbacks[callbackId] = noop;
  9583. });
  9584. } else {
  9585. var xhr = createXhr();
  9586. xhr.open(method, url, true);
  9587. forEach(headers, function(value, key) {
  9588. if (isDefined(value)) {
  9589. xhr.setRequestHeader(key, value);
  9590. }
  9591. });
  9592. xhr.onload = function requestLoaded() {
  9593. var statusText = xhr.statusText || '';
  9594. // responseText is the old-school way of retrieving response (supported by IE9)
  9595. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  9596. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  9597. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  9598. var status = xhr.status === 1223 ? 204 : xhr.status;
  9599. // fix status code when it is 0 (0 status is undocumented).
  9600. // Occurs when accessing file resources or on Android 4.1 stock browser
  9601. // while retrieving files from application cache.
  9602. if (status === 0) {
  9603. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  9604. }
  9605. completeRequest(callback,
  9606. status,
  9607. response,
  9608. xhr.getAllResponseHeaders(),
  9609. statusText);
  9610. };
  9611. var requestError = function() {
  9612. // The response is always empty
  9613. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  9614. completeRequest(callback, -1, null, null, '');
  9615. };
  9616. xhr.onerror = requestError;
  9617. xhr.onabort = requestError;
  9618. if (withCredentials) {
  9619. xhr.withCredentials = true;
  9620. }
  9621. if (responseType) {
  9622. try {
  9623. xhr.responseType = responseType;
  9624. } catch (e) {
  9625. // WebKit added support for the json responseType value on 09/03/2013
  9626. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  9627. // known to throw when setting the value "json" as the response type. Other older
  9628. // browsers implementing the responseType
  9629. //
  9630. // The json response type can be ignored if not supported, because JSON payloads are
  9631. // parsed on the client-side regardless.
  9632. if (responseType !== 'json') {
  9633. throw e;
  9634. }
  9635. }
  9636. }
  9637. xhr.send(post);
  9638. }
  9639. if (timeout > 0) {
  9640. var timeoutId = $browserDefer(timeoutRequest, timeout);
  9641. } else if (isPromiseLike(timeout)) {
  9642. timeout.then(timeoutRequest);
  9643. }
  9644. function timeoutRequest() {
  9645. jsonpDone && jsonpDone();
  9646. xhr && xhr.abort();
  9647. }
  9648. function completeRequest(callback, status, response, headersString, statusText) {
  9649. // cancel timeout and subsequent timeout promise resolution
  9650. if (timeoutId !== undefined) {
  9651. $browserDefer.cancel(timeoutId);
  9652. }
  9653. jsonpDone = xhr = null;
  9654. callback(status, response, headersString, statusText);
  9655. $browser.$$completeOutstandingRequest(noop);
  9656. }
  9657. };
  9658. function jsonpReq(url, callbackId, done) {
  9659. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  9660. // - fetches local scripts via XHR and evals them
  9661. // - adds and immediately removes script elements from the document
  9662. var script = rawDocument.createElement('script'), callback = null;
  9663. script.type = "text/javascript";
  9664. script.src = url;
  9665. script.async = true;
  9666. callback = function(event) {
  9667. removeEventListenerFn(script, "load", callback);
  9668. removeEventListenerFn(script, "error", callback);
  9669. rawDocument.body.removeChild(script);
  9670. script = null;
  9671. var status = -1;
  9672. var text = "unknown";
  9673. if (event) {
  9674. if (event.type === "load" && !callbacks[callbackId].called) {
  9675. event = { type: "error" };
  9676. }
  9677. text = event.type;
  9678. status = event.type === "error" ? 404 : 200;
  9679. }
  9680. if (done) {
  9681. done(status, text);
  9682. }
  9683. };
  9684. addEventListenerFn(script, "load", callback);
  9685. addEventListenerFn(script, "error", callback);
  9686. rawDocument.body.appendChild(script);
  9687. return callback;
  9688. }
  9689. }
  9690. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  9691. $interpolateMinErr.throwNoconcat = function(text) {
  9692. throw $interpolateMinErr('noconcat',
  9693. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  9694. "interpolations that concatenate multiple expressions when a trusted value is " +
  9695. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  9696. };
  9697. $interpolateMinErr.interr = function(text, err) {
  9698. return $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
  9699. };
  9700. /**
  9701. * @ngdoc provider
  9702. * @name $interpolateProvider
  9703. *
  9704. * @description
  9705. *
  9706. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  9707. *
  9708. * @example
  9709. <example module="customInterpolationApp">
  9710. <file name="index.html">
  9711. <script>
  9712. var customInterpolationApp = angular.module('customInterpolationApp', []);
  9713. customInterpolationApp.config(function($interpolateProvider) {
  9714. $interpolateProvider.startSymbol('//');
  9715. $interpolateProvider.endSymbol('//');
  9716. });
  9717. customInterpolationApp.controller('DemoController', function() {
  9718. this.label = "This binding is brought you by // interpolation symbols.";
  9719. });
  9720. </script>
  9721. <div ng-app="App" ng-controller="DemoController as demo">
  9722. //demo.label//
  9723. </div>
  9724. </file>
  9725. <file name="protractor.js" type="protractor">
  9726. it('should interpolate binding with custom symbols', function() {
  9727. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  9728. });
  9729. </file>
  9730. </example>
  9731. */
  9732. function $InterpolateProvider() {
  9733. var startSymbol = '{{';
  9734. var endSymbol = '}}';
  9735. /**
  9736. * @ngdoc method
  9737. * @name $interpolateProvider#startSymbol
  9738. * @description
  9739. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  9740. *
  9741. * @param {string=} value new value to set the starting symbol to.
  9742. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  9743. */
  9744. this.startSymbol = function(value) {
  9745. if (value) {
  9746. startSymbol = value;
  9747. return this;
  9748. } else {
  9749. return startSymbol;
  9750. }
  9751. };
  9752. /**
  9753. * @ngdoc method
  9754. * @name $interpolateProvider#endSymbol
  9755. * @description
  9756. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  9757. *
  9758. * @param {string=} value new value to set the ending symbol to.
  9759. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  9760. */
  9761. this.endSymbol = function(value) {
  9762. if (value) {
  9763. endSymbol = value;
  9764. return this;
  9765. } else {
  9766. return endSymbol;
  9767. }
  9768. };
  9769. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  9770. var startSymbolLength = startSymbol.length,
  9771. endSymbolLength = endSymbol.length,
  9772. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  9773. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  9774. function escape(ch) {
  9775. return '\\\\\\' + ch;
  9776. }
  9777. function unescapeText(text) {
  9778. return text.replace(escapedStartRegexp, startSymbol).
  9779. replace(escapedEndRegexp, endSymbol);
  9780. }
  9781. function stringify(value) {
  9782. if (value == null) { // null || undefined
  9783. return '';
  9784. }
  9785. switch (typeof value) {
  9786. case 'string':
  9787. break;
  9788. case 'number':
  9789. value = '' + value;
  9790. break;
  9791. default:
  9792. value = toJson(value);
  9793. }
  9794. return value;
  9795. }
  9796. /**
  9797. * @ngdoc service
  9798. * @name $interpolate
  9799. * @kind function
  9800. *
  9801. * @requires $parse
  9802. * @requires $sce
  9803. *
  9804. * @description
  9805. *
  9806. * Compiles a string with markup into an interpolation function. This service is used by the
  9807. * HTML {@link ng.$compile $compile} service for data binding. See
  9808. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  9809. * interpolation markup.
  9810. *
  9811. *
  9812. * ```js
  9813. * var $interpolate = ...; // injected
  9814. * var exp = $interpolate('Hello {{name | uppercase}}!');
  9815. * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
  9816. * ```
  9817. *
  9818. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  9819. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  9820. * evaluate to a value other than `undefined`.
  9821. *
  9822. * ```js
  9823. * var $interpolate = ...; // injected
  9824. * var context = {greeting: 'Hello', name: undefined };
  9825. *
  9826. * // default "forgiving" mode
  9827. * var exp = $interpolate('{{greeting}} {{name}}!');
  9828. * expect(exp(context)).toEqual('Hello !');
  9829. *
  9830. * // "allOrNothing" mode
  9831. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  9832. * expect(exp(context)).toBeUndefined();
  9833. * context.name = 'Angular';
  9834. * expect(exp(context)).toEqual('Hello Angular!');
  9835. * ```
  9836. *
  9837. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  9838. *
  9839. * ####Escaped Interpolation
  9840. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  9841. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  9842. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  9843. * or binding.
  9844. *
  9845. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  9846. * degree, while also enabling code examples to work without relying on the
  9847. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  9848. *
  9849. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  9850. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  9851. * interpolation start/end markers with their escaped counterparts.**
  9852. *
  9853. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  9854. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  9855. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  9856. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  9857. * this is typically useful only when user-data is used in rendering a template from the server, or
  9858. * when otherwise untrusted data is used by a directive.
  9859. *
  9860. * <example>
  9861. * <file name="index.html">
  9862. * <div ng-init="username='A user'">
  9863. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  9864. * </p>
  9865. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  9866. * application, but fails to accomplish their task, because the server has correctly
  9867. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  9868. * characters.</p>
  9869. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  9870. * from the database by an administrator.</p>
  9871. * </div>
  9872. * </file>
  9873. * </example>
  9874. *
  9875. * @param {string} text The text with markup to interpolate.
  9876. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  9877. * embedded expression in order to return an interpolation function. Strings with no
  9878. * embedded expression will return null for the interpolation function.
  9879. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  9880. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  9881. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  9882. * provides Strict Contextual Escaping for details.
  9883. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  9884. * unless all embedded expressions evaluate to a value other than `undefined`.
  9885. * @returns {function(context)} an interpolation function which is used to compute the
  9886. * interpolated string. The function has these parameters:
  9887. *
  9888. * - `context`: evaluation context for all expressions embedded in the interpolated text
  9889. */
  9890. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  9891. allOrNothing = !!allOrNothing;
  9892. var startIndex,
  9893. endIndex,
  9894. index = 0,
  9895. expressions = [],
  9896. parseFns = [],
  9897. textLength = text.length,
  9898. exp,
  9899. concat = [],
  9900. expressionPositions = [];
  9901. while (index < textLength) {
  9902. if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  9903. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
  9904. if (index !== startIndex) {
  9905. concat.push(unescapeText(text.substring(index, startIndex)));
  9906. }
  9907. exp = text.substring(startIndex + startSymbolLength, endIndex);
  9908. expressions.push(exp);
  9909. parseFns.push($parse(exp, parseStringifyInterceptor));
  9910. index = endIndex + endSymbolLength;
  9911. expressionPositions.push(concat.length);
  9912. concat.push('');
  9913. } else {
  9914. // we did not find an interpolation, so we have to add the remainder to the separators array
  9915. if (index !== textLength) {
  9916. concat.push(unescapeText(text.substring(index)));
  9917. }
  9918. break;
  9919. }
  9920. }
  9921. // Concatenating expressions makes it hard to reason about whether some combination of
  9922. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  9923. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  9924. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  9925. // make it obvious that you bound the value to some user controlled value. This helps reduce
  9926. // the load when auditing for XSS issues.
  9927. if (trustedContext && concat.length > 1) {
  9928. $interpolateMinErr.throwNoconcat(text);
  9929. }
  9930. if (!mustHaveExpression || expressions.length) {
  9931. var compute = function(values) {
  9932. for (var i = 0, ii = expressions.length; i < ii; i++) {
  9933. if (allOrNothing && isUndefined(values[i])) return;
  9934. concat[expressionPositions[i]] = values[i];
  9935. }
  9936. return concat.join('');
  9937. };
  9938. var getValue = function(value) {
  9939. return trustedContext ?
  9940. $sce.getTrusted(trustedContext, value) :
  9941. $sce.valueOf(value);
  9942. };
  9943. return extend(function interpolationFn(context) {
  9944. var i = 0;
  9945. var ii = expressions.length;
  9946. var values = new Array(ii);
  9947. try {
  9948. for (; i < ii; i++) {
  9949. values[i] = parseFns[i](context);
  9950. }
  9951. return compute(values);
  9952. } catch (err) {
  9953. $exceptionHandler($interpolateMinErr.interr(text, err));
  9954. }
  9955. }, {
  9956. // all of these properties are undocumented for now
  9957. exp: text, //just for compatibility with regular watchers created via $watch
  9958. expressions: expressions,
  9959. $$watchDelegate: function(scope, listener) {
  9960. var lastValue;
  9961. return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
  9962. var currValue = compute(values);
  9963. if (isFunction(listener)) {
  9964. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  9965. }
  9966. lastValue = currValue;
  9967. });
  9968. }
  9969. });
  9970. }
  9971. function parseStringifyInterceptor(value) {
  9972. try {
  9973. value = getValue(value);
  9974. return allOrNothing && !isDefined(value) ? value : stringify(value);
  9975. } catch (err) {
  9976. $exceptionHandler($interpolateMinErr.interr(text, err));
  9977. }
  9978. }
  9979. }
  9980. /**
  9981. * @ngdoc method
  9982. * @name $interpolate#startSymbol
  9983. * @description
  9984. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  9985. *
  9986. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  9987. * the symbol.
  9988. *
  9989. * @returns {string} start symbol.
  9990. */
  9991. $interpolate.startSymbol = function() {
  9992. return startSymbol;
  9993. };
  9994. /**
  9995. * @ngdoc method
  9996. * @name $interpolate#endSymbol
  9997. * @description
  9998. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  9999. *
  10000. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  10001. * the symbol.
  10002. *
  10003. * @returns {string} end symbol.
  10004. */
  10005. $interpolate.endSymbol = function() {
  10006. return endSymbol;
  10007. };
  10008. return $interpolate;
  10009. }];
  10010. }
  10011. function $IntervalProvider() {
  10012. this.$get = ['$rootScope', '$window', '$q', '$$q',
  10013. function($rootScope, $window, $q, $$q) {
  10014. var intervals = {};
  10015. /**
  10016. * @ngdoc service
  10017. * @name $interval
  10018. *
  10019. * @description
  10020. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  10021. * milliseconds.
  10022. *
  10023. * The return value of registering an interval function is a promise. This promise will be
  10024. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  10025. * run indefinitely if `count` is not defined. The value of the notification will be the
  10026. * number of iterations that have run.
  10027. * To cancel an interval, call `$interval.cancel(promise)`.
  10028. *
  10029. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  10030. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  10031. * time.
  10032. *
  10033. * <div class="alert alert-warning">
  10034. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  10035. * with them. In particular they are not automatically destroyed when a controller's scope or a
  10036. * directive's element are destroyed.
  10037. * You should take this into consideration and make sure to always cancel the interval at the
  10038. * appropriate moment. See the example below for more details on how and when to do this.
  10039. * </div>
  10040. *
  10041. * @param {function()} fn A function that should be called repeatedly.
  10042. * @param {number} delay Number of milliseconds between each function call.
  10043. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  10044. * indefinitely.
  10045. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  10046. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  10047. * @param {...*=} Pass additional parameters to the executed function.
  10048. * @returns {promise} A promise which will be notified on each iteration.
  10049. *
  10050. * @example
  10051. * <example module="intervalExample">
  10052. * <file name="index.html">
  10053. * <script>
  10054. * angular.module('intervalExample', [])
  10055. * .controller('ExampleController', ['$scope', '$interval',
  10056. * function($scope, $interval) {
  10057. * $scope.format = 'M/d/yy h:mm:ss a';
  10058. * $scope.blood_1 = 100;
  10059. * $scope.blood_2 = 120;
  10060. *
  10061. * var stop;
  10062. * $scope.fight = function() {
  10063. * // Don't start a new fight if we are already fighting
  10064. * if ( angular.isDefined(stop) ) return;
  10065. *
  10066. * stop = $interval(function() {
  10067. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  10068. * $scope.blood_1 = $scope.blood_1 - 3;
  10069. * $scope.blood_2 = $scope.blood_2 - 4;
  10070. * } else {
  10071. * $scope.stopFight();
  10072. * }
  10073. * }, 100);
  10074. * };
  10075. *
  10076. * $scope.stopFight = function() {
  10077. * if (angular.isDefined(stop)) {
  10078. * $interval.cancel(stop);
  10079. * stop = undefined;
  10080. * }
  10081. * };
  10082. *
  10083. * $scope.resetFight = function() {
  10084. * $scope.blood_1 = 100;
  10085. * $scope.blood_2 = 120;
  10086. * };
  10087. *
  10088. * $scope.$on('$destroy', function() {
  10089. * // Make sure that the interval is destroyed too
  10090. * $scope.stopFight();
  10091. * });
  10092. * }])
  10093. * // Register the 'myCurrentTime' directive factory method.
  10094. * // We inject $interval and dateFilter service since the factory method is DI.
  10095. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  10096. * function($interval, dateFilter) {
  10097. * // return the directive link function. (compile function not needed)
  10098. * return function(scope, element, attrs) {
  10099. * var format, // date format
  10100. * stopTime; // so that we can cancel the time updates
  10101. *
  10102. * // used to update the UI
  10103. * function updateTime() {
  10104. * element.text(dateFilter(new Date(), format));
  10105. * }
  10106. *
  10107. * // watch the expression, and update the UI on change.
  10108. * scope.$watch(attrs.myCurrentTime, function(value) {
  10109. * format = value;
  10110. * updateTime();
  10111. * });
  10112. *
  10113. * stopTime = $interval(updateTime, 1000);
  10114. *
  10115. * // listen on DOM destroy (removal) event, and cancel the next UI update
  10116. * // to prevent updating time after the DOM element was removed.
  10117. * element.on('$destroy', function() {
  10118. * $interval.cancel(stopTime);
  10119. * });
  10120. * }
  10121. * }]);
  10122. * </script>
  10123. *
  10124. * <div>
  10125. * <div ng-controller="ExampleController">
  10126. * <label>Date format: <input ng-model="format"></label> <hr/>
  10127. * Current time is: <span my-current-time="format"></span>
  10128. * <hr/>
  10129. * Blood 1 : <font color='red'>{{blood_1}}</font>
  10130. * Blood 2 : <font color='red'>{{blood_2}}</font>
  10131. * <button type="button" data-ng-click="fight()">Fight</button>
  10132. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  10133. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  10134. * </div>
  10135. * </div>
  10136. *
  10137. * </file>
  10138. * </example>
  10139. */
  10140. function interval(fn, delay, count, invokeApply) {
  10141. var hasParams = arguments.length > 4,
  10142. args = hasParams ? sliceArgs(arguments, 4) : [],
  10143. setInterval = $window.setInterval,
  10144. clearInterval = $window.clearInterval,
  10145. iteration = 0,
  10146. skipApply = (isDefined(invokeApply) && !invokeApply),
  10147. deferred = (skipApply ? $$q : $q).defer(),
  10148. promise = deferred.promise;
  10149. count = isDefined(count) ? count : 0;
  10150. promise.then(null, null, (!hasParams) ? fn : function() {
  10151. fn.apply(null, args);
  10152. });
  10153. promise.$$intervalId = setInterval(function tick() {
  10154. deferred.notify(iteration++);
  10155. if (count > 0 && iteration >= count) {
  10156. deferred.resolve(iteration);
  10157. clearInterval(promise.$$intervalId);
  10158. delete intervals[promise.$$intervalId];
  10159. }
  10160. if (!skipApply) $rootScope.$apply();
  10161. }, delay);
  10162. intervals[promise.$$intervalId] = deferred;
  10163. return promise;
  10164. }
  10165. /**
  10166. * @ngdoc method
  10167. * @name $interval#cancel
  10168. *
  10169. * @description
  10170. * Cancels a task associated with the `promise`.
  10171. *
  10172. * @param {Promise=} promise returned by the `$interval` function.
  10173. * @returns {boolean} Returns `true` if the task was successfully canceled.
  10174. */
  10175. interval.cancel = function(promise) {
  10176. if (promise && promise.$$intervalId in intervals) {
  10177. intervals[promise.$$intervalId].reject('canceled');
  10178. $window.clearInterval(promise.$$intervalId);
  10179. delete intervals[promise.$$intervalId];
  10180. return true;
  10181. }
  10182. return false;
  10183. };
  10184. return interval;
  10185. }];
  10186. }
  10187. /**
  10188. * @ngdoc service
  10189. * @name $locale
  10190. *
  10191. * @description
  10192. * $locale service provides localization rules for various Angular components. As of right now the
  10193. * only public api is:
  10194. *
  10195. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  10196. */
  10197. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  10198. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  10199. var $locationMinErr = minErr('$location');
  10200. /**
  10201. * Encode path using encodeUriSegment, ignoring forward slashes
  10202. *
  10203. * @param {string} path Path to encode
  10204. * @returns {string}
  10205. */
  10206. function encodePath(path) {
  10207. var segments = path.split('/'),
  10208. i = segments.length;
  10209. while (i--) {
  10210. segments[i] = encodeUriSegment(segments[i]);
  10211. }
  10212. return segments.join('/');
  10213. }
  10214. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  10215. var parsedUrl = urlResolve(absoluteUrl);
  10216. locationObj.$$protocol = parsedUrl.protocol;
  10217. locationObj.$$host = parsedUrl.hostname;
  10218. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  10219. }
  10220. function parseAppUrl(relativeUrl, locationObj) {
  10221. var prefixed = (relativeUrl.charAt(0) !== '/');
  10222. if (prefixed) {
  10223. relativeUrl = '/' + relativeUrl;
  10224. }
  10225. var match = urlResolve(relativeUrl);
  10226. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  10227. match.pathname.substring(1) : match.pathname);
  10228. locationObj.$$search = parseKeyValue(match.search);
  10229. locationObj.$$hash = decodeURIComponent(match.hash);
  10230. // make sure path starts with '/';
  10231. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  10232. locationObj.$$path = '/' + locationObj.$$path;
  10233. }
  10234. }
  10235. /**
  10236. *
  10237. * @param {string} begin
  10238. * @param {string} whole
  10239. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  10240. * expected string.
  10241. */
  10242. function beginsWith(begin, whole) {
  10243. if (whole.indexOf(begin) === 0) {
  10244. return whole.substr(begin.length);
  10245. }
  10246. }
  10247. function stripHash(url) {
  10248. var index = url.indexOf('#');
  10249. return index == -1 ? url : url.substr(0, index);
  10250. }
  10251. function trimEmptyHash(url) {
  10252. return url.replace(/(#.+)|#$/, '$1');
  10253. }
  10254. function stripFile(url) {
  10255. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  10256. }
  10257. /* return the server only (scheme://host:port) */
  10258. function serverBase(url) {
  10259. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  10260. }
  10261. /**
  10262. * LocationHtml5Url represents an url
  10263. * This object is exposed as $location service when HTML5 mode is enabled and supported
  10264. *
  10265. * @constructor
  10266. * @param {string} appBase application base URL
  10267. * @param {string} appBaseNoFile application base URL stripped of any filename
  10268. * @param {string} basePrefix url path prefix
  10269. */
  10270. function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
  10271. this.$$html5 = true;
  10272. basePrefix = basePrefix || '';
  10273. parseAbsoluteUrl(appBase, this);
  10274. /**
  10275. * Parse given html5 (regular) url string into properties
  10276. * @param {string} url HTML5 url
  10277. * @private
  10278. */
  10279. this.$$parse = function(url) {
  10280. var pathUrl = beginsWith(appBaseNoFile, url);
  10281. if (!isString(pathUrl)) {
  10282. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  10283. appBaseNoFile);
  10284. }
  10285. parseAppUrl(pathUrl, this);
  10286. if (!this.$$path) {
  10287. this.$$path = '/';
  10288. }
  10289. this.$$compose();
  10290. };
  10291. /**
  10292. * Compose url and update `absUrl` property
  10293. * @private
  10294. */
  10295. this.$$compose = function() {
  10296. var search = toKeyValue(this.$$search),
  10297. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10298. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10299. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  10300. };
  10301. this.$$parseLinkUrl = function(url, relHref) {
  10302. if (relHref && relHref[0] === '#') {
  10303. // special case for links to hash fragments:
  10304. // keep the old url and only replace the hash fragment
  10305. this.hash(relHref.slice(1));
  10306. return true;
  10307. }
  10308. var appUrl, prevAppUrl;
  10309. var rewrittenUrl;
  10310. if ((appUrl = beginsWith(appBase, url)) !== undefined) {
  10311. prevAppUrl = appUrl;
  10312. if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) {
  10313. rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  10314. } else {
  10315. rewrittenUrl = appBase + prevAppUrl;
  10316. }
  10317. } else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) {
  10318. rewrittenUrl = appBaseNoFile + appUrl;
  10319. } else if (appBaseNoFile == url + '/') {
  10320. rewrittenUrl = appBaseNoFile;
  10321. }
  10322. if (rewrittenUrl) {
  10323. this.$$parse(rewrittenUrl);
  10324. }
  10325. return !!rewrittenUrl;
  10326. };
  10327. }
  10328. /**
  10329. * LocationHashbangUrl represents url
  10330. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  10331. * It also serves as the base class for html5 mode fallback on legacy browsers.
  10332. *
  10333. * @constructor
  10334. * @param {string} appBase application base URL
  10335. * @param {string} appBaseNoFile application base URL stripped of any filename
  10336. * @param {string} hashPrefix hashbang prefix
  10337. */
  10338. function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
  10339. parseAbsoluteUrl(appBase, this);
  10340. /**
  10341. * Parse given hashbang url into properties
  10342. * @param {string} url Hashbang url
  10343. * @private
  10344. */
  10345. this.$$parse = function(url) {
  10346. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  10347. var withoutHashUrl;
  10348. if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
  10349. // The rest of the url starts with a hash so we have
  10350. // got either a hashbang path or a plain hash fragment
  10351. withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
  10352. if (isUndefined(withoutHashUrl)) {
  10353. // There was no hashbang prefix so we just have a hash fragment
  10354. withoutHashUrl = withoutBaseUrl;
  10355. }
  10356. } else {
  10357. // There was no hashbang path nor hash fragment:
  10358. // If we are in HTML5 mode we use what is left as the path;
  10359. // Otherwise we ignore what is left
  10360. if (this.$$html5) {
  10361. withoutHashUrl = withoutBaseUrl;
  10362. } else {
  10363. withoutHashUrl = '';
  10364. if (isUndefined(withoutBaseUrl)) {
  10365. appBase = url;
  10366. this.replace();
  10367. }
  10368. }
  10369. }
  10370. parseAppUrl(withoutHashUrl, this);
  10371. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  10372. this.$$compose();
  10373. /*
  10374. * In Windows, on an anchor node on documents loaded from
  10375. * the filesystem, the browser will return a pathname
  10376. * prefixed with the drive name ('/C:/path') when a
  10377. * pathname without a drive is set:
  10378. * * a.setAttribute('href', '/foo')
  10379. * * a.pathname === '/C:/foo' //true
  10380. *
  10381. * Inside of Angular, we're always using pathnames that
  10382. * do not include drive names for routing.
  10383. */
  10384. function removeWindowsDriveName(path, url, base) {
  10385. /*
  10386. Matches paths for file protocol on windows,
  10387. such as /C:/foo/bar, and captures only /foo/bar.
  10388. */
  10389. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  10390. var firstPathSegmentMatch;
  10391. //Get the relative path from the input URL.
  10392. if (url.indexOf(base) === 0) {
  10393. url = url.replace(base, '');
  10394. }
  10395. // The input URL intentionally contains a first path segment that ends with a colon.
  10396. if (windowsFilePathExp.exec(url)) {
  10397. return path;
  10398. }
  10399. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  10400. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  10401. }
  10402. };
  10403. /**
  10404. * Compose hashbang url and update `absUrl` property
  10405. * @private
  10406. */
  10407. this.$$compose = function() {
  10408. var search = toKeyValue(this.$$search),
  10409. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10410. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10411. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  10412. };
  10413. this.$$parseLinkUrl = function(url, relHref) {
  10414. if (stripHash(appBase) == stripHash(url)) {
  10415. this.$$parse(url);
  10416. return true;
  10417. }
  10418. return false;
  10419. };
  10420. }
  10421. /**
  10422. * LocationHashbangUrl represents url
  10423. * This object is exposed as $location service when html5 history api is enabled but the browser
  10424. * does not support it.
  10425. *
  10426. * @constructor
  10427. * @param {string} appBase application base URL
  10428. * @param {string} appBaseNoFile application base URL stripped of any filename
  10429. * @param {string} hashPrefix hashbang prefix
  10430. */
  10431. function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
  10432. this.$$html5 = true;
  10433. LocationHashbangUrl.apply(this, arguments);
  10434. this.$$parseLinkUrl = function(url, relHref) {
  10435. if (relHref && relHref[0] === '#') {
  10436. // special case for links to hash fragments:
  10437. // keep the old url and only replace the hash fragment
  10438. this.hash(relHref.slice(1));
  10439. return true;
  10440. }
  10441. var rewrittenUrl;
  10442. var appUrl;
  10443. if (appBase == stripHash(url)) {
  10444. rewrittenUrl = url;
  10445. } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
  10446. rewrittenUrl = appBase + hashPrefix + appUrl;
  10447. } else if (appBaseNoFile === url + '/') {
  10448. rewrittenUrl = appBaseNoFile;
  10449. }
  10450. if (rewrittenUrl) {
  10451. this.$$parse(rewrittenUrl);
  10452. }
  10453. return !!rewrittenUrl;
  10454. };
  10455. this.$$compose = function() {
  10456. var search = toKeyValue(this.$$search),
  10457. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10458. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10459. // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
  10460. this.$$absUrl = appBase + hashPrefix + this.$$url;
  10461. };
  10462. }
  10463. var locationPrototype = {
  10464. /**
  10465. * Are we in html5 mode?
  10466. * @private
  10467. */
  10468. $$html5: false,
  10469. /**
  10470. * Has any change been replacing?
  10471. * @private
  10472. */
  10473. $$replace: false,
  10474. /**
  10475. * @ngdoc method
  10476. * @name $location#absUrl
  10477. *
  10478. * @description
  10479. * This method is getter only.
  10480. *
  10481. * Return full url representation with all segments encoded according to rules specified in
  10482. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  10483. *
  10484. *
  10485. * ```js
  10486. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10487. * var absUrl = $location.absUrl();
  10488. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  10489. * ```
  10490. *
  10491. * @return {string} full url
  10492. */
  10493. absUrl: locationGetter('$$absUrl'),
  10494. /**
  10495. * @ngdoc method
  10496. * @name $location#url
  10497. *
  10498. * @description
  10499. * This method is getter / setter.
  10500. *
  10501. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  10502. *
  10503. * Change path, search and hash, when called with parameter and return `$location`.
  10504. *
  10505. *
  10506. * ```js
  10507. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10508. * var url = $location.url();
  10509. * // => "/some/path?foo=bar&baz=xoxo"
  10510. * ```
  10511. *
  10512. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  10513. * @return {string} url
  10514. */
  10515. url: function(url) {
  10516. if (isUndefined(url)) {
  10517. return this.$$url;
  10518. }
  10519. var match = PATH_MATCH.exec(url);
  10520. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  10521. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  10522. this.hash(match[5] || '');
  10523. return this;
  10524. },
  10525. /**
  10526. * @ngdoc method
  10527. * @name $location#protocol
  10528. *
  10529. * @description
  10530. * This method is getter only.
  10531. *
  10532. * Return protocol of current url.
  10533. *
  10534. *
  10535. * ```js
  10536. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10537. * var protocol = $location.protocol();
  10538. * // => "http"
  10539. * ```
  10540. *
  10541. * @return {string} protocol of current url
  10542. */
  10543. protocol: locationGetter('$$protocol'),
  10544. /**
  10545. * @ngdoc method
  10546. * @name $location#host
  10547. *
  10548. * @description
  10549. * This method is getter only.
  10550. *
  10551. * Return host of current url.
  10552. *
  10553. * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  10554. *
  10555. *
  10556. * ```js
  10557. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10558. * var host = $location.host();
  10559. * // => "example.com"
  10560. *
  10561. * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  10562. * host = $location.host();
  10563. * // => "example.com"
  10564. * host = location.host;
  10565. * // => "example.com:8080"
  10566. * ```
  10567. *
  10568. * @return {string} host of current url.
  10569. */
  10570. host: locationGetter('$$host'),
  10571. /**
  10572. * @ngdoc method
  10573. * @name $location#port
  10574. *
  10575. * @description
  10576. * This method is getter only.
  10577. *
  10578. * Return port of current url.
  10579. *
  10580. *
  10581. * ```js
  10582. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10583. * var port = $location.port();
  10584. * // => 80
  10585. * ```
  10586. *
  10587. * @return {Number} port
  10588. */
  10589. port: locationGetter('$$port'),
  10590. /**
  10591. * @ngdoc method
  10592. * @name $location#path
  10593. *
  10594. * @description
  10595. * This method is getter / setter.
  10596. *
  10597. * Return path of current url when called without any parameter.
  10598. *
  10599. * Change path when called with parameter and return `$location`.
  10600. *
  10601. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  10602. * if it is missing.
  10603. *
  10604. *
  10605. * ```js
  10606. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10607. * var path = $location.path();
  10608. * // => "/some/path"
  10609. * ```
  10610. *
  10611. * @param {(string|number)=} path New path
  10612. * @return {string} path
  10613. */
  10614. path: locationGetterSetter('$$path', function(path) {
  10615. path = path !== null ? path.toString() : '';
  10616. return path.charAt(0) == '/' ? path : '/' + path;
  10617. }),
  10618. /**
  10619. * @ngdoc method
  10620. * @name $location#search
  10621. *
  10622. * @description
  10623. * This method is getter / setter.
  10624. *
  10625. * Return search part (as object) of current url when called without any parameter.
  10626. *
  10627. * Change search part when called with parameter and return `$location`.
  10628. *
  10629. *
  10630. * ```js
  10631. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10632. * var searchObject = $location.search();
  10633. * // => {foo: 'bar', baz: 'xoxo'}
  10634. *
  10635. * // set foo to 'yipee'
  10636. * $location.search('foo', 'yipee');
  10637. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  10638. * ```
  10639. *
  10640. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  10641. * hash object.
  10642. *
  10643. * When called with a single argument the method acts as a setter, setting the `search` component
  10644. * of `$location` to the specified value.
  10645. *
  10646. * If the argument is a hash object containing an array of values, these values will be encoded
  10647. * as duplicate search parameters in the url.
  10648. *
  10649. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  10650. * will override only a single search property.
  10651. *
  10652. * If `paramValue` is an array, it will override the property of the `search` component of
  10653. * `$location` specified via the first argument.
  10654. *
  10655. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  10656. *
  10657. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  10658. * value nor trailing equal sign.
  10659. *
  10660. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  10661. * one or more arguments returns `$location` object itself.
  10662. */
  10663. search: function(search, paramValue) {
  10664. switch (arguments.length) {
  10665. case 0:
  10666. return this.$$search;
  10667. case 1:
  10668. if (isString(search) || isNumber(search)) {
  10669. search = search.toString();
  10670. this.$$search = parseKeyValue(search);
  10671. } else if (isObject(search)) {
  10672. search = copy(search, {});
  10673. // remove object undefined or null properties
  10674. forEach(search, function(value, key) {
  10675. if (value == null) delete search[key];
  10676. });
  10677. this.$$search = search;
  10678. } else {
  10679. throw $locationMinErr('isrcharg',
  10680. 'The first argument of the `$location#search()` call must be a string or an object.');
  10681. }
  10682. break;
  10683. default:
  10684. if (isUndefined(paramValue) || paramValue === null) {
  10685. delete this.$$search[search];
  10686. } else {
  10687. this.$$search[search] = paramValue;
  10688. }
  10689. }
  10690. this.$$compose();
  10691. return this;
  10692. },
  10693. /**
  10694. * @ngdoc method
  10695. * @name $location#hash
  10696. *
  10697. * @description
  10698. * This method is getter / setter.
  10699. *
  10700. * Return hash fragment when called without any parameter.
  10701. *
  10702. * Change hash fragment when called with parameter and return `$location`.
  10703. *
  10704. *
  10705. * ```js
  10706. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  10707. * var hash = $location.hash();
  10708. * // => "hashValue"
  10709. * ```
  10710. *
  10711. * @param {(string|number)=} hash New hash fragment
  10712. * @return {string} hash
  10713. */
  10714. hash: locationGetterSetter('$$hash', function(hash) {
  10715. return hash !== null ? hash.toString() : '';
  10716. }),
  10717. /**
  10718. * @ngdoc method
  10719. * @name $location#replace
  10720. *
  10721. * @description
  10722. * If called, all changes to $location during current `$digest` will be replacing current history
  10723. * record, instead of adding new one.
  10724. */
  10725. replace: function() {
  10726. this.$$replace = true;
  10727. return this;
  10728. }
  10729. };
  10730. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  10731. Location.prototype = Object.create(locationPrototype);
  10732. /**
  10733. * @ngdoc method
  10734. * @name $location#state
  10735. *
  10736. * @description
  10737. * This method is getter / setter.
  10738. *
  10739. * Return the history state object when called without any parameter.
  10740. *
  10741. * Change the history state object when called with one parameter and return `$location`.
  10742. * The state object is later passed to `pushState` or `replaceState`.
  10743. *
  10744. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  10745. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  10746. * older browsers (like IE9 or Android < 4.0), don't use this method.
  10747. *
  10748. * @param {object=} state State object for pushState or replaceState
  10749. * @return {object} state
  10750. */
  10751. Location.prototype.state = function(state) {
  10752. if (!arguments.length) {
  10753. return this.$$state;
  10754. }
  10755. if (Location !== LocationHtml5Url || !this.$$html5) {
  10756. throw $locationMinErr('nostate', 'History API state support is available only ' +
  10757. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  10758. }
  10759. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  10760. // but we're changing the $$state reference to $browser.state() during the $digest
  10761. // so the modification window is narrow.
  10762. this.$$state = isUndefined(state) ? null : state;
  10763. return this;
  10764. };
  10765. });
  10766. function locationGetter(property) {
  10767. return function() {
  10768. return this[property];
  10769. };
  10770. }
  10771. function locationGetterSetter(property, preprocess) {
  10772. return function(value) {
  10773. if (isUndefined(value)) {
  10774. return this[property];
  10775. }
  10776. this[property] = preprocess(value);
  10777. this.$$compose();
  10778. return this;
  10779. };
  10780. }
  10781. /**
  10782. * @ngdoc service
  10783. * @name $location
  10784. *
  10785. * @requires $rootElement
  10786. *
  10787. * @description
  10788. * The $location service parses the URL in the browser address bar (based on the
  10789. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  10790. * available to your application. Changes to the URL in the address bar are reflected into
  10791. * $location service and changes to $location are reflected into the browser address bar.
  10792. *
  10793. * **The $location service:**
  10794. *
  10795. * - Exposes the current URL in the browser address bar, so you can
  10796. * - Watch and observe the URL.
  10797. * - Change the URL.
  10798. * - Synchronizes the URL with the browser when the user
  10799. * - Changes the address bar.
  10800. * - Clicks the back or forward button (or clicks a History link).
  10801. * - Clicks on a link.
  10802. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  10803. *
  10804. * For more information see {@link guide/$location Developer Guide: Using $location}
  10805. */
  10806. /**
  10807. * @ngdoc provider
  10808. * @name $locationProvider
  10809. * @description
  10810. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  10811. */
  10812. function $LocationProvider() {
  10813. var hashPrefix = '',
  10814. html5Mode = {
  10815. enabled: false,
  10816. requireBase: true,
  10817. rewriteLinks: true
  10818. };
  10819. /**
  10820. * @ngdoc method
  10821. * @name $locationProvider#hashPrefix
  10822. * @description
  10823. * @param {string=} prefix Prefix for hash part (containing path and search)
  10824. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  10825. */
  10826. this.hashPrefix = function(prefix) {
  10827. if (isDefined(prefix)) {
  10828. hashPrefix = prefix;
  10829. return this;
  10830. } else {
  10831. return hashPrefix;
  10832. }
  10833. };
  10834. /**
  10835. * @ngdoc method
  10836. * @name $locationProvider#html5Mode
  10837. * @description
  10838. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  10839. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  10840. * properties:
  10841. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  10842. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  10843. * support `pushState`.
  10844. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  10845. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  10846. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  10847. * See the {@link guide/$location $location guide for more information}
  10848. * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
  10849. * enables/disables url rewriting for relative links.
  10850. *
  10851. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  10852. */
  10853. this.html5Mode = function(mode) {
  10854. if (isBoolean(mode)) {
  10855. html5Mode.enabled = mode;
  10856. return this;
  10857. } else if (isObject(mode)) {
  10858. if (isBoolean(mode.enabled)) {
  10859. html5Mode.enabled = mode.enabled;
  10860. }
  10861. if (isBoolean(mode.requireBase)) {
  10862. html5Mode.requireBase = mode.requireBase;
  10863. }
  10864. if (isBoolean(mode.rewriteLinks)) {
  10865. html5Mode.rewriteLinks = mode.rewriteLinks;
  10866. }
  10867. return this;
  10868. } else {
  10869. return html5Mode;
  10870. }
  10871. };
  10872. /**
  10873. * @ngdoc event
  10874. * @name $location#$locationChangeStart
  10875. * @eventType broadcast on root scope
  10876. * @description
  10877. * Broadcasted before a URL will change.
  10878. *
  10879. * This change can be prevented by calling
  10880. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  10881. * details about event object. Upon successful change
  10882. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  10883. *
  10884. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10885. * the browser supports the HTML5 History API.
  10886. *
  10887. * @param {Object} angularEvent Synthetic event object.
  10888. * @param {string} newUrl New URL
  10889. * @param {string=} oldUrl URL that was before it was changed.
  10890. * @param {string=} newState New history state object
  10891. * @param {string=} oldState History state object that was before it was changed.
  10892. */
  10893. /**
  10894. * @ngdoc event
  10895. * @name $location#$locationChangeSuccess
  10896. * @eventType broadcast on root scope
  10897. * @description
  10898. * Broadcasted after a URL was changed.
  10899. *
  10900. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10901. * the browser supports the HTML5 History API.
  10902. *
  10903. * @param {Object} angularEvent Synthetic event object.
  10904. * @param {string} newUrl New URL
  10905. * @param {string=} oldUrl URL that was before it was changed.
  10906. * @param {string=} newState New history state object
  10907. * @param {string=} oldState History state object that was before it was changed.
  10908. */
  10909. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  10910. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  10911. var $location,
  10912. LocationMode,
  10913. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  10914. initialUrl = $browser.url(),
  10915. appBase;
  10916. if (html5Mode.enabled) {
  10917. if (!baseHref && html5Mode.requireBase) {
  10918. throw $locationMinErr('nobase',
  10919. "$location in HTML5 mode requires a <base> tag to be present!");
  10920. }
  10921. appBase = serverBase(initialUrl) + (baseHref || '/');
  10922. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  10923. } else {
  10924. appBase = stripHash(initialUrl);
  10925. LocationMode = LocationHashbangUrl;
  10926. }
  10927. var appBaseNoFile = stripFile(appBase);
  10928. $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
  10929. $location.$$parseLinkUrl(initialUrl, initialUrl);
  10930. $location.$$state = $browser.state();
  10931. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  10932. function setBrowserUrlWithFallback(url, replace, state) {
  10933. var oldUrl = $location.url();
  10934. var oldState = $location.$$state;
  10935. try {
  10936. $browser.url(url, replace, state);
  10937. // Make sure $location.state() returns referentially identical (not just deeply equal)
  10938. // state object; this makes possible quick checking if the state changed in the digest
  10939. // loop. Checking deep equality would be too expensive.
  10940. $location.$$state = $browser.state();
  10941. } catch (e) {
  10942. // Restore old values if pushState fails
  10943. $location.url(oldUrl);
  10944. $location.$$state = oldState;
  10945. throw e;
  10946. }
  10947. }
  10948. $rootElement.on('click', function(event) {
  10949. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  10950. // currently we open nice url link and redirect then
  10951. if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
  10952. var elm = jqLite(event.target);
  10953. // traverse the DOM up to find first A tag
  10954. while (nodeName_(elm[0]) !== 'a') {
  10955. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  10956. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  10957. }
  10958. var absHref = elm.prop('href');
  10959. // get the actual href attribute - see
  10960. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  10961. var relHref = elm.attr('href') || elm.attr('xlink:href');
  10962. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  10963. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  10964. // an animation.
  10965. absHref = urlResolve(absHref.animVal).href;
  10966. }
  10967. // Ignore when url is started with javascript: or mailto:
  10968. if (IGNORE_URI_REGEXP.test(absHref)) return;
  10969. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  10970. if ($location.$$parseLinkUrl(absHref, relHref)) {
  10971. // We do a preventDefault for all urls that are part of the angular application,
  10972. // in html5mode and also without, so that we are able to abort navigation without
  10973. // getting double entries in the location history.
  10974. event.preventDefault();
  10975. // update location manually
  10976. if ($location.absUrl() != $browser.url()) {
  10977. $rootScope.$apply();
  10978. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  10979. $window.angular['ff-684208-preventDefault'] = true;
  10980. }
  10981. }
  10982. }
  10983. });
  10984. // rewrite hashbang url <> html5 url
  10985. if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
  10986. $browser.url($location.absUrl(), true);
  10987. }
  10988. var initializing = true;
  10989. // update $location when $browser url changes
  10990. $browser.onUrlChange(function(newUrl, newState) {
  10991. if (isUndefined(beginsWith(appBaseNoFile, newUrl))) {
  10992. // If we are navigating outside of the app then force a reload
  10993. $window.location.href = newUrl;
  10994. return;
  10995. }
  10996. $rootScope.$evalAsync(function() {
  10997. var oldUrl = $location.absUrl();
  10998. var oldState = $location.$$state;
  10999. var defaultPrevented;
  11000. $location.$$parse(newUrl);
  11001. $location.$$state = newState;
  11002. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  11003. newState, oldState).defaultPrevented;
  11004. // if the location was changed by a `$locationChangeStart` handler then stop
  11005. // processing this location change
  11006. if ($location.absUrl() !== newUrl) return;
  11007. if (defaultPrevented) {
  11008. $location.$$parse(oldUrl);
  11009. $location.$$state = oldState;
  11010. setBrowserUrlWithFallback(oldUrl, false, oldState);
  11011. } else {
  11012. initializing = false;
  11013. afterLocationChange(oldUrl, oldState);
  11014. }
  11015. });
  11016. if (!$rootScope.$$phase) $rootScope.$digest();
  11017. });
  11018. // update browser
  11019. $rootScope.$watch(function $locationWatch() {
  11020. var oldUrl = trimEmptyHash($browser.url());
  11021. var newUrl = trimEmptyHash($location.absUrl());
  11022. var oldState = $browser.state();
  11023. var currentReplace = $location.$$replace;
  11024. var urlOrStateChanged = oldUrl !== newUrl ||
  11025. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  11026. if (initializing || urlOrStateChanged) {
  11027. initializing = false;
  11028. $rootScope.$evalAsync(function() {
  11029. var newUrl = $location.absUrl();
  11030. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  11031. $location.$$state, oldState).defaultPrevented;
  11032. // if the location was changed by a `$locationChangeStart` handler then stop
  11033. // processing this location change
  11034. if ($location.absUrl() !== newUrl) return;
  11035. if (defaultPrevented) {
  11036. $location.$$parse(oldUrl);
  11037. $location.$$state = oldState;
  11038. } else {
  11039. if (urlOrStateChanged) {
  11040. setBrowserUrlWithFallback(newUrl, currentReplace,
  11041. oldState === $location.$$state ? null : $location.$$state);
  11042. }
  11043. afterLocationChange(oldUrl, oldState);
  11044. }
  11045. });
  11046. }
  11047. $location.$$replace = false;
  11048. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  11049. // there is a change
  11050. });
  11051. return $location;
  11052. function afterLocationChange(oldUrl, oldState) {
  11053. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  11054. $location.$$state, oldState);
  11055. }
  11056. }];
  11057. }
  11058. /**
  11059. * @ngdoc service
  11060. * @name $log
  11061. * @requires $window
  11062. *
  11063. * @description
  11064. * Simple service for logging. Default implementation safely writes the message
  11065. * into the browser's console (if present).
  11066. *
  11067. * The main purpose of this service is to simplify debugging and troubleshooting.
  11068. *
  11069. * The default is to log `debug` messages. You can use
  11070. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  11071. *
  11072. * @example
  11073. <example module="logExample">
  11074. <file name="script.js">
  11075. angular.module('logExample', [])
  11076. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  11077. $scope.$log = $log;
  11078. $scope.message = 'Hello World!';
  11079. }]);
  11080. </file>
  11081. <file name="index.html">
  11082. <div ng-controller="LogController">
  11083. <p>Reload this page with open console, enter text and hit the log button...</p>
  11084. <label>Message:
  11085. <input type="text" ng-model="message" /></label>
  11086. <button ng-click="$log.log(message)">log</button>
  11087. <button ng-click="$log.warn(message)">warn</button>
  11088. <button ng-click="$log.info(message)">info</button>
  11089. <button ng-click="$log.error(message)">error</button>
  11090. <button ng-click="$log.debug(message)">debug</button>
  11091. </div>
  11092. </file>
  11093. </example>
  11094. */
  11095. /**
  11096. * @ngdoc provider
  11097. * @name $logProvider
  11098. * @description
  11099. * Use the `$logProvider` to configure how the application logs messages
  11100. */
  11101. function $LogProvider() {
  11102. var debug = true,
  11103. self = this;
  11104. /**
  11105. * @ngdoc method
  11106. * @name $logProvider#debugEnabled
  11107. * @description
  11108. * @param {boolean=} flag enable or disable debug level messages
  11109. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  11110. */
  11111. this.debugEnabled = function(flag) {
  11112. if (isDefined(flag)) {
  11113. debug = flag;
  11114. return this;
  11115. } else {
  11116. return debug;
  11117. }
  11118. };
  11119. this.$get = ['$window', function($window) {
  11120. return {
  11121. /**
  11122. * @ngdoc method
  11123. * @name $log#log
  11124. *
  11125. * @description
  11126. * Write a log message
  11127. */
  11128. log: consoleLog('log'),
  11129. /**
  11130. * @ngdoc method
  11131. * @name $log#info
  11132. *
  11133. * @description
  11134. * Write an information message
  11135. */
  11136. info: consoleLog('info'),
  11137. /**
  11138. * @ngdoc method
  11139. * @name $log#warn
  11140. *
  11141. * @description
  11142. * Write a warning message
  11143. */
  11144. warn: consoleLog('warn'),
  11145. /**
  11146. * @ngdoc method
  11147. * @name $log#error
  11148. *
  11149. * @description
  11150. * Write an error message
  11151. */
  11152. error: consoleLog('error'),
  11153. /**
  11154. * @ngdoc method
  11155. * @name $log#debug
  11156. *
  11157. * @description
  11158. * Write a debug message
  11159. */
  11160. debug: (function() {
  11161. var fn = consoleLog('debug');
  11162. return function() {
  11163. if (debug) {
  11164. fn.apply(self, arguments);
  11165. }
  11166. };
  11167. }())
  11168. };
  11169. function formatError(arg) {
  11170. if (arg instanceof Error) {
  11171. if (arg.stack) {
  11172. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  11173. ? 'Error: ' + arg.message + '\n' + arg.stack
  11174. : arg.stack;
  11175. } else if (arg.sourceURL) {
  11176. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  11177. }
  11178. }
  11179. return arg;
  11180. }
  11181. function consoleLog(type) {
  11182. var console = $window.console || {},
  11183. logFn = console[type] || console.log || noop,
  11184. hasApply = false;
  11185. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  11186. // The reason behind this is that console.log has type "object" in IE8...
  11187. try {
  11188. hasApply = !!logFn.apply;
  11189. } catch (e) {}
  11190. if (hasApply) {
  11191. return function() {
  11192. var args = [];
  11193. forEach(arguments, function(arg) {
  11194. args.push(formatError(arg));
  11195. });
  11196. return logFn.apply(console, args);
  11197. };
  11198. }
  11199. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  11200. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  11201. return function(arg1, arg2) {
  11202. logFn(arg1, arg2 == null ? '' : arg2);
  11203. };
  11204. }
  11205. }];
  11206. }
  11207. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  11208. * Any commits to this file should be reviewed with security in mind. *
  11209. * Changes to this file can potentially create security vulnerabilities. *
  11210. * An approval from 2 Core members with history of modifying *
  11211. * this file is required. *
  11212. * *
  11213. * Does the change somehow allow for arbitrary javascript to be executed? *
  11214. * Or allows for someone to change the prototype of built-in objects? *
  11215. * Or gives undesired access to variables likes document or window? *
  11216. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  11217. var $parseMinErr = minErr('$parse');
  11218. // Sandboxing Angular Expressions
  11219. // ------------------------------
  11220. // Angular expressions are generally considered safe because these expressions only have direct
  11221. // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
  11222. // obtaining a reference to native JS functions such as the Function constructor.
  11223. //
  11224. // As an example, consider the following Angular expression:
  11225. //
  11226. // {}.toString.constructor('alert("evil JS code")')
  11227. //
  11228. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  11229. // against the expression language, but not to prevent exploits that were enabled by exposing
  11230. // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
  11231. // practice and therefore we are not even trying to protect against interaction with an object
  11232. // explicitly exposed in this way.
  11233. //
  11234. // In general, it is not possible to access a Window object from an angular expression unless a
  11235. // window or some DOM object that has a reference to window is published onto a Scope.
  11236. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  11237. // native objects.
  11238. //
  11239. // See https://docs.angularjs.org/guide/security
  11240. function ensureSafeMemberName(name, fullExpression) {
  11241. if (name === "__defineGetter__" || name === "__defineSetter__"
  11242. || name === "__lookupGetter__" || name === "__lookupSetter__"
  11243. || name === "__proto__") {
  11244. throw $parseMinErr('isecfld',
  11245. 'Attempting to access a disallowed field in Angular expressions! '
  11246. + 'Expression: {0}', fullExpression);
  11247. }
  11248. return name;
  11249. }
  11250. function ensureSafeObject(obj, fullExpression) {
  11251. // nifty check if obj is Function that is fast and works across iframes and other contexts
  11252. if (obj) {
  11253. if (obj.constructor === obj) {
  11254. throw $parseMinErr('isecfn',
  11255. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  11256. fullExpression);
  11257. } else if (// isWindow(obj)
  11258. obj.window === obj) {
  11259. throw $parseMinErr('isecwindow',
  11260. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  11261. fullExpression);
  11262. } else if (// isElement(obj)
  11263. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  11264. throw $parseMinErr('isecdom',
  11265. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  11266. fullExpression);
  11267. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  11268. obj === Object) {
  11269. throw $parseMinErr('isecobj',
  11270. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  11271. fullExpression);
  11272. }
  11273. }
  11274. return obj;
  11275. }
  11276. var CALL = Function.prototype.call;
  11277. var APPLY = Function.prototype.apply;
  11278. var BIND = Function.prototype.bind;
  11279. function ensureSafeFunction(obj, fullExpression) {
  11280. if (obj) {
  11281. if (obj.constructor === obj) {
  11282. throw $parseMinErr('isecfn',
  11283. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  11284. fullExpression);
  11285. } else if (obj === CALL || obj === APPLY || obj === BIND) {
  11286. throw $parseMinErr('isecff',
  11287. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  11288. fullExpression);
  11289. }
  11290. }
  11291. }
  11292. var OPERATORS = createMap();
  11293. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  11294. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  11295. /////////////////////////////////////////
  11296. /**
  11297. * @constructor
  11298. */
  11299. var Lexer = function(options) {
  11300. this.options = options;
  11301. };
  11302. Lexer.prototype = {
  11303. constructor: Lexer,
  11304. lex: function(text) {
  11305. this.text = text;
  11306. this.index = 0;
  11307. this.tokens = [];
  11308. while (this.index < this.text.length) {
  11309. var ch = this.text.charAt(this.index);
  11310. if (ch === '"' || ch === "'") {
  11311. this.readString(ch);
  11312. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  11313. this.readNumber();
  11314. } else if (this.isIdent(ch)) {
  11315. this.readIdent();
  11316. } else if (this.is(ch, '(){}[].,;:?')) {
  11317. this.tokens.push({index: this.index, text: ch});
  11318. this.index++;
  11319. } else if (this.isWhitespace(ch)) {
  11320. this.index++;
  11321. } else {
  11322. var ch2 = ch + this.peek();
  11323. var ch3 = ch2 + this.peek(2);
  11324. var op1 = OPERATORS[ch];
  11325. var op2 = OPERATORS[ch2];
  11326. var op3 = OPERATORS[ch3];
  11327. if (op1 || op2 || op3) {
  11328. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  11329. this.tokens.push({index: this.index, text: token, operator: true});
  11330. this.index += token.length;
  11331. } else {
  11332. this.throwError('Unexpected next character ', this.index, this.index + 1);
  11333. }
  11334. }
  11335. }
  11336. return this.tokens;
  11337. },
  11338. is: function(ch, chars) {
  11339. return chars.indexOf(ch) !== -1;
  11340. },
  11341. peek: function(i) {
  11342. var num = i || 1;
  11343. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  11344. },
  11345. isNumber: function(ch) {
  11346. return ('0' <= ch && ch <= '9') && typeof ch === "string";
  11347. },
  11348. isWhitespace: function(ch) {
  11349. // IE treats non-breaking space as \u00A0
  11350. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  11351. ch === '\n' || ch === '\v' || ch === '\u00A0');
  11352. },
  11353. isIdent: function(ch) {
  11354. return ('a' <= ch && ch <= 'z' ||
  11355. 'A' <= ch && ch <= 'Z' ||
  11356. '_' === ch || ch === '$');
  11357. },
  11358. isExpOperator: function(ch) {
  11359. return (ch === '-' || ch === '+' || this.isNumber(ch));
  11360. },
  11361. throwError: function(error, start, end) {
  11362. end = end || this.index;
  11363. var colStr = (isDefined(start)
  11364. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  11365. : ' ' + end);
  11366. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  11367. error, colStr, this.text);
  11368. },
  11369. readNumber: function() {
  11370. var number = '';
  11371. var start = this.index;
  11372. while (this.index < this.text.length) {
  11373. var ch = lowercase(this.text.charAt(this.index));
  11374. if (ch == '.' || this.isNumber(ch)) {
  11375. number += ch;
  11376. } else {
  11377. var peekCh = this.peek();
  11378. if (ch == 'e' && this.isExpOperator(peekCh)) {
  11379. number += ch;
  11380. } else if (this.isExpOperator(ch) &&
  11381. peekCh && this.isNumber(peekCh) &&
  11382. number.charAt(number.length - 1) == 'e') {
  11383. number += ch;
  11384. } else if (this.isExpOperator(ch) &&
  11385. (!peekCh || !this.isNumber(peekCh)) &&
  11386. number.charAt(number.length - 1) == 'e') {
  11387. this.throwError('Invalid exponent');
  11388. } else {
  11389. break;
  11390. }
  11391. }
  11392. this.index++;
  11393. }
  11394. this.tokens.push({
  11395. index: start,
  11396. text: number,
  11397. constant: true,
  11398. value: Number(number)
  11399. });
  11400. },
  11401. readIdent: function() {
  11402. var start = this.index;
  11403. while (this.index < this.text.length) {
  11404. var ch = this.text.charAt(this.index);
  11405. if (!(this.isIdent(ch) || this.isNumber(ch))) {
  11406. break;
  11407. }
  11408. this.index++;
  11409. }
  11410. this.tokens.push({
  11411. index: start,
  11412. text: this.text.slice(start, this.index),
  11413. identifier: true
  11414. });
  11415. },
  11416. readString: function(quote) {
  11417. var start = this.index;
  11418. this.index++;
  11419. var string = '';
  11420. var rawString = quote;
  11421. var escape = false;
  11422. while (this.index < this.text.length) {
  11423. var ch = this.text.charAt(this.index);
  11424. rawString += ch;
  11425. if (escape) {
  11426. if (ch === 'u') {
  11427. var hex = this.text.substring(this.index + 1, this.index + 5);
  11428. if (!hex.match(/[\da-f]{4}/i)) {
  11429. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  11430. }
  11431. this.index += 4;
  11432. string += String.fromCharCode(parseInt(hex, 16));
  11433. } else {
  11434. var rep = ESCAPE[ch];
  11435. string = string + (rep || ch);
  11436. }
  11437. escape = false;
  11438. } else if (ch === '\\') {
  11439. escape = true;
  11440. } else if (ch === quote) {
  11441. this.index++;
  11442. this.tokens.push({
  11443. index: start,
  11444. text: rawString,
  11445. constant: true,
  11446. value: string
  11447. });
  11448. return;
  11449. } else {
  11450. string += ch;
  11451. }
  11452. this.index++;
  11453. }
  11454. this.throwError('Unterminated quote', start);
  11455. }
  11456. };
  11457. var AST = function(lexer, options) {
  11458. this.lexer = lexer;
  11459. this.options = options;
  11460. };
  11461. AST.Program = 'Program';
  11462. AST.ExpressionStatement = 'ExpressionStatement';
  11463. AST.AssignmentExpression = 'AssignmentExpression';
  11464. AST.ConditionalExpression = 'ConditionalExpression';
  11465. AST.LogicalExpression = 'LogicalExpression';
  11466. AST.BinaryExpression = 'BinaryExpression';
  11467. AST.UnaryExpression = 'UnaryExpression';
  11468. AST.CallExpression = 'CallExpression';
  11469. AST.MemberExpression = 'MemberExpression';
  11470. AST.Identifier = 'Identifier';
  11471. AST.Literal = 'Literal';
  11472. AST.ArrayExpression = 'ArrayExpression';
  11473. AST.Property = 'Property';
  11474. AST.ObjectExpression = 'ObjectExpression';
  11475. AST.ThisExpression = 'ThisExpression';
  11476. // Internal use only
  11477. AST.NGValueParameter = 'NGValueParameter';
  11478. AST.prototype = {
  11479. ast: function(text) {
  11480. this.text = text;
  11481. this.tokens = this.lexer.lex(text);
  11482. var value = this.program();
  11483. if (this.tokens.length !== 0) {
  11484. this.throwError('is an unexpected token', this.tokens[0]);
  11485. }
  11486. return value;
  11487. },
  11488. program: function() {
  11489. var body = [];
  11490. while (true) {
  11491. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  11492. body.push(this.expressionStatement());
  11493. if (!this.expect(';')) {
  11494. return { type: AST.Program, body: body};
  11495. }
  11496. }
  11497. },
  11498. expressionStatement: function() {
  11499. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  11500. },
  11501. filterChain: function() {
  11502. var left = this.expression();
  11503. var token;
  11504. while ((token = this.expect('|'))) {
  11505. left = this.filter(left);
  11506. }
  11507. return left;
  11508. },
  11509. expression: function() {
  11510. return this.assignment();
  11511. },
  11512. assignment: function() {
  11513. var result = this.ternary();
  11514. if (this.expect('=')) {
  11515. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  11516. }
  11517. return result;
  11518. },
  11519. ternary: function() {
  11520. var test = this.logicalOR();
  11521. var alternate;
  11522. var consequent;
  11523. if (this.expect('?')) {
  11524. alternate = this.expression();
  11525. if (this.consume(':')) {
  11526. consequent = this.expression();
  11527. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  11528. }
  11529. }
  11530. return test;
  11531. },
  11532. logicalOR: function() {
  11533. var left = this.logicalAND();
  11534. while (this.expect('||')) {
  11535. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  11536. }
  11537. return left;
  11538. },
  11539. logicalAND: function() {
  11540. var left = this.equality();
  11541. while (this.expect('&&')) {
  11542. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  11543. }
  11544. return left;
  11545. },
  11546. equality: function() {
  11547. var left = this.relational();
  11548. var token;
  11549. while ((token = this.expect('==','!=','===','!=='))) {
  11550. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  11551. }
  11552. return left;
  11553. },
  11554. relational: function() {
  11555. var left = this.additive();
  11556. var token;
  11557. while ((token = this.expect('<', '>', '<=', '>='))) {
  11558. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  11559. }
  11560. return left;
  11561. },
  11562. additive: function() {
  11563. var left = this.multiplicative();
  11564. var token;
  11565. while ((token = this.expect('+','-'))) {
  11566. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  11567. }
  11568. return left;
  11569. },
  11570. multiplicative: function() {
  11571. var left = this.unary();
  11572. var token;
  11573. while ((token = this.expect('*','/','%'))) {
  11574. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  11575. }
  11576. return left;
  11577. },
  11578. unary: function() {
  11579. var token;
  11580. if ((token = this.expect('+', '-', '!'))) {
  11581. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  11582. } else {
  11583. return this.primary();
  11584. }
  11585. },
  11586. primary: function() {
  11587. var primary;
  11588. if (this.expect('(')) {
  11589. primary = this.filterChain();
  11590. this.consume(')');
  11591. } else if (this.expect('[')) {
  11592. primary = this.arrayDeclaration();
  11593. } else if (this.expect('{')) {
  11594. primary = this.object();
  11595. } else if (this.constants.hasOwnProperty(this.peek().text)) {
  11596. primary = copy(this.constants[this.consume().text]);
  11597. } else if (this.peek().identifier) {
  11598. primary = this.identifier();
  11599. } else if (this.peek().constant) {
  11600. primary = this.constant();
  11601. } else {
  11602. this.throwError('not a primary expression', this.peek());
  11603. }
  11604. var next;
  11605. while ((next = this.expect('(', '[', '.'))) {
  11606. if (next.text === '(') {
  11607. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  11608. this.consume(')');
  11609. } else if (next.text === '[') {
  11610. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  11611. this.consume(']');
  11612. } else if (next.text === '.') {
  11613. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  11614. } else {
  11615. this.throwError('IMPOSSIBLE');
  11616. }
  11617. }
  11618. return primary;
  11619. },
  11620. filter: function(baseExpression) {
  11621. var args = [baseExpression];
  11622. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  11623. while (this.expect(':')) {
  11624. args.push(this.expression());
  11625. }
  11626. return result;
  11627. },
  11628. parseArguments: function() {
  11629. var args = [];
  11630. if (this.peekToken().text !== ')') {
  11631. do {
  11632. args.push(this.expression());
  11633. } while (this.expect(','));
  11634. }
  11635. return args;
  11636. },
  11637. identifier: function() {
  11638. var token = this.consume();
  11639. if (!token.identifier) {
  11640. this.throwError('is not a valid identifier', token);
  11641. }
  11642. return { type: AST.Identifier, name: token.text };
  11643. },
  11644. constant: function() {
  11645. // TODO check that it is a constant
  11646. return { type: AST.Literal, value: this.consume().value };
  11647. },
  11648. arrayDeclaration: function() {
  11649. var elements = [];
  11650. if (this.peekToken().text !== ']') {
  11651. do {
  11652. if (this.peek(']')) {
  11653. // Support trailing commas per ES5.1.
  11654. break;
  11655. }
  11656. elements.push(this.expression());
  11657. } while (this.expect(','));
  11658. }
  11659. this.consume(']');
  11660. return { type: AST.ArrayExpression, elements: elements };
  11661. },
  11662. object: function() {
  11663. var properties = [], property;
  11664. if (this.peekToken().text !== '}') {
  11665. do {
  11666. if (this.peek('}')) {
  11667. // Support trailing commas per ES5.1.
  11668. break;
  11669. }
  11670. property = {type: AST.Property, kind: 'init'};
  11671. if (this.peek().constant) {
  11672. property.key = this.constant();
  11673. } else if (this.peek().identifier) {
  11674. property.key = this.identifier();
  11675. } else {
  11676. this.throwError("invalid key", this.peek());
  11677. }
  11678. this.consume(':');
  11679. property.value = this.expression();
  11680. properties.push(property);
  11681. } while (this.expect(','));
  11682. }
  11683. this.consume('}');
  11684. return {type: AST.ObjectExpression, properties: properties };
  11685. },
  11686. throwError: function(msg, token) {
  11687. throw $parseMinErr('syntax',
  11688. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  11689. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  11690. },
  11691. consume: function(e1) {
  11692. if (this.tokens.length === 0) {
  11693. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  11694. }
  11695. var token = this.expect(e1);
  11696. if (!token) {
  11697. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  11698. }
  11699. return token;
  11700. },
  11701. peekToken: function() {
  11702. if (this.tokens.length === 0) {
  11703. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  11704. }
  11705. return this.tokens[0];
  11706. },
  11707. peek: function(e1, e2, e3, e4) {
  11708. return this.peekAhead(0, e1, e2, e3, e4);
  11709. },
  11710. peekAhead: function(i, e1, e2, e3, e4) {
  11711. if (this.tokens.length > i) {
  11712. var token = this.tokens[i];
  11713. var t = token.text;
  11714. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  11715. (!e1 && !e2 && !e3 && !e4)) {
  11716. return token;
  11717. }
  11718. }
  11719. return false;
  11720. },
  11721. expect: function(e1, e2, e3, e4) {
  11722. var token = this.peek(e1, e2, e3, e4);
  11723. if (token) {
  11724. this.tokens.shift();
  11725. return token;
  11726. }
  11727. return false;
  11728. },
  11729. /* `undefined` is not a constant, it is an identifier,
  11730. * but using it as an identifier is not supported
  11731. */
  11732. constants: {
  11733. 'true': { type: AST.Literal, value: true },
  11734. 'false': { type: AST.Literal, value: false },
  11735. 'null': { type: AST.Literal, value: null },
  11736. 'undefined': {type: AST.Literal, value: undefined },
  11737. 'this': {type: AST.ThisExpression }
  11738. }
  11739. };
  11740. function ifDefined(v, d) {
  11741. return typeof v !== 'undefined' ? v : d;
  11742. }
  11743. function plusFn(l, r) {
  11744. if (typeof l === 'undefined') return r;
  11745. if (typeof r === 'undefined') return l;
  11746. return l + r;
  11747. }
  11748. function isStateless($filter, filterName) {
  11749. var fn = $filter(filterName);
  11750. return !fn.$stateful;
  11751. }
  11752. function findConstantAndWatchExpressions(ast, $filter) {
  11753. var allConstants;
  11754. var argsToWatch;
  11755. switch (ast.type) {
  11756. case AST.Program:
  11757. allConstants = true;
  11758. forEach(ast.body, function(expr) {
  11759. findConstantAndWatchExpressions(expr.expression, $filter);
  11760. allConstants = allConstants && expr.expression.constant;
  11761. });
  11762. ast.constant = allConstants;
  11763. break;
  11764. case AST.Literal:
  11765. ast.constant = true;
  11766. ast.toWatch = [];
  11767. break;
  11768. case AST.UnaryExpression:
  11769. findConstantAndWatchExpressions(ast.argument, $filter);
  11770. ast.constant = ast.argument.constant;
  11771. ast.toWatch = ast.argument.toWatch;
  11772. break;
  11773. case AST.BinaryExpression:
  11774. findConstantAndWatchExpressions(ast.left, $filter);
  11775. findConstantAndWatchExpressions(ast.right, $filter);
  11776. ast.constant = ast.left.constant && ast.right.constant;
  11777. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  11778. break;
  11779. case AST.LogicalExpression:
  11780. findConstantAndWatchExpressions(ast.left, $filter);
  11781. findConstantAndWatchExpressions(ast.right, $filter);
  11782. ast.constant = ast.left.constant && ast.right.constant;
  11783. ast.toWatch = ast.constant ? [] : [ast];
  11784. break;
  11785. case AST.ConditionalExpression:
  11786. findConstantAndWatchExpressions(ast.test, $filter);
  11787. findConstantAndWatchExpressions(ast.alternate, $filter);
  11788. findConstantAndWatchExpressions(ast.consequent, $filter);
  11789. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  11790. ast.toWatch = ast.constant ? [] : [ast];
  11791. break;
  11792. case AST.Identifier:
  11793. ast.constant = false;
  11794. ast.toWatch = [ast];
  11795. break;
  11796. case AST.MemberExpression:
  11797. findConstantAndWatchExpressions(ast.object, $filter);
  11798. if (ast.computed) {
  11799. findConstantAndWatchExpressions(ast.property, $filter);
  11800. }
  11801. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  11802. ast.toWatch = [ast];
  11803. break;
  11804. case AST.CallExpression:
  11805. allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
  11806. argsToWatch = [];
  11807. forEach(ast.arguments, function(expr) {
  11808. findConstantAndWatchExpressions(expr, $filter);
  11809. allConstants = allConstants && expr.constant;
  11810. if (!expr.constant) {
  11811. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  11812. }
  11813. });
  11814. ast.constant = allConstants;
  11815. ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
  11816. break;
  11817. case AST.AssignmentExpression:
  11818. findConstantAndWatchExpressions(ast.left, $filter);
  11819. findConstantAndWatchExpressions(ast.right, $filter);
  11820. ast.constant = ast.left.constant && ast.right.constant;
  11821. ast.toWatch = [ast];
  11822. break;
  11823. case AST.ArrayExpression:
  11824. allConstants = true;
  11825. argsToWatch = [];
  11826. forEach(ast.elements, function(expr) {
  11827. findConstantAndWatchExpressions(expr, $filter);
  11828. allConstants = allConstants && expr.constant;
  11829. if (!expr.constant) {
  11830. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  11831. }
  11832. });
  11833. ast.constant = allConstants;
  11834. ast.toWatch = argsToWatch;
  11835. break;
  11836. case AST.ObjectExpression:
  11837. allConstants = true;
  11838. argsToWatch = [];
  11839. forEach(ast.properties, function(property) {
  11840. findConstantAndWatchExpressions(property.value, $filter);
  11841. allConstants = allConstants && property.value.constant;
  11842. if (!property.value.constant) {
  11843. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  11844. }
  11845. });
  11846. ast.constant = allConstants;
  11847. ast.toWatch = argsToWatch;
  11848. break;
  11849. case AST.ThisExpression:
  11850. ast.constant = false;
  11851. ast.toWatch = [];
  11852. break;
  11853. }
  11854. }
  11855. function getInputs(body) {
  11856. if (body.length != 1) return;
  11857. var lastExpression = body[0].expression;
  11858. var candidate = lastExpression.toWatch;
  11859. if (candidate.length !== 1) return candidate;
  11860. return candidate[0] !== lastExpression ? candidate : undefined;
  11861. }
  11862. function isAssignable(ast) {
  11863. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  11864. }
  11865. function assignableAST(ast) {
  11866. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  11867. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  11868. }
  11869. }
  11870. function isLiteral(ast) {
  11871. return ast.body.length === 0 ||
  11872. ast.body.length === 1 && (
  11873. ast.body[0].expression.type === AST.Literal ||
  11874. ast.body[0].expression.type === AST.ArrayExpression ||
  11875. ast.body[0].expression.type === AST.ObjectExpression);
  11876. }
  11877. function isConstant(ast) {
  11878. return ast.constant;
  11879. }
  11880. function ASTCompiler(astBuilder, $filter) {
  11881. this.astBuilder = astBuilder;
  11882. this.$filter = $filter;
  11883. }
  11884. ASTCompiler.prototype = {
  11885. compile: function(expression, expensiveChecks) {
  11886. var self = this;
  11887. var ast = this.astBuilder.ast(expression);
  11888. this.state = {
  11889. nextId: 0,
  11890. filters: {},
  11891. expensiveChecks: expensiveChecks,
  11892. fn: {vars: [], body: [], own: {}},
  11893. assign: {vars: [], body: [], own: {}},
  11894. inputs: []
  11895. };
  11896. findConstantAndWatchExpressions(ast, self.$filter);
  11897. var extra = '';
  11898. var assignable;
  11899. this.stage = 'assign';
  11900. if ((assignable = assignableAST(ast))) {
  11901. this.state.computing = 'assign';
  11902. var result = this.nextId();
  11903. this.recurse(assignable, result);
  11904. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  11905. }
  11906. var toWatch = getInputs(ast.body);
  11907. self.stage = 'inputs';
  11908. forEach(toWatch, function(watch, key) {
  11909. var fnKey = 'fn' + key;
  11910. self.state[fnKey] = {vars: [], body: [], own: {}};
  11911. self.state.computing = fnKey;
  11912. var intoId = self.nextId();
  11913. self.recurse(watch, intoId);
  11914. self.return_(intoId);
  11915. self.state.inputs.push(fnKey);
  11916. watch.watchId = key;
  11917. });
  11918. this.state.computing = 'fn';
  11919. this.stage = 'main';
  11920. this.recurse(ast);
  11921. var fnString =
  11922. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  11923. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  11924. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  11925. this.filterPrefix() +
  11926. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  11927. extra +
  11928. this.watchFns() +
  11929. 'return fn;';
  11930. /* jshint -W054 */
  11931. var fn = (new Function('$filter',
  11932. 'ensureSafeMemberName',
  11933. 'ensureSafeObject',
  11934. 'ensureSafeFunction',
  11935. 'ifDefined',
  11936. 'plus',
  11937. 'text',
  11938. fnString))(
  11939. this.$filter,
  11940. ensureSafeMemberName,
  11941. ensureSafeObject,
  11942. ensureSafeFunction,
  11943. ifDefined,
  11944. plusFn,
  11945. expression);
  11946. /* jshint +W054 */
  11947. this.state = this.stage = undefined;
  11948. fn.literal = isLiteral(ast);
  11949. fn.constant = isConstant(ast);
  11950. return fn;
  11951. },
  11952. USE: 'use',
  11953. STRICT: 'strict',
  11954. watchFns: function() {
  11955. var result = [];
  11956. var fns = this.state.inputs;
  11957. var self = this;
  11958. forEach(fns, function(name) {
  11959. result.push('var ' + name + '=' + self.generateFunction(name, 's'));
  11960. });
  11961. if (fns.length) {
  11962. result.push('fn.inputs=[' + fns.join(',') + '];');
  11963. }
  11964. return result.join('');
  11965. },
  11966. generateFunction: function(name, params) {
  11967. return 'function(' + params + '){' +
  11968. this.varsPrefix(name) +
  11969. this.body(name) +
  11970. '};';
  11971. },
  11972. filterPrefix: function() {
  11973. var parts = [];
  11974. var self = this;
  11975. forEach(this.state.filters, function(id, filter) {
  11976. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  11977. });
  11978. if (parts.length) return 'var ' + parts.join(',') + ';';
  11979. return '';
  11980. },
  11981. varsPrefix: function(section) {
  11982. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  11983. },
  11984. body: function(section) {
  11985. return this.state[section].body.join('');
  11986. },
  11987. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  11988. var left, right, self = this, args, expression;
  11989. recursionFn = recursionFn || noop;
  11990. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  11991. intoId = intoId || this.nextId();
  11992. this.if_('i',
  11993. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  11994. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  11995. );
  11996. return;
  11997. }
  11998. switch (ast.type) {
  11999. case AST.Program:
  12000. forEach(ast.body, function(expression, pos) {
  12001. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  12002. if (pos !== ast.body.length - 1) {
  12003. self.current().body.push(right, ';');
  12004. } else {
  12005. self.return_(right);
  12006. }
  12007. });
  12008. break;
  12009. case AST.Literal:
  12010. expression = this.escape(ast.value);
  12011. this.assign(intoId, expression);
  12012. recursionFn(expression);
  12013. break;
  12014. case AST.UnaryExpression:
  12015. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  12016. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  12017. this.assign(intoId, expression);
  12018. recursionFn(expression);
  12019. break;
  12020. case AST.BinaryExpression:
  12021. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  12022. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  12023. if (ast.operator === '+') {
  12024. expression = this.plus(left, right);
  12025. } else if (ast.operator === '-') {
  12026. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  12027. } else {
  12028. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  12029. }
  12030. this.assign(intoId, expression);
  12031. recursionFn(expression);
  12032. break;
  12033. case AST.LogicalExpression:
  12034. intoId = intoId || this.nextId();
  12035. self.recurse(ast.left, intoId);
  12036. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  12037. recursionFn(intoId);
  12038. break;
  12039. case AST.ConditionalExpression:
  12040. intoId = intoId || this.nextId();
  12041. self.recurse(ast.test, intoId);
  12042. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  12043. recursionFn(intoId);
  12044. break;
  12045. case AST.Identifier:
  12046. intoId = intoId || this.nextId();
  12047. if (nameId) {
  12048. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  12049. nameId.computed = false;
  12050. nameId.name = ast.name;
  12051. }
  12052. ensureSafeMemberName(ast.name);
  12053. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  12054. function() {
  12055. self.if_(self.stage === 'inputs' || 's', function() {
  12056. if (create && create !== 1) {
  12057. self.if_(
  12058. self.not(self.nonComputedMember('s', ast.name)),
  12059. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  12060. }
  12061. self.assign(intoId, self.nonComputedMember('s', ast.name));
  12062. });
  12063. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  12064. );
  12065. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
  12066. self.addEnsureSafeObject(intoId);
  12067. }
  12068. recursionFn(intoId);
  12069. break;
  12070. case AST.MemberExpression:
  12071. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  12072. intoId = intoId || this.nextId();
  12073. self.recurse(ast.object, left, undefined, function() {
  12074. self.if_(self.notNull(left), function() {
  12075. if (ast.computed) {
  12076. right = self.nextId();
  12077. self.recurse(ast.property, right);
  12078. self.addEnsureSafeMemberName(right);
  12079. if (create && create !== 1) {
  12080. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  12081. }
  12082. expression = self.ensureSafeObject(self.computedMember(left, right));
  12083. self.assign(intoId, expression);
  12084. if (nameId) {
  12085. nameId.computed = true;
  12086. nameId.name = right;
  12087. }
  12088. } else {
  12089. ensureSafeMemberName(ast.property.name);
  12090. if (create && create !== 1) {
  12091. self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  12092. }
  12093. expression = self.nonComputedMember(left, ast.property.name);
  12094. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
  12095. expression = self.ensureSafeObject(expression);
  12096. }
  12097. self.assign(intoId, expression);
  12098. if (nameId) {
  12099. nameId.computed = false;
  12100. nameId.name = ast.property.name;
  12101. }
  12102. }
  12103. }, function() {
  12104. self.assign(intoId, 'undefined');
  12105. });
  12106. recursionFn(intoId);
  12107. }, !!create);
  12108. break;
  12109. case AST.CallExpression:
  12110. intoId = intoId || this.nextId();
  12111. if (ast.filter) {
  12112. right = self.filter(ast.callee.name);
  12113. args = [];
  12114. forEach(ast.arguments, function(expr) {
  12115. var argument = self.nextId();
  12116. self.recurse(expr, argument);
  12117. args.push(argument);
  12118. });
  12119. expression = right + '(' + args.join(',') + ')';
  12120. self.assign(intoId, expression);
  12121. recursionFn(intoId);
  12122. } else {
  12123. right = self.nextId();
  12124. left = {};
  12125. args = [];
  12126. self.recurse(ast.callee, right, left, function() {
  12127. self.if_(self.notNull(right), function() {
  12128. self.addEnsureSafeFunction(right);
  12129. forEach(ast.arguments, function(expr) {
  12130. self.recurse(expr, self.nextId(), undefined, function(argument) {
  12131. args.push(self.ensureSafeObject(argument));
  12132. });
  12133. });
  12134. if (left.name) {
  12135. if (!self.state.expensiveChecks) {
  12136. self.addEnsureSafeObject(left.context);
  12137. }
  12138. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  12139. } else {
  12140. expression = right + '(' + args.join(',') + ')';
  12141. }
  12142. expression = self.ensureSafeObject(expression);
  12143. self.assign(intoId, expression);
  12144. }, function() {
  12145. self.assign(intoId, 'undefined');
  12146. });
  12147. recursionFn(intoId);
  12148. });
  12149. }
  12150. break;
  12151. case AST.AssignmentExpression:
  12152. right = this.nextId();
  12153. left = {};
  12154. if (!isAssignable(ast.left)) {
  12155. throw $parseMinErr('lval', 'Trying to assing a value to a non l-value');
  12156. }
  12157. this.recurse(ast.left, undefined, left, function() {
  12158. self.if_(self.notNull(left.context), function() {
  12159. self.recurse(ast.right, right);
  12160. self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
  12161. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  12162. self.assign(intoId, expression);
  12163. recursionFn(intoId || expression);
  12164. });
  12165. }, 1);
  12166. break;
  12167. case AST.ArrayExpression:
  12168. args = [];
  12169. forEach(ast.elements, function(expr) {
  12170. self.recurse(expr, self.nextId(), undefined, function(argument) {
  12171. args.push(argument);
  12172. });
  12173. });
  12174. expression = '[' + args.join(',') + ']';
  12175. this.assign(intoId, expression);
  12176. recursionFn(expression);
  12177. break;
  12178. case AST.ObjectExpression:
  12179. args = [];
  12180. forEach(ast.properties, function(property) {
  12181. self.recurse(property.value, self.nextId(), undefined, function(expr) {
  12182. args.push(self.escape(
  12183. property.key.type === AST.Identifier ? property.key.name :
  12184. ('' + property.key.value)) +
  12185. ':' + expr);
  12186. });
  12187. });
  12188. expression = '{' + args.join(',') + '}';
  12189. this.assign(intoId, expression);
  12190. recursionFn(expression);
  12191. break;
  12192. case AST.ThisExpression:
  12193. this.assign(intoId, 's');
  12194. recursionFn('s');
  12195. break;
  12196. case AST.NGValueParameter:
  12197. this.assign(intoId, 'v');
  12198. recursionFn('v');
  12199. break;
  12200. }
  12201. },
  12202. getHasOwnProperty: function(element, property) {
  12203. var key = element + '.' + property;
  12204. var own = this.current().own;
  12205. if (!own.hasOwnProperty(key)) {
  12206. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  12207. }
  12208. return own[key];
  12209. },
  12210. assign: function(id, value) {
  12211. if (!id) return;
  12212. this.current().body.push(id, '=', value, ';');
  12213. return id;
  12214. },
  12215. filter: function(filterName) {
  12216. if (!this.state.filters.hasOwnProperty(filterName)) {
  12217. this.state.filters[filterName] = this.nextId(true);
  12218. }
  12219. return this.state.filters[filterName];
  12220. },
  12221. ifDefined: function(id, defaultValue) {
  12222. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  12223. },
  12224. plus: function(left, right) {
  12225. return 'plus(' + left + ',' + right + ')';
  12226. },
  12227. return_: function(id) {
  12228. this.current().body.push('return ', id, ';');
  12229. },
  12230. if_: function(test, alternate, consequent) {
  12231. if (test === true) {
  12232. alternate();
  12233. } else {
  12234. var body = this.current().body;
  12235. body.push('if(', test, '){');
  12236. alternate();
  12237. body.push('}');
  12238. if (consequent) {
  12239. body.push('else{');
  12240. consequent();
  12241. body.push('}');
  12242. }
  12243. }
  12244. },
  12245. not: function(expression) {
  12246. return '!(' + expression + ')';
  12247. },
  12248. notNull: function(expression) {
  12249. return expression + '!=null';
  12250. },
  12251. nonComputedMember: function(left, right) {
  12252. return left + '.' + right;
  12253. },
  12254. computedMember: function(left, right) {
  12255. return left + '[' + right + ']';
  12256. },
  12257. member: function(left, right, computed) {
  12258. if (computed) return this.computedMember(left, right);
  12259. return this.nonComputedMember(left, right);
  12260. },
  12261. addEnsureSafeObject: function(item) {
  12262. this.current().body.push(this.ensureSafeObject(item), ';');
  12263. },
  12264. addEnsureSafeMemberName: function(item) {
  12265. this.current().body.push(this.ensureSafeMemberName(item), ';');
  12266. },
  12267. addEnsureSafeFunction: function(item) {
  12268. this.current().body.push(this.ensureSafeFunction(item), ';');
  12269. },
  12270. ensureSafeObject: function(item) {
  12271. return 'ensureSafeObject(' + item + ',text)';
  12272. },
  12273. ensureSafeMemberName: function(item) {
  12274. return 'ensureSafeMemberName(' + item + ',text)';
  12275. },
  12276. ensureSafeFunction: function(item) {
  12277. return 'ensureSafeFunction(' + item + ',text)';
  12278. },
  12279. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  12280. var self = this;
  12281. return function() {
  12282. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  12283. };
  12284. },
  12285. lazyAssign: function(id, value) {
  12286. var self = this;
  12287. return function() {
  12288. self.assign(id, value);
  12289. };
  12290. },
  12291. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  12292. stringEscapeFn: function(c) {
  12293. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  12294. },
  12295. escape: function(value) {
  12296. if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
  12297. if (isNumber(value)) return value.toString();
  12298. if (value === true) return 'true';
  12299. if (value === false) return 'false';
  12300. if (value === null) return 'null';
  12301. if (typeof value === 'undefined') return 'undefined';
  12302. throw $parseMinErr('esc', 'IMPOSSIBLE');
  12303. },
  12304. nextId: function(skip, init) {
  12305. var id = 'v' + (this.state.nextId++);
  12306. if (!skip) {
  12307. this.current().vars.push(id + (init ? '=' + init : ''));
  12308. }
  12309. return id;
  12310. },
  12311. current: function() {
  12312. return this.state[this.state.computing];
  12313. }
  12314. };
  12315. function ASTInterpreter(astBuilder, $filter) {
  12316. this.astBuilder = astBuilder;
  12317. this.$filter = $filter;
  12318. }
  12319. ASTInterpreter.prototype = {
  12320. compile: function(expression, expensiveChecks) {
  12321. var self = this;
  12322. var ast = this.astBuilder.ast(expression);
  12323. this.expression = expression;
  12324. this.expensiveChecks = expensiveChecks;
  12325. findConstantAndWatchExpressions(ast, self.$filter);
  12326. var assignable;
  12327. var assign;
  12328. if ((assignable = assignableAST(ast))) {
  12329. assign = this.recurse(assignable);
  12330. }
  12331. var toWatch = getInputs(ast.body);
  12332. var inputs;
  12333. if (toWatch) {
  12334. inputs = [];
  12335. forEach(toWatch, function(watch, key) {
  12336. var input = self.recurse(watch);
  12337. watch.input = input;
  12338. inputs.push(input);
  12339. watch.watchId = key;
  12340. });
  12341. }
  12342. var expressions = [];
  12343. forEach(ast.body, function(expression) {
  12344. expressions.push(self.recurse(expression.expression));
  12345. });
  12346. var fn = ast.body.length === 0 ? function() {} :
  12347. ast.body.length === 1 ? expressions[0] :
  12348. function(scope, locals) {
  12349. var lastValue;
  12350. forEach(expressions, function(exp) {
  12351. lastValue = exp(scope, locals);
  12352. });
  12353. return lastValue;
  12354. };
  12355. if (assign) {
  12356. fn.assign = function(scope, value, locals) {
  12357. return assign(scope, locals, value);
  12358. };
  12359. }
  12360. if (inputs) {
  12361. fn.inputs = inputs;
  12362. }
  12363. fn.literal = isLiteral(ast);
  12364. fn.constant = isConstant(ast);
  12365. return fn;
  12366. },
  12367. recurse: function(ast, context, create) {
  12368. var left, right, self = this, args, expression;
  12369. if (ast.input) {
  12370. return this.inputs(ast.input, ast.watchId);
  12371. }
  12372. switch (ast.type) {
  12373. case AST.Literal:
  12374. return this.value(ast.value, context);
  12375. case AST.UnaryExpression:
  12376. right = this.recurse(ast.argument);
  12377. return this['unary' + ast.operator](right, context);
  12378. case AST.BinaryExpression:
  12379. left = this.recurse(ast.left);
  12380. right = this.recurse(ast.right);
  12381. return this['binary' + ast.operator](left, right, context);
  12382. case AST.LogicalExpression:
  12383. left = this.recurse(ast.left);
  12384. right = this.recurse(ast.right);
  12385. return this['binary' + ast.operator](left, right, context);
  12386. case AST.ConditionalExpression:
  12387. return this['ternary?:'](
  12388. this.recurse(ast.test),
  12389. this.recurse(ast.alternate),
  12390. this.recurse(ast.consequent),
  12391. context
  12392. );
  12393. case AST.Identifier:
  12394. ensureSafeMemberName(ast.name, self.expression);
  12395. return self.identifier(ast.name,
  12396. self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
  12397. context, create, self.expression);
  12398. case AST.MemberExpression:
  12399. left = this.recurse(ast.object, false, !!create);
  12400. if (!ast.computed) {
  12401. ensureSafeMemberName(ast.property.name, self.expression);
  12402. right = ast.property.name;
  12403. }
  12404. if (ast.computed) right = this.recurse(ast.property);
  12405. return ast.computed ?
  12406. this.computedMember(left, right, context, create, self.expression) :
  12407. this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
  12408. case AST.CallExpression:
  12409. args = [];
  12410. forEach(ast.arguments, function(expr) {
  12411. args.push(self.recurse(expr));
  12412. });
  12413. if (ast.filter) right = this.$filter(ast.callee.name);
  12414. if (!ast.filter) right = this.recurse(ast.callee, true);
  12415. return ast.filter ?
  12416. function(scope, locals, assign, inputs) {
  12417. var values = [];
  12418. for (var i = 0; i < args.length; ++i) {
  12419. values.push(args[i](scope, locals, assign, inputs));
  12420. }
  12421. var value = right.apply(undefined, values, inputs);
  12422. return context ? {context: undefined, name: undefined, value: value} : value;
  12423. } :
  12424. function(scope, locals, assign, inputs) {
  12425. var rhs = right(scope, locals, assign, inputs);
  12426. var value;
  12427. if (rhs.value != null) {
  12428. ensureSafeObject(rhs.context, self.expression);
  12429. ensureSafeFunction(rhs.value, self.expression);
  12430. var values = [];
  12431. for (var i = 0; i < args.length; ++i) {
  12432. values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
  12433. }
  12434. value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
  12435. }
  12436. return context ? {value: value} : value;
  12437. };
  12438. case AST.AssignmentExpression:
  12439. left = this.recurse(ast.left, true, 1);
  12440. right = this.recurse(ast.right);
  12441. return function(scope, locals, assign, inputs) {
  12442. var lhs = left(scope, locals, assign, inputs);
  12443. var rhs = right(scope, locals, assign, inputs);
  12444. ensureSafeObject(lhs.value, self.expression);
  12445. lhs.context[lhs.name] = rhs;
  12446. return context ? {value: rhs} : rhs;
  12447. };
  12448. case AST.ArrayExpression:
  12449. args = [];
  12450. forEach(ast.elements, function(expr) {
  12451. args.push(self.recurse(expr));
  12452. });
  12453. return function(scope, locals, assign, inputs) {
  12454. var value = [];
  12455. for (var i = 0; i < args.length; ++i) {
  12456. value.push(args[i](scope, locals, assign, inputs));
  12457. }
  12458. return context ? {value: value} : value;
  12459. };
  12460. case AST.ObjectExpression:
  12461. args = [];
  12462. forEach(ast.properties, function(property) {
  12463. args.push({key: property.key.type === AST.Identifier ?
  12464. property.key.name :
  12465. ('' + property.key.value),
  12466. value: self.recurse(property.value)
  12467. });
  12468. });
  12469. return function(scope, locals, assign, inputs) {
  12470. var value = {};
  12471. for (var i = 0; i < args.length; ++i) {
  12472. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  12473. }
  12474. return context ? {value: value} : value;
  12475. };
  12476. case AST.ThisExpression:
  12477. return function(scope) {
  12478. return context ? {value: scope} : scope;
  12479. };
  12480. case AST.NGValueParameter:
  12481. return function(scope, locals, assign, inputs) {
  12482. return context ? {value: assign} : assign;
  12483. };
  12484. }
  12485. },
  12486. 'unary+': function(argument, context) {
  12487. return function(scope, locals, assign, inputs) {
  12488. var arg = argument(scope, locals, assign, inputs);
  12489. if (isDefined(arg)) {
  12490. arg = +arg;
  12491. } else {
  12492. arg = 0;
  12493. }
  12494. return context ? {value: arg} : arg;
  12495. };
  12496. },
  12497. 'unary-': function(argument, context) {
  12498. return function(scope, locals, assign, inputs) {
  12499. var arg = argument(scope, locals, assign, inputs);
  12500. if (isDefined(arg)) {
  12501. arg = -arg;
  12502. } else {
  12503. arg = 0;
  12504. }
  12505. return context ? {value: arg} : arg;
  12506. };
  12507. },
  12508. 'unary!': function(argument, context) {
  12509. return function(scope, locals, assign, inputs) {
  12510. var arg = !argument(scope, locals, assign, inputs);
  12511. return context ? {value: arg} : arg;
  12512. };
  12513. },
  12514. 'binary+': function(left, right, context) {
  12515. return function(scope, locals, assign, inputs) {
  12516. var lhs = left(scope, locals, assign, inputs);
  12517. var rhs = right(scope, locals, assign, inputs);
  12518. var arg = plusFn(lhs, rhs);
  12519. return context ? {value: arg} : arg;
  12520. };
  12521. },
  12522. 'binary-': function(left, right, context) {
  12523. return function(scope, locals, assign, inputs) {
  12524. var lhs = left(scope, locals, assign, inputs);
  12525. var rhs = right(scope, locals, assign, inputs);
  12526. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  12527. return context ? {value: arg} : arg;
  12528. };
  12529. },
  12530. 'binary*': function(left, right, context) {
  12531. return function(scope, locals, assign, inputs) {
  12532. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  12533. return context ? {value: arg} : arg;
  12534. };
  12535. },
  12536. 'binary/': function(left, right, context) {
  12537. return function(scope, locals, assign, inputs) {
  12538. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  12539. return context ? {value: arg} : arg;
  12540. };
  12541. },
  12542. 'binary%': function(left, right, context) {
  12543. return function(scope, locals, assign, inputs) {
  12544. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  12545. return context ? {value: arg} : arg;
  12546. };
  12547. },
  12548. 'binary===': function(left, right, context) {
  12549. return function(scope, locals, assign, inputs) {
  12550. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  12551. return context ? {value: arg} : arg;
  12552. };
  12553. },
  12554. 'binary!==': function(left, right, context) {
  12555. return function(scope, locals, assign, inputs) {
  12556. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  12557. return context ? {value: arg} : arg;
  12558. };
  12559. },
  12560. 'binary==': function(left, right, context) {
  12561. return function(scope, locals, assign, inputs) {
  12562. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  12563. return context ? {value: arg} : arg;
  12564. };
  12565. },
  12566. 'binary!=': function(left, right, context) {
  12567. return function(scope, locals, assign, inputs) {
  12568. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  12569. return context ? {value: arg} : arg;
  12570. };
  12571. },
  12572. 'binary<': function(left, right, context) {
  12573. return function(scope, locals, assign, inputs) {
  12574. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  12575. return context ? {value: arg} : arg;
  12576. };
  12577. },
  12578. 'binary>': function(left, right, context) {
  12579. return function(scope, locals, assign, inputs) {
  12580. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  12581. return context ? {value: arg} : arg;
  12582. };
  12583. },
  12584. 'binary<=': function(left, right, context) {
  12585. return function(scope, locals, assign, inputs) {
  12586. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  12587. return context ? {value: arg} : arg;
  12588. };
  12589. },
  12590. 'binary>=': function(left, right, context) {
  12591. return function(scope, locals, assign, inputs) {
  12592. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  12593. return context ? {value: arg} : arg;
  12594. };
  12595. },
  12596. 'binary&&': function(left, right, context) {
  12597. return function(scope, locals, assign, inputs) {
  12598. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  12599. return context ? {value: arg} : arg;
  12600. };
  12601. },
  12602. 'binary||': function(left, right, context) {
  12603. return function(scope, locals, assign, inputs) {
  12604. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  12605. return context ? {value: arg} : arg;
  12606. };
  12607. },
  12608. 'ternary?:': function(test, alternate, consequent, context) {
  12609. return function(scope, locals, assign, inputs) {
  12610. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  12611. return context ? {value: arg} : arg;
  12612. };
  12613. },
  12614. value: function(value, context) {
  12615. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  12616. },
  12617. identifier: function(name, expensiveChecks, context, create, expression) {
  12618. return function(scope, locals, assign, inputs) {
  12619. var base = locals && (name in locals) ? locals : scope;
  12620. if (create && create !== 1 && base && !(base[name])) {
  12621. base[name] = {};
  12622. }
  12623. var value = base ? base[name] : undefined;
  12624. if (expensiveChecks) {
  12625. ensureSafeObject(value, expression);
  12626. }
  12627. if (context) {
  12628. return {context: base, name: name, value: value};
  12629. } else {
  12630. return value;
  12631. }
  12632. };
  12633. },
  12634. computedMember: function(left, right, context, create, expression) {
  12635. return function(scope, locals, assign, inputs) {
  12636. var lhs = left(scope, locals, assign, inputs);
  12637. var rhs;
  12638. var value;
  12639. if (lhs != null) {
  12640. rhs = right(scope, locals, assign, inputs);
  12641. ensureSafeMemberName(rhs, expression);
  12642. if (create && create !== 1 && lhs && !(lhs[rhs])) {
  12643. lhs[rhs] = {};
  12644. }
  12645. value = lhs[rhs];
  12646. ensureSafeObject(value, expression);
  12647. }
  12648. if (context) {
  12649. return {context: lhs, name: rhs, value: value};
  12650. } else {
  12651. return value;
  12652. }
  12653. };
  12654. },
  12655. nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
  12656. return function(scope, locals, assign, inputs) {
  12657. var lhs = left(scope, locals, assign, inputs);
  12658. if (create && create !== 1 && lhs && !(lhs[right])) {
  12659. lhs[right] = {};
  12660. }
  12661. var value = lhs != null ? lhs[right] : undefined;
  12662. if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
  12663. ensureSafeObject(value, expression);
  12664. }
  12665. if (context) {
  12666. return {context: lhs, name: right, value: value};
  12667. } else {
  12668. return value;
  12669. }
  12670. };
  12671. },
  12672. inputs: function(input, watchId) {
  12673. return function(scope, value, locals, inputs) {
  12674. if (inputs) return inputs[watchId];
  12675. return input(scope, value, locals);
  12676. };
  12677. }
  12678. };
  12679. /**
  12680. * @constructor
  12681. */
  12682. var Parser = function(lexer, $filter, options) {
  12683. this.lexer = lexer;
  12684. this.$filter = $filter;
  12685. this.options = options;
  12686. this.ast = new AST(this.lexer);
  12687. this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
  12688. new ASTCompiler(this.ast, $filter);
  12689. };
  12690. Parser.prototype = {
  12691. constructor: Parser,
  12692. parse: function(text) {
  12693. return this.astCompiler.compile(text, this.options.expensiveChecks);
  12694. }
  12695. };
  12696. var getterFnCacheDefault = createMap();
  12697. var getterFnCacheExpensive = createMap();
  12698. function isPossiblyDangerousMemberName(name) {
  12699. return name == 'constructor';
  12700. }
  12701. var objectValueOf = Object.prototype.valueOf;
  12702. function getValueOf(value) {
  12703. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  12704. }
  12705. ///////////////////////////////////
  12706. /**
  12707. * @ngdoc service
  12708. * @name $parse
  12709. * @kind function
  12710. *
  12711. * @description
  12712. *
  12713. * Converts Angular {@link guide/expression expression} into a function.
  12714. *
  12715. * ```js
  12716. * var getter = $parse('user.name');
  12717. * var setter = getter.assign;
  12718. * var context = {user:{name:'angular'}};
  12719. * var locals = {user:{name:'local'}};
  12720. *
  12721. * expect(getter(context)).toEqual('angular');
  12722. * setter(context, 'newValue');
  12723. * expect(context.user.name).toEqual('newValue');
  12724. * expect(getter(context, locals)).toEqual('local');
  12725. * ```
  12726. *
  12727. *
  12728. * @param {string} expression String expression to compile.
  12729. * @returns {function(context, locals)} a function which represents the compiled expression:
  12730. *
  12731. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12732. * are evaluated against (typically a scope object).
  12733. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12734. * `context`.
  12735. *
  12736. * The returned function also has the following properties:
  12737. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  12738. * literal.
  12739. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  12740. * constant literals.
  12741. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  12742. * set to a function to change its value on the given context.
  12743. *
  12744. */
  12745. /**
  12746. * @ngdoc provider
  12747. * @name $parseProvider
  12748. *
  12749. * @description
  12750. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  12751. * service.
  12752. */
  12753. function $ParseProvider() {
  12754. var cacheDefault = createMap();
  12755. var cacheExpensive = createMap();
  12756. this.$get = ['$filter', function($filter) {
  12757. var noUnsafeEval = csp().noUnsafeEval;
  12758. var $parseOptions = {
  12759. csp: noUnsafeEval,
  12760. expensiveChecks: false
  12761. },
  12762. $parseOptionsExpensive = {
  12763. csp: noUnsafeEval,
  12764. expensiveChecks: true
  12765. };
  12766. return function $parse(exp, interceptorFn, expensiveChecks) {
  12767. var parsedExpression, oneTime, cacheKey;
  12768. switch (typeof exp) {
  12769. case 'string':
  12770. exp = exp.trim();
  12771. cacheKey = exp;
  12772. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  12773. parsedExpression = cache[cacheKey];
  12774. if (!parsedExpression) {
  12775. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  12776. oneTime = true;
  12777. exp = exp.substring(2);
  12778. }
  12779. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  12780. var lexer = new Lexer(parseOptions);
  12781. var parser = new Parser(lexer, $filter, parseOptions);
  12782. parsedExpression = parser.parse(exp);
  12783. if (parsedExpression.constant) {
  12784. parsedExpression.$$watchDelegate = constantWatchDelegate;
  12785. } else if (oneTime) {
  12786. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  12787. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  12788. } else if (parsedExpression.inputs) {
  12789. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  12790. }
  12791. cache[cacheKey] = parsedExpression;
  12792. }
  12793. return addInterceptor(parsedExpression, interceptorFn);
  12794. case 'function':
  12795. return addInterceptor(exp, interceptorFn);
  12796. default:
  12797. return noop;
  12798. }
  12799. };
  12800. function expressionInputDirtyCheck(newValue, oldValueOfValue) {
  12801. if (newValue == null || oldValueOfValue == null) { // null/undefined
  12802. return newValue === oldValueOfValue;
  12803. }
  12804. if (typeof newValue === 'object') {
  12805. // attempt to convert the value to a primitive type
  12806. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  12807. // be cheaply dirty-checked
  12808. newValue = getValueOf(newValue);
  12809. if (typeof newValue === 'object') {
  12810. // objects/arrays are not supported - deep-watching them would be too expensive
  12811. return false;
  12812. }
  12813. // fall-through to the primitive equality check
  12814. }
  12815. //Primitive or NaN
  12816. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  12817. }
  12818. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  12819. var inputExpressions = parsedExpression.inputs;
  12820. var lastResult;
  12821. if (inputExpressions.length === 1) {
  12822. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  12823. inputExpressions = inputExpressions[0];
  12824. return scope.$watch(function expressionInputWatch(scope) {
  12825. var newInputValue = inputExpressions(scope);
  12826. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
  12827. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  12828. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  12829. }
  12830. return lastResult;
  12831. }, listener, objectEquality, prettyPrintExpression);
  12832. }
  12833. var oldInputValueOfValues = [];
  12834. var oldInputValues = [];
  12835. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  12836. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  12837. oldInputValues[i] = null;
  12838. }
  12839. return scope.$watch(function expressionInputsWatch(scope) {
  12840. var changed = false;
  12841. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  12842. var newInputValue = inputExpressions[i](scope);
  12843. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
  12844. oldInputValues[i] = newInputValue;
  12845. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  12846. }
  12847. }
  12848. if (changed) {
  12849. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  12850. }
  12851. return lastResult;
  12852. }, listener, objectEquality, prettyPrintExpression);
  12853. }
  12854. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  12855. var unwatch, lastValue;
  12856. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  12857. return parsedExpression(scope);
  12858. }, function oneTimeListener(value, old, scope) {
  12859. lastValue = value;
  12860. if (isFunction(listener)) {
  12861. listener.apply(this, arguments);
  12862. }
  12863. if (isDefined(value)) {
  12864. scope.$$postDigest(function() {
  12865. if (isDefined(lastValue)) {
  12866. unwatch();
  12867. }
  12868. });
  12869. }
  12870. }, objectEquality);
  12871. }
  12872. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  12873. var unwatch, lastValue;
  12874. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  12875. return parsedExpression(scope);
  12876. }, function oneTimeListener(value, old, scope) {
  12877. lastValue = value;
  12878. if (isFunction(listener)) {
  12879. listener.call(this, value, old, scope);
  12880. }
  12881. if (isAllDefined(value)) {
  12882. scope.$$postDigest(function() {
  12883. if (isAllDefined(lastValue)) unwatch();
  12884. });
  12885. }
  12886. }, objectEquality);
  12887. function isAllDefined(value) {
  12888. var allDefined = true;
  12889. forEach(value, function(val) {
  12890. if (!isDefined(val)) allDefined = false;
  12891. });
  12892. return allDefined;
  12893. }
  12894. }
  12895. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  12896. var unwatch;
  12897. return unwatch = scope.$watch(function constantWatch(scope) {
  12898. return parsedExpression(scope);
  12899. }, function constantListener(value, old, scope) {
  12900. if (isFunction(listener)) {
  12901. listener.apply(this, arguments);
  12902. }
  12903. unwatch();
  12904. }, objectEquality);
  12905. }
  12906. function addInterceptor(parsedExpression, interceptorFn) {
  12907. if (!interceptorFn) return parsedExpression;
  12908. var watchDelegate = parsedExpression.$$watchDelegate;
  12909. var regularWatch =
  12910. watchDelegate !== oneTimeLiteralWatchDelegate &&
  12911. watchDelegate !== oneTimeWatchDelegate;
  12912. var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
  12913. var value = parsedExpression(scope, locals, assign, inputs);
  12914. return interceptorFn(value, scope, locals);
  12915. } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
  12916. var value = parsedExpression(scope, locals, assign, inputs);
  12917. var result = interceptorFn(value, scope, locals);
  12918. // we only return the interceptor's result if the
  12919. // initial value is defined (for bind-once)
  12920. return isDefined(value) ? result : value;
  12921. };
  12922. // Propagate $$watchDelegates other then inputsWatchDelegate
  12923. if (parsedExpression.$$watchDelegate &&
  12924. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  12925. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  12926. } else if (!interceptorFn.$stateful) {
  12927. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  12928. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  12929. fn.$$watchDelegate = inputsWatchDelegate;
  12930. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  12931. }
  12932. return fn;
  12933. }
  12934. }];
  12935. }
  12936. /**
  12937. * @ngdoc service
  12938. * @name $q
  12939. * @requires $rootScope
  12940. *
  12941. * @description
  12942. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  12943. * when they are done processing.
  12944. *
  12945. * This is an implementation of promises/deferred objects inspired by
  12946. * [Kris Kowal's Q](https://github.com/kriskowal/q).
  12947. *
  12948. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  12949. * implementations, and the other which resembles ES6 promises to some degree.
  12950. *
  12951. * # $q constructor
  12952. *
  12953. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  12954. * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
  12955. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  12956. *
  12957. * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
  12958. * available yet.
  12959. *
  12960. * It can be used like so:
  12961. *
  12962. * ```js
  12963. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  12964. * // are available in the current lexical scope (they could have been injected or passed in).
  12965. *
  12966. * function asyncGreet(name) {
  12967. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  12968. * return $q(function(resolve, reject) {
  12969. * setTimeout(function() {
  12970. * if (okToGreet(name)) {
  12971. * resolve('Hello, ' + name + '!');
  12972. * } else {
  12973. * reject('Greeting ' + name + ' is not allowed.');
  12974. * }
  12975. * }, 1000);
  12976. * });
  12977. * }
  12978. *
  12979. * var promise = asyncGreet('Robin Hood');
  12980. * promise.then(function(greeting) {
  12981. * alert('Success: ' + greeting);
  12982. * }, function(reason) {
  12983. * alert('Failed: ' + reason);
  12984. * });
  12985. * ```
  12986. *
  12987. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  12988. *
  12989. * However, the more traditional CommonJS-style usage is still available, and documented below.
  12990. *
  12991. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  12992. * interface for interacting with an object that represents the result of an action that is
  12993. * performed asynchronously, and may or may not be finished at any given point in time.
  12994. *
  12995. * From the perspective of dealing with error handling, deferred and promise APIs are to
  12996. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  12997. *
  12998. * ```js
  12999. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  13000. * // are available in the current lexical scope (they could have been injected or passed in).
  13001. *
  13002. * function asyncGreet(name) {
  13003. * var deferred = $q.defer();
  13004. *
  13005. * setTimeout(function() {
  13006. * deferred.notify('About to greet ' + name + '.');
  13007. *
  13008. * if (okToGreet(name)) {
  13009. * deferred.resolve('Hello, ' + name + '!');
  13010. * } else {
  13011. * deferred.reject('Greeting ' + name + ' is not allowed.');
  13012. * }
  13013. * }, 1000);
  13014. *
  13015. * return deferred.promise;
  13016. * }
  13017. *
  13018. * var promise = asyncGreet('Robin Hood');
  13019. * promise.then(function(greeting) {
  13020. * alert('Success: ' + greeting);
  13021. * }, function(reason) {
  13022. * alert('Failed: ' + reason);
  13023. * }, function(update) {
  13024. * alert('Got notification: ' + update);
  13025. * });
  13026. * ```
  13027. *
  13028. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  13029. * comes in the way of guarantees that promise and deferred APIs make, see
  13030. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  13031. *
  13032. * Additionally the promise api allows for composition that is very hard to do with the
  13033. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  13034. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  13035. * section on serial or parallel joining of promises.
  13036. *
  13037. * # The Deferred API
  13038. *
  13039. * A new instance of deferred is constructed by calling `$q.defer()`.
  13040. *
  13041. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  13042. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  13043. * of the task.
  13044. *
  13045. * **Methods**
  13046. *
  13047. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  13048. * constructed via `$q.reject`, the promise will be rejected instead.
  13049. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  13050. * resolving it with a rejection constructed via `$q.reject`.
  13051. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  13052. * multiple times before the promise is either resolved or rejected.
  13053. *
  13054. * **Properties**
  13055. *
  13056. * - promise – `{Promise}` – promise object associated with this deferred.
  13057. *
  13058. *
  13059. * # The Promise API
  13060. *
  13061. * A new promise instance is created when a deferred instance is created and can be retrieved by
  13062. * calling `deferred.promise`.
  13063. *
  13064. * The purpose of the promise object is to allow for interested parties to get access to the result
  13065. * of the deferred task when it completes.
  13066. *
  13067. * **Methods**
  13068. *
  13069. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  13070. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  13071. * as soon as the result is available. The callbacks are called with a single argument: the result
  13072. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  13073. * provide a progress indication, before the promise is resolved or rejected.
  13074. *
  13075. * This method *returns a new promise* which is resolved or rejected via the return value of the
  13076. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  13077. * with the value which is resolved in that promise using
  13078. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  13079. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  13080. * resolved or rejected from the notifyCallback method.
  13081. *
  13082. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  13083. *
  13084. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  13085. * but to do so without modifying the final value. This is useful to release resources or do some
  13086. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  13087. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  13088. * more information.
  13089. *
  13090. * # Chaining promises
  13091. *
  13092. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  13093. * possible to create a chain of promises:
  13094. *
  13095. * ```js
  13096. * promiseB = promiseA.then(function(result) {
  13097. * return result + 1;
  13098. * });
  13099. *
  13100. * // promiseB will be resolved immediately after promiseA is resolved and its value
  13101. * // will be the result of promiseA incremented by 1
  13102. * ```
  13103. *
  13104. * It is possible to create chains of any length and since a promise can be resolved with another
  13105. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  13106. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  13107. * $http's response interceptors.
  13108. *
  13109. *
  13110. * # Differences between Kris Kowal's Q and $q
  13111. *
  13112. * There are two main differences:
  13113. *
  13114. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  13115. * mechanism in angular, which means faster propagation of resolution or rejection into your
  13116. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  13117. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  13118. * all the important functionality needed for common async tasks.
  13119. *
  13120. * # Testing
  13121. *
  13122. * ```js
  13123. * it('should simulate promise', inject(function($q, $rootScope) {
  13124. * var deferred = $q.defer();
  13125. * var promise = deferred.promise;
  13126. * var resolvedValue;
  13127. *
  13128. * promise.then(function(value) { resolvedValue = value; });
  13129. * expect(resolvedValue).toBeUndefined();
  13130. *
  13131. * // Simulate resolving of promise
  13132. * deferred.resolve(123);
  13133. * // Note that the 'then' function does not get called synchronously.
  13134. * // This is because we want the promise API to always be async, whether or not
  13135. * // it got called synchronously or asynchronously.
  13136. * expect(resolvedValue).toBeUndefined();
  13137. *
  13138. * // Propagate promise resolution to 'then' functions using $apply().
  13139. * $rootScope.$apply();
  13140. * expect(resolvedValue).toEqual(123);
  13141. * }));
  13142. * ```
  13143. *
  13144. * @param {function(function, function)} resolver Function which is responsible for resolving or
  13145. * rejecting the newly created promise. The first parameter is a function which resolves the
  13146. * promise, the second parameter is a function which rejects the promise.
  13147. *
  13148. * @returns {Promise} The newly created promise.
  13149. */
  13150. function $QProvider() {
  13151. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  13152. return qFactory(function(callback) {
  13153. $rootScope.$evalAsync(callback);
  13154. }, $exceptionHandler);
  13155. }];
  13156. }
  13157. function $$QProvider() {
  13158. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  13159. return qFactory(function(callback) {
  13160. $browser.defer(callback);
  13161. }, $exceptionHandler);
  13162. }];
  13163. }
  13164. /**
  13165. * Constructs a promise manager.
  13166. *
  13167. * @param {function(function)} nextTick Function for executing functions in the next turn.
  13168. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  13169. * debugging purposes.
  13170. * @returns {object} Promise manager.
  13171. */
  13172. function qFactory(nextTick, exceptionHandler) {
  13173. var $qMinErr = minErr('$q', TypeError);
  13174. function callOnce(self, resolveFn, rejectFn) {
  13175. var called = false;
  13176. function wrap(fn) {
  13177. return function(value) {
  13178. if (called) return;
  13179. called = true;
  13180. fn.call(self, value);
  13181. };
  13182. }
  13183. return [wrap(resolveFn), wrap(rejectFn)];
  13184. }
  13185. /**
  13186. * @ngdoc method
  13187. * @name ng.$q#defer
  13188. * @kind function
  13189. *
  13190. * @description
  13191. * Creates a `Deferred` object which represents a task which will finish in the future.
  13192. *
  13193. * @returns {Deferred} Returns a new instance of deferred.
  13194. */
  13195. var defer = function() {
  13196. return new Deferred();
  13197. };
  13198. function Promise() {
  13199. this.$$state = { status: 0 };
  13200. }
  13201. extend(Promise.prototype, {
  13202. then: function(onFulfilled, onRejected, progressBack) {
  13203. if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
  13204. return this;
  13205. }
  13206. var result = new Deferred();
  13207. this.$$state.pending = this.$$state.pending || [];
  13208. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  13209. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  13210. return result.promise;
  13211. },
  13212. "catch": function(callback) {
  13213. return this.then(null, callback);
  13214. },
  13215. "finally": function(callback, progressBack) {
  13216. return this.then(function(value) {
  13217. return handleCallback(value, true, callback);
  13218. }, function(error) {
  13219. return handleCallback(error, false, callback);
  13220. }, progressBack);
  13221. }
  13222. });
  13223. //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
  13224. function simpleBind(context, fn) {
  13225. return function(value) {
  13226. fn.call(context, value);
  13227. };
  13228. }
  13229. function processQueue(state) {
  13230. var fn, deferred, pending;
  13231. pending = state.pending;
  13232. state.processScheduled = false;
  13233. state.pending = undefined;
  13234. for (var i = 0, ii = pending.length; i < ii; ++i) {
  13235. deferred = pending[i][0];
  13236. fn = pending[i][state.status];
  13237. try {
  13238. if (isFunction(fn)) {
  13239. deferred.resolve(fn(state.value));
  13240. } else if (state.status === 1) {
  13241. deferred.resolve(state.value);
  13242. } else {
  13243. deferred.reject(state.value);
  13244. }
  13245. } catch (e) {
  13246. deferred.reject(e);
  13247. exceptionHandler(e);
  13248. }
  13249. }
  13250. }
  13251. function scheduleProcessQueue(state) {
  13252. if (state.processScheduled || !state.pending) return;
  13253. state.processScheduled = true;
  13254. nextTick(function() { processQueue(state); });
  13255. }
  13256. function Deferred() {
  13257. this.promise = new Promise();
  13258. //Necessary to support unbound execution :/
  13259. this.resolve = simpleBind(this, this.resolve);
  13260. this.reject = simpleBind(this, this.reject);
  13261. this.notify = simpleBind(this, this.notify);
  13262. }
  13263. extend(Deferred.prototype, {
  13264. resolve: function(val) {
  13265. if (this.promise.$$state.status) return;
  13266. if (val === this.promise) {
  13267. this.$$reject($qMinErr(
  13268. 'qcycle',
  13269. "Expected promise to be resolved with value other than itself '{0}'",
  13270. val));
  13271. } else {
  13272. this.$$resolve(val);
  13273. }
  13274. },
  13275. $$resolve: function(val) {
  13276. var then, fns;
  13277. fns = callOnce(this, this.$$resolve, this.$$reject);
  13278. try {
  13279. if ((isObject(val) || isFunction(val))) then = val && val.then;
  13280. if (isFunction(then)) {
  13281. this.promise.$$state.status = -1;
  13282. then.call(val, fns[0], fns[1], this.notify);
  13283. } else {
  13284. this.promise.$$state.value = val;
  13285. this.promise.$$state.status = 1;
  13286. scheduleProcessQueue(this.promise.$$state);
  13287. }
  13288. } catch (e) {
  13289. fns[1](e);
  13290. exceptionHandler(e);
  13291. }
  13292. },
  13293. reject: function(reason) {
  13294. if (this.promise.$$state.status) return;
  13295. this.$$reject(reason);
  13296. },
  13297. $$reject: function(reason) {
  13298. this.promise.$$state.value = reason;
  13299. this.promise.$$state.status = 2;
  13300. scheduleProcessQueue(this.promise.$$state);
  13301. },
  13302. notify: function(progress) {
  13303. var callbacks = this.promise.$$state.pending;
  13304. if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
  13305. nextTick(function() {
  13306. var callback, result;
  13307. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  13308. result = callbacks[i][0];
  13309. callback = callbacks[i][3];
  13310. try {
  13311. result.notify(isFunction(callback) ? callback(progress) : progress);
  13312. } catch (e) {
  13313. exceptionHandler(e);
  13314. }
  13315. }
  13316. });
  13317. }
  13318. }
  13319. });
  13320. /**
  13321. * @ngdoc method
  13322. * @name $q#reject
  13323. * @kind function
  13324. *
  13325. * @description
  13326. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  13327. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  13328. * a promise chain, you don't need to worry about it.
  13329. *
  13330. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  13331. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  13332. * a promise error callback and you want to forward the error to the promise derived from the
  13333. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  13334. * `reject`.
  13335. *
  13336. * ```js
  13337. * promiseB = promiseA.then(function(result) {
  13338. * // success: do something and resolve promiseB
  13339. * // with the old or a new result
  13340. * return result;
  13341. * }, function(reason) {
  13342. * // error: handle the error if possible and
  13343. * // resolve promiseB with newPromiseOrValue,
  13344. * // otherwise forward the rejection to promiseB
  13345. * if (canHandle(reason)) {
  13346. * // handle the error and recover
  13347. * return newPromiseOrValue;
  13348. * }
  13349. * return $q.reject(reason);
  13350. * });
  13351. * ```
  13352. *
  13353. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  13354. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  13355. */
  13356. var reject = function(reason) {
  13357. var result = new Deferred();
  13358. result.reject(reason);
  13359. return result.promise;
  13360. };
  13361. var makePromise = function makePromise(value, resolved) {
  13362. var result = new Deferred();
  13363. if (resolved) {
  13364. result.resolve(value);
  13365. } else {
  13366. result.reject(value);
  13367. }
  13368. return result.promise;
  13369. };
  13370. var handleCallback = function handleCallback(value, isResolved, callback) {
  13371. var callbackOutput = null;
  13372. try {
  13373. if (isFunction(callback)) callbackOutput = callback();
  13374. } catch (e) {
  13375. return makePromise(e, false);
  13376. }
  13377. if (isPromiseLike(callbackOutput)) {
  13378. return callbackOutput.then(function() {
  13379. return makePromise(value, isResolved);
  13380. }, function(error) {
  13381. return makePromise(error, false);
  13382. });
  13383. } else {
  13384. return makePromise(value, isResolved);
  13385. }
  13386. };
  13387. /**
  13388. * @ngdoc method
  13389. * @name $q#when
  13390. * @kind function
  13391. *
  13392. * @description
  13393. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  13394. * This is useful when you are dealing with an object that might or might not be a promise, or if
  13395. * the promise comes from a source that can't be trusted.
  13396. *
  13397. * @param {*} value Value or a promise
  13398. * @param {Function=} successCallback
  13399. * @param {Function=} errorCallback
  13400. * @param {Function=} progressCallback
  13401. * @returns {Promise} Returns a promise of the passed value or promise
  13402. */
  13403. var when = function(value, callback, errback, progressBack) {
  13404. var result = new Deferred();
  13405. result.resolve(value);
  13406. return result.promise.then(callback, errback, progressBack);
  13407. };
  13408. /**
  13409. * @ngdoc method
  13410. * @name $q#resolve
  13411. * @kind function
  13412. *
  13413. * @description
  13414. * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
  13415. *
  13416. * @param {*} value Value or a promise
  13417. * @param {Function=} successCallback
  13418. * @param {Function=} errorCallback
  13419. * @param {Function=} progressCallback
  13420. * @returns {Promise} Returns a promise of the passed value or promise
  13421. */
  13422. var resolve = when;
  13423. /**
  13424. * @ngdoc method
  13425. * @name $q#all
  13426. * @kind function
  13427. *
  13428. * @description
  13429. * Combines multiple promises into a single promise that is resolved when all of the input
  13430. * promises are resolved.
  13431. *
  13432. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  13433. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  13434. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  13435. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  13436. * with the same rejection value.
  13437. */
  13438. function all(promises) {
  13439. var deferred = new Deferred(),
  13440. counter = 0,
  13441. results = isArray(promises) ? [] : {};
  13442. forEach(promises, function(promise, key) {
  13443. counter++;
  13444. when(promise).then(function(value) {
  13445. if (results.hasOwnProperty(key)) return;
  13446. results[key] = value;
  13447. if (!(--counter)) deferred.resolve(results);
  13448. }, function(reason) {
  13449. if (results.hasOwnProperty(key)) return;
  13450. deferred.reject(reason);
  13451. });
  13452. });
  13453. if (counter === 0) {
  13454. deferred.resolve(results);
  13455. }
  13456. return deferred.promise;
  13457. }
  13458. var $Q = function Q(resolver) {
  13459. if (!isFunction(resolver)) {
  13460. throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
  13461. }
  13462. if (!(this instanceof Q)) {
  13463. // More useful when $Q is the Promise itself.
  13464. return new Q(resolver);
  13465. }
  13466. var deferred = new Deferred();
  13467. function resolveFn(value) {
  13468. deferred.resolve(value);
  13469. }
  13470. function rejectFn(reason) {
  13471. deferred.reject(reason);
  13472. }
  13473. resolver(resolveFn, rejectFn);
  13474. return deferred.promise;
  13475. };
  13476. $Q.defer = defer;
  13477. $Q.reject = reject;
  13478. $Q.when = when;
  13479. $Q.resolve = resolve;
  13480. $Q.all = all;
  13481. return $Q;
  13482. }
  13483. function $$RAFProvider() { //rAF
  13484. this.$get = ['$window', '$timeout', function($window, $timeout) {
  13485. var requestAnimationFrame = $window.requestAnimationFrame ||
  13486. $window.webkitRequestAnimationFrame;
  13487. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  13488. $window.webkitCancelAnimationFrame ||
  13489. $window.webkitCancelRequestAnimationFrame;
  13490. var rafSupported = !!requestAnimationFrame;
  13491. var raf = rafSupported
  13492. ? function(fn) {
  13493. var id = requestAnimationFrame(fn);
  13494. return function() {
  13495. cancelAnimationFrame(id);
  13496. };
  13497. }
  13498. : function(fn) {
  13499. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  13500. return function() {
  13501. $timeout.cancel(timer);
  13502. };
  13503. };
  13504. raf.supported = rafSupported;
  13505. return raf;
  13506. }];
  13507. }
  13508. /**
  13509. * DESIGN NOTES
  13510. *
  13511. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  13512. *
  13513. * The typical use of scope is to watch the expressions, which most of the time return the same
  13514. * value as last time so we optimize the operation.
  13515. *
  13516. * Closures construction is expensive in terms of speed as well as memory:
  13517. * - No closures, instead use prototypical inheritance for API
  13518. * - Internal state needs to be stored on scope directly, which means that private state is
  13519. * exposed as $$____ properties
  13520. *
  13521. * Loop operations are optimized by using while(count--) { ... }
  13522. * - this means that in order to keep the same order of execution as addition we have to add
  13523. * items to the array at the beginning (unshift) instead of at the end (push)
  13524. *
  13525. * Child scopes are created and removed often
  13526. * - Using an array would be slow since inserts in middle are expensive so we use linked list
  13527. *
  13528. * There are few watches then a lot of observers. This is why you don't want the observer to be
  13529. * implemented in the same way as watch. Watch requires return of initialization function which
  13530. * are expensive to construct.
  13531. */
  13532. /**
  13533. * @ngdoc provider
  13534. * @name $rootScopeProvider
  13535. * @description
  13536. *
  13537. * Provider for the $rootScope service.
  13538. */
  13539. /**
  13540. * @ngdoc method
  13541. * @name $rootScopeProvider#digestTtl
  13542. * @description
  13543. *
  13544. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  13545. * assuming that the model is unstable.
  13546. *
  13547. * The current default is 10 iterations.
  13548. *
  13549. * In complex applications it's possible that the dependencies between `$watch`s will result in
  13550. * several digest iterations. However if an application needs more than the default 10 digest
  13551. * iterations for its model to stabilize then you should investigate what is causing the model to
  13552. * continuously change during the digest.
  13553. *
  13554. * Increasing the TTL could have performance implications, so you should not change it without
  13555. * proper justification.
  13556. *
  13557. * @param {number} limit The number of digest iterations.
  13558. */
  13559. /**
  13560. * @ngdoc service
  13561. * @name $rootScope
  13562. * @description
  13563. *
  13564. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  13565. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  13566. * between the model and the view, via a mechanism for watching the model for changes.
  13567. * They also provide an event emission/broadcast and subscription facility. See the
  13568. * {@link guide/scope developer guide on scopes}.
  13569. */
  13570. function $RootScopeProvider() {
  13571. var TTL = 10;
  13572. var $rootScopeMinErr = minErr('$rootScope');
  13573. var lastDirtyWatch = null;
  13574. var applyAsyncId = null;
  13575. this.digestTtl = function(value) {
  13576. if (arguments.length) {
  13577. TTL = value;
  13578. }
  13579. return TTL;
  13580. };
  13581. function createChildScopeClass(parent) {
  13582. function ChildScope() {
  13583. this.$$watchers = this.$$nextSibling =
  13584. this.$$childHead = this.$$childTail = null;
  13585. this.$$listeners = {};
  13586. this.$$listenerCount = {};
  13587. this.$$watchersCount = 0;
  13588. this.$id = nextUid();
  13589. this.$$ChildScope = null;
  13590. }
  13591. ChildScope.prototype = parent;
  13592. return ChildScope;
  13593. }
  13594. this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
  13595. function($injector, $exceptionHandler, $parse, $browser) {
  13596. function destroyChildScope($event) {
  13597. $event.currentScope.$$destroyed = true;
  13598. }
  13599. /**
  13600. * @ngdoc type
  13601. * @name $rootScope.Scope
  13602. *
  13603. * @description
  13604. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  13605. * {@link auto.$injector $injector}. Child scopes are created using the
  13606. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  13607. * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
  13608. * an in-depth introduction and usage examples.
  13609. *
  13610. *
  13611. * # Inheritance
  13612. * A scope can inherit from a parent scope, as in this example:
  13613. * ```js
  13614. var parent = $rootScope;
  13615. var child = parent.$new();
  13616. parent.salutation = "Hello";
  13617. expect(child.salutation).toEqual('Hello');
  13618. child.salutation = "Welcome";
  13619. expect(child.salutation).toEqual('Welcome');
  13620. expect(parent.salutation).toEqual('Hello');
  13621. * ```
  13622. *
  13623. * When interacting with `Scope` in tests, additional helper methods are available on the
  13624. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  13625. * details.
  13626. *
  13627. *
  13628. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  13629. * provided for the current scope. Defaults to {@link ng}.
  13630. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  13631. * append/override services provided by `providers`. This is handy
  13632. * when unit-testing and having the need to override a default
  13633. * service.
  13634. * @returns {Object} Newly created scope.
  13635. *
  13636. */
  13637. function Scope() {
  13638. this.$id = nextUid();
  13639. this.$$phase = this.$parent = this.$$watchers =
  13640. this.$$nextSibling = this.$$prevSibling =
  13641. this.$$childHead = this.$$childTail = null;
  13642. this.$root = this;
  13643. this.$$destroyed = false;
  13644. this.$$listeners = {};
  13645. this.$$listenerCount = {};
  13646. this.$$watchersCount = 0;
  13647. this.$$isolateBindings = null;
  13648. }
  13649. /**
  13650. * @ngdoc property
  13651. * @name $rootScope.Scope#$id
  13652. *
  13653. * @description
  13654. * Unique scope ID (monotonically increasing) useful for debugging.
  13655. */
  13656. /**
  13657. * @ngdoc property
  13658. * @name $rootScope.Scope#$parent
  13659. *
  13660. * @description
  13661. * Reference to the parent scope.
  13662. */
  13663. /**
  13664. * @ngdoc property
  13665. * @name $rootScope.Scope#$root
  13666. *
  13667. * @description
  13668. * Reference to the root scope.
  13669. */
  13670. Scope.prototype = {
  13671. constructor: Scope,
  13672. /**
  13673. * @ngdoc method
  13674. * @name $rootScope.Scope#$new
  13675. * @kind function
  13676. *
  13677. * @description
  13678. * Creates a new child {@link ng.$rootScope.Scope scope}.
  13679. *
  13680. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  13681. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  13682. *
  13683. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  13684. * desired for the scope and its child scopes to be permanently detached from the parent and
  13685. * thus stop participating in model change detection and listener notification by invoking.
  13686. *
  13687. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  13688. * parent scope. The scope is isolated, as it can not see parent scope properties.
  13689. * When creating widgets, it is useful for the widget to not accidentally read parent
  13690. * state.
  13691. *
  13692. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  13693. * of the newly created scope. Defaults to `this` scope if not provided.
  13694. * This is used when creating a transclude scope to correctly place it
  13695. * in the scope hierarchy while maintaining the correct prototypical
  13696. * inheritance.
  13697. *
  13698. * @returns {Object} The newly created child scope.
  13699. *
  13700. */
  13701. $new: function(isolate, parent) {
  13702. var child;
  13703. parent = parent || this;
  13704. if (isolate) {
  13705. child = new Scope();
  13706. child.$root = this.$root;
  13707. } else {
  13708. // Only create a child scope class if somebody asks for one,
  13709. // but cache it to allow the VM to optimize lookups.
  13710. if (!this.$$ChildScope) {
  13711. this.$$ChildScope = createChildScopeClass(this);
  13712. }
  13713. child = new this.$$ChildScope();
  13714. }
  13715. child.$parent = parent;
  13716. child.$$prevSibling = parent.$$childTail;
  13717. if (parent.$$childHead) {
  13718. parent.$$childTail.$$nextSibling = child;
  13719. parent.$$childTail = child;
  13720. } else {
  13721. parent.$$childHead = parent.$$childTail = child;
  13722. }
  13723. // When the new scope is not isolated or we inherit from `this`, and
  13724. // the parent scope is destroyed, the property `$$destroyed` is inherited
  13725. // prototypically. In all other cases, this property needs to be set
  13726. // when the parent scope is destroyed.
  13727. // The listener needs to be added after the parent is set
  13728. if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
  13729. return child;
  13730. },
  13731. /**
  13732. * @ngdoc method
  13733. * @name $rootScope.Scope#$watch
  13734. * @kind function
  13735. *
  13736. * @description
  13737. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  13738. *
  13739. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  13740. * $digest()} and should return the value that will be watched. (Since
  13741. * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
  13742. * `watchExpression` can execute multiple times per
  13743. * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
  13744. * - The `listener` is called only when the value from the current `watchExpression` and the
  13745. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  13746. * see below). Inequality is determined according to reference inequality,
  13747. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  13748. * via the `!==` Javascript operator, unless `objectEquality == true`
  13749. * (see next point)
  13750. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  13751. * according to the {@link angular.equals} function. To save the value of the object for
  13752. * later comparison, the {@link angular.copy} function is used. This therefore means that
  13753. * watching complex objects will have adverse memory and performance implications.
  13754. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  13755. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  13756. * iteration limit is 10 to prevent an infinite loop deadlock.
  13757. *
  13758. *
  13759. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  13760. * you can register a `watchExpression` function with no `listener`. (Be prepared for
  13761. * multiple calls to your `watchExpression` because it will execute multiple times in a
  13762. * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
  13763. *
  13764. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  13765. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  13766. * watcher. In rare cases, this is undesirable because the listener is called when the result
  13767. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  13768. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  13769. * listener was called due to initialization.
  13770. *
  13771. *
  13772. *
  13773. * # Example
  13774. * ```js
  13775. // let's assume that scope was dependency injected as the $rootScope
  13776. var scope = $rootScope;
  13777. scope.name = 'misko';
  13778. scope.counter = 0;
  13779. expect(scope.counter).toEqual(0);
  13780. scope.$watch('name', function(newValue, oldValue) {
  13781. scope.counter = scope.counter + 1;
  13782. });
  13783. expect(scope.counter).toEqual(0);
  13784. scope.$digest();
  13785. // the listener is always called during the first $digest loop after it was registered
  13786. expect(scope.counter).toEqual(1);
  13787. scope.$digest();
  13788. // but now it will not be called unless the value changes
  13789. expect(scope.counter).toEqual(1);
  13790. scope.name = 'adam';
  13791. scope.$digest();
  13792. expect(scope.counter).toEqual(2);
  13793. // Using a function as a watchExpression
  13794. var food;
  13795. scope.foodCounter = 0;
  13796. expect(scope.foodCounter).toEqual(0);
  13797. scope.$watch(
  13798. // This function returns the value being watched. It is called for each turn of the $digest loop
  13799. function() { return food; },
  13800. // This is the change listener, called when the value returned from the above function changes
  13801. function(newValue, oldValue) {
  13802. if ( newValue !== oldValue ) {
  13803. // Only increment the counter if the value changed
  13804. scope.foodCounter = scope.foodCounter + 1;
  13805. }
  13806. }
  13807. );
  13808. // No digest has been run so the counter will be zero
  13809. expect(scope.foodCounter).toEqual(0);
  13810. // Run the digest but since food has not changed count will still be zero
  13811. scope.$digest();
  13812. expect(scope.foodCounter).toEqual(0);
  13813. // Update food and run digest. Now the counter will increment
  13814. food = 'cheeseburger';
  13815. scope.$digest();
  13816. expect(scope.foodCounter).toEqual(1);
  13817. * ```
  13818. *
  13819. *
  13820. *
  13821. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  13822. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  13823. * a call to the `listener`.
  13824. *
  13825. * - `string`: Evaluated as {@link guide/expression expression}
  13826. * - `function(scope)`: called with current `scope` as a parameter.
  13827. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  13828. * of `watchExpression` changes.
  13829. *
  13830. * - `newVal` contains the current value of the `watchExpression`
  13831. * - `oldVal` contains the previous value of the `watchExpression`
  13832. * - `scope` refers to the current scope
  13833. * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
  13834. * comparing for reference equality.
  13835. * @returns {function()} Returns a deregistration function for this listener.
  13836. */
  13837. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  13838. var get = $parse(watchExp);
  13839. if (get.$$watchDelegate) {
  13840. return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
  13841. }
  13842. var scope = this,
  13843. array = scope.$$watchers,
  13844. watcher = {
  13845. fn: listener,
  13846. last: initWatchVal,
  13847. get: get,
  13848. exp: prettyPrintExpression || watchExp,
  13849. eq: !!objectEquality
  13850. };
  13851. lastDirtyWatch = null;
  13852. if (!isFunction(listener)) {
  13853. watcher.fn = noop;
  13854. }
  13855. if (!array) {
  13856. array = scope.$$watchers = [];
  13857. }
  13858. // we use unshift since we use a while loop in $digest for speed.
  13859. // the while loop reads in reverse order.
  13860. array.unshift(watcher);
  13861. incrementWatchersCount(this, 1);
  13862. return function deregisterWatch() {
  13863. if (arrayRemove(array, watcher) >= 0) {
  13864. incrementWatchersCount(scope, -1);
  13865. }
  13866. lastDirtyWatch = null;
  13867. };
  13868. },
  13869. /**
  13870. * @ngdoc method
  13871. * @name $rootScope.Scope#$watchGroup
  13872. * @kind function
  13873. *
  13874. * @description
  13875. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  13876. * If any one expression in the collection changes the `listener` is executed.
  13877. *
  13878. * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
  13879. * call to $digest() to see if any items changes.
  13880. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  13881. *
  13882. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  13883. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  13884. *
  13885. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  13886. * expression in `watchExpressions` changes
  13887. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  13888. * those of `watchExpression`
  13889. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  13890. * those of `watchExpression`
  13891. * The `scope` refers to the current scope.
  13892. * @returns {function()} Returns a de-registration function for all listeners.
  13893. */
  13894. $watchGroup: function(watchExpressions, listener) {
  13895. var oldValues = new Array(watchExpressions.length);
  13896. var newValues = new Array(watchExpressions.length);
  13897. var deregisterFns = [];
  13898. var self = this;
  13899. var changeReactionScheduled = false;
  13900. var firstRun = true;
  13901. if (!watchExpressions.length) {
  13902. // No expressions means we call the listener ASAP
  13903. var shouldCall = true;
  13904. self.$evalAsync(function() {
  13905. if (shouldCall) listener(newValues, newValues, self);
  13906. });
  13907. return function deregisterWatchGroup() {
  13908. shouldCall = false;
  13909. };
  13910. }
  13911. if (watchExpressions.length === 1) {
  13912. // Special case size of one
  13913. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  13914. newValues[0] = value;
  13915. oldValues[0] = oldValue;
  13916. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  13917. });
  13918. }
  13919. forEach(watchExpressions, function(expr, i) {
  13920. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  13921. newValues[i] = value;
  13922. oldValues[i] = oldValue;
  13923. if (!changeReactionScheduled) {
  13924. changeReactionScheduled = true;
  13925. self.$evalAsync(watchGroupAction);
  13926. }
  13927. });
  13928. deregisterFns.push(unwatchFn);
  13929. });
  13930. function watchGroupAction() {
  13931. changeReactionScheduled = false;
  13932. if (firstRun) {
  13933. firstRun = false;
  13934. listener(newValues, newValues, self);
  13935. } else {
  13936. listener(newValues, oldValues, self);
  13937. }
  13938. }
  13939. return function deregisterWatchGroup() {
  13940. while (deregisterFns.length) {
  13941. deregisterFns.shift()();
  13942. }
  13943. };
  13944. },
  13945. /**
  13946. * @ngdoc method
  13947. * @name $rootScope.Scope#$watchCollection
  13948. * @kind function
  13949. *
  13950. * @description
  13951. * Shallow watches the properties of an object and fires whenever any of the properties change
  13952. * (for arrays, this implies watching the array items; for object maps, this implies watching
  13953. * the properties). If a change is detected, the `listener` callback is fired.
  13954. *
  13955. * - The `obj` collection is observed via standard $watch operation and is examined on every
  13956. * call to $digest() to see if any items have been added, removed, or moved.
  13957. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  13958. * adding, removing, and moving items belonging to an object or array.
  13959. *
  13960. *
  13961. * # Example
  13962. * ```js
  13963. $scope.names = ['igor', 'matias', 'misko', 'james'];
  13964. $scope.dataCount = 4;
  13965. $scope.$watchCollection('names', function(newNames, oldNames) {
  13966. $scope.dataCount = newNames.length;
  13967. });
  13968. expect($scope.dataCount).toEqual(4);
  13969. $scope.$digest();
  13970. //still at 4 ... no changes
  13971. expect($scope.dataCount).toEqual(4);
  13972. $scope.names.pop();
  13973. $scope.$digest();
  13974. //now there's been a change
  13975. expect($scope.dataCount).toEqual(3);
  13976. * ```
  13977. *
  13978. *
  13979. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  13980. * expression value should evaluate to an object or an array which is observed on each
  13981. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  13982. * collection will trigger a call to the `listener`.
  13983. *
  13984. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  13985. * when a change is detected.
  13986. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  13987. * - The `oldCollection` object is a copy of the former collection data.
  13988. * Due to performance considerations, the`oldCollection` value is computed only if the
  13989. * `listener` function declares two or more arguments.
  13990. * - The `scope` argument refers to the current scope.
  13991. *
  13992. * @returns {function()} Returns a de-registration function for this listener. When the
  13993. * de-registration function is executed, the internal watch operation is terminated.
  13994. */
  13995. $watchCollection: function(obj, listener) {
  13996. $watchCollectionInterceptor.$stateful = true;
  13997. var self = this;
  13998. // the current value, updated on each dirty-check run
  13999. var newValue;
  14000. // a shallow copy of the newValue from the last dirty-check run,
  14001. // updated to match newValue during dirty-check run
  14002. var oldValue;
  14003. // a shallow copy of the newValue from when the last change happened
  14004. var veryOldValue;
  14005. // only track veryOldValue if the listener is asking for it
  14006. var trackVeryOldValue = (listener.length > 1);
  14007. var changeDetected = 0;
  14008. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  14009. var internalArray = [];
  14010. var internalObject = {};
  14011. var initRun = true;
  14012. var oldLength = 0;
  14013. function $watchCollectionInterceptor(_value) {
  14014. newValue = _value;
  14015. var newLength, key, bothNaN, newItem, oldItem;
  14016. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  14017. if (isUndefined(newValue)) return;
  14018. if (!isObject(newValue)) { // if primitive
  14019. if (oldValue !== newValue) {
  14020. oldValue = newValue;
  14021. changeDetected++;
  14022. }
  14023. } else if (isArrayLike(newValue)) {
  14024. if (oldValue !== internalArray) {
  14025. // we are transitioning from something which was not an array into array.
  14026. oldValue = internalArray;
  14027. oldLength = oldValue.length = 0;
  14028. changeDetected++;
  14029. }
  14030. newLength = newValue.length;
  14031. if (oldLength !== newLength) {
  14032. // if lengths do not match we need to trigger change notification
  14033. changeDetected++;
  14034. oldValue.length = oldLength = newLength;
  14035. }
  14036. // copy the items to oldValue and look for changes.
  14037. for (var i = 0; i < newLength; i++) {
  14038. oldItem = oldValue[i];
  14039. newItem = newValue[i];
  14040. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  14041. if (!bothNaN && (oldItem !== newItem)) {
  14042. changeDetected++;
  14043. oldValue[i] = newItem;
  14044. }
  14045. }
  14046. } else {
  14047. if (oldValue !== internalObject) {
  14048. // we are transitioning from something which was not an object into object.
  14049. oldValue = internalObject = {};
  14050. oldLength = 0;
  14051. changeDetected++;
  14052. }
  14053. // copy the items to oldValue and look for changes.
  14054. newLength = 0;
  14055. for (key in newValue) {
  14056. if (newValue.hasOwnProperty(key)) {
  14057. newLength++;
  14058. newItem = newValue[key];
  14059. oldItem = oldValue[key];
  14060. if (key in oldValue) {
  14061. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  14062. if (!bothNaN && (oldItem !== newItem)) {
  14063. changeDetected++;
  14064. oldValue[key] = newItem;
  14065. }
  14066. } else {
  14067. oldLength++;
  14068. oldValue[key] = newItem;
  14069. changeDetected++;
  14070. }
  14071. }
  14072. }
  14073. if (oldLength > newLength) {
  14074. // we used to have more keys, need to find them and destroy them.
  14075. changeDetected++;
  14076. for (key in oldValue) {
  14077. if (!newValue.hasOwnProperty(key)) {
  14078. oldLength--;
  14079. delete oldValue[key];
  14080. }
  14081. }
  14082. }
  14083. }
  14084. return changeDetected;
  14085. }
  14086. function $watchCollectionAction() {
  14087. if (initRun) {
  14088. initRun = false;
  14089. listener(newValue, newValue, self);
  14090. } else {
  14091. listener(newValue, veryOldValue, self);
  14092. }
  14093. // make a copy for the next time a collection is changed
  14094. if (trackVeryOldValue) {
  14095. if (!isObject(newValue)) {
  14096. //primitive
  14097. veryOldValue = newValue;
  14098. } else if (isArrayLike(newValue)) {
  14099. veryOldValue = new Array(newValue.length);
  14100. for (var i = 0; i < newValue.length; i++) {
  14101. veryOldValue[i] = newValue[i];
  14102. }
  14103. } else { // if object
  14104. veryOldValue = {};
  14105. for (var key in newValue) {
  14106. if (hasOwnProperty.call(newValue, key)) {
  14107. veryOldValue[key] = newValue[key];
  14108. }
  14109. }
  14110. }
  14111. }
  14112. }
  14113. return this.$watch(changeDetector, $watchCollectionAction);
  14114. },
  14115. /**
  14116. * @ngdoc method
  14117. * @name $rootScope.Scope#$digest
  14118. * @kind function
  14119. *
  14120. * @description
  14121. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  14122. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  14123. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  14124. * until no more listeners are firing. This means that it is possible to get into an infinite
  14125. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  14126. * iterations exceeds 10.
  14127. *
  14128. * Usually, you don't call `$digest()` directly in
  14129. * {@link ng.directive:ngController controllers} or in
  14130. * {@link ng.$compileProvider#directive directives}.
  14131. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  14132. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  14133. *
  14134. * If you want to be notified whenever `$digest()` is called,
  14135. * you can register a `watchExpression` function with
  14136. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  14137. *
  14138. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  14139. *
  14140. * # Example
  14141. * ```js
  14142. var scope = ...;
  14143. scope.name = 'misko';
  14144. scope.counter = 0;
  14145. expect(scope.counter).toEqual(0);
  14146. scope.$watch('name', function(newValue, oldValue) {
  14147. scope.counter = scope.counter + 1;
  14148. });
  14149. expect(scope.counter).toEqual(0);
  14150. scope.$digest();
  14151. // the listener is always called during the first $digest loop after it was registered
  14152. expect(scope.counter).toEqual(1);
  14153. scope.$digest();
  14154. // but now it will not be called unless the value changes
  14155. expect(scope.counter).toEqual(1);
  14156. scope.name = 'adam';
  14157. scope.$digest();
  14158. expect(scope.counter).toEqual(2);
  14159. * ```
  14160. *
  14161. */
  14162. $digest: function() {
  14163. var watch, value, last,
  14164. watchers,
  14165. length,
  14166. dirty, ttl = TTL,
  14167. next, current, target = this,
  14168. watchLog = [],
  14169. logIdx, logMsg, asyncTask;
  14170. beginPhase('$digest');
  14171. // Check for changes to browser url that happened in sync before the call to $digest
  14172. $browser.$$checkUrlChange();
  14173. if (this === $rootScope && applyAsyncId !== null) {
  14174. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  14175. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  14176. $browser.defer.cancel(applyAsyncId);
  14177. flushApplyAsync();
  14178. }
  14179. lastDirtyWatch = null;
  14180. do { // "while dirty" loop
  14181. dirty = false;
  14182. current = target;
  14183. while (asyncQueue.length) {
  14184. try {
  14185. asyncTask = asyncQueue.shift();
  14186. asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
  14187. } catch (e) {
  14188. $exceptionHandler(e);
  14189. }
  14190. lastDirtyWatch = null;
  14191. }
  14192. traverseScopesLoop:
  14193. do { // "traverse the scopes" loop
  14194. if ((watchers = current.$$watchers)) {
  14195. // process our watches
  14196. length = watchers.length;
  14197. while (length--) {
  14198. try {
  14199. watch = watchers[length];
  14200. // Most common watches are on primitives, in which case we can short
  14201. // circuit it with === operator, only when === fails do we use .equals
  14202. if (watch) {
  14203. if ((value = watch.get(current)) !== (last = watch.last) &&
  14204. !(watch.eq
  14205. ? equals(value, last)
  14206. : (typeof value === 'number' && typeof last === 'number'
  14207. && isNaN(value) && isNaN(last)))) {
  14208. dirty = true;
  14209. lastDirtyWatch = watch;
  14210. watch.last = watch.eq ? copy(value, null) : value;
  14211. watch.fn(value, ((last === initWatchVal) ? value : last), current);
  14212. if (ttl < 5) {
  14213. logIdx = 4 - ttl;
  14214. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  14215. watchLog[logIdx].push({
  14216. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  14217. newVal: value,
  14218. oldVal: last
  14219. });
  14220. }
  14221. } else if (watch === lastDirtyWatch) {
  14222. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  14223. // have already been tested.
  14224. dirty = false;
  14225. break traverseScopesLoop;
  14226. }
  14227. }
  14228. } catch (e) {
  14229. $exceptionHandler(e);
  14230. }
  14231. }
  14232. }
  14233. // Insanity Warning: scope depth-first traversal
  14234. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  14235. // this piece should be kept in sync with the traversal in $broadcast
  14236. if (!(next = ((current.$$watchersCount && current.$$childHead) ||
  14237. (current !== target && current.$$nextSibling)))) {
  14238. while (current !== target && !(next = current.$$nextSibling)) {
  14239. current = current.$parent;
  14240. }
  14241. }
  14242. } while ((current = next));
  14243. // `break traverseScopesLoop;` takes us to here
  14244. if ((dirty || asyncQueue.length) && !(ttl--)) {
  14245. clearPhase();
  14246. throw $rootScopeMinErr('infdig',
  14247. '{0} $digest() iterations reached. Aborting!\n' +
  14248. 'Watchers fired in the last 5 iterations: {1}',
  14249. TTL, watchLog);
  14250. }
  14251. } while (dirty || asyncQueue.length);
  14252. clearPhase();
  14253. while (postDigestQueue.length) {
  14254. try {
  14255. postDigestQueue.shift()();
  14256. } catch (e) {
  14257. $exceptionHandler(e);
  14258. }
  14259. }
  14260. },
  14261. /**
  14262. * @ngdoc event
  14263. * @name $rootScope.Scope#$destroy
  14264. * @eventType broadcast on scope being destroyed
  14265. *
  14266. * @description
  14267. * Broadcasted when a scope and its children are being destroyed.
  14268. *
  14269. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  14270. * clean up DOM bindings before an element is removed from the DOM.
  14271. */
  14272. /**
  14273. * @ngdoc method
  14274. * @name $rootScope.Scope#$destroy
  14275. * @kind function
  14276. *
  14277. * @description
  14278. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  14279. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  14280. * propagate to the current scope and its children. Removal also implies that the current
  14281. * scope is eligible for garbage collection.
  14282. *
  14283. * The `$destroy()` is usually used by directives such as
  14284. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  14285. * unrolling of the loop.
  14286. *
  14287. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  14288. * Application code can register a `$destroy` event handler that will give it a chance to
  14289. * perform any necessary cleanup.
  14290. *
  14291. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  14292. * clean up DOM bindings before an element is removed from the DOM.
  14293. */
  14294. $destroy: function() {
  14295. // We can't destroy a scope that has been already destroyed.
  14296. if (this.$$destroyed) return;
  14297. var parent = this.$parent;
  14298. this.$broadcast('$destroy');
  14299. this.$$destroyed = true;
  14300. if (this === $rootScope) {
  14301. //Remove handlers attached to window when $rootScope is removed
  14302. $browser.$$applicationDestroyed();
  14303. }
  14304. incrementWatchersCount(this, -this.$$watchersCount);
  14305. for (var eventName in this.$$listenerCount) {
  14306. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  14307. }
  14308. // sever all the references to parent scopes (after this cleanup, the current scope should
  14309. // not be retained by any of our references and should be eligible for garbage collection)
  14310. if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  14311. if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  14312. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  14313. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  14314. // Disable listeners, watchers and apply/digest methods
  14315. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  14316. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  14317. this.$$listeners = {};
  14318. // All of the code below is bogus code that works around V8's memory leak via optimized code
  14319. // and inline caches.
  14320. //
  14321. // see:
  14322. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  14323. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  14324. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  14325. this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
  14326. this.$$childTail = this.$root = this.$$watchers = null;
  14327. },
  14328. /**
  14329. * @ngdoc method
  14330. * @name $rootScope.Scope#$eval
  14331. * @kind function
  14332. *
  14333. * @description
  14334. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  14335. * the expression are propagated (uncaught). This is useful when evaluating Angular
  14336. * expressions.
  14337. *
  14338. * # Example
  14339. * ```js
  14340. var scope = ng.$rootScope.Scope();
  14341. scope.a = 1;
  14342. scope.b = 2;
  14343. expect(scope.$eval('a+b')).toEqual(3);
  14344. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  14345. * ```
  14346. *
  14347. * @param {(string|function())=} expression An angular expression to be executed.
  14348. *
  14349. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14350. * - `function(scope)`: execute the function with the current `scope` parameter.
  14351. *
  14352. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  14353. * @returns {*} The result of evaluating the expression.
  14354. */
  14355. $eval: function(expr, locals) {
  14356. return $parse(expr)(this, locals);
  14357. },
  14358. /**
  14359. * @ngdoc method
  14360. * @name $rootScope.Scope#$evalAsync
  14361. * @kind function
  14362. *
  14363. * @description
  14364. * Executes the expression on the current scope at a later point in time.
  14365. *
  14366. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  14367. * that:
  14368. *
  14369. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  14370. * rendering).
  14371. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  14372. * `expression` execution.
  14373. *
  14374. * Any exceptions from the execution of the expression are forwarded to the
  14375. * {@link ng.$exceptionHandler $exceptionHandler} service.
  14376. *
  14377. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  14378. * will be scheduled. However, it is encouraged to always call code that changes the model
  14379. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  14380. *
  14381. * @param {(string|function())=} expression An angular expression to be executed.
  14382. *
  14383. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14384. * - `function(scope)`: execute the function with the current `scope` parameter.
  14385. *
  14386. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  14387. */
  14388. $evalAsync: function(expr, locals) {
  14389. // if we are outside of an $digest loop and this is the first time we are scheduling async
  14390. // task also schedule async auto-flush
  14391. if (!$rootScope.$$phase && !asyncQueue.length) {
  14392. $browser.defer(function() {
  14393. if (asyncQueue.length) {
  14394. $rootScope.$digest();
  14395. }
  14396. });
  14397. }
  14398. asyncQueue.push({scope: this, expression: expr, locals: locals});
  14399. },
  14400. $$postDigest: function(fn) {
  14401. postDigestQueue.push(fn);
  14402. },
  14403. /**
  14404. * @ngdoc method
  14405. * @name $rootScope.Scope#$apply
  14406. * @kind function
  14407. *
  14408. * @description
  14409. * `$apply()` is used to execute an expression in angular from outside of the angular
  14410. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  14411. * Because we are calling into the angular framework we need to perform proper scope life
  14412. * cycle of {@link ng.$exceptionHandler exception handling},
  14413. * {@link ng.$rootScope.Scope#$digest executing watches}.
  14414. *
  14415. * ## Life cycle
  14416. *
  14417. * # Pseudo-Code of `$apply()`
  14418. * ```js
  14419. function $apply(expr) {
  14420. try {
  14421. return $eval(expr);
  14422. } catch (e) {
  14423. $exceptionHandler(e);
  14424. } finally {
  14425. $root.$digest();
  14426. }
  14427. }
  14428. * ```
  14429. *
  14430. *
  14431. * Scope's `$apply()` method transitions through the following stages:
  14432. *
  14433. * 1. The {@link guide/expression expression} is executed using the
  14434. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  14435. * 2. Any exceptions from the execution of the expression are forwarded to the
  14436. * {@link ng.$exceptionHandler $exceptionHandler} service.
  14437. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  14438. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  14439. *
  14440. *
  14441. * @param {(string|function())=} exp An angular expression to be executed.
  14442. *
  14443. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14444. * - `function(scope)`: execute the function with current `scope` parameter.
  14445. *
  14446. * @returns {*} The result of evaluating the expression.
  14447. */
  14448. $apply: function(expr) {
  14449. try {
  14450. beginPhase('$apply');
  14451. try {
  14452. return this.$eval(expr);
  14453. } finally {
  14454. clearPhase();
  14455. }
  14456. } catch (e) {
  14457. $exceptionHandler(e);
  14458. } finally {
  14459. try {
  14460. $rootScope.$digest();
  14461. } catch (e) {
  14462. $exceptionHandler(e);
  14463. throw e;
  14464. }
  14465. }
  14466. },
  14467. /**
  14468. * @ngdoc method
  14469. * @name $rootScope.Scope#$applyAsync
  14470. * @kind function
  14471. *
  14472. * @description
  14473. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  14474. * varies across browsers, but is typically around ~10 milliseconds.
  14475. *
  14476. * This can be used to queue up multiple expressions which need to be evaluated in the same
  14477. * digest.
  14478. *
  14479. * @param {(string|function())=} exp An angular expression to be executed.
  14480. *
  14481. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14482. * - `function(scope)`: execute the function with current `scope` parameter.
  14483. */
  14484. $applyAsync: function(expr) {
  14485. var scope = this;
  14486. expr && applyAsyncQueue.push($applyAsyncExpression);
  14487. scheduleApplyAsync();
  14488. function $applyAsyncExpression() {
  14489. scope.$eval(expr);
  14490. }
  14491. },
  14492. /**
  14493. * @ngdoc method
  14494. * @name $rootScope.Scope#$on
  14495. * @kind function
  14496. *
  14497. * @description
  14498. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  14499. * discussion of event life cycle.
  14500. *
  14501. * The event listener function format is: `function(event, args...)`. The `event` object
  14502. * passed into the listener has the following attributes:
  14503. *
  14504. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  14505. * `$broadcast`-ed.
  14506. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  14507. * event propagates through the scope hierarchy, this property is set to null.
  14508. * - `name` - `{string}`: name of the event.
  14509. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  14510. * further event propagation (available only for events that were `$emit`-ed).
  14511. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  14512. * to true.
  14513. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  14514. *
  14515. * @param {string} name Event name to listen on.
  14516. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  14517. * @returns {function()} Returns a deregistration function for this listener.
  14518. */
  14519. $on: function(name, listener) {
  14520. var namedListeners = this.$$listeners[name];
  14521. if (!namedListeners) {
  14522. this.$$listeners[name] = namedListeners = [];
  14523. }
  14524. namedListeners.push(listener);
  14525. var current = this;
  14526. do {
  14527. if (!current.$$listenerCount[name]) {
  14528. current.$$listenerCount[name] = 0;
  14529. }
  14530. current.$$listenerCount[name]++;
  14531. } while ((current = current.$parent));
  14532. var self = this;
  14533. return function() {
  14534. var indexOfListener = namedListeners.indexOf(listener);
  14535. if (indexOfListener !== -1) {
  14536. namedListeners[indexOfListener] = null;
  14537. decrementListenerCount(self, 1, name);
  14538. }
  14539. };
  14540. },
  14541. /**
  14542. * @ngdoc method
  14543. * @name $rootScope.Scope#$emit
  14544. * @kind function
  14545. *
  14546. * @description
  14547. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  14548. * registered {@link ng.$rootScope.Scope#$on} listeners.
  14549. *
  14550. * The event life cycle starts at the scope on which `$emit` was called. All
  14551. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  14552. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  14553. * registered listeners along the way. The event will stop propagating if one of the listeners
  14554. * cancels it.
  14555. *
  14556. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  14557. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  14558. *
  14559. * @param {string} name Event name to emit.
  14560. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  14561. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  14562. */
  14563. $emit: function(name, args) {
  14564. var empty = [],
  14565. namedListeners,
  14566. scope = this,
  14567. stopPropagation = false,
  14568. event = {
  14569. name: name,
  14570. targetScope: scope,
  14571. stopPropagation: function() {stopPropagation = true;},
  14572. preventDefault: function() {
  14573. event.defaultPrevented = true;
  14574. },
  14575. defaultPrevented: false
  14576. },
  14577. listenerArgs = concat([event], arguments, 1),
  14578. i, length;
  14579. do {
  14580. namedListeners = scope.$$listeners[name] || empty;
  14581. event.currentScope = scope;
  14582. for (i = 0, length = namedListeners.length; i < length; i++) {
  14583. // if listeners were deregistered, defragment the array
  14584. if (!namedListeners[i]) {
  14585. namedListeners.splice(i, 1);
  14586. i--;
  14587. length--;
  14588. continue;
  14589. }
  14590. try {
  14591. //allow all listeners attached to the current scope to run
  14592. namedListeners[i].apply(null, listenerArgs);
  14593. } catch (e) {
  14594. $exceptionHandler(e);
  14595. }
  14596. }
  14597. //if any listener on the current scope stops propagation, prevent bubbling
  14598. if (stopPropagation) {
  14599. event.currentScope = null;
  14600. return event;
  14601. }
  14602. //traverse upwards
  14603. scope = scope.$parent;
  14604. } while (scope);
  14605. event.currentScope = null;
  14606. return event;
  14607. },
  14608. /**
  14609. * @ngdoc method
  14610. * @name $rootScope.Scope#$broadcast
  14611. * @kind function
  14612. *
  14613. * @description
  14614. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  14615. * registered {@link ng.$rootScope.Scope#$on} listeners.
  14616. *
  14617. * The event life cycle starts at the scope on which `$broadcast` was called. All
  14618. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  14619. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  14620. * scope and calls all registered listeners along the way. The event cannot be canceled.
  14621. *
  14622. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  14623. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  14624. *
  14625. * @param {string} name Event name to broadcast.
  14626. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  14627. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  14628. */
  14629. $broadcast: function(name, args) {
  14630. var target = this,
  14631. current = target,
  14632. next = target,
  14633. event = {
  14634. name: name,
  14635. targetScope: target,
  14636. preventDefault: function() {
  14637. event.defaultPrevented = true;
  14638. },
  14639. defaultPrevented: false
  14640. };
  14641. if (!target.$$listenerCount[name]) return event;
  14642. var listenerArgs = concat([event], arguments, 1),
  14643. listeners, i, length;
  14644. //down while you can, then up and next sibling or up and next sibling until back at root
  14645. while ((current = next)) {
  14646. event.currentScope = current;
  14647. listeners = current.$$listeners[name] || [];
  14648. for (i = 0, length = listeners.length; i < length; i++) {
  14649. // if listeners were deregistered, defragment the array
  14650. if (!listeners[i]) {
  14651. listeners.splice(i, 1);
  14652. i--;
  14653. length--;
  14654. continue;
  14655. }
  14656. try {
  14657. listeners[i].apply(null, listenerArgs);
  14658. } catch (e) {
  14659. $exceptionHandler(e);
  14660. }
  14661. }
  14662. // Insanity Warning: scope depth-first traversal
  14663. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  14664. // this piece should be kept in sync with the traversal in $digest
  14665. // (though it differs due to having the extra check for $$listenerCount)
  14666. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  14667. (current !== target && current.$$nextSibling)))) {
  14668. while (current !== target && !(next = current.$$nextSibling)) {
  14669. current = current.$parent;
  14670. }
  14671. }
  14672. }
  14673. event.currentScope = null;
  14674. return event;
  14675. }
  14676. };
  14677. var $rootScope = new Scope();
  14678. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  14679. var asyncQueue = $rootScope.$$asyncQueue = [];
  14680. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  14681. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  14682. return $rootScope;
  14683. function beginPhase(phase) {
  14684. if ($rootScope.$$phase) {
  14685. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  14686. }
  14687. $rootScope.$$phase = phase;
  14688. }
  14689. function clearPhase() {
  14690. $rootScope.$$phase = null;
  14691. }
  14692. function incrementWatchersCount(current, count) {
  14693. do {
  14694. current.$$watchersCount += count;
  14695. } while ((current = current.$parent));
  14696. }
  14697. function decrementListenerCount(current, count, name) {
  14698. do {
  14699. current.$$listenerCount[name] -= count;
  14700. if (current.$$listenerCount[name] === 0) {
  14701. delete current.$$listenerCount[name];
  14702. }
  14703. } while ((current = current.$parent));
  14704. }
  14705. /**
  14706. * function used as an initial value for watchers.
  14707. * because it's unique we can easily tell it apart from other values
  14708. */
  14709. function initWatchVal() {}
  14710. function flushApplyAsync() {
  14711. while (applyAsyncQueue.length) {
  14712. try {
  14713. applyAsyncQueue.shift()();
  14714. } catch (e) {
  14715. $exceptionHandler(e);
  14716. }
  14717. }
  14718. applyAsyncId = null;
  14719. }
  14720. function scheduleApplyAsync() {
  14721. if (applyAsyncId === null) {
  14722. applyAsyncId = $browser.defer(function() {
  14723. $rootScope.$apply(flushApplyAsync);
  14724. });
  14725. }
  14726. }
  14727. }];
  14728. }
  14729. /**
  14730. * @description
  14731. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  14732. */
  14733. function $$SanitizeUriProvider() {
  14734. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  14735. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  14736. /**
  14737. * @description
  14738. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  14739. * urls during a[href] sanitization.
  14740. *
  14741. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  14742. *
  14743. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  14744. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  14745. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  14746. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  14747. *
  14748. * @param {RegExp=} regexp New regexp to whitelist urls with.
  14749. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  14750. * chaining otherwise.
  14751. */
  14752. this.aHrefSanitizationWhitelist = function(regexp) {
  14753. if (isDefined(regexp)) {
  14754. aHrefSanitizationWhitelist = regexp;
  14755. return this;
  14756. }
  14757. return aHrefSanitizationWhitelist;
  14758. };
  14759. /**
  14760. * @description
  14761. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  14762. * urls during img[src] sanitization.
  14763. *
  14764. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  14765. *
  14766. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  14767. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  14768. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  14769. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  14770. *
  14771. * @param {RegExp=} regexp New regexp to whitelist urls with.
  14772. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  14773. * chaining otherwise.
  14774. */
  14775. this.imgSrcSanitizationWhitelist = function(regexp) {
  14776. if (isDefined(regexp)) {
  14777. imgSrcSanitizationWhitelist = regexp;
  14778. return this;
  14779. }
  14780. return imgSrcSanitizationWhitelist;
  14781. };
  14782. this.$get = function() {
  14783. return function sanitizeUri(uri, isImage) {
  14784. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  14785. var normalizedVal;
  14786. normalizedVal = urlResolve(uri).href;
  14787. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  14788. return 'unsafe:' + normalizedVal;
  14789. }
  14790. return uri;
  14791. };
  14792. };
  14793. }
  14794. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  14795. * Any commits to this file should be reviewed with security in mind. *
  14796. * Changes to this file can potentially create security vulnerabilities. *
  14797. * An approval from 2 Core members with history of modifying *
  14798. * this file is required. *
  14799. * *
  14800. * Does the change somehow allow for arbitrary javascript to be executed? *
  14801. * Or allows for someone to change the prototype of built-in objects? *
  14802. * Or gives undesired access to variables likes document or window? *
  14803. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  14804. var $sceMinErr = minErr('$sce');
  14805. var SCE_CONTEXTS = {
  14806. HTML: 'html',
  14807. CSS: 'css',
  14808. URL: 'url',
  14809. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  14810. // url. (e.g. ng-include, script src, templateUrl)
  14811. RESOURCE_URL: 'resourceUrl',
  14812. JS: 'js'
  14813. };
  14814. // Helper functions follow.
  14815. function adjustMatcher(matcher) {
  14816. if (matcher === 'self') {
  14817. return matcher;
  14818. } else if (isString(matcher)) {
  14819. // Strings match exactly except for 2 wildcards - '*' and '**'.
  14820. // '*' matches any character except those from the set ':/.?&'.
  14821. // '**' matches any character (like .* in a RegExp).
  14822. // More than 2 *'s raises an error as it's ill defined.
  14823. if (matcher.indexOf('***') > -1) {
  14824. throw $sceMinErr('iwcard',
  14825. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  14826. }
  14827. matcher = escapeForRegexp(matcher).
  14828. replace('\\*\\*', '.*').
  14829. replace('\\*', '[^:/.?&;]*');
  14830. return new RegExp('^' + matcher + '$');
  14831. } else if (isRegExp(matcher)) {
  14832. // The only other type of matcher allowed is a Regexp.
  14833. // Match entire URL / disallow partial matches.
  14834. // Flags are reset (i.e. no global, ignoreCase or multiline)
  14835. return new RegExp('^' + matcher.source + '$');
  14836. } else {
  14837. throw $sceMinErr('imatcher',
  14838. 'Matchers may only be "self", string patterns or RegExp objects');
  14839. }
  14840. }
  14841. function adjustMatchers(matchers) {
  14842. var adjustedMatchers = [];
  14843. if (isDefined(matchers)) {
  14844. forEach(matchers, function(matcher) {
  14845. adjustedMatchers.push(adjustMatcher(matcher));
  14846. });
  14847. }
  14848. return adjustedMatchers;
  14849. }
  14850. /**
  14851. * @ngdoc service
  14852. * @name $sceDelegate
  14853. * @kind function
  14854. *
  14855. * @description
  14856. *
  14857. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  14858. * Contextual Escaping (SCE)} services to AngularJS.
  14859. *
  14860. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  14861. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  14862. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  14863. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  14864. * work because `$sce` delegates to `$sceDelegate` for these operations.
  14865. *
  14866. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  14867. *
  14868. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  14869. * can override it completely to change the behavior of `$sce`, the common case would
  14870. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  14871. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  14872. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  14873. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  14874. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  14875. */
  14876. /**
  14877. * @ngdoc provider
  14878. * @name $sceDelegateProvider
  14879. * @description
  14880. *
  14881. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  14882. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  14883. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  14884. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  14885. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  14886. *
  14887. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  14888. * Strict Contextual Escaping (SCE)}.
  14889. *
  14890. * **Example**: Consider the following case. <a name="example"></a>
  14891. *
  14892. * - your app is hosted at url `http://myapp.example.com/`
  14893. * - but some of your templates are hosted on other domains you control such as
  14894. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  14895. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  14896. *
  14897. * Here is what a secure configuration for this scenario might look like:
  14898. *
  14899. * ```
  14900. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  14901. * $sceDelegateProvider.resourceUrlWhitelist([
  14902. * // Allow same origin resource loads.
  14903. * 'self',
  14904. * // Allow loading from our assets domain. Notice the difference between * and **.
  14905. * 'http://srv*.assets.example.com/**'
  14906. * ]);
  14907. *
  14908. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  14909. * $sceDelegateProvider.resourceUrlBlacklist([
  14910. * 'http://myapp.example.com/clickThru**'
  14911. * ]);
  14912. * });
  14913. * ```
  14914. */
  14915. function $SceDelegateProvider() {
  14916. this.SCE_CONTEXTS = SCE_CONTEXTS;
  14917. // Resource URLs can also be trusted by policy.
  14918. var resourceUrlWhitelist = ['self'],
  14919. resourceUrlBlacklist = [];
  14920. /**
  14921. * @ngdoc method
  14922. * @name $sceDelegateProvider#resourceUrlWhitelist
  14923. * @kind function
  14924. *
  14925. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  14926. * provided. This must be an array or null. A snapshot of this array is used so further
  14927. * changes to the array are ignored.
  14928. *
  14929. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  14930. * allowed in this array.
  14931. *
  14932. * Note: **an empty whitelist array will block all URLs**!
  14933. *
  14934. * @return {Array} the currently set whitelist array.
  14935. *
  14936. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  14937. * same origin resource requests.
  14938. *
  14939. * @description
  14940. * Sets/Gets the whitelist of trusted resource URLs.
  14941. */
  14942. this.resourceUrlWhitelist = function(value) {
  14943. if (arguments.length) {
  14944. resourceUrlWhitelist = adjustMatchers(value);
  14945. }
  14946. return resourceUrlWhitelist;
  14947. };
  14948. /**
  14949. * @ngdoc method
  14950. * @name $sceDelegateProvider#resourceUrlBlacklist
  14951. * @kind function
  14952. *
  14953. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  14954. * provided. This must be an array or null. A snapshot of this array is used so further
  14955. * changes to the array are ignored.
  14956. *
  14957. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  14958. * allowed in this array.
  14959. *
  14960. * The typical usage for the blacklist is to **block
  14961. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  14962. * these would otherwise be trusted but actually return content from the redirected domain.
  14963. *
  14964. * Finally, **the blacklist overrides the whitelist** and has the final say.
  14965. *
  14966. * @return {Array} the currently set blacklist array.
  14967. *
  14968. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  14969. * is no blacklist.)
  14970. *
  14971. * @description
  14972. * Sets/Gets the blacklist of trusted resource URLs.
  14973. */
  14974. this.resourceUrlBlacklist = function(value) {
  14975. if (arguments.length) {
  14976. resourceUrlBlacklist = adjustMatchers(value);
  14977. }
  14978. return resourceUrlBlacklist;
  14979. };
  14980. this.$get = ['$injector', function($injector) {
  14981. var htmlSanitizer = function htmlSanitizer(html) {
  14982. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  14983. };
  14984. if ($injector.has('$sanitize')) {
  14985. htmlSanitizer = $injector.get('$sanitize');
  14986. }
  14987. function matchUrl(matcher, parsedUrl) {
  14988. if (matcher === 'self') {
  14989. return urlIsSameOrigin(parsedUrl);
  14990. } else {
  14991. // definitely a regex. See adjustMatchers()
  14992. return !!matcher.exec(parsedUrl.href);
  14993. }
  14994. }
  14995. function isResourceUrlAllowedByPolicy(url) {
  14996. var parsedUrl = urlResolve(url.toString());
  14997. var i, n, allowed = false;
  14998. // Ensure that at least one item from the whitelist allows this url.
  14999. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  15000. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  15001. allowed = true;
  15002. break;
  15003. }
  15004. }
  15005. if (allowed) {
  15006. // Ensure that no item from the blacklist blocked this url.
  15007. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  15008. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  15009. allowed = false;
  15010. break;
  15011. }
  15012. }
  15013. }
  15014. return allowed;
  15015. }
  15016. function generateHolderType(Base) {
  15017. var holderType = function TrustedValueHolderType(trustedValue) {
  15018. this.$$unwrapTrustedValue = function() {
  15019. return trustedValue;
  15020. };
  15021. };
  15022. if (Base) {
  15023. holderType.prototype = new Base();
  15024. }
  15025. holderType.prototype.valueOf = function sceValueOf() {
  15026. return this.$$unwrapTrustedValue();
  15027. };
  15028. holderType.prototype.toString = function sceToString() {
  15029. return this.$$unwrapTrustedValue().toString();
  15030. };
  15031. return holderType;
  15032. }
  15033. var trustedValueHolderBase = generateHolderType(),
  15034. byType = {};
  15035. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  15036. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  15037. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  15038. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  15039. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  15040. /**
  15041. * @ngdoc method
  15042. * @name $sceDelegate#trustAs
  15043. *
  15044. * @description
  15045. * Returns an object that is trusted by angular for use in specified strict
  15046. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  15047. * attribute interpolation, any dom event binding attribute interpolation
  15048. * such as for onclick, etc.) that uses the provided value.
  15049. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  15050. *
  15051. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  15052. * resourceUrl, html, js and css.
  15053. * @param {*} value The value that that should be considered trusted/safe.
  15054. * @returns {*} A value that can be used to stand in for the provided `value` in places
  15055. * where Angular expects a $sce.trustAs() return value.
  15056. */
  15057. function trustAs(type, trustedValue) {
  15058. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  15059. if (!Constructor) {
  15060. throw $sceMinErr('icontext',
  15061. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  15062. type, trustedValue);
  15063. }
  15064. if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
  15065. return trustedValue;
  15066. }
  15067. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  15068. // mutable objects, we ensure here that the value passed in is actually a string.
  15069. if (typeof trustedValue !== 'string') {
  15070. throw $sceMinErr('itype',
  15071. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  15072. type);
  15073. }
  15074. return new Constructor(trustedValue);
  15075. }
  15076. /**
  15077. * @ngdoc method
  15078. * @name $sceDelegate#valueOf
  15079. *
  15080. * @description
  15081. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  15082. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  15083. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  15084. *
  15085. * If the passed parameter is not a value that had been returned by {@link
  15086. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  15087. *
  15088. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  15089. * call or anything else.
  15090. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  15091. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  15092. * `value` unchanged.
  15093. */
  15094. function valueOf(maybeTrusted) {
  15095. if (maybeTrusted instanceof trustedValueHolderBase) {
  15096. return maybeTrusted.$$unwrapTrustedValue();
  15097. } else {
  15098. return maybeTrusted;
  15099. }
  15100. }
  15101. /**
  15102. * @ngdoc method
  15103. * @name $sceDelegate#getTrusted
  15104. *
  15105. * @description
  15106. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  15107. * returns the originally supplied value if the queried context type is a supertype of the
  15108. * created type. If this condition isn't satisfied, throws an exception.
  15109. *
  15110. * @param {string} type The kind of context in which this value is to be used.
  15111. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  15112. * `$sceDelegate.trustAs`} call.
  15113. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  15114. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  15115. */
  15116. function getTrusted(type, maybeTrusted) {
  15117. if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
  15118. return maybeTrusted;
  15119. }
  15120. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  15121. if (constructor && maybeTrusted instanceof constructor) {
  15122. return maybeTrusted.$$unwrapTrustedValue();
  15123. }
  15124. // If we get here, then we may only take one of two actions.
  15125. // 1. sanitize the value for the requested type, or
  15126. // 2. throw an exception.
  15127. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  15128. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  15129. return maybeTrusted;
  15130. } else {
  15131. throw $sceMinErr('insecurl',
  15132. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  15133. maybeTrusted.toString());
  15134. }
  15135. } else if (type === SCE_CONTEXTS.HTML) {
  15136. return htmlSanitizer(maybeTrusted);
  15137. }
  15138. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  15139. }
  15140. return { trustAs: trustAs,
  15141. getTrusted: getTrusted,
  15142. valueOf: valueOf };
  15143. }];
  15144. }
  15145. /**
  15146. * @ngdoc provider
  15147. * @name $sceProvider
  15148. * @description
  15149. *
  15150. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  15151. * - enable/disable Strict Contextual Escaping (SCE) in a module
  15152. * - override the default implementation with a custom delegate
  15153. *
  15154. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  15155. */
  15156. /* jshint maxlen: false*/
  15157. /**
  15158. * @ngdoc service
  15159. * @name $sce
  15160. * @kind function
  15161. *
  15162. * @description
  15163. *
  15164. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  15165. *
  15166. * # Strict Contextual Escaping
  15167. *
  15168. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  15169. * contexts to result in a value that is marked as safe to use for that context. One example of
  15170. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  15171. * to these contexts as privileged or SCE contexts.
  15172. *
  15173. * As of version 1.2, Angular ships with SCE enabled by default.
  15174. *
  15175. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  15176. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  15177. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  15178. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  15179. * to the top of your HTML document.
  15180. *
  15181. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  15182. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  15183. *
  15184. * Here's an example of a binding in a privileged context:
  15185. *
  15186. * ```
  15187. * <input ng-model="userHtml" aria-label="User input">
  15188. * <div ng-bind-html="userHtml"></div>
  15189. * ```
  15190. *
  15191. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  15192. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  15193. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  15194. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  15195. * security vulnerabilities.)
  15196. *
  15197. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  15198. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  15199. *
  15200. * How would you ensure that every place that used these types of bindings was bound to a value that
  15201. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  15202. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  15203. * properties/fields and forgot to update the binding to the sanitized value?
  15204. *
  15205. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  15206. * determine that something explicitly says it's safe to use a value for binding in that
  15207. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  15208. * for those values that you can easily tell are safe - because they were received from your server,
  15209. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  15210. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  15211. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  15212. *
  15213. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  15214. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  15215. * obtain values that will be accepted by SCE / privileged contexts.
  15216. *
  15217. *
  15218. * ## How does it work?
  15219. *
  15220. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  15221. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  15222. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  15223. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  15224. *
  15225. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  15226. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  15227. * simplified):
  15228. *
  15229. * ```
  15230. * var ngBindHtmlDirective = ['$sce', function($sce) {
  15231. * return function(scope, element, attr) {
  15232. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  15233. * element.html(value || '');
  15234. * });
  15235. * };
  15236. * }];
  15237. * ```
  15238. *
  15239. * ## Impact on loading templates
  15240. *
  15241. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  15242. * `templateUrl`'s specified by {@link guide/directive directives}.
  15243. *
  15244. * By default, Angular only loads templates from the same domain and protocol as the application
  15245. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  15246. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  15247. * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  15248. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  15249. *
  15250. * *Please note*:
  15251. * The browser's
  15252. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  15253. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  15254. * policy apply in addition to this and may further restrict whether the template is successfully
  15255. * loaded. This means that without the right CORS policy, loading templates from a different domain
  15256. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  15257. * browsers.
  15258. *
  15259. * ## This feels like too much overhead
  15260. *
  15261. * It's important to remember that SCE only applies to interpolation expressions.
  15262. *
  15263. * If your expressions are constant literals, they're automatically trusted and you don't need to
  15264. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  15265. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  15266. *
  15267. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  15268. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  15269. *
  15270. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  15271. * templates in `ng-include` from your application's domain without having to even know about SCE.
  15272. * It blocks loading templates from other domains or loading templates over http from an https
  15273. * served document. You can change these by setting your own custom {@link
  15274. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  15275. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  15276. *
  15277. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  15278. * application that's secure and can be audited to verify that with much more ease than bolting
  15279. * security onto an application later.
  15280. *
  15281. * <a name="contexts"></a>
  15282. * ## What trusted context types are supported?
  15283. *
  15284. * | Context | Notes |
  15285. * |---------------------|----------------|
  15286. * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. |
  15287. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  15288. * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=` and `<img src=` sanitize their urls and don't constitute an SCE context. |
  15289. * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
  15290. * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. |
  15291. *
  15292. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  15293. *
  15294. * Each element in these arrays must be one of the following:
  15295. *
  15296. * - **'self'**
  15297. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  15298. * domain** as the application document using the **same protocol**.
  15299. * - **String** (except the special value `'self'`)
  15300. * - The string is matched against the full *normalized / absolute URL* of the resource
  15301. * being tested (substring matches are not good enough.)
  15302. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  15303. * match themselves.
  15304. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  15305. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
  15306. * in a whitelist.
  15307. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  15308. * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
  15309. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  15310. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  15311. * http://foo.example.com/templates/**).
  15312. * - **RegExp** (*see caveat below*)
  15313. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  15314. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  15315. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  15316. * have good test coverage). For instance, the use of `.` in the regex is correct only in a
  15317. * small number of cases. A `.` character in the regex used when matching the scheme or a
  15318. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  15319. * is highly recommended to use the string patterns and only fall back to regular expressions
  15320. * as a last resort.
  15321. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  15322. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  15323. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  15324. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  15325. * - If you are generating your JavaScript from some other templating engine (not
  15326. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  15327. * remember to escape your regular expression (and be aware that you might need more than
  15328. * one level of escaping depending on your templating engine and the way you interpolated
  15329. * the value.) Do make use of your platform's escaping mechanism as it might be good
  15330. * enough before coding your own. E.g. Ruby has
  15331. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  15332. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  15333. * Javascript lacks a similar built in function for escaping. Take a look at Google
  15334. * Closure library's [goog.string.regExpEscape(s)](
  15335. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  15336. *
  15337. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  15338. *
  15339. * ## Show me an example using SCE.
  15340. *
  15341. * <example module="mySceApp" deps="angular-sanitize.js">
  15342. * <file name="index.html">
  15343. * <div ng-controller="AppController as myCtrl">
  15344. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  15345. * <b>User comments</b><br>
  15346. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  15347. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  15348. * exploit.
  15349. * <div class="well">
  15350. * <div ng-repeat="userComment in myCtrl.userComments">
  15351. * <b>{{userComment.name}}</b>:
  15352. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  15353. * <br>
  15354. * </div>
  15355. * </div>
  15356. * </div>
  15357. * </file>
  15358. *
  15359. * <file name="script.js">
  15360. * angular.module('mySceApp', ['ngSanitize'])
  15361. * .controller('AppController', ['$http', '$templateCache', '$sce',
  15362. * function($http, $templateCache, $sce) {
  15363. * var self = this;
  15364. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  15365. * self.userComments = userComments;
  15366. * });
  15367. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  15368. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  15369. * 'sanitization.&quot;">Hover over this text.</span>');
  15370. * }]);
  15371. * </file>
  15372. *
  15373. * <file name="test_data.json">
  15374. * [
  15375. * { "name": "Alice",
  15376. * "htmlComment":
  15377. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  15378. * },
  15379. * { "name": "Bob",
  15380. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  15381. * }
  15382. * ]
  15383. * </file>
  15384. *
  15385. * <file name="protractor.js" type="protractor">
  15386. * describe('SCE doc demo', function() {
  15387. * it('should sanitize untrusted values', function() {
  15388. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  15389. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  15390. * });
  15391. *
  15392. * it('should NOT sanitize explicitly trusted values', function() {
  15393. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  15394. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  15395. * 'sanitization.&quot;">Hover over this text.</span>');
  15396. * });
  15397. * });
  15398. * </file>
  15399. * </example>
  15400. *
  15401. *
  15402. *
  15403. * ## Can I disable SCE completely?
  15404. *
  15405. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  15406. * for little coding overhead. It will be much harder to take an SCE disabled application and
  15407. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  15408. * for cases where you have a lot of existing code that was written before SCE was introduced and
  15409. * you're migrating them a module at a time.
  15410. *
  15411. * That said, here's how you can completely disable SCE:
  15412. *
  15413. * ```
  15414. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  15415. * // Completely disable SCE. For demonstration purposes only!
  15416. * // Do not use in new projects.
  15417. * $sceProvider.enabled(false);
  15418. * });
  15419. * ```
  15420. *
  15421. */
  15422. /* jshint maxlen: 100 */
  15423. function $SceProvider() {
  15424. var enabled = true;
  15425. /**
  15426. * @ngdoc method
  15427. * @name $sceProvider#enabled
  15428. * @kind function
  15429. *
  15430. * @param {boolean=} value If provided, then enables/disables SCE.
  15431. * @return {boolean} true if SCE is enabled, false otherwise.
  15432. *
  15433. * @description
  15434. * Enables/disables SCE and returns the current value.
  15435. */
  15436. this.enabled = function(value) {
  15437. if (arguments.length) {
  15438. enabled = !!value;
  15439. }
  15440. return enabled;
  15441. };
  15442. /* Design notes on the default implementation for SCE.
  15443. *
  15444. * The API contract for the SCE delegate
  15445. * -------------------------------------
  15446. * The SCE delegate object must provide the following 3 methods:
  15447. *
  15448. * - trustAs(contextEnum, value)
  15449. * This method is used to tell the SCE service that the provided value is OK to use in the
  15450. * contexts specified by contextEnum. It must return an object that will be accepted by
  15451. * getTrusted() for a compatible contextEnum and return this value.
  15452. *
  15453. * - valueOf(value)
  15454. * For values that were not produced by trustAs(), return them as is. For values that were
  15455. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  15456. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  15457. * such a value.
  15458. *
  15459. * - getTrusted(contextEnum, value)
  15460. * This function should return the a value that is safe to use in the context specified by
  15461. * contextEnum or throw and exception otherwise.
  15462. *
  15463. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  15464. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  15465. * instance, an implementation could maintain a registry of all trusted objects by context. In
  15466. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  15467. * return the same object passed in if it was found in the registry under a compatible context or
  15468. * throw an exception otherwise. An implementation might only wrap values some of the time based
  15469. * on some criteria. getTrusted() might return a value and not throw an exception for special
  15470. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  15471. *
  15472. *
  15473. * A note on the inheritance model for SCE contexts
  15474. * ------------------------------------------------
  15475. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  15476. * is purely an implementation details.
  15477. *
  15478. * The contract is simply this:
  15479. *
  15480. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  15481. * will also succeed.
  15482. *
  15483. * Inheritance happens to capture this in a natural way. In some future, we
  15484. * may not use inheritance anymore. That is OK because no code outside of
  15485. * sce.js and sceSpecs.js would need to be aware of this detail.
  15486. */
  15487. this.$get = ['$parse', '$sceDelegate', function(
  15488. $parse, $sceDelegate) {
  15489. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  15490. // the "expression(javascript expression)" syntax which is insecure.
  15491. if (enabled && msie < 8) {
  15492. throw $sceMinErr('iequirks',
  15493. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  15494. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  15495. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  15496. }
  15497. var sce = shallowCopy(SCE_CONTEXTS);
  15498. /**
  15499. * @ngdoc method
  15500. * @name $sce#isEnabled
  15501. * @kind function
  15502. *
  15503. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  15504. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  15505. *
  15506. * @description
  15507. * Returns a boolean indicating if SCE is enabled.
  15508. */
  15509. sce.isEnabled = function() {
  15510. return enabled;
  15511. };
  15512. sce.trustAs = $sceDelegate.trustAs;
  15513. sce.getTrusted = $sceDelegate.getTrusted;
  15514. sce.valueOf = $sceDelegate.valueOf;
  15515. if (!enabled) {
  15516. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  15517. sce.valueOf = identity;
  15518. }
  15519. /**
  15520. * @ngdoc method
  15521. * @name $sce#parseAs
  15522. *
  15523. * @description
  15524. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  15525. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  15526. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  15527. * *result*)}
  15528. *
  15529. * @param {string} type The kind of SCE context in which this result will be used.
  15530. * @param {string} expression String expression to compile.
  15531. * @returns {function(context, locals)} a function which represents the compiled expression:
  15532. *
  15533. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15534. * are evaluated against (typically a scope object).
  15535. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15536. * `context`.
  15537. */
  15538. sce.parseAs = function sceParseAs(type, expr) {
  15539. var parsed = $parse(expr);
  15540. if (parsed.literal && parsed.constant) {
  15541. return parsed;
  15542. } else {
  15543. return $parse(expr, function(value) {
  15544. return sce.getTrusted(type, value);
  15545. });
  15546. }
  15547. };
  15548. /**
  15549. * @ngdoc method
  15550. * @name $sce#trustAs
  15551. *
  15552. * @description
  15553. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  15554. * returns an object that is trusted by angular for use in specified strict contextual
  15555. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  15556. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  15557. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  15558. * escaping.
  15559. *
  15560. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  15561. * resourceUrl, html, js and css.
  15562. * @param {*} value The value that that should be considered trusted/safe.
  15563. * @returns {*} A value that can be used to stand in for the provided `value` in places
  15564. * where Angular expects a $sce.trustAs() return value.
  15565. */
  15566. /**
  15567. * @ngdoc method
  15568. * @name $sce#trustAsHtml
  15569. *
  15570. * @description
  15571. * Shorthand method. `$sce.trustAsHtml(value)` →
  15572. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  15573. *
  15574. * @param {*} value The value to trustAs.
  15575. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  15576. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  15577. * only accept expressions that are either literal constants or are the
  15578. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15579. */
  15580. /**
  15581. * @ngdoc method
  15582. * @name $sce#trustAsUrl
  15583. *
  15584. * @description
  15585. * Shorthand method. `$sce.trustAsUrl(value)` →
  15586. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  15587. *
  15588. * @param {*} value The value to trustAs.
  15589. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  15590. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  15591. * only accept expressions that are either literal constants or are the
  15592. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15593. */
  15594. /**
  15595. * @ngdoc method
  15596. * @name $sce#trustAsResourceUrl
  15597. *
  15598. * @description
  15599. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  15600. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  15601. *
  15602. * @param {*} value The value to trustAs.
  15603. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  15604. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  15605. * only accept expressions that are either literal constants or are the return
  15606. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15607. */
  15608. /**
  15609. * @ngdoc method
  15610. * @name $sce#trustAsJs
  15611. *
  15612. * @description
  15613. * Shorthand method. `$sce.trustAsJs(value)` →
  15614. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  15615. *
  15616. * @param {*} value The value to trustAs.
  15617. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  15618. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  15619. * only accept expressions that are either literal constants or are the
  15620. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15621. */
  15622. /**
  15623. * @ngdoc method
  15624. * @name $sce#getTrusted
  15625. *
  15626. * @description
  15627. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  15628. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  15629. * originally supplied value if the queried context type is a supertype of the created type.
  15630. * If this condition isn't satisfied, throws an exception.
  15631. *
  15632. * @param {string} type The kind of context in which this value is to be used.
  15633. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  15634. * call.
  15635. * @returns {*} The value the was originally provided to
  15636. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  15637. * Otherwise, throws an exception.
  15638. */
  15639. /**
  15640. * @ngdoc method
  15641. * @name $sce#getTrustedHtml
  15642. *
  15643. * @description
  15644. * Shorthand method. `$sce.getTrustedHtml(value)` →
  15645. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  15646. *
  15647. * @param {*} value The value to pass to `$sce.getTrusted`.
  15648. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  15649. */
  15650. /**
  15651. * @ngdoc method
  15652. * @name $sce#getTrustedCss
  15653. *
  15654. * @description
  15655. * Shorthand method. `$sce.getTrustedCss(value)` →
  15656. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  15657. *
  15658. * @param {*} value The value to pass to `$sce.getTrusted`.
  15659. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  15660. */
  15661. /**
  15662. * @ngdoc method
  15663. * @name $sce#getTrustedUrl
  15664. *
  15665. * @description
  15666. * Shorthand method. `$sce.getTrustedUrl(value)` →
  15667. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  15668. *
  15669. * @param {*} value The value to pass to `$sce.getTrusted`.
  15670. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  15671. */
  15672. /**
  15673. * @ngdoc method
  15674. * @name $sce#getTrustedResourceUrl
  15675. *
  15676. * @description
  15677. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  15678. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  15679. *
  15680. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  15681. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  15682. */
  15683. /**
  15684. * @ngdoc method
  15685. * @name $sce#getTrustedJs
  15686. *
  15687. * @description
  15688. * Shorthand method. `$sce.getTrustedJs(value)` →
  15689. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  15690. *
  15691. * @param {*} value The value to pass to `$sce.getTrusted`.
  15692. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  15693. */
  15694. /**
  15695. * @ngdoc method
  15696. * @name $sce#parseAsHtml
  15697. *
  15698. * @description
  15699. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  15700. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  15701. *
  15702. * @param {string} expression String expression to compile.
  15703. * @returns {function(context, locals)} a function which represents the compiled expression:
  15704. *
  15705. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15706. * are evaluated against (typically a scope object).
  15707. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15708. * `context`.
  15709. */
  15710. /**
  15711. * @ngdoc method
  15712. * @name $sce#parseAsCss
  15713. *
  15714. * @description
  15715. * Shorthand method. `$sce.parseAsCss(value)` →
  15716. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  15717. *
  15718. * @param {string} expression String expression to compile.
  15719. * @returns {function(context, locals)} a function which represents the compiled expression:
  15720. *
  15721. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15722. * are evaluated against (typically a scope object).
  15723. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15724. * `context`.
  15725. */
  15726. /**
  15727. * @ngdoc method
  15728. * @name $sce#parseAsUrl
  15729. *
  15730. * @description
  15731. * Shorthand method. `$sce.parseAsUrl(value)` →
  15732. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  15733. *
  15734. * @param {string} expression String expression to compile.
  15735. * @returns {function(context, locals)} a function which represents the compiled expression:
  15736. *
  15737. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15738. * are evaluated against (typically a scope object).
  15739. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15740. * `context`.
  15741. */
  15742. /**
  15743. * @ngdoc method
  15744. * @name $sce#parseAsResourceUrl
  15745. *
  15746. * @description
  15747. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  15748. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  15749. *
  15750. * @param {string} expression String expression to compile.
  15751. * @returns {function(context, locals)} a function which represents the compiled expression:
  15752. *
  15753. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15754. * are evaluated against (typically a scope object).
  15755. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15756. * `context`.
  15757. */
  15758. /**
  15759. * @ngdoc method
  15760. * @name $sce#parseAsJs
  15761. *
  15762. * @description
  15763. * Shorthand method. `$sce.parseAsJs(value)` →
  15764. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  15765. *
  15766. * @param {string} expression String expression to compile.
  15767. * @returns {function(context, locals)} a function which represents the compiled expression:
  15768. *
  15769. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15770. * are evaluated against (typically a scope object).
  15771. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15772. * `context`.
  15773. */
  15774. // Shorthand delegations.
  15775. var parse = sce.parseAs,
  15776. getTrusted = sce.getTrusted,
  15777. trustAs = sce.trustAs;
  15778. forEach(SCE_CONTEXTS, function(enumValue, name) {
  15779. var lName = lowercase(name);
  15780. sce[camelCase("parse_as_" + lName)] = function(expr) {
  15781. return parse(enumValue, expr);
  15782. };
  15783. sce[camelCase("get_trusted_" + lName)] = function(value) {
  15784. return getTrusted(enumValue, value);
  15785. };
  15786. sce[camelCase("trust_as_" + lName)] = function(value) {
  15787. return trustAs(enumValue, value);
  15788. };
  15789. });
  15790. return sce;
  15791. }];
  15792. }
  15793. /**
  15794. * !!! This is an undocumented "private" service !!!
  15795. *
  15796. * @name $sniffer
  15797. * @requires $window
  15798. * @requires $document
  15799. *
  15800. * @property {boolean} history Does the browser support html5 history api ?
  15801. * @property {boolean} transitions Does the browser support CSS transition events ?
  15802. * @property {boolean} animations Does the browser support CSS animation events ?
  15803. *
  15804. * @description
  15805. * This is very simple implementation of testing browser's features.
  15806. */
  15807. function $SnifferProvider() {
  15808. this.$get = ['$window', '$document', function($window, $document) {
  15809. var eventSupport = {},
  15810. android =
  15811. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  15812. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  15813. document = $document[0] || {},
  15814. vendorPrefix,
  15815. vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
  15816. bodyStyle = document.body && document.body.style,
  15817. transitions = false,
  15818. animations = false,
  15819. match;
  15820. if (bodyStyle) {
  15821. for (var prop in bodyStyle) {
  15822. if (match = vendorRegex.exec(prop)) {
  15823. vendorPrefix = match[0];
  15824. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  15825. break;
  15826. }
  15827. }
  15828. if (!vendorPrefix) {
  15829. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  15830. }
  15831. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  15832. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  15833. if (android && (!transitions || !animations)) {
  15834. transitions = isString(bodyStyle.webkitTransition);
  15835. animations = isString(bodyStyle.webkitAnimation);
  15836. }
  15837. }
  15838. return {
  15839. // Android has history.pushState, but it does not update location correctly
  15840. // so let's not use the history API at all.
  15841. // http://code.google.com/p/android/issues/detail?id=17471
  15842. // https://github.com/angular/angular.js/issues/904
  15843. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  15844. // so let's not use the history API also
  15845. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  15846. // jshint -W018
  15847. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  15848. // jshint +W018
  15849. hasEvent: function(event) {
  15850. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  15851. // it. In particular the event is not fired when backspace or delete key are pressed or
  15852. // when cut operation is performed.
  15853. // IE10+ implements 'input' event but it erroneously fires under various situations,
  15854. // e.g. when placeholder changes, or a form is focused.
  15855. if (event === 'input' && msie <= 11) return false;
  15856. if (isUndefined(eventSupport[event])) {
  15857. var divElm = document.createElement('div');
  15858. eventSupport[event] = 'on' + event in divElm;
  15859. }
  15860. return eventSupport[event];
  15861. },
  15862. csp: csp(),
  15863. vendorPrefix: vendorPrefix,
  15864. transitions: transitions,
  15865. animations: animations,
  15866. android: android
  15867. };
  15868. }];
  15869. }
  15870. var $compileMinErr = minErr('$compile');
  15871. /**
  15872. * @ngdoc service
  15873. * @name $templateRequest
  15874. *
  15875. * @description
  15876. * The `$templateRequest` service runs security checks then downloads the provided template using
  15877. * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
  15878. * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
  15879. * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
  15880. * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
  15881. * when `tpl` is of type string and `$templateCache` has the matching entry.
  15882. *
  15883. * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
  15884. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  15885. *
  15886. * @return {Promise} a promise for the HTTP response data of the given URL.
  15887. *
  15888. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  15889. */
  15890. function $TemplateRequestProvider() {
  15891. this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
  15892. function handleRequestFn(tpl, ignoreRequestError) {
  15893. handleRequestFn.totalPendingRequests++;
  15894. // We consider the template cache holds only trusted templates, so
  15895. // there's no need to go through whitelisting again for keys that already
  15896. // are included in there. This also makes Angular accept any script
  15897. // directive, no matter its name. However, we still need to unwrap trusted
  15898. // types.
  15899. if (!isString(tpl) || !$templateCache.get(tpl)) {
  15900. tpl = $sce.getTrustedResourceUrl(tpl);
  15901. }
  15902. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  15903. if (isArray(transformResponse)) {
  15904. transformResponse = transformResponse.filter(function(transformer) {
  15905. return transformer !== defaultHttpResponseTransform;
  15906. });
  15907. } else if (transformResponse === defaultHttpResponseTransform) {
  15908. transformResponse = null;
  15909. }
  15910. var httpOptions = {
  15911. cache: $templateCache,
  15912. transformResponse: transformResponse
  15913. };
  15914. return $http.get(tpl, httpOptions)
  15915. ['finally'](function() {
  15916. handleRequestFn.totalPendingRequests--;
  15917. })
  15918. .then(function(response) {
  15919. $templateCache.put(tpl, response.data);
  15920. return response.data;
  15921. }, handleError);
  15922. function handleError(resp) {
  15923. if (!ignoreRequestError) {
  15924. throw $compileMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
  15925. tpl, resp.status, resp.statusText);
  15926. }
  15927. return $q.reject(resp);
  15928. }
  15929. }
  15930. handleRequestFn.totalPendingRequests = 0;
  15931. return handleRequestFn;
  15932. }];
  15933. }
  15934. function $$TestabilityProvider() {
  15935. this.$get = ['$rootScope', '$browser', '$location',
  15936. function($rootScope, $browser, $location) {
  15937. /**
  15938. * @name $testability
  15939. *
  15940. * @description
  15941. * The private $$testability service provides a collection of methods for use when debugging
  15942. * or by automated test and debugging tools.
  15943. */
  15944. var testability = {};
  15945. /**
  15946. * @name $$testability#findBindings
  15947. *
  15948. * @description
  15949. * Returns an array of elements that are bound (via ng-bind or {{}})
  15950. * to expressions matching the input.
  15951. *
  15952. * @param {Element} element The element root to search from.
  15953. * @param {string} expression The binding expression to match.
  15954. * @param {boolean} opt_exactMatch If true, only returns exact matches
  15955. * for the expression. Filters and whitespace are ignored.
  15956. */
  15957. testability.findBindings = function(element, expression, opt_exactMatch) {
  15958. var bindings = element.getElementsByClassName('ng-binding');
  15959. var matches = [];
  15960. forEach(bindings, function(binding) {
  15961. var dataBinding = angular.element(binding).data('$binding');
  15962. if (dataBinding) {
  15963. forEach(dataBinding, function(bindingName) {
  15964. if (opt_exactMatch) {
  15965. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  15966. if (matcher.test(bindingName)) {
  15967. matches.push(binding);
  15968. }
  15969. } else {
  15970. if (bindingName.indexOf(expression) != -1) {
  15971. matches.push(binding);
  15972. }
  15973. }
  15974. });
  15975. }
  15976. });
  15977. return matches;
  15978. };
  15979. /**
  15980. * @name $$testability#findModels
  15981. *
  15982. * @description
  15983. * Returns an array of elements that are two-way found via ng-model to
  15984. * expressions matching the input.
  15985. *
  15986. * @param {Element} element The element root to search from.
  15987. * @param {string} expression The model expression to match.
  15988. * @param {boolean} opt_exactMatch If true, only returns exact matches
  15989. * for the expression.
  15990. */
  15991. testability.findModels = function(element, expression, opt_exactMatch) {
  15992. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  15993. for (var p = 0; p < prefixes.length; ++p) {
  15994. var attributeEquals = opt_exactMatch ? '=' : '*=';
  15995. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  15996. var elements = element.querySelectorAll(selector);
  15997. if (elements.length) {
  15998. return elements;
  15999. }
  16000. }
  16001. };
  16002. /**
  16003. * @name $$testability#getLocation
  16004. *
  16005. * @description
  16006. * Shortcut for getting the location in a browser agnostic way. Returns
  16007. * the path, search, and hash. (e.g. /path?a=b#hash)
  16008. */
  16009. testability.getLocation = function() {
  16010. return $location.url();
  16011. };
  16012. /**
  16013. * @name $$testability#setLocation
  16014. *
  16015. * @description
  16016. * Shortcut for navigating to a location without doing a full page reload.
  16017. *
  16018. * @param {string} url The location url (path, search and hash,
  16019. * e.g. /path?a=b#hash) to go to.
  16020. */
  16021. testability.setLocation = function(url) {
  16022. if (url !== $location.url()) {
  16023. $location.url(url);
  16024. $rootScope.$digest();
  16025. }
  16026. };
  16027. /**
  16028. * @name $$testability#whenStable
  16029. *
  16030. * @description
  16031. * Calls the callback when $timeout and $http requests are completed.
  16032. *
  16033. * @param {function} callback
  16034. */
  16035. testability.whenStable = function(callback) {
  16036. $browser.notifyWhenNoOutstandingRequests(callback);
  16037. };
  16038. return testability;
  16039. }];
  16040. }
  16041. function $TimeoutProvider() {
  16042. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  16043. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  16044. var deferreds = {};
  16045. /**
  16046. * @ngdoc service
  16047. * @name $timeout
  16048. *
  16049. * @description
  16050. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  16051. * block and delegates any exceptions to
  16052. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16053. *
  16054. * The return value of calling `$timeout` is a promise, which will be resolved when
  16055. * the delay has passed and the timeout function, if provided, is executed.
  16056. *
  16057. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  16058. *
  16059. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  16060. * synchronously flush the queue of deferred functions.
  16061. *
  16062. * If you only want a promise that will be resolved after some specified delay
  16063. * then you can call `$timeout` without the `fn` function.
  16064. *
  16065. * @param {function()=} fn A function, whose execution should be delayed.
  16066. * @param {number=} [delay=0] Delay in milliseconds.
  16067. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  16068. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  16069. * @param {...*=} Pass additional parameters to the executed function.
  16070. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
  16071. * promise will be resolved with is the return value of the `fn` function.
  16072. *
  16073. */
  16074. function timeout(fn, delay, invokeApply) {
  16075. if (!isFunction(fn)) {
  16076. invokeApply = delay;
  16077. delay = fn;
  16078. fn = noop;
  16079. }
  16080. var args = sliceArgs(arguments, 3),
  16081. skipApply = (isDefined(invokeApply) && !invokeApply),
  16082. deferred = (skipApply ? $$q : $q).defer(),
  16083. promise = deferred.promise,
  16084. timeoutId;
  16085. timeoutId = $browser.defer(function() {
  16086. try {
  16087. deferred.resolve(fn.apply(null, args));
  16088. } catch (e) {
  16089. deferred.reject(e);
  16090. $exceptionHandler(e);
  16091. }
  16092. finally {
  16093. delete deferreds[promise.$$timeoutId];
  16094. }
  16095. if (!skipApply) $rootScope.$apply();
  16096. }, delay);
  16097. promise.$$timeoutId = timeoutId;
  16098. deferreds[timeoutId] = deferred;
  16099. return promise;
  16100. }
  16101. /**
  16102. * @ngdoc method
  16103. * @name $timeout#cancel
  16104. *
  16105. * @description
  16106. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  16107. * resolved with a rejection.
  16108. *
  16109. * @param {Promise=} promise Promise returned by the `$timeout` function.
  16110. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  16111. * canceled.
  16112. */
  16113. timeout.cancel = function(promise) {
  16114. if (promise && promise.$$timeoutId in deferreds) {
  16115. deferreds[promise.$$timeoutId].reject('canceled');
  16116. delete deferreds[promise.$$timeoutId];
  16117. return $browser.defer.cancel(promise.$$timeoutId);
  16118. }
  16119. return false;
  16120. };
  16121. return timeout;
  16122. }];
  16123. }
  16124. // NOTE: The usage of window and document instead of $window and $document here is
  16125. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  16126. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  16127. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  16128. // doesn't know about mocked locations and resolves URLs to the real document - which is
  16129. // exactly the behavior needed here. There is little value is mocking these out for this
  16130. // service.
  16131. var urlParsingNode = document.createElement("a");
  16132. var originUrl = urlResolve(window.location.href);
  16133. /**
  16134. *
  16135. * Implementation Notes for non-IE browsers
  16136. * ----------------------------------------
  16137. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  16138. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  16139. * URL will be resolved into an absolute URL in the context of the application document.
  16140. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  16141. * properties are all populated to reflect the normalized URL. This approach has wide
  16142. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  16143. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  16144. *
  16145. * Implementation Notes for IE
  16146. * ---------------------------
  16147. * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
  16148. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  16149. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  16150. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  16151. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  16152. * properties such as protocol, hostname, port, etc.
  16153. *
  16154. * References:
  16155. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  16156. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  16157. * http://url.spec.whatwg.org/#urlutils
  16158. * https://github.com/angular/angular.js/pull/2902
  16159. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  16160. *
  16161. * @kind function
  16162. * @param {string} url The URL to be parsed.
  16163. * @description Normalizes and parses a URL.
  16164. * @returns {object} Returns the normalized URL as a dictionary.
  16165. *
  16166. * | member name | Description |
  16167. * |---------------|----------------|
  16168. * | href | A normalized version of the provided URL if it was not an absolute URL |
  16169. * | protocol | The protocol including the trailing colon |
  16170. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  16171. * | search | The search params, minus the question mark |
  16172. * | hash | The hash string, minus the hash symbol
  16173. * | hostname | The hostname
  16174. * | port | The port, without ":"
  16175. * | pathname | The pathname, beginning with "/"
  16176. *
  16177. */
  16178. function urlResolve(url) {
  16179. var href = url;
  16180. if (msie) {
  16181. // Normalize before parse. Refer Implementation Notes on why this is
  16182. // done in two steps on IE.
  16183. urlParsingNode.setAttribute("href", href);
  16184. href = urlParsingNode.href;
  16185. }
  16186. urlParsingNode.setAttribute('href', href);
  16187. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  16188. return {
  16189. href: urlParsingNode.href,
  16190. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  16191. host: urlParsingNode.host,
  16192. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  16193. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  16194. hostname: urlParsingNode.hostname,
  16195. port: urlParsingNode.port,
  16196. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  16197. ? urlParsingNode.pathname
  16198. : '/' + urlParsingNode.pathname
  16199. };
  16200. }
  16201. /**
  16202. * Parse a request URL and determine whether this is a same-origin request as the application document.
  16203. *
  16204. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  16205. * or a parsed URL object.
  16206. * @returns {boolean} Whether the request is for the same origin as the application document.
  16207. */
  16208. function urlIsSameOrigin(requestUrl) {
  16209. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  16210. return (parsed.protocol === originUrl.protocol &&
  16211. parsed.host === originUrl.host);
  16212. }
  16213. /**
  16214. * @ngdoc service
  16215. * @name $window
  16216. *
  16217. * @description
  16218. * A reference to the browser's `window` object. While `window`
  16219. * is globally available in JavaScript, it causes testability problems, because
  16220. * it is a global variable. In angular we always refer to it through the
  16221. * `$window` service, so it may be overridden, removed or mocked for testing.
  16222. *
  16223. * Expressions, like the one defined for the `ngClick` directive in the example
  16224. * below, are evaluated with respect to the current scope. Therefore, there is
  16225. * no risk of inadvertently coding in a dependency on a global value in such an
  16226. * expression.
  16227. *
  16228. * @example
  16229. <example module="windowExample">
  16230. <file name="index.html">
  16231. <script>
  16232. angular.module('windowExample', [])
  16233. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  16234. $scope.greeting = 'Hello, World!';
  16235. $scope.doGreeting = function(greeting) {
  16236. $window.alert(greeting);
  16237. };
  16238. }]);
  16239. </script>
  16240. <div ng-controller="ExampleController">
  16241. <input type="text" ng-model="greeting" aria-label="greeting" />
  16242. <button ng-click="doGreeting(greeting)">ALERT</button>
  16243. </div>
  16244. </file>
  16245. <file name="protractor.js" type="protractor">
  16246. it('should display the greeting in the input box', function() {
  16247. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  16248. // If we click the button it will block the test runner
  16249. // element(':button').click();
  16250. });
  16251. </file>
  16252. </example>
  16253. */
  16254. function $WindowProvider() {
  16255. this.$get = valueFn(window);
  16256. }
  16257. /**
  16258. * @name $$cookieReader
  16259. * @requires $document
  16260. *
  16261. * @description
  16262. * This is a private service for reading cookies used by $http and ngCookies
  16263. *
  16264. * @return {Object} a key/value map of the current cookies
  16265. */
  16266. function $$CookieReader($document) {
  16267. var rawDocument = $document[0] || {};
  16268. var lastCookies = {};
  16269. var lastCookieString = '';
  16270. function safeDecodeURIComponent(str) {
  16271. try {
  16272. return decodeURIComponent(str);
  16273. } catch (e) {
  16274. return str;
  16275. }
  16276. }
  16277. return function() {
  16278. var cookieArray, cookie, i, index, name;
  16279. var currentCookieString = rawDocument.cookie || '';
  16280. if (currentCookieString !== lastCookieString) {
  16281. lastCookieString = currentCookieString;
  16282. cookieArray = lastCookieString.split('; ');
  16283. lastCookies = {};
  16284. for (i = 0; i < cookieArray.length; i++) {
  16285. cookie = cookieArray[i];
  16286. index = cookie.indexOf('=');
  16287. if (index > 0) { //ignore nameless cookies
  16288. name = safeDecodeURIComponent(cookie.substring(0, index));
  16289. // the first value that is seen for a cookie is the most
  16290. // specific one. values for the same cookie name that
  16291. // follow are for less specific paths.
  16292. if (lastCookies[name] === undefined) {
  16293. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  16294. }
  16295. }
  16296. }
  16297. }
  16298. return lastCookies;
  16299. };
  16300. }
  16301. $$CookieReader.$inject = ['$document'];
  16302. function $$CookieReaderProvider() {
  16303. this.$get = $$CookieReader;
  16304. }
  16305. /* global currencyFilter: true,
  16306. dateFilter: true,
  16307. filterFilter: true,
  16308. jsonFilter: true,
  16309. limitToFilter: true,
  16310. lowercaseFilter: true,
  16311. numberFilter: true,
  16312. orderByFilter: true,
  16313. uppercaseFilter: true,
  16314. */
  16315. /**
  16316. * @ngdoc provider
  16317. * @name $filterProvider
  16318. * @description
  16319. *
  16320. * Filters are just functions which transform input to an output. However filters need to be
  16321. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  16322. * annotated with dependencies and is responsible for creating a filter function.
  16323. *
  16324. * <div class="alert alert-warning">
  16325. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  16326. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  16327. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  16328. * (`myapp_subsection_filterx`).
  16329. * </div>
  16330. *
  16331. * ```js
  16332. * // Filter registration
  16333. * function MyModule($provide, $filterProvider) {
  16334. * // create a service to demonstrate injection (not always needed)
  16335. * $provide.value('greet', function(name){
  16336. * return 'Hello ' + name + '!';
  16337. * });
  16338. *
  16339. * // register a filter factory which uses the
  16340. * // greet service to demonstrate DI.
  16341. * $filterProvider.register('greet', function(greet){
  16342. * // return the filter function which uses the greet service
  16343. * // to generate salutation
  16344. * return function(text) {
  16345. * // filters need to be forgiving so check input validity
  16346. * return text && greet(text) || text;
  16347. * };
  16348. * });
  16349. * }
  16350. * ```
  16351. *
  16352. * The filter function is registered with the `$injector` under the filter name suffix with
  16353. * `Filter`.
  16354. *
  16355. * ```js
  16356. * it('should be the same instance', inject(
  16357. * function($filterProvider) {
  16358. * $filterProvider.register('reverse', function(){
  16359. * return ...;
  16360. * });
  16361. * },
  16362. * function($filter, reverseFilter) {
  16363. * expect($filter('reverse')).toBe(reverseFilter);
  16364. * });
  16365. * ```
  16366. *
  16367. *
  16368. * For more information about how angular filters work, and how to create your own filters, see
  16369. * {@link guide/filter Filters} in the Angular Developer Guide.
  16370. */
  16371. /**
  16372. * @ngdoc service
  16373. * @name $filter
  16374. * @kind function
  16375. * @description
  16376. * Filters are used for formatting data displayed to the user.
  16377. *
  16378. * The general syntax in templates is as follows:
  16379. *
  16380. * {{ expression [| filter_name[:parameter_value] ... ] }}
  16381. *
  16382. * @param {String} name Name of the filter function to retrieve
  16383. * @return {Function} the filter function
  16384. * @example
  16385. <example name="$filter" module="filterExample">
  16386. <file name="index.html">
  16387. <div ng-controller="MainCtrl">
  16388. <h3>{{ originalText }}</h3>
  16389. <h3>{{ filteredText }}</h3>
  16390. </div>
  16391. </file>
  16392. <file name="script.js">
  16393. angular.module('filterExample', [])
  16394. .controller('MainCtrl', function($scope, $filter) {
  16395. $scope.originalText = 'hello';
  16396. $scope.filteredText = $filter('uppercase')($scope.originalText);
  16397. });
  16398. </file>
  16399. </example>
  16400. */
  16401. $FilterProvider.$inject = ['$provide'];
  16402. function $FilterProvider($provide) {
  16403. var suffix = 'Filter';
  16404. /**
  16405. * @ngdoc method
  16406. * @name $filterProvider#register
  16407. * @param {string|Object} name Name of the filter function, or an object map of filters where
  16408. * the keys are the filter names and the values are the filter factories.
  16409. *
  16410. * <div class="alert alert-warning">
  16411. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  16412. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  16413. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  16414. * (`myapp_subsection_filterx`).
  16415. * </div>
  16416. * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
  16417. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  16418. * of the registered filter instances.
  16419. */
  16420. function register(name, factory) {
  16421. if (isObject(name)) {
  16422. var filters = {};
  16423. forEach(name, function(filter, key) {
  16424. filters[key] = register(key, filter);
  16425. });
  16426. return filters;
  16427. } else {
  16428. return $provide.factory(name + suffix, factory);
  16429. }
  16430. }
  16431. this.register = register;
  16432. this.$get = ['$injector', function($injector) {
  16433. return function(name) {
  16434. return $injector.get(name + suffix);
  16435. };
  16436. }];
  16437. ////////////////////////////////////////
  16438. /* global
  16439. currencyFilter: false,
  16440. dateFilter: false,
  16441. filterFilter: false,
  16442. jsonFilter: false,
  16443. limitToFilter: false,
  16444. lowercaseFilter: false,
  16445. numberFilter: false,
  16446. orderByFilter: false,
  16447. uppercaseFilter: false,
  16448. */
  16449. register('currency', currencyFilter);
  16450. register('date', dateFilter);
  16451. register('filter', filterFilter);
  16452. register('json', jsonFilter);
  16453. register('limitTo', limitToFilter);
  16454. register('lowercase', lowercaseFilter);
  16455. register('number', numberFilter);
  16456. register('orderBy', orderByFilter);
  16457. register('uppercase', uppercaseFilter);
  16458. }
  16459. /**
  16460. * @ngdoc filter
  16461. * @name filter
  16462. * @kind function
  16463. *
  16464. * @description
  16465. * Selects a subset of items from `array` and returns it as a new array.
  16466. *
  16467. * @param {Array} array The source array.
  16468. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  16469. * `array`.
  16470. *
  16471. * Can be one of:
  16472. *
  16473. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  16474. * objects with string properties in `array` that match this string will be returned. This also
  16475. * applies to nested object properties.
  16476. * The predicate can be negated by prefixing the string with `!`.
  16477. *
  16478. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  16479. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  16480. * which have property `name` containing "M" and property `phone` containing "1". A special
  16481. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  16482. * property of the object or its nested object properties. That's equivalent to the simple
  16483. * substring match with a `string` as described above. The predicate can be negated by prefixing
  16484. * the string with `!`.
  16485. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  16486. * not containing "M".
  16487. *
  16488. * Note that a named property will match properties on the same level only, while the special
  16489. * `$` property will match properties on the same level or deeper. E.g. an array item like
  16490. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  16491. * **will** be matched by `{$: 'John'}`.
  16492. *
  16493. * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
  16494. * The function is called for each element of the array, with the element, its index, and
  16495. * the entire array itself as arguments.
  16496. *
  16497. * The final result is an array of those elements that the predicate returned true for.
  16498. *
  16499. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  16500. * determining if the expected value (from the filter expression) and actual value (from
  16501. * the object in the array) should be considered a match.
  16502. *
  16503. * Can be one of:
  16504. *
  16505. * - `function(actual, expected)`:
  16506. * The function will be given the object value and the predicate value to compare and
  16507. * should return true if both values should be considered equal.
  16508. *
  16509. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  16510. * This is essentially strict comparison of expected and actual.
  16511. *
  16512. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  16513. * insensitive way.
  16514. *
  16515. * Primitive values are converted to strings. Objects are not compared against primitives,
  16516. * unless they have a custom `toString` method (e.g. `Date` objects).
  16517. *
  16518. * @example
  16519. <example>
  16520. <file name="index.html">
  16521. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  16522. {name:'Mary', phone:'800-BIG-MARY'},
  16523. {name:'Mike', phone:'555-4321'},
  16524. {name:'Adam', phone:'555-5678'},
  16525. {name:'Julie', phone:'555-8765'},
  16526. {name:'Juliette', phone:'555-5678'}]"></div>
  16527. <label>Search: <input ng-model="searchText"></label>
  16528. <table id="searchTextResults">
  16529. <tr><th>Name</th><th>Phone</th></tr>
  16530. <tr ng-repeat="friend in friends | filter:searchText">
  16531. <td>{{friend.name}}</td>
  16532. <td>{{friend.phone}}</td>
  16533. </tr>
  16534. </table>
  16535. <hr>
  16536. <label>Any: <input ng-model="search.$"></label> <br>
  16537. <label>Name only <input ng-model="search.name"></label><br>
  16538. <label>Phone only <input ng-model="search.phone"></label><br>
  16539. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  16540. <table id="searchObjResults">
  16541. <tr><th>Name</th><th>Phone</th></tr>
  16542. <tr ng-repeat="friendObj in friends | filter:search:strict">
  16543. <td>{{friendObj.name}}</td>
  16544. <td>{{friendObj.phone}}</td>
  16545. </tr>
  16546. </table>
  16547. </file>
  16548. <file name="protractor.js" type="protractor">
  16549. var expectFriendNames = function(expectedNames, key) {
  16550. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  16551. arr.forEach(function(wd, i) {
  16552. expect(wd.getText()).toMatch(expectedNames[i]);
  16553. });
  16554. });
  16555. };
  16556. it('should search across all fields when filtering with a string', function() {
  16557. var searchText = element(by.model('searchText'));
  16558. searchText.clear();
  16559. searchText.sendKeys('m');
  16560. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  16561. searchText.clear();
  16562. searchText.sendKeys('76');
  16563. expectFriendNames(['John', 'Julie'], 'friend');
  16564. });
  16565. it('should search in specific fields when filtering with a predicate object', function() {
  16566. var searchAny = element(by.model('search.$'));
  16567. searchAny.clear();
  16568. searchAny.sendKeys('i');
  16569. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  16570. });
  16571. it('should use a equal comparison when comparator is true', function() {
  16572. var searchName = element(by.model('search.name'));
  16573. var strict = element(by.model('strict'));
  16574. searchName.clear();
  16575. searchName.sendKeys('Julie');
  16576. strict.click();
  16577. expectFriendNames(['Julie'], 'friendObj');
  16578. });
  16579. </file>
  16580. </example>
  16581. */
  16582. function filterFilter() {
  16583. return function(array, expression, comparator) {
  16584. if (!isArrayLike(array)) {
  16585. if (array == null) {
  16586. return array;
  16587. } else {
  16588. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  16589. }
  16590. }
  16591. var expressionType = getTypeForFilter(expression);
  16592. var predicateFn;
  16593. var matchAgainstAnyProp;
  16594. switch (expressionType) {
  16595. case 'function':
  16596. predicateFn = expression;
  16597. break;
  16598. case 'boolean':
  16599. case 'null':
  16600. case 'number':
  16601. case 'string':
  16602. matchAgainstAnyProp = true;
  16603. //jshint -W086
  16604. case 'object':
  16605. //jshint +W086
  16606. predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
  16607. break;
  16608. default:
  16609. return array;
  16610. }
  16611. return Array.prototype.filter.call(array, predicateFn);
  16612. };
  16613. }
  16614. // Helper functions for `filterFilter`
  16615. function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
  16616. var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
  16617. var predicateFn;
  16618. if (comparator === true) {
  16619. comparator = equals;
  16620. } else if (!isFunction(comparator)) {
  16621. comparator = function(actual, expected) {
  16622. if (isUndefined(actual)) {
  16623. // No substring matching against `undefined`
  16624. return false;
  16625. }
  16626. if ((actual === null) || (expected === null)) {
  16627. // No substring matching against `null`; only match against `null`
  16628. return actual === expected;
  16629. }
  16630. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  16631. // Should not compare primitives against objects, unless they have custom `toString` method
  16632. return false;
  16633. }
  16634. actual = lowercase('' + actual);
  16635. expected = lowercase('' + expected);
  16636. return actual.indexOf(expected) !== -1;
  16637. };
  16638. }
  16639. predicateFn = function(item) {
  16640. if (shouldMatchPrimitives && !isObject(item)) {
  16641. return deepCompare(item, expression.$, comparator, false);
  16642. }
  16643. return deepCompare(item, expression, comparator, matchAgainstAnyProp);
  16644. };
  16645. return predicateFn;
  16646. }
  16647. function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
  16648. var actualType = getTypeForFilter(actual);
  16649. var expectedType = getTypeForFilter(expected);
  16650. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  16651. return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
  16652. } else if (isArray(actual)) {
  16653. // In case `actual` is an array, consider it a match
  16654. // if ANY of it's items matches `expected`
  16655. return actual.some(function(item) {
  16656. return deepCompare(item, expected, comparator, matchAgainstAnyProp);
  16657. });
  16658. }
  16659. switch (actualType) {
  16660. case 'object':
  16661. var key;
  16662. if (matchAgainstAnyProp) {
  16663. for (key in actual) {
  16664. if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
  16665. return true;
  16666. }
  16667. }
  16668. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
  16669. } else if (expectedType === 'object') {
  16670. for (key in expected) {
  16671. var expectedVal = expected[key];
  16672. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  16673. continue;
  16674. }
  16675. var matchAnyProperty = key === '$';
  16676. var actualVal = matchAnyProperty ? actual : actual[key];
  16677. if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
  16678. return false;
  16679. }
  16680. }
  16681. return true;
  16682. } else {
  16683. return comparator(actual, expected);
  16684. }
  16685. break;
  16686. case 'function':
  16687. return false;
  16688. default:
  16689. return comparator(actual, expected);
  16690. }
  16691. }
  16692. // Used for easily differentiating between `null` and actual `object`
  16693. function getTypeForFilter(val) {
  16694. return (val === null) ? 'null' : typeof val;
  16695. }
  16696. /**
  16697. * @ngdoc filter
  16698. * @name currency
  16699. * @kind function
  16700. *
  16701. * @description
  16702. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  16703. * symbol for current locale is used.
  16704. *
  16705. * @param {number} amount Input to filter.
  16706. * @param {string=} symbol Currency symbol or identifier to be displayed.
  16707. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  16708. * @returns {string} Formatted number.
  16709. *
  16710. *
  16711. * @example
  16712. <example module="currencyExample">
  16713. <file name="index.html">
  16714. <script>
  16715. angular.module('currencyExample', [])
  16716. .controller('ExampleController', ['$scope', function($scope) {
  16717. $scope.amount = 1234.56;
  16718. }]);
  16719. </script>
  16720. <div ng-controller="ExampleController">
  16721. <input type="number" ng-model="amount" aria-label="amount"> <br>
  16722. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  16723. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
  16724. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  16725. </div>
  16726. </file>
  16727. <file name="protractor.js" type="protractor">
  16728. it('should init with 1234.56', function() {
  16729. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  16730. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  16731. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  16732. });
  16733. it('should update', function() {
  16734. if (browser.params.browser == 'safari') {
  16735. // Safari does not understand the minus key. See
  16736. // https://github.com/angular/protractor/issues/481
  16737. return;
  16738. }
  16739. element(by.model('amount')).clear();
  16740. element(by.model('amount')).sendKeys('-1234');
  16741. expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
  16742. expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
  16743. expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
  16744. });
  16745. </file>
  16746. </example>
  16747. */
  16748. currencyFilter.$inject = ['$locale'];
  16749. function currencyFilter($locale) {
  16750. var formats = $locale.NUMBER_FORMATS;
  16751. return function(amount, currencySymbol, fractionSize) {
  16752. if (isUndefined(currencySymbol)) {
  16753. currencySymbol = formats.CURRENCY_SYM;
  16754. }
  16755. if (isUndefined(fractionSize)) {
  16756. fractionSize = formats.PATTERNS[1].maxFrac;
  16757. }
  16758. // if null or undefined pass it through
  16759. return (amount == null)
  16760. ? amount
  16761. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  16762. replace(/\u00A4/g, currencySymbol);
  16763. };
  16764. }
  16765. /**
  16766. * @ngdoc filter
  16767. * @name number
  16768. * @kind function
  16769. *
  16770. * @description
  16771. * Formats a number as text.
  16772. *
  16773. * If the input is null or undefined, it will just be returned.
  16774. * If the input is infinite (Infinity/-Infinity) the Infinity symbol '∞' is returned.
  16775. * If the input is not a number an empty string is returned.
  16776. *
  16777. *
  16778. * @param {number|string} number Number to format.
  16779. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  16780. * If this is not provided then the fraction size is computed from the current locale's number
  16781. * formatting pattern. In the case of the default locale, it will be 3.
  16782. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
  16783. *
  16784. * @example
  16785. <example module="numberFilterExample">
  16786. <file name="index.html">
  16787. <script>
  16788. angular.module('numberFilterExample', [])
  16789. .controller('ExampleController', ['$scope', function($scope) {
  16790. $scope.val = 1234.56789;
  16791. }]);
  16792. </script>
  16793. <div ng-controller="ExampleController">
  16794. <label>Enter number: <input ng-model='val'></label><br>
  16795. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  16796. No fractions: <span>{{val | number:0}}</span><br>
  16797. Negative number: <span>{{-val | number:4}}</span>
  16798. </div>
  16799. </file>
  16800. <file name="protractor.js" type="protractor">
  16801. it('should format numbers', function() {
  16802. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  16803. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  16804. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  16805. });
  16806. it('should update', function() {
  16807. element(by.model('val')).clear();
  16808. element(by.model('val')).sendKeys('3374.333');
  16809. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  16810. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  16811. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  16812. });
  16813. </file>
  16814. </example>
  16815. */
  16816. numberFilter.$inject = ['$locale'];
  16817. function numberFilter($locale) {
  16818. var formats = $locale.NUMBER_FORMATS;
  16819. return function(number, fractionSize) {
  16820. // if null or undefined pass it through
  16821. return (number == null)
  16822. ? number
  16823. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  16824. fractionSize);
  16825. };
  16826. }
  16827. var DECIMAL_SEP = '.';
  16828. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  16829. if (isObject(number)) return '';
  16830. var isNegative = number < 0;
  16831. number = Math.abs(number);
  16832. var isInfinity = number === Infinity;
  16833. if (!isInfinity && !isFinite(number)) return '';
  16834. var numStr = number + '',
  16835. formatedText = '',
  16836. hasExponent = false,
  16837. parts = [];
  16838. if (isInfinity) formatedText = '\u221e';
  16839. if (!isInfinity && numStr.indexOf('e') !== -1) {
  16840. var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
  16841. if (match && match[2] == '-' && match[3] > fractionSize + 1) {
  16842. number = 0;
  16843. } else {
  16844. formatedText = numStr;
  16845. hasExponent = true;
  16846. }
  16847. }
  16848. if (!isInfinity && !hasExponent) {
  16849. var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
  16850. // determine fractionSize if it is not specified
  16851. if (isUndefined(fractionSize)) {
  16852. fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
  16853. }
  16854. // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
  16855. // inspired by:
  16856. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
  16857. number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
  16858. var fraction = ('' + number).split(DECIMAL_SEP);
  16859. var whole = fraction[0];
  16860. fraction = fraction[1] || '';
  16861. var i, pos = 0,
  16862. lgroup = pattern.lgSize,
  16863. group = pattern.gSize;
  16864. if (whole.length >= (lgroup + group)) {
  16865. pos = whole.length - lgroup;
  16866. for (i = 0; i < pos; i++) {
  16867. if ((pos - i) % group === 0 && i !== 0) {
  16868. formatedText += groupSep;
  16869. }
  16870. formatedText += whole.charAt(i);
  16871. }
  16872. }
  16873. for (i = pos; i < whole.length; i++) {
  16874. if ((whole.length - i) % lgroup === 0 && i !== 0) {
  16875. formatedText += groupSep;
  16876. }
  16877. formatedText += whole.charAt(i);
  16878. }
  16879. // format fraction part.
  16880. while (fraction.length < fractionSize) {
  16881. fraction += '0';
  16882. }
  16883. if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
  16884. } else {
  16885. if (fractionSize > 0 && number < 1) {
  16886. formatedText = number.toFixed(fractionSize);
  16887. number = parseFloat(formatedText);
  16888. }
  16889. }
  16890. if (number === 0) {
  16891. isNegative = false;
  16892. }
  16893. parts.push(isNegative ? pattern.negPre : pattern.posPre,
  16894. formatedText,
  16895. isNegative ? pattern.negSuf : pattern.posSuf);
  16896. return parts.join('');
  16897. }
  16898. function padNumber(num, digits, trim) {
  16899. var neg = '';
  16900. if (num < 0) {
  16901. neg = '-';
  16902. num = -num;
  16903. }
  16904. num = '' + num;
  16905. while (num.length < digits) num = '0' + num;
  16906. if (trim) {
  16907. num = num.substr(num.length - digits);
  16908. }
  16909. return neg + num;
  16910. }
  16911. function dateGetter(name, size, offset, trim) {
  16912. offset = offset || 0;
  16913. return function(date) {
  16914. var value = date['get' + name]();
  16915. if (offset > 0 || value > -offset) {
  16916. value += offset;
  16917. }
  16918. if (value === 0 && offset == -12) value = 12;
  16919. return padNumber(value, size, trim);
  16920. };
  16921. }
  16922. function dateStrGetter(name, shortForm) {
  16923. return function(date, formats) {
  16924. var value = date['get' + name]();
  16925. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  16926. return formats[get][value];
  16927. };
  16928. }
  16929. function timeZoneGetter(date, formats, offset) {
  16930. var zone = -1 * offset;
  16931. var paddedZone = (zone >= 0) ? "+" : "";
  16932. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  16933. padNumber(Math.abs(zone % 60), 2);
  16934. return paddedZone;
  16935. }
  16936. function getFirstThursdayOfYear(year) {
  16937. // 0 = index of January
  16938. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  16939. // 4 = index of Thursday (+1 to account for 1st = 5)
  16940. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  16941. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  16942. }
  16943. function getThursdayThisWeek(datetime) {
  16944. return new Date(datetime.getFullYear(), datetime.getMonth(),
  16945. // 4 = index of Thursday
  16946. datetime.getDate() + (4 - datetime.getDay()));
  16947. }
  16948. function weekGetter(size) {
  16949. return function(date) {
  16950. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  16951. thisThurs = getThursdayThisWeek(date);
  16952. var diff = +thisThurs - +firstThurs,
  16953. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  16954. return padNumber(result, size);
  16955. };
  16956. }
  16957. function ampmGetter(date, formats) {
  16958. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  16959. }
  16960. function eraGetter(date, formats) {
  16961. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  16962. }
  16963. function longEraGetter(date, formats) {
  16964. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  16965. }
  16966. var DATE_FORMATS = {
  16967. yyyy: dateGetter('FullYear', 4),
  16968. yy: dateGetter('FullYear', 2, 0, true),
  16969. y: dateGetter('FullYear', 1),
  16970. MMMM: dateStrGetter('Month'),
  16971. MMM: dateStrGetter('Month', true),
  16972. MM: dateGetter('Month', 2, 1),
  16973. M: dateGetter('Month', 1, 1),
  16974. dd: dateGetter('Date', 2),
  16975. d: dateGetter('Date', 1),
  16976. HH: dateGetter('Hours', 2),
  16977. H: dateGetter('Hours', 1),
  16978. hh: dateGetter('Hours', 2, -12),
  16979. h: dateGetter('Hours', 1, -12),
  16980. mm: dateGetter('Minutes', 2),
  16981. m: dateGetter('Minutes', 1),
  16982. ss: dateGetter('Seconds', 2),
  16983. s: dateGetter('Seconds', 1),
  16984. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  16985. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  16986. sss: dateGetter('Milliseconds', 3),
  16987. EEEE: dateStrGetter('Day'),
  16988. EEE: dateStrGetter('Day', true),
  16989. a: ampmGetter,
  16990. Z: timeZoneGetter,
  16991. ww: weekGetter(2),
  16992. w: weekGetter(1),
  16993. G: eraGetter,
  16994. GG: eraGetter,
  16995. GGG: eraGetter,
  16996. GGGG: longEraGetter
  16997. };
  16998. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
  16999. NUMBER_STRING = /^\-?\d+$/;
  17000. /**
  17001. * @ngdoc filter
  17002. * @name date
  17003. * @kind function
  17004. *
  17005. * @description
  17006. * Formats `date` to a string based on the requested `format`.
  17007. *
  17008. * `format` string can be composed of the following elements:
  17009. *
  17010. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  17011. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  17012. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  17013. * * `'MMMM'`: Month in year (January-December)
  17014. * * `'MMM'`: Month in year (Jan-Dec)
  17015. * * `'MM'`: Month in year, padded (01-12)
  17016. * * `'M'`: Month in year (1-12)
  17017. * * `'dd'`: Day in month, padded (01-31)
  17018. * * `'d'`: Day in month (1-31)
  17019. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  17020. * * `'EEE'`: Day in Week, (Sun-Sat)
  17021. * * `'HH'`: Hour in day, padded (00-23)
  17022. * * `'H'`: Hour in day (0-23)
  17023. * * `'hh'`: Hour in AM/PM, padded (01-12)
  17024. * * `'h'`: Hour in AM/PM, (1-12)
  17025. * * `'mm'`: Minute in hour, padded (00-59)
  17026. * * `'m'`: Minute in hour (0-59)
  17027. * * `'ss'`: Second in minute, padded (00-59)
  17028. * * `'s'`: Second in minute (0-59)
  17029. * * `'sss'`: Millisecond in second, padded (000-999)
  17030. * * `'a'`: AM/PM marker
  17031. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  17032. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  17033. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  17034. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  17035. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  17036. *
  17037. * `format` string can also be one of the following predefined
  17038. * {@link guide/i18n localizable formats}:
  17039. *
  17040. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  17041. * (e.g. Sep 3, 2010 12:05:08 PM)
  17042. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  17043. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  17044. * (e.g. Friday, September 3, 2010)
  17045. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  17046. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  17047. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  17048. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  17049. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  17050. *
  17051. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  17052. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  17053. * (e.g. `"h 'o''clock'"`).
  17054. *
  17055. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  17056. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  17057. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  17058. * specified in the string input, the time is considered to be in the local timezone.
  17059. * @param {string=} format Formatting rules (see Description). If not specified,
  17060. * `mediumDate` is used.
  17061. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  17062. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  17063. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  17064. * If not specified, the timezone of the browser will be used.
  17065. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  17066. *
  17067. * @example
  17068. <example>
  17069. <file name="index.html">
  17070. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  17071. <span>{{1288323623006 | date:'medium'}}</span><br>
  17072. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  17073. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  17074. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  17075. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  17076. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  17077. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  17078. </file>
  17079. <file name="protractor.js" type="protractor">
  17080. it('should format date', function() {
  17081. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  17082. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  17083. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  17084. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  17085. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  17086. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  17087. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  17088. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  17089. });
  17090. </file>
  17091. </example>
  17092. */
  17093. dateFilter.$inject = ['$locale'];
  17094. function dateFilter($locale) {
  17095. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  17096. // 1 2 3 4 5 6 7 8 9 10 11
  17097. function jsonStringToDate(string) {
  17098. var match;
  17099. if (match = string.match(R_ISO8601_STR)) {
  17100. var date = new Date(0),
  17101. tzHour = 0,
  17102. tzMin = 0,
  17103. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  17104. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  17105. if (match[9]) {
  17106. tzHour = toInt(match[9] + match[10]);
  17107. tzMin = toInt(match[9] + match[11]);
  17108. }
  17109. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  17110. var h = toInt(match[4] || 0) - tzHour;
  17111. var m = toInt(match[5] || 0) - tzMin;
  17112. var s = toInt(match[6] || 0);
  17113. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  17114. timeSetter.call(date, h, m, s, ms);
  17115. return date;
  17116. }
  17117. return string;
  17118. }
  17119. return function(date, format, timezone) {
  17120. var text = '',
  17121. parts = [],
  17122. fn, match;
  17123. format = format || 'mediumDate';
  17124. format = $locale.DATETIME_FORMATS[format] || format;
  17125. if (isString(date)) {
  17126. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  17127. }
  17128. if (isNumber(date)) {
  17129. date = new Date(date);
  17130. }
  17131. if (!isDate(date) || !isFinite(date.getTime())) {
  17132. return date;
  17133. }
  17134. while (format) {
  17135. match = DATE_FORMATS_SPLIT.exec(format);
  17136. if (match) {
  17137. parts = concat(parts, match, 1);
  17138. format = parts.pop();
  17139. } else {
  17140. parts.push(format);
  17141. format = null;
  17142. }
  17143. }
  17144. var dateTimezoneOffset = date.getTimezoneOffset();
  17145. if (timezone) {
  17146. dateTimezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
  17147. date = convertTimezoneToLocal(date, timezone, true);
  17148. }
  17149. forEach(parts, function(value) {
  17150. fn = DATE_FORMATS[value];
  17151. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  17152. : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  17153. });
  17154. return text;
  17155. };
  17156. }
  17157. /**
  17158. * @ngdoc filter
  17159. * @name json
  17160. * @kind function
  17161. *
  17162. * @description
  17163. * Allows you to convert a JavaScript object into JSON string.
  17164. *
  17165. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  17166. * the binding is automatically converted to JSON.
  17167. *
  17168. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  17169. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  17170. * @returns {string} JSON string.
  17171. *
  17172. *
  17173. * @example
  17174. <example>
  17175. <file name="index.html">
  17176. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  17177. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  17178. </file>
  17179. <file name="protractor.js" type="protractor">
  17180. it('should jsonify filtered objects', function() {
  17181. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  17182. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  17183. });
  17184. </file>
  17185. </example>
  17186. *
  17187. */
  17188. function jsonFilter() {
  17189. return function(object, spacing) {
  17190. if (isUndefined(spacing)) {
  17191. spacing = 2;
  17192. }
  17193. return toJson(object, spacing);
  17194. };
  17195. }
  17196. /**
  17197. * @ngdoc filter
  17198. * @name lowercase
  17199. * @kind function
  17200. * @description
  17201. * Converts string to lowercase.
  17202. * @see angular.lowercase
  17203. */
  17204. var lowercaseFilter = valueFn(lowercase);
  17205. /**
  17206. * @ngdoc filter
  17207. * @name uppercase
  17208. * @kind function
  17209. * @description
  17210. * Converts string to uppercase.
  17211. * @see angular.uppercase
  17212. */
  17213. var uppercaseFilter = valueFn(uppercase);
  17214. /**
  17215. * @ngdoc filter
  17216. * @name limitTo
  17217. * @kind function
  17218. *
  17219. * @description
  17220. * Creates a new array or string containing only a specified number of elements. The elements
  17221. * are taken from either the beginning or the end of the source array, string or number, as specified by
  17222. * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
  17223. * converted to a string.
  17224. *
  17225. * @param {Array|string|number} input Source array, string or number to be limited.
  17226. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  17227. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  17228. * If the number is negative, `limit` number of items from the end of the source array/string
  17229. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  17230. * the input will be returned unchanged.
  17231. * @param {(string|number)=} begin Index at which to begin limitation. As a negative index, `begin`
  17232. * indicates an offset from the end of `input`. Defaults to `0`.
  17233. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  17234. * had less than `limit` elements.
  17235. *
  17236. * @example
  17237. <example module="limitToExample">
  17238. <file name="index.html">
  17239. <script>
  17240. angular.module('limitToExample', [])
  17241. .controller('ExampleController', ['$scope', function($scope) {
  17242. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  17243. $scope.letters = "abcdefghi";
  17244. $scope.longNumber = 2345432342;
  17245. $scope.numLimit = 3;
  17246. $scope.letterLimit = 3;
  17247. $scope.longNumberLimit = 3;
  17248. }]);
  17249. </script>
  17250. <div ng-controller="ExampleController">
  17251. <label>
  17252. Limit {{numbers}} to:
  17253. <input type="number" step="1" ng-model="numLimit">
  17254. </label>
  17255. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  17256. <label>
  17257. Limit {{letters}} to:
  17258. <input type="number" step="1" ng-model="letterLimit">
  17259. </label>
  17260. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  17261. <label>
  17262. Limit {{longNumber}} to:
  17263. <input type="number" step="1" ng-model="longNumberLimit">
  17264. </label>
  17265. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  17266. </div>
  17267. </file>
  17268. <file name="protractor.js" type="protractor">
  17269. var numLimitInput = element(by.model('numLimit'));
  17270. var letterLimitInput = element(by.model('letterLimit'));
  17271. var longNumberLimitInput = element(by.model('longNumberLimit'));
  17272. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  17273. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  17274. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  17275. it('should limit the number array to first three items', function() {
  17276. expect(numLimitInput.getAttribute('value')).toBe('3');
  17277. expect(letterLimitInput.getAttribute('value')).toBe('3');
  17278. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  17279. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  17280. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  17281. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  17282. });
  17283. // There is a bug in safari and protractor that doesn't like the minus key
  17284. // it('should update the output when -3 is entered', function() {
  17285. // numLimitInput.clear();
  17286. // numLimitInput.sendKeys('-3');
  17287. // letterLimitInput.clear();
  17288. // letterLimitInput.sendKeys('-3');
  17289. // longNumberLimitInput.clear();
  17290. // longNumberLimitInput.sendKeys('-3');
  17291. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  17292. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  17293. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  17294. // });
  17295. it('should not exceed the maximum size of input array', function() {
  17296. numLimitInput.clear();
  17297. numLimitInput.sendKeys('100');
  17298. letterLimitInput.clear();
  17299. letterLimitInput.sendKeys('100');
  17300. longNumberLimitInput.clear();
  17301. longNumberLimitInput.sendKeys('100');
  17302. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  17303. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  17304. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  17305. });
  17306. </file>
  17307. </example>
  17308. */
  17309. function limitToFilter() {
  17310. return function(input, limit, begin) {
  17311. if (Math.abs(Number(limit)) === Infinity) {
  17312. limit = Number(limit);
  17313. } else {
  17314. limit = toInt(limit);
  17315. }
  17316. if (isNaN(limit)) return input;
  17317. if (isNumber(input)) input = input.toString();
  17318. if (!isArray(input) && !isString(input)) return input;
  17319. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  17320. begin = (begin < 0 && begin >= -input.length) ? input.length + begin : begin;
  17321. if (limit >= 0) {
  17322. return input.slice(begin, begin + limit);
  17323. } else {
  17324. if (begin === 0) {
  17325. return input.slice(limit, input.length);
  17326. } else {
  17327. return input.slice(Math.max(0, begin + limit), begin);
  17328. }
  17329. }
  17330. };
  17331. }
  17332. /**
  17333. * @ngdoc filter
  17334. * @name orderBy
  17335. * @kind function
  17336. *
  17337. * @description
  17338. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  17339. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  17340. * as expected, make sure they are actually being saved as numbers and not strings.
  17341. *
  17342. * @param {Array} array The array to sort.
  17343. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
  17344. * used by the comparator to determine the order of elements.
  17345. *
  17346. * Can be one of:
  17347. *
  17348. * - `function`: Getter function. The result of this function will be sorted using the
  17349. * `<`, `===`, `>` operator.
  17350. * - `string`: An Angular expression. The result of this expression is used to compare elements
  17351. * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
  17352. * 3 first characters of a property called `name`). The result of a constant expression
  17353. * is interpreted as a property name to be used in comparisons (for example `"special name"`
  17354. * to sort object by the value of their `special name` property). An expression can be
  17355. * optionally prefixed with `+` or `-` to control ascending or descending sort order
  17356. * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
  17357. * element itself is used to compare where sorting.
  17358. * - `Array`: An array of function or string predicates. The first predicate in the array
  17359. * is used for sorting, but when two items are equivalent, the next predicate is used.
  17360. *
  17361. * If the predicate is missing or empty then it defaults to `'+'`.
  17362. *
  17363. * @param {boolean=} reverse Reverse the order of the array.
  17364. * @returns {Array} Sorted copy of the source array.
  17365. *
  17366. *
  17367. * @example
  17368. * The example below demonstrates a simple ngRepeat, where the data is sorted
  17369. * by age in descending order (predicate is set to `'-age'`).
  17370. * `reverse` is not set, which means it defaults to `false`.
  17371. <example module="orderByExample">
  17372. <file name="index.html">
  17373. <script>
  17374. angular.module('orderByExample', [])
  17375. .controller('ExampleController', ['$scope', function($scope) {
  17376. $scope.friends =
  17377. [{name:'John', phone:'555-1212', age:10},
  17378. {name:'Mary', phone:'555-9876', age:19},
  17379. {name:'Mike', phone:'555-4321', age:21},
  17380. {name:'Adam', phone:'555-5678', age:35},
  17381. {name:'Julie', phone:'555-8765', age:29}];
  17382. }]);
  17383. </script>
  17384. <div ng-controller="ExampleController">
  17385. <table class="friend">
  17386. <tr>
  17387. <th>Name</th>
  17388. <th>Phone Number</th>
  17389. <th>Age</th>
  17390. </tr>
  17391. <tr ng-repeat="friend in friends | orderBy:'-age'">
  17392. <td>{{friend.name}}</td>
  17393. <td>{{friend.phone}}</td>
  17394. <td>{{friend.age}}</td>
  17395. </tr>
  17396. </table>
  17397. </div>
  17398. </file>
  17399. </example>
  17400. *
  17401. * The predicate and reverse parameters can be controlled dynamically through scope properties,
  17402. * as shown in the next example.
  17403. * @example
  17404. <example module="orderByExample">
  17405. <file name="index.html">
  17406. <script>
  17407. angular.module('orderByExample', [])
  17408. .controller('ExampleController', ['$scope', function($scope) {
  17409. $scope.friends =
  17410. [{name:'John', phone:'555-1212', age:10},
  17411. {name:'Mary', phone:'555-9876', age:19},
  17412. {name:'Mike', phone:'555-4321', age:21},
  17413. {name:'Adam', phone:'555-5678', age:35},
  17414. {name:'Julie', phone:'555-8765', age:29}];
  17415. $scope.predicate = 'age';
  17416. $scope.reverse = true;
  17417. $scope.order = function(predicate) {
  17418. $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
  17419. $scope.predicate = predicate;
  17420. };
  17421. }]);
  17422. </script>
  17423. <style type="text/css">
  17424. .sortorder:after {
  17425. content: '\25b2';
  17426. }
  17427. .sortorder.reverse:after {
  17428. content: '\25bc';
  17429. }
  17430. </style>
  17431. <div ng-controller="ExampleController">
  17432. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  17433. <hr/>
  17434. [ <a href="" ng-click="predicate=''">unsorted</a> ]
  17435. <table class="friend">
  17436. <tr>
  17437. <th>
  17438. <a href="" ng-click="order('name')">Name</a>
  17439. <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
  17440. </th>
  17441. <th>
  17442. <a href="" ng-click="order('phone')">Phone Number</a>
  17443. <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
  17444. </th>
  17445. <th>
  17446. <a href="" ng-click="order('age')">Age</a>
  17447. <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
  17448. </th>
  17449. </tr>
  17450. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  17451. <td>{{friend.name}}</td>
  17452. <td>{{friend.phone}}</td>
  17453. <td>{{friend.age}}</td>
  17454. </tr>
  17455. </table>
  17456. </div>
  17457. </file>
  17458. </example>
  17459. *
  17460. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  17461. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  17462. * desired parameters.
  17463. *
  17464. * Example:
  17465. *
  17466. * @example
  17467. <example module="orderByExample">
  17468. <file name="index.html">
  17469. <div ng-controller="ExampleController">
  17470. <table class="friend">
  17471. <tr>
  17472. <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
  17473. (<a href="" ng-click="order('-name',false)">^</a>)</th>
  17474. <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
  17475. <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
  17476. </tr>
  17477. <tr ng-repeat="friend in friends">
  17478. <td>{{friend.name}}</td>
  17479. <td>{{friend.phone}}</td>
  17480. <td>{{friend.age}}</td>
  17481. </tr>
  17482. </table>
  17483. </div>
  17484. </file>
  17485. <file name="script.js">
  17486. angular.module('orderByExample', [])
  17487. .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
  17488. var orderBy = $filter('orderBy');
  17489. $scope.friends = [
  17490. { name: 'John', phone: '555-1212', age: 10 },
  17491. { name: 'Mary', phone: '555-9876', age: 19 },
  17492. { name: 'Mike', phone: '555-4321', age: 21 },
  17493. { name: 'Adam', phone: '555-5678', age: 35 },
  17494. { name: 'Julie', phone: '555-8765', age: 29 }
  17495. ];
  17496. $scope.order = function(predicate, reverse) {
  17497. $scope.friends = orderBy($scope.friends, predicate, reverse);
  17498. };
  17499. $scope.order('-age',false);
  17500. }]);
  17501. </file>
  17502. </example>
  17503. */
  17504. orderByFilter.$inject = ['$parse'];
  17505. function orderByFilter($parse) {
  17506. return function(array, sortPredicate, reverseOrder) {
  17507. if (!(isArrayLike(array))) return array;
  17508. if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
  17509. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  17510. var predicates = processPredicates(sortPredicate, reverseOrder);
  17511. // Add a predicate at the end that evaluates to the element index. This makes the
  17512. // sort stable as it works as a tie-breaker when all the input predicates cannot
  17513. // distinguish between two elements.
  17514. predicates.push({ get: function() { return {}; }, descending: reverseOrder ? -1 : 1});
  17515. // The next three lines are a version of a Swartzian Transform idiom from Perl
  17516. // (sometimes called the Decorate-Sort-Undecorate idiom)
  17517. // See https://en.wikipedia.org/wiki/Schwartzian_transform
  17518. var compareValues = Array.prototype.map.call(array, getComparisonObject);
  17519. compareValues.sort(doComparison);
  17520. array = compareValues.map(function(item) { return item.value; });
  17521. return array;
  17522. function getComparisonObject(value, index) {
  17523. return {
  17524. value: value,
  17525. predicateValues: predicates.map(function(predicate) {
  17526. return getPredicateValue(predicate.get(value), index);
  17527. })
  17528. };
  17529. }
  17530. function doComparison(v1, v2) {
  17531. var result = 0;
  17532. for (var index=0, length = predicates.length; index < length; ++index) {
  17533. result = compare(v1.predicateValues[index], v2.predicateValues[index]) * predicates[index].descending;
  17534. if (result) break;
  17535. }
  17536. return result;
  17537. }
  17538. };
  17539. function processPredicates(sortPredicate, reverseOrder) {
  17540. reverseOrder = reverseOrder ? -1 : 1;
  17541. return sortPredicate.map(function(predicate) {
  17542. var descending = 1, get = identity;
  17543. if (isFunction(predicate)) {
  17544. get = predicate;
  17545. } else if (isString(predicate)) {
  17546. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  17547. descending = predicate.charAt(0) == '-' ? -1 : 1;
  17548. predicate = predicate.substring(1);
  17549. }
  17550. if (predicate !== '') {
  17551. get = $parse(predicate);
  17552. if (get.constant) {
  17553. var key = get();
  17554. get = function(value) { return value[key]; };
  17555. }
  17556. }
  17557. }
  17558. return { get: get, descending: descending * reverseOrder };
  17559. });
  17560. }
  17561. function isPrimitive(value) {
  17562. switch (typeof value) {
  17563. case 'number': /* falls through */
  17564. case 'boolean': /* falls through */
  17565. case 'string':
  17566. return true;
  17567. default:
  17568. return false;
  17569. }
  17570. }
  17571. function objectValue(value, index) {
  17572. // If `valueOf` is a valid function use that
  17573. if (typeof value.valueOf === 'function') {
  17574. value = value.valueOf();
  17575. if (isPrimitive(value)) return value;
  17576. }
  17577. // If `toString` is a valid function and not the one from `Object.prototype` use that
  17578. if (hasCustomToString(value)) {
  17579. value = value.toString();
  17580. if (isPrimitive(value)) return value;
  17581. }
  17582. // We have a basic object so we use the position of the object in the collection
  17583. return index;
  17584. }
  17585. function getPredicateValue(value, index) {
  17586. var type = typeof value;
  17587. if (value === null) {
  17588. type = 'string';
  17589. value = 'null';
  17590. } else if (type === 'string') {
  17591. value = value.toLowerCase();
  17592. } else if (type === 'object') {
  17593. value = objectValue(value, index);
  17594. }
  17595. return { value: value, type: type };
  17596. }
  17597. function compare(v1, v2) {
  17598. var result = 0;
  17599. if (v1.type === v2.type) {
  17600. if (v1.value !== v2.value) {
  17601. result = v1.value < v2.value ? -1 : 1;
  17602. }
  17603. } else {
  17604. result = v1.type < v2.type ? -1 : 1;
  17605. }
  17606. return result;
  17607. }
  17608. }
  17609. function ngDirective(directive) {
  17610. if (isFunction(directive)) {
  17611. directive = {
  17612. link: directive
  17613. };
  17614. }
  17615. directive.restrict = directive.restrict || 'AC';
  17616. return valueFn(directive);
  17617. }
  17618. /**
  17619. * @ngdoc directive
  17620. * @name a
  17621. * @restrict E
  17622. *
  17623. * @description
  17624. * Modifies the default behavior of the html A tag so that the default action is prevented when
  17625. * the href attribute is empty.
  17626. *
  17627. * This change permits the easy creation of action links with the `ngClick` directive
  17628. * without changing the location or causing page reloads, e.g.:
  17629. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  17630. */
  17631. var htmlAnchorDirective = valueFn({
  17632. restrict: 'E',
  17633. compile: function(element, attr) {
  17634. if (!attr.href && !attr.xlinkHref) {
  17635. return function(scope, element) {
  17636. // If the linked element is not an anchor tag anymore, do nothing
  17637. if (element[0].nodeName.toLowerCase() !== 'a') return;
  17638. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  17639. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  17640. 'xlink:href' : 'href';
  17641. element.on('click', function(event) {
  17642. // if we have no href url, then don't navigate anywhere.
  17643. if (!element.attr(href)) {
  17644. event.preventDefault();
  17645. }
  17646. });
  17647. };
  17648. }
  17649. }
  17650. });
  17651. /**
  17652. * @ngdoc directive
  17653. * @name ngHref
  17654. * @restrict A
  17655. * @priority 99
  17656. *
  17657. * @description
  17658. * Using Angular markup like `{{hash}}` in an href attribute will
  17659. * make the link go to the wrong URL if the user clicks it before
  17660. * Angular has a chance to replace the `{{hash}}` markup with its
  17661. * value. Until Angular replaces the markup the link will be broken
  17662. * and will most likely return a 404 error. The `ngHref` directive
  17663. * solves this problem.
  17664. *
  17665. * The wrong way to write it:
  17666. * ```html
  17667. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  17668. * ```
  17669. *
  17670. * The correct way to write it:
  17671. * ```html
  17672. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  17673. * ```
  17674. *
  17675. * @element A
  17676. * @param {template} ngHref any string which can contain `{{}}` markup.
  17677. *
  17678. * @example
  17679. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  17680. * in links and their different behaviors:
  17681. <example>
  17682. <file name="index.html">
  17683. <input ng-model="value" /><br />
  17684. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  17685. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  17686. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  17687. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  17688. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  17689. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  17690. </file>
  17691. <file name="protractor.js" type="protractor">
  17692. it('should execute ng-click but not reload when href without value', function() {
  17693. element(by.id('link-1')).click();
  17694. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  17695. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  17696. });
  17697. it('should execute ng-click but not reload when href empty string', function() {
  17698. element(by.id('link-2')).click();
  17699. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  17700. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  17701. });
  17702. it('should execute ng-click and change url when ng-href specified', function() {
  17703. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  17704. element(by.id('link-3')).click();
  17705. // At this point, we navigate away from an Angular page, so we need
  17706. // to use browser.driver to get the base webdriver.
  17707. browser.wait(function() {
  17708. return browser.driver.getCurrentUrl().then(function(url) {
  17709. return url.match(/\/123$/);
  17710. });
  17711. }, 5000, 'page should navigate to /123');
  17712. });
  17713. it('should execute ng-click but not reload when href empty string and name specified', function() {
  17714. element(by.id('link-4')).click();
  17715. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  17716. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  17717. });
  17718. it('should execute ng-click but not reload when no href but name specified', function() {
  17719. element(by.id('link-5')).click();
  17720. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  17721. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  17722. });
  17723. it('should only change url when only ng-href', function() {
  17724. element(by.model('value')).clear();
  17725. element(by.model('value')).sendKeys('6');
  17726. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  17727. element(by.id('link-6')).click();
  17728. // At this point, we navigate away from an Angular page, so we need
  17729. // to use browser.driver to get the base webdriver.
  17730. browser.wait(function() {
  17731. return browser.driver.getCurrentUrl().then(function(url) {
  17732. return url.match(/\/6$/);
  17733. });
  17734. }, 5000, 'page should navigate to /6');
  17735. });
  17736. </file>
  17737. </example>
  17738. */
  17739. /**
  17740. * @ngdoc directive
  17741. * @name ngSrc
  17742. * @restrict A
  17743. * @priority 99
  17744. *
  17745. * @description
  17746. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  17747. * work right: The browser will fetch from the URL with the literal
  17748. * text `{{hash}}` until Angular replaces the expression inside
  17749. * `{{hash}}`. The `ngSrc` directive solves this problem.
  17750. *
  17751. * The buggy way to write it:
  17752. * ```html
  17753. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  17754. * ```
  17755. *
  17756. * The correct way to write it:
  17757. * ```html
  17758. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  17759. * ```
  17760. *
  17761. * @element IMG
  17762. * @param {template} ngSrc any string which can contain `{{}}` markup.
  17763. */
  17764. /**
  17765. * @ngdoc directive
  17766. * @name ngSrcset
  17767. * @restrict A
  17768. * @priority 99
  17769. *
  17770. * @description
  17771. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  17772. * work right: The browser will fetch from the URL with the literal
  17773. * text `{{hash}}` until Angular replaces the expression inside
  17774. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  17775. *
  17776. * The buggy way to write it:
  17777. * ```html
  17778. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  17779. * ```
  17780. *
  17781. * The correct way to write it:
  17782. * ```html
  17783. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  17784. * ```
  17785. *
  17786. * @element IMG
  17787. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  17788. */
  17789. /**
  17790. * @ngdoc directive
  17791. * @name ngDisabled
  17792. * @restrict A
  17793. * @priority 100
  17794. *
  17795. * @description
  17796. *
  17797. * This directive sets the `disabled` attribute on the element if the
  17798. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  17799. *
  17800. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  17801. * attribute. The following example would make the button enabled on Chrome/Firefox
  17802. * but not on older IEs:
  17803. *
  17804. * ```html
  17805. * <!-- See below for an example of ng-disabled being used correctly -->
  17806. * <div ng-init="isDisabled = false">
  17807. * <button disabled="{{isDisabled}}">Disabled</button>
  17808. * </div>
  17809. * ```
  17810. *
  17811. * This is because the HTML specification does not require browsers to preserve the values of
  17812. * boolean attributes such as `disabled` (Their presence means true and their absence means false.)
  17813. * If we put an Angular interpolation expression into such an attribute then the
  17814. * binding information would be lost when the browser removes the attribute.
  17815. *
  17816. * @example
  17817. <example>
  17818. <file name="index.html">
  17819. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  17820. <button ng-model="button" ng-disabled="checked">Button</button>
  17821. </file>
  17822. <file name="protractor.js" type="protractor">
  17823. it('should toggle button', function() {
  17824. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  17825. element(by.model('checked')).click();
  17826. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  17827. });
  17828. </file>
  17829. </example>
  17830. *
  17831. * @element INPUT
  17832. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  17833. * then the `disabled` attribute will be set on the element
  17834. */
  17835. /**
  17836. * @ngdoc directive
  17837. * @name ngChecked
  17838. * @restrict A
  17839. * @priority 100
  17840. *
  17841. * @description
  17842. * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
  17843. *
  17844. * Note that this directive should not be used together with {@link ngModel `ngModel`},
  17845. * as this can lead to unexpected behavior.
  17846. *
  17847. * ### Why do we need `ngChecked`?
  17848. *
  17849. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17850. * such as checked. (Their presence means true and their absence means false.)
  17851. * If we put an Angular interpolation expression into such an attribute then the
  17852. * binding information would be lost when the browser removes the attribute.
  17853. * The `ngChecked` directive solves this problem for the `checked` attribute.
  17854. * This complementary directive is not removed by the browser and so provides
  17855. * a permanent reliable place to store the binding information.
  17856. * @example
  17857. <example>
  17858. <file name="index.html">
  17859. <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
  17860. <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
  17861. </file>
  17862. <file name="protractor.js" type="protractor">
  17863. it('should check both checkBoxes', function() {
  17864. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  17865. element(by.model('master')).click();
  17866. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  17867. });
  17868. </file>
  17869. </example>
  17870. *
  17871. * @element INPUT
  17872. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  17873. * then the `checked` attribute will be set on the element
  17874. */
  17875. /**
  17876. * @ngdoc directive
  17877. * @name ngReadonly
  17878. * @restrict A
  17879. * @priority 100
  17880. *
  17881. * @description
  17882. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17883. * such as readonly. (Their presence means true and their absence means false.)
  17884. * If we put an Angular interpolation expression into such an attribute then the
  17885. * binding information would be lost when the browser removes the attribute.
  17886. * The `ngReadonly` directive solves this problem for the `readonly` attribute.
  17887. * This complementary directive is not removed by the browser and so provides
  17888. * a permanent reliable place to store the binding information.
  17889. * @example
  17890. <example>
  17891. <file name="index.html">
  17892. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  17893. <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
  17894. </file>
  17895. <file name="protractor.js" type="protractor">
  17896. it('should toggle readonly attr', function() {
  17897. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  17898. element(by.model('checked')).click();
  17899. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  17900. });
  17901. </file>
  17902. </example>
  17903. *
  17904. * @element INPUT
  17905. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  17906. * then special attribute "readonly" will be set on the element
  17907. */
  17908. /**
  17909. * @ngdoc directive
  17910. * @name ngSelected
  17911. * @restrict A
  17912. * @priority 100
  17913. *
  17914. * @description
  17915. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17916. * such as selected. (Their presence means true and their absence means false.)
  17917. * If we put an Angular interpolation expression into such an attribute then the
  17918. * binding information would be lost when the browser removes the attribute.
  17919. * The `ngSelected` directive solves this problem for the `selected` attribute.
  17920. * This complementary directive is not removed by the browser and so provides
  17921. * a permanent reliable place to store the binding information.
  17922. *
  17923. * @example
  17924. <example>
  17925. <file name="index.html">
  17926. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  17927. <select aria-label="ngSelected demo">
  17928. <option>Hello!</option>
  17929. <option id="greet" ng-selected="selected">Greetings!</option>
  17930. </select>
  17931. </file>
  17932. <file name="protractor.js" type="protractor">
  17933. it('should select Greetings!', function() {
  17934. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  17935. element(by.model('selected')).click();
  17936. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  17937. });
  17938. </file>
  17939. </example>
  17940. *
  17941. * @element OPTION
  17942. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  17943. * then special attribute "selected" will be set on the element
  17944. */
  17945. /**
  17946. * @ngdoc directive
  17947. * @name ngOpen
  17948. * @restrict A
  17949. * @priority 100
  17950. *
  17951. * @description
  17952. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17953. * such as open. (Their presence means true and their absence means false.)
  17954. * If we put an Angular interpolation expression into such an attribute then the
  17955. * binding information would be lost when the browser removes the attribute.
  17956. * The `ngOpen` directive solves this problem for the `open` attribute.
  17957. * This complementary directive is not removed by the browser and so provides
  17958. * a permanent reliable place to store the binding information.
  17959. * @example
  17960. <example>
  17961. <file name="index.html">
  17962. <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
  17963. <details id="details" ng-open="open">
  17964. <summary>Show/Hide me</summary>
  17965. </details>
  17966. </file>
  17967. <file name="protractor.js" type="protractor">
  17968. it('should toggle open', function() {
  17969. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  17970. element(by.model('open')).click();
  17971. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  17972. });
  17973. </file>
  17974. </example>
  17975. *
  17976. * @element DETAILS
  17977. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  17978. * then special attribute "open" will be set on the element
  17979. */
  17980. var ngAttributeAliasDirectives = {};
  17981. // boolean attrs are evaluated
  17982. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  17983. // binding to multiple is not supported
  17984. if (propName == "multiple") return;
  17985. function defaultLinkFn(scope, element, attr) {
  17986. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  17987. attr.$set(attrName, !!value);
  17988. });
  17989. }
  17990. var normalized = directiveNormalize('ng-' + attrName);
  17991. var linkFn = defaultLinkFn;
  17992. if (propName === 'checked') {
  17993. linkFn = function(scope, element, attr) {
  17994. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  17995. if (attr.ngModel !== attr[normalized]) {
  17996. defaultLinkFn(scope, element, attr);
  17997. }
  17998. };
  17999. }
  18000. ngAttributeAliasDirectives[normalized] = function() {
  18001. return {
  18002. restrict: 'A',
  18003. priority: 100,
  18004. link: linkFn
  18005. };
  18006. };
  18007. });
  18008. // aliased input attrs are evaluated
  18009. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  18010. ngAttributeAliasDirectives[ngAttr] = function() {
  18011. return {
  18012. priority: 100,
  18013. link: function(scope, element, attr) {
  18014. //special case ngPattern when a literal regular expression value
  18015. //is used as the expression (this way we don't have to watch anything).
  18016. if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
  18017. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  18018. if (match) {
  18019. attr.$set("ngPattern", new RegExp(match[1], match[2]));
  18020. return;
  18021. }
  18022. }
  18023. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  18024. attr.$set(ngAttr, value);
  18025. });
  18026. }
  18027. };
  18028. };
  18029. });
  18030. // ng-src, ng-srcset, ng-href are interpolated
  18031. forEach(['src', 'srcset', 'href'], function(attrName) {
  18032. var normalized = directiveNormalize('ng-' + attrName);
  18033. ngAttributeAliasDirectives[normalized] = function() {
  18034. return {
  18035. priority: 99, // it needs to run after the attributes are interpolated
  18036. link: function(scope, element, attr) {
  18037. var propName = attrName,
  18038. name = attrName;
  18039. if (attrName === 'href' &&
  18040. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  18041. name = 'xlinkHref';
  18042. attr.$attr[name] = 'xlink:href';
  18043. propName = null;
  18044. }
  18045. attr.$observe(normalized, function(value) {
  18046. if (!value) {
  18047. if (attrName === 'href') {
  18048. attr.$set(name, null);
  18049. }
  18050. return;
  18051. }
  18052. attr.$set(name, value);
  18053. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  18054. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  18055. // to set the property as well to achieve the desired effect.
  18056. // we use attr[attrName] value since $set can sanitize the url.
  18057. if (msie && propName) element.prop(propName, attr[name]);
  18058. });
  18059. }
  18060. };
  18061. };
  18062. });
  18063. /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
  18064. */
  18065. var nullFormCtrl = {
  18066. $addControl: noop,
  18067. $$renameControl: nullFormRenameControl,
  18068. $removeControl: noop,
  18069. $setValidity: noop,
  18070. $setDirty: noop,
  18071. $setPristine: noop,
  18072. $setSubmitted: noop
  18073. },
  18074. SUBMITTED_CLASS = 'ng-submitted';
  18075. function nullFormRenameControl(control, name) {
  18076. control.$name = name;
  18077. }
  18078. /**
  18079. * @ngdoc type
  18080. * @name form.FormController
  18081. *
  18082. * @property {boolean} $pristine True if user has not interacted with the form yet.
  18083. * @property {boolean} $dirty True if user has already interacted with the form.
  18084. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  18085. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  18086. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  18087. *
  18088. * @property {Object} $error Is an object hash, containing references to controls or
  18089. * forms with failing validators, where:
  18090. *
  18091. * - keys are validation tokens (error names),
  18092. * - values are arrays of controls or forms that have a failing validator for given error name.
  18093. *
  18094. * Built-in validation tokens:
  18095. *
  18096. * - `email`
  18097. * - `max`
  18098. * - `maxlength`
  18099. * - `min`
  18100. * - `minlength`
  18101. * - `number`
  18102. * - `pattern`
  18103. * - `required`
  18104. * - `url`
  18105. * - `date`
  18106. * - `datetimelocal`
  18107. * - `time`
  18108. * - `week`
  18109. * - `month`
  18110. *
  18111. * @description
  18112. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  18113. * such as being valid/invalid or dirty/pristine.
  18114. *
  18115. * Each {@link ng.directive:form form} directive creates an instance
  18116. * of `FormController`.
  18117. *
  18118. */
  18119. //asks for $scope to fool the BC controller module
  18120. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  18121. function FormController(element, attrs, $scope, $animate, $interpolate) {
  18122. var form = this,
  18123. controls = [];
  18124. var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl;
  18125. // init state
  18126. form.$error = {};
  18127. form.$$success = {};
  18128. form.$pending = undefined;
  18129. form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
  18130. form.$dirty = false;
  18131. form.$pristine = true;
  18132. form.$valid = true;
  18133. form.$invalid = false;
  18134. form.$submitted = false;
  18135. parentForm.$addControl(form);
  18136. /**
  18137. * @ngdoc method
  18138. * @name form.FormController#$rollbackViewValue
  18139. *
  18140. * @description
  18141. * Rollback all form controls pending updates to the `$modelValue`.
  18142. *
  18143. * Updates may be pending by a debounced event or because the input is waiting for a some future
  18144. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  18145. * a form that uses `ng-model-options` to pend updates.
  18146. */
  18147. form.$rollbackViewValue = function() {
  18148. forEach(controls, function(control) {
  18149. control.$rollbackViewValue();
  18150. });
  18151. };
  18152. /**
  18153. * @ngdoc method
  18154. * @name form.FormController#$commitViewValue
  18155. *
  18156. * @description
  18157. * Commit all form controls pending updates to the `$modelValue`.
  18158. *
  18159. * Updates may be pending by a debounced event or because the input is waiting for a some future
  18160. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  18161. * usually handles calling this in response to input events.
  18162. */
  18163. form.$commitViewValue = function() {
  18164. forEach(controls, function(control) {
  18165. control.$commitViewValue();
  18166. });
  18167. };
  18168. /**
  18169. * @ngdoc method
  18170. * @name form.FormController#$addControl
  18171. *
  18172. * @description
  18173. * Register a control with the form.
  18174. *
  18175. * Input elements using ngModelController do this automatically when they are linked.
  18176. */
  18177. form.$addControl = function(control) {
  18178. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  18179. // and not added to the scope. Now we throw an error.
  18180. assertNotHasOwnProperty(control.$name, 'input');
  18181. controls.push(control);
  18182. if (control.$name) {
  18183. form[control.$name] = control;
  18184. }
  18185. };
  18186. // Private API: rename a form control
  18187. form.$$renameControl = function(control, newName) {
  18188. var oldName = control.$name;
  18189. if (form[oldName] === control) {
  18190. delete form[oldName];
  18191. }
  18192. form[newName] = control;
  18193. control.$name = newName;
  18194. };
  18195. /**
  18196. * @ngdoc method
  18197. * @name form.FormController#$removeControl
  18198. *
  18199. * @description
  18200. * Deregister a control from the form.
  18201. *
  18202. * Input elements using ngModelController do this automatically when they are destroyed.
  18203. */
  18204. form.$removeControl = function(control) {
  18205. if (control.$name && form[control.$name] === control) {
  18206. delete form[control.$name];
  18207. }
  18208. forEach(form.$pending, function(value, name) {
  18209. form.$setValidity(name, null, control);
  18210. });
  18211. forEach(form.$error, function(value, name) {
  18212. form.$setValidity(name, null, control);
  18213. });
  18214. forEach(form.$$success, function(value, name) {
  18215. form.$setValidity(name, null, control);
  18216. });
  18217. arrayRemove(controls, control);
  18218. };
  18219. /**
  18220. * @ngdoc method
  18221. * @name form.FormController#$setValidity
  18222. *
  18223. * @description
  18224. * Sets the validity of a form control.
  18225. *
  18226. * This method will also propagate to parent forms.
  18227. */
  18228. addSetValidityMethod({
  18229. ctrl: this,
  18230. $element: element,
  18231. set: function(object, property, controller) {
  18232. var list = object[property];
  18233. if (!list) {
  18234. object[property] = [controller];
  18235. } else {
  18236. var index = list.indexOf(controller);
  18237. if (index === -1) {
  18238. list.push(controller);
  18239. }
  18240. }
  18241. },
  18242. unset: function(object, property, controller) {
  18243. var list = object[property];
  18244. if (!list) {
  18245. return;
  18246. }
  18247. arrayRemove(list, controller);
  18248. if (list.length === 0) {
  18249. delete object[property];
  18250. }
  18251. },
  18252. parentForm: parentForm,
  18253. $animate: $animate
  18254. });
  18255. /**
  18256. * @ngdoc method
  18257. * @name form.FormController#$setDirty
  18258. *
  18259. * @description
  18260. * Sets the form to a dirty state.
  18261. *
  18262. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  18263. * state (ng-dirty class). This method will also propagate to parent forms.
  18264. */
  18265. form.$setDirty = function() {
  18266. $animate.removeClass(element, PRISTINE_CLASS);
  18267. $animate.addClass(element, DIRTY_CLASS);
  18268. form.$dirty = true;
  18269. form.$pristine = false;
  18270. parentForm.$setDirty();
  18271. };
  18272. /**
  18273. * @ngdoc method
  18274. * @name form.FormController#$setPristine
  18275. *
  18276. * @description
  18277. * Sets the form to its pristine state.
  18278. *
  18279. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  18280. * state (ng-pristine class). This method will also propagate to all the controls contained
  18281. * in this form.
  18282. *
  18283. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  18284. * saving or resetting it.
  18285. */
  18286. form.$setPristine = function() {
  18287. $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  18288. form.$dirty = false;
  18289. form.$pristine = true;
  18290. form.$submitted = false;
  18291. forEach(controls, function(control) {
  18292. control.$setPristine();
  18293. });
  18294. };
  18295. /**
  18296. * @ngdoc method
  18297. * @name form.FormController#$setUntouched
  18298. *
  18299. * @description
  18300. * Sets the form to its untouched state.
  18301. *
  18302. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  18303. * untouched state (ng-untouched class).
  18304. *
  18305. * Setting a form controls back to their untouched state is often useful when setting the form
  18306. * back to its pristine state.
  18307. */
  18308. form.$setUntouched = function() {
  18309. forEach(controls, function(control) {
  18310. control.$setUntouched();
  18311. });
  18312. };
  18313. /**
  18314. * @ngdoc method
  18315. * @name form.FormController#$setSubmitted
  18316. *
  18317. * @description
  18318. * Sets the form to its submitted state.
  18319. */
  18320. form.$setSubmitted = function() {
  18321. $animate.addClass(element, SUBMITTED_CLASS);
  18322. form.$submitted = true;
  18323. parentForm.$setSubmitted();
  18324. };
  18325. }
  18326. /**
  18327. * @ngdoc directive
  18328. * @name ngForm
  18329. * @restrict EAC
  18330. *
  18331. * @description
  18332. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  18333. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  18334. * sub-group of controls needs to be determined.
  18335. *
  18336. * Note: the purpose of `ngForm` is to group controls,
  18337. * but not to be a replacement for the `<form>` tag with all of its capabilities
  18338. * (e.g. posting to the server, ...).
  18339. *
  18340. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  18341. * related scope, under this name.
  18342. *
  18343. */
  18344. /**
  18345. * @ngdoc directive
  18346. * @name form
  18347. * @restrict E
  18348. *
  18349. * @description
  18350. * Directive that instantiates
  18351. * {@link form.FormController FormController}.
  18352. *
  18353. * If the `name` attribute is specified, the form controller is published onto the current scope under
  18354. * this name.
  18355. *
  18356. * # Alias: {@link ng.directive:ngForm `ngForm`}
  18357. *
  18358. * In Angular, forms can be nested. This means that the outer form is valid when all of the child
  18359. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  18360. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
  18361. * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
  18362. * using Angular validation directives in forms that are dynamically generated using the
  18363. * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
  18364. * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
  18365. * `ngForm` directive and nest these in an outer `form` element.
  18366. *
  18367. *
  18368. * # CSS classes
  18369. * - `ng-valid` is set if the form is valid.
  18370. * - `ng-invalid` is set if the form is invalid.
  18371. * - `ng-pristine` is set if the form is pristine.
  18372. * - `ng-dirty` is set if the form is dirty.
  18373. * - `ng-submitted` is set if the form was submitted.
  18374. *
  18375. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  18376. *
  18377. *
  18378. * # Submitting a form and preventing the default action
  18379. *
  18380. * Since the role of forms in client-side Angular applications is different than in classical
  18381. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  18382. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  18383. * to handle the form submission in an application-specific way.
  18384. *
  18385. * For this reason, Angular prevents the default action (form submission to the server) unless the
  18386. * `<form>` element has an `action` attribute specified.
  18387. *
  18388. * You can use one of the following two ways to specify what javascript method should be called when
  18389. * a form is submitted:
  18390. *
  18391. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  18392. * - {@link ng.directive:ngClick ngClick} directive on the first
  18393. * button or input field of type submit (input[type=submit])
  18394. *
  18395. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  18396. * or {@link ng.directive:ngClick ngClick} directives.
  18397. * This is because of the following form submission rules in the HTML specification:
  18398. *
  18399. * - If a form has only one input field then hitting enter in this field triggers form submit
  18400. * (`ngSubmit`)
  18401. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  18402. * doesn't trigger submit
  18403. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  18404. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  18405. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  18406. *
  18407. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  18408. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  18409. * to have access to the updated model.
  18410. *
  18411. * ## Animation Hooks
  18412. *
  18413. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  18414. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  18415. * other validations that are performed within the form. Animations in ngForm are similar to how
  18416. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  18417. * as JS animations.
  18418. *
  18419. * The following example shows a simple way to utilize CSS transitions to style a form element
  18420. * that has been rendered as invalid after it has been validated:
  18421. *
  18422. * <pre>
  18423. * //be sure to include ngAnimate as a module to hook into more
  18424. * //advanced animations
  18425. * .my-form {
  18426. * transition:0.5s linear all;
  18427. * background: white;
  18428. * }
  18429. * .my-form.ng-invalid {
  18430. * background: red;
  18431. * color:white;
  18432. * }
  18433. * </pre>
  18434. *
  18435. * @example
  18436. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  18437. <file name="index.html">
  18438. <script>
  18439. angular.module('formExample', [])
  18440. .controller('FormController', ['$scope', function($scope) {
  18441. $scope.userType = 'guest';
  18442. }]);
  18443. </script>
  18444. <style>
  18445. .my-form {
  18446. transition:all linear 0.5s;
  18447. background: transparent;
  18448. }
  18449. .my-form.ng-invalid {
  18450. background: red;
  18451. }
  18452. </style>
  18453. <form name="myForm" ng-controller="FormController" class="my-form">
  18454. userType: <input name="input" ng-model="userType" required>
  18455. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  18456. <code>userType = {{userType}}</code><br>
  18457. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  18458. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  18459. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  18460. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  18461. </form>
  18462. </file>
  18463. <file name="protractor.js" type="protractor">
  18464. it('should initialize to model', function() {
  18465. var userType = element(by.binding('userType'));
  18466. var valid = element(by.binding('myForm.input.$valid'));
  18467. expect(userType.getText()).toContain('guest');
  18468. expect(valid.getText()).toContain('true');
  18469. });
  18470. it('should be invalid if empty', function() {
  18471. var userType = element(by.binding('userType'));
  18472. var valid = element(by.binding('myForm.input.$valid'));
  18473. var userInput = element(by.model('userType'));
  18474. userInput.clear();
  18475. userInput.sendKeys('');
  18476. expect(userType.getText()).toEqual('userType =');
  18477. expect(valid.getText()).toContain('false');
  18478. });
  18479. </file>
  18480. </example>
  18481. *
  18482. * @param {string=} name Name of the form. If specified, the form controller will be published into
  18483. * related scope, under this name.
  18484. */
  18485. var formDirectiveFactory = function(isNgForm) {
  18486. return ['$timeout', '$parse', function($timeout, $parse) {
  18487. var formDirective = {
  18488. name: 'form',
  18489. restrict: isNgForm ? 'EAC' : 'E',
  18490. controller: FormController,
  18491. compile: function ngFormCompile(formElement, attr) {
  18492. // Setup initial state of the control
  18493. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  18494. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  18495. return {
  18496. pre: function ngFormPreLink(scope, formElement, attr, controller) {
  18497. // if `action` attr is not present on the form, prevent the default action (submission)
  18498. if (!('action' in attr)) {
  18499. // we can't use jq events because if a form is destroyed during submission the default
  18500. // action is not prevented. see #1238
  18501. //
  18502. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  18503. // page reload if the form was destroyed by submission of the form via a click handler
  18504. // on a button in the form. Looks like an IE9 specific bug.
  18505. var handleFormSubmission = function(event) {
  18506. scope.$apply(function() {
  18507. controller.$commitViewValue();
  18508. controller.$setSubmitted();
  18509. });
  18510. event.preventDefault();
  18511. };
  18512. addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  18513. // unregister the preventDefault listener so that we don't not leak memory but in a
  18514. // way that will achieve the prevention of the default action.
  18515. formElement.on('$destroy', function() {
  18516. $timeout(function() {
  18517. removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  18518. }, 0, false);
  18519. });
  18520. }
  18521. var parentFormCtrl = controller.$$parentForm;
  18522. var setter = nameAttr ? getSetter(controller.$name) : noop;
  18523. if (nameAttr) {
  18524. setter(scope, controller);
  18525. attr.$observe(nameAttr, function(newValue) {
  18526. if (controller.$name === newValue) return;
  18527. setter(scope, undefined);
  18528. parentFormCtrl.$$renameControl(controller, newValue);
  18529. setter = getSetter(controller.$name);
  18530. setter(scope, controller);
  18531. });
  18532. }
  18533. formElement.on('$destroy', function() {
  18534. parentFormCtrl.$removeControl(controller);
  18535. setter(scope, undefined);
  18536. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  18537. });
  18538. }
  18539. };
  18540. }
  18541. };
  18542. return formDirective;
  18543. function getSetter(expression) {
  18544. if (expression === '') {
  18545. //create an assignable expression, so forms with an empty name can be renamed later
  18546. return $parse('this[""]').assign;
  18547. }
  18548. return $parse(expression).assign || noop;
  18549. }
  18550. }];
  18551. };
  18552. var formDirective = formDirectiveFactory();
  18553. var ngFormDirective = formDirectiveFactory(true);
  18554. /* global VALID_CLASS: false,
  18555. INVALID_CLASS: false,
  18556. PRISTINE_CLASS: false,
  18557. DIRTY_CLASS: false,
  18558. UNTOUCHED_CLASS: false,
  18559. TOUCHED_CLASS: false,
  18560. ngModelMinErr: false,
  18561. */
  18562. // Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  18563. 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)/;
  18564. var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
  18565. var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
  18566. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
  18567. var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
  18568. var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  18569. var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
  18570. var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
  18571. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  18572. var inputType = {
  18573. /**
  18574. * @ngdoc input
  18575. * @name input[text]
  18576. *
  18577. * @description
  18578. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  18579. *
  18580. *
  18581. * @param {string} ngModel Assignable angular expression to data-bind to.
  18582. * @param {string=} name Property name of the form under which the control is published.
  18583. * @param {string=} required Adds `required` validation error key if the value is not entered.
  18584. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18585. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18586. * `required` when you want to data-bind to the `required` attribute.
  18587. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  18588. * minlength.
  18589. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  18590. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  18591. * any length.
  18592. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  18593. * that contains the regular expression body that will be converted to a regular expression
  18594. * as in the ngPattern directive.
  18595. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  18596. * a RegExp found by evaluating the Angular expression given in the attribute value.
  18597. * If the expression evaluates to a RegExp object, then this is used directly.
  18598. * If the expression evaluates to a string, then it will be converted to a RegExp
  18599. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  18600. * `new RegExp('^abc$')`.<br />
  18601. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  18602. * start at the index of the last search's match, thus not taking the whole input value into
  18603. * account.
  18604. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18605. * interaction with the input element.
  18606. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  18607. * This parameter is ignored for input[type=password] controls, which will never trim the
  18608. * input.
  18609. *
  18610. * @example
  18611. <example name="text-input-directive" module="textInputExample">
  18612. <file name="index.html">
  18613. <script>
  18614. angular.module('textInputExample', [])
  18615. .controller('ExampleController', ['$scope', function($scope) {
  18616. $scope.example = {
  18617. text: 'guest',
  18618. word: /^\s*\w*\s*$/
  18619. };
  18620. }]);
  18621. </script>
  18622. <form name="myForm" ng-controller="ExampleController">
  18623. <label>Single word:
  18624. <input type="text" name="input" ng-model="example.text"
  18625. ng-pattern="example.word" required ng-trim="false">
  18626. </label>
  18627. <div role="alert">
  18628. <span class="error" ng-show="myForm.input.$error.required">
  18629. Required!</span>
  18630. <span class="error" ng-show="myForm.input.$error.pattern">
  18631. Single word only!</span>
  18632. </div>
  18633. <tt>text = {{example.text}}</tt><br/>
  18634. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18635. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18636. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18637. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18638. </form>
  18639. </file>
  18640. <file name="protractor.js" type="protractor">
  18641. var text = element(by.binding('example.text'));
  18642. var valid = element(by.binding('myForm.input.$valid'));
  18643. var input = element(by.model('example.text'));
  18644. it('should initialize to model', function() {
  18645. expect(text.getText()).toContain('guest');
  18646. expect(valid.getText()).toContain('true');
  18647. });
  18648. it('should be invalid if empty', function() {
  18649. input.clear();
  18650. input.sendKeys('');
  18651. expect(text.getText()).toEqual('text =');
  18652. expect(valid.getText()).toContain('false');
  18653. });
  18654. it('should be invalid if multi word', function() {
  18655. input.clear();
  18656. input.sendKeys('hello world');
  18657. expect(valid.getText()).toContain('false');
  18658. });
  18659. </file>
  18660. </example>
  18661. */
  18662. 'text': textInputType,
  18663. /**
  18664. * @ngdoc input
  18665. * @name input[date]
  18666. *
  18667. * @description
  18668. * Input with date validation and transformation. In browsers that do not yet support
  18669. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  18670. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  18671. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  18672. * expected input format via a placeholder or label.
  18673. *
  18674. * The model must always be a Date object, otherwise Angular will throw an error.
  18675. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18676. *
  18677. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18678. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18679. *
  18680. * @param {string} ngModel Assignable angular expression to data-bind to.
  18681. * @param {string=} name Property name of the form under which the control is published.
  18682. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  18683. * valid ISO date string (yyyy-MM-dd).
  18684. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  18685. * a valid ISO date string (yyyy-MM-dd).
  18686. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18687. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18688. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18689. * `required` when you want to data-bind to the `required` attribute.
  18690. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18691. * interaction with the input element.
  18692. *
  18693. * @example
  18694. <example name="date-input-directive" module="dateInputExample">
  18695. <file name="index.html">
  18696. <script>
  18697. angular.module('dateInputExample', [])
  18698. .controller('DateController', ['$scope', function($scope) {
  18699. $scope.example = {
  18700. value: new Date(2013, 9, 22)
  18701. };
  18702. }]);
  18703. </script>
  18704. <form name="myForm" ng-controller="DateController as dateCtrl">
  18705. <label for="exampleInput">Pick a date in 2013:</label>
  18706. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  18707. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  18708. <div role="alert">
  18709. <span class="error" ng-show="myForm.input.$error.required">
  18710. Required!</span>
  18711. <span class="error" ng-show="myForm.input.$error.date">
  18712. Not a valid date!</span>
  18713. </div>
  18714. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  18715. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18716. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18717. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18718. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18719. </form>
  18720. </file>
  18721. <file name="protractor.js" type="protractor">
  18722. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  18723. var valid = element(by.binding('myForm.input.$valid'));
  18724. var input = element(by.model('example.value'));
  18725. // currently protractor/webdriver does not support
  18726. // sending keys to all known HTML5 input controls
  18727. // for various browsers (see https://github.com/angular/protractor/issues/562).
  18728. function setInput(val) {
  18729. // set the value of the element and force validation.
  18730. var scr = "var ipt = document.getElementById('exampleInput'); " +
  18731. "ipt.value = '" + val + "';" +
  18732. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  18733. browser.executeScript(scr);
  18734. }
  18735. it('should initialize to model', function() {
  18736. expect(value.getText()).toContain('2013-10-22');
  18737. expect(valid.getText()).toContain('myForm.input.$valid = true');
  18738. });
  18739. it('should be invalid if empty', function() {
  18740. setInput('');
  18741. expect(value.getText()).toEqual('value =');
  18742. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18743. });
  18744. it('should be invalid if over max', function() {
  18745. setInput('2015-01-01');
  18746. expect(value.getText()).toContain('');
  18747. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18748. });
  18749. </file>
  18750. </example>
  18751. */
  18752. 'date': createDateInputType('date', DATE_REGEXP,
  18753. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  18754. 'yyyy-MM-dd'),
  18755. /**
  18756. * @ngdoc input
  18757. * @name input[datetime-local]
  18758. *
  18759. * @description
  18760. * Input with datetime validation and transformation. In browsers that do not yet support
  18761. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  18762. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  18763. *
  18764. * The model must always be a Date object, otherwise Angular will throw an error.
  18765. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18766. *
  18767. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18768. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18769. *
  18770. * @param {string} ngModel Assignable angular expression to data-bind to.
  18771. * @param {string=} name Property name of the form under which the control is published.
  18772. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  18773. * valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  18774. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  18775. * a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  18776. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18777. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18778. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18779. * `required` when you want to data-bind to the `required` attribute.
  18780. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18781. * interaction with the input element.
  18782. *
  18783. * @example
  18784. <example name="datetimelocal-input-directive" module="dateExample">
  18785. <file name="index.html">
  18786. <script>
  18787. angular.module('dateExample', [])
  18788. .controller('DateController', ['$scope', function($scope) {
  18789. $scope.example = {
  18790. value: new Date(2010, 11, 28, 14, 57)
  18791. };
  18792. }]);
  18793. </script>
  18794. <form name="myForm" ng-controller="DateController as dateCtrl">
  18795. <label for="exampleInput">Pick a date between in 2013:</label>
  18796. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  18797. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  18798. <div role="alert">
  18799. <span class="error" ng-show="myForm.input.$error.required">
  18800. Required!</span>
  18801. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  18802. Not a valid date!</span>
  18803. </div>
  18804. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  18805. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18806. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18807. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18808. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18809. </form>
  18810. </file>
  18811. <file name="protractor.js" type="protractor">
  18812. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  18813. var valid = element(by.binding('myForm.input.$valid'));
  18814. var input = element(by.model('example.value'));
  18815. // currently protractor/webdriver does not support
  18816. // sending keys to all known HTML5 input controls
  18817. // for various browsers (https://github.com/angular/protractor/issues/562).
  18818. function setInput(val) {
  18819. // set the value of the element and force validation.
  18820. var scr = "var ipt = document.getElementById('exampleInput'); " +
  18821. "ipt.value = '" + val + "';" +
  18822. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  18823. browser.executeScript(scr);
  18824. }
  18825. it('should initialize to model', function() {
  18826. expect(value.getText()).toContain('2010-12-28T14:57:00');
  18827. expect(valid.getText()).toContain('myForm.input.$valid = true');
  18828. });
  18829. it('should be invalid if empty', function() {
  18830. setInput('');
  18831. expect(value.getText()).toEqual('value =');
  18832. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18833. });
  18834. it('should be invalid if over max', function() {
  18835. setInput('2015-01-01T23:59:00');
  18836. expect(value.getText()).toContain('');
  18837. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18838. });
  18839. </file>
  18840. </example>
  18841. */
  18842. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  18843. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  18844. 'yyyy-MM-ddTHH:mm:ss.sss'),
  18845. /**
  18846. * @ngdoc input
  18847. * @name input[time]
  18848. *
  18849. * @description
  18850. * Input with time validation and transformation. In browsers that do not yet support
  18851. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  18852. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  18853. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  18854. *
  18855. * The model must always be a Date object, otherwise Angular will throw an error.
  18856. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18857. *
  18858. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18859. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18860. *
  18861. * @param {string} ngModel Assignable angular expression to data-bind to.
  18862. * @param {string=} name Property name of the form under which the control is published.
  18863. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  18864. * valid ISO time format (HH:mm:ss).
  18865. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a
  18866. * valid ISO time format (HH:mm:ss).
  18867. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18868. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18869. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18870. * `required` when you want to data-bind to the `required` attribute.
  18871. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18872. * interaction with the input element.
  18873. *
  18874. * @example
  18875. <example name="time-input-directive" module="timeExample">
  18876. <file name="index.html">
  18877. <script>
  18878. angular.module('timeExample', [])
  18879. .controller('DateController', ['$scope', function($scope) {
  18880. $scope.example = {
  18881. value: new Date(1970, 0, 1, 14, 57, 0)
  18882. };
  18883. }]);
  18884. </script>
  18885. <form name="myForm" ng-controller="DateController as dateCtrl">
  18886. <label for="exampleInput">Pick a between 8am and 5pm:</label>
  18887. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  18888. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  18889. <div role="alert">
  18890. <span class="error" ng-show="myForm.input.$error.required">
  18891. Required!</span>
  18892. <span class="error" ng-show="myForm.input.$error.time">
  18893. Not a valid date!</span>
  18894. </div>
  18895. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  18896. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18897. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18898. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18899. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18900. </form>
  18901. </file>
  18902. <file name="protractor.js" type="protractor">
  18903. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  18904. var valid = element(by.binding('myForm.input.$valid'));
  18905. var input = element(by.model('example.value'));
  18906. // currently protractor/webdriver does not support
  18907. // sending keys to all known HTML5 input controls
  18908. // for various browsers (https://github.com/angular/protractor/issues/562).
  18909. function setInput(val) {
  18910. // set the value of the element and force validation.
  18911. var scr = "var ipt = document.getElementById('exampleInput'); " +
  18912. "ipt.value = '" + val + "';" +
  18913. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  18914. browser.executeScript(scr);
  18915. }
  18916. it('should initialize to model', function() {
  18917. expect(value.getText()).toContain('14:57:00');
  18918. expect(valid.getText()).toContain('myForm.input.$valid = true');
  18919. });
  18920. it('should be invalid if empty', function() {
  18921. setInput('');
  18922. expect(value.getText()).toEqual('value =');
  18923. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18924. });
  18925. it('should be invalid if over max', function() {
  18926. setInput('23:59:00');
  18927. expect(value.getText()).toContain('');
  18928. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18929. });
  18930. </file>
  18931. </example>
  18932. */
  18933. 'time': createDateInputType('time', TIME_REGEXP,
  18934. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  18935. 'HH:mm:ss.sss'),
  18936. /**
  18937. * @ngdoc input
  18938. * @name input[week]
  18939. *
  18940. * @description
  18941. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  18942. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  18943. * week format (yyyy-W##), for example: `2013-W02`.
  18944. *
  18945. * The model must always be a Date object, otherwise Angular will throw an error.
  18946. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18947. *
  18948. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18949. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18950. *
  18951. * @param {string} ngModel Assignable angular expression to data-bind to.
  18952. * @param {string=} name Property name of the form under which the control is published.
  18953. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  18954. * valid ISO week format (yyyy-W##).
  18955. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  18956. * a valid ISO week format (yyyy-W##).
  18957. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18958. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18959. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18960. * `required` when you want to data-bind to the `required` attribute.
  18961. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18962. * interaction with the input element.
  18963. *
  18964. * @example
  18965. <example name="week-input-directive" module="weekExample">
  18966. <file name="index.html">
  18967. <script>
  18968. angular.module('weekExample', [])
  18969. .controller('DateController', ['$scope', function($scope) {
  18970. $scope.example = {
  18971. value: new Date(2013, 0, 3)
  18972. };
  18973. }]);
  18974. </script>
  18975. <form name="myForm" ng-controller="DateController as dateCtrl">
  18976. <label>Pick a date between in 2013:
  18977. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  18978. placeholder="YYYY-W##" min="2012-W32"
  18979. max="2013-W52" required />
  18980. </label>
  18981. <div role="alert">
  18982. <span class="error" ng-show="myForm.input.$error.required">
  18983. Required!</span>
  18984. <span class="error" ng-show="myForm.input.$error.week">
  18985. Not a valid date!</span>
  18986. </div>
  18987. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  18988. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18989. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18990. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18991. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18992. </form>
  18993. </file>
  18994. <file name="protractor.js" type="protractor">
  18995. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  18996. var valid = element(by.binding('myForm.input.$valid'));
  18997. var input = element(by.model('example.value'));
  18998. // currently protractor/webdriver does not support
  18999. // sending keys to all known HTML5 input controls
  19000. // for various browsers (https://github.com/angular/protractor/issues/562).
  19001. function setInput(val) {
  19002. // set the value of the element and force validation.
  19003. var scr = "var ipt = document.getElementById('exampleInput'); " +
  19004. "ipt.value = '" + val + "';" +
  19005. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  19006. browser.executeScript(scr);
  19007. }
  19008. it('should initialize to model', function() {
  19009. expect(value.getText()).toContain('2013-W01');
  19010. expect(valid.getText()).toContain('myForm.input.$valid = true');
  19011. });
  19012. it('should be invalid if empty', function() {
  19013. setInput('');
  19014. expect(value.getText()).toEqual('value =');
  19015. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19016. });
  19017. it('should be invalid if over max', function() {
  19018. setInput('2015-W01');
  19019. expect(value.getText()).toContain('');
  19020. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19021. });
  19022. </file>
  19023. </example>
  19024. */
  19025. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  19026. /**
  19027. * @ngdoc input
  19028. * @name input[month]
  19029. *
  19030. * @description
  19031. * Input with month validation and transformation. In browsers that do not yet support
  19032. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  19033. * month format (yyyy-MM), for example: `2009-01`.
  19034. *
  19035. * The model must always be a Date object, otherwise Angular will throw an error.
  19036. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  19037. * If the model is not set to the first of the month, the next view to model update will set it
  19038. * to the first of the month.
  19039. *
  19040. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  19041. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  19042. *
  19043. * @param {string} ngModel Assignable angular expression to data-bind to.
  19044. * @param {string=} name Property name of the form under which the control is published.
  19045. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be
  19046. * a valid ISO month format (yyyy-MM).
  19047. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must
  19048. * be a valid ISO month format (yyyy-MM).
  19049. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19050. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19051. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19052. * `required` when you want to data-bind to the `required` attribute.
  19053. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19054. * interaction with the input element.
  19055. *
  19056. * @example
  19057. <example name="month-input-directive" module="monthExample">
  19058. <file name="index.html">
  19059. <script>
  19060. angular.module('monthExample', [])
  19061. .controller('DateController', ['$scope', function($scope) {
  19062. $scope.example = {
  19063. value: new Date(2013, 9, 1)
  19064. };
  19065. }]);
  19066. </script>
  19067. <form name="myForm" ng-controller="DateController as dateCtrl">
  19068. <label for="exampleInput">Pick a month in 2013:</label>
  19069. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  19070. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  19071. <div role="alert">
  19072. <span class="error" ng-show="myForm.input.$error.required">
  19073. Required!</span>
  19074. <span class="error" ng-show="myForm.input.$error.month">
  19075. Not a valid month!</span>
  19076. </div>
  19077. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  19078. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19079. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19080. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19081. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19082. </form>
  19083. </file>
  19084. <file name="protractor.js" type="protractor">
  19085. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  19086. var valid = element(by.binding('myForm.input.$valid'));
  19087. var input = element(by.model('example.value'));
  19088. // currently protractor/webdriver does not support
  19089. // sending keys to all known HTML5 input controls
  19090. // for various browsers (https://github.com/angular/protractor/issues/562).
  19091. function setInput(val) {
  19092. // set the value of the element and force validation.
  19093. var scr = "var ipt = document.getElementById('exampleInput'); " +
  19094. "ipt.value = '" + val + "';" +
  19095. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  19096. browser.executeScript(scr);
  19097. }
  19098. it('should initialize to model', function() {
  19099. expect(value.getText()).toContain('2013-10');
  19100. expect(valid.getText()).toContain('myForm.input.$valid = true');
  19101. });
  19102. it('should be invalid if empty', function() {
  19103. setInput('');
  19104. expect(value.getText()).toEqual('value =');
  19105. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19106. });
  19107. it('should be invalid if over max', function() {
  19108. setInput('2015-01');
  19109. expect(value.getText()).toContain('');
  19110. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19111. });
  19112. </file>
  19113. </example>
  19114. */
  19115. 'month': createDateInputType('month', MONTH_REGEXP,
  19116. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  19117. 'yyyy-MM'),
  19118. /**
  19119. * @ngdoc input
  19120. * @name input[number]
  19121. *
  19122. * @description
  19123. * Text input with number validation and transformation. Sets the `number` validation
  19124. * error if not a valid number.
  19125. *
  19126. * <div class="alert alert-warning">
  19127. * The model must always be of type `number` otherwise Angular will throw an error.
  19128. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  19129. * error docs for more information and an example of how to convert your model if necessary.
  19130. * </div>
  19131. *
  19132. * ## Issues with HTML5 constraint validation
  19133. *
  19134. * In browsers that follow the
  19135. * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
  19136. * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
  19137. * If a non-number is entered in the input, the browser will report the value as an empty string,
  19138. * which means the view / model values in `ngModel` and subsequently the scope value
  19139. * will also be an empty string.
  19140. *
  19141. *
  19142. * @param {string} ngModel Assignable angular expression to data-bind to.
  19143. * @param {string=} name Property name of the form under which the control is published.
  19144. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  19145. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  19146. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19147. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19148. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19149. * `required` when you want to data-bind to the `required` attribute.
  19150. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19151. * minlength.
  19152. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19153. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19154. * any length.
  19155. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19156. * that contains the regular expression body that will be converted to a regular expression
  19157. * as in the ngPattern directive.
  19158. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19159. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19160. * If the expression evaluates to a RegExp object, then this is used directly.
  19161. * If the expression evaluates to a string, then it will be converted to a RegExp
  19162. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19163. * `new RegExp('^abc$')`.<br />
  19164. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19165. * start at the index of the last search's match, thus not taking the whole input value into
  19166. * account.
  19167. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19168. * interaction with the input element.
  19169. *
  19170. * @example
  19171. <example name="number-input-directive" module="numberExample">
  19172. <file name="index.html">
  19173. <script>
  19174. angular.module('numberExample', [])
  19175. .controller('ExampleController', ['$scope', function($scope) {
  19176. $scope.example = {
  19177. value: 12
  19178. };
  19179. }]);
  19180. </script>
  19181. <form name="myForm" ng-controller="ExampleController">
  19182. <label>Number:
  19183. <input type="number" name="input" ng-model="example.value"
  19184. min="0" max="99" required>
  19185. </label>
  19186. <div role="alert">
  19187. <span class="error" ng-show="myForm.input.$error.required">
  19188. Required!</span>
  19189. <span class="error" ng-show="myForm.input.$error.number">
  19190. Not valid number!</span>
  19191. </div>
  19192. <tt>value = {{example.value}}</tt><br/>
  19193. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19194. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19195. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19196. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19197. </form>
  19198. </file>
  19199. <file name="protractor.js" type="protractor">
  19200. var value = element(by.binding('example.value'));
  19201. var valid = element(by.binding('myForm.input.$valid'));
  19202. var input = element(by.model('example.value'));
  19203. it('should initialize to model', function() {
  19204. expect(value.getText()).toContain('12');
  19205. expect(valid.getText()).toContain('true');
  19206. });
  19207. it('should be invalid if empty', function() {
  19208. input.clear();
  19209. input.sendKeys('');
  19210. expect(value.getText()).toEqual('value =');
  19211. expect(valid.getText()).toContain('false');
  19212. });
  19213. it('should be invalid if over max', function() {
  19214. input.clear();
  19215. input.sendKeys('123');
  19216. expect(value.getText()).toEqual('value =');
  19217. expect(valid.getText()).toContain('false');
  19218. });
  19219. </file>
  19220. </example>
  19221. */
  19222. 'number': numberInputType,
  19223. /**
  19224. * @ngdoc input
  19225. * @name input[url]
  19226. *
  19227. * @description
  19228. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  19229. * valid URL.
  19230. *
  19231. * <div class="alert alert-warning">
  19232. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  19233. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  19234. * the built-in validators (see the {@link guide/forms Forms guide})
  19235. * </div>
  19236. *
  19237. * @param {string} ngModel Assignable angular expression to data-bind to.
  19238. * @param {string=} name Property name of the form under which the control is published.
  19239. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19240. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19241. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19242. * `required` when you want to data-bind to the `required` attribute.
  19243. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19244. * minlength.
  19245. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19246. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19247. * any length.
  19248. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19249. * that contains the regular expression body that will be converted to a regular expression
  19250. * as in the ngPattern directive.
  19251. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19252. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19253. * If the expression evaluates to a RegExp object, then this is used directly.
  19254. * If the expression evaluates to a string, then it will be converted to a RegExp
  19255. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19256. * `new RegExp('^abc$')`.<br />
  19257. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19258. * start at the index of the last search's match, thus not taking the whole input value into
  19259. * account.
  19260. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19261. * interaction with the input element.
  19262. *
  19263. * @example
  19264. <example name="url-input-directive" module="urlExample">
  19265. <file name="index.html">
  19266. <script>
  19267. angular.module('urlExample', [])
  19268. .controller('ExampleController', ['$scope', function($scope) {
  19269. $scope.url = {
  19270. text: 'http://google.com'
  19271. };
  19272. }]);
  19273. </script>
  19274. <form name="myForm" ng-controller="ExampleController">
  19275. <label>URL:
  19276. <input type="url" name="input" ng-model="url.text" required>
  19277. <label>
  19278. <div role="alert">
  19279. <span class="error" ng-show="myForm.input.$error.required">
  19280. Required!</span>
  19281. <span class="error" ng-show="myForm.input.$error.url">
  19282. Not valid url!</span>
  19283. </div>
  19284. <tt>text = {{url.text}}</tt><br/>
  19285. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19286. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19287. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19288. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19289. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  19290. </form>
  19291. </file>
  19292. <file name="protractor.js" type="protractor">
  19293. var text = element(by.binding('url.text'));
  19294. var valid = element(by.binding('myForm.input.$valid'));
  19295. var input = element(by.model('url.text'));
  19296. it('should initialize to model', function() {
  19297. expect(text.getText()).toContain('http://google.com');
  19298. expect(valid.getText()).toContain('true');
  19299. });
  19300. it('should be invalid if empty', function() {
  19301. input.clear();
  19302. input.sendKeys('');
  19303. expect(text.getText()).toEqual('text =');
  19304. expect(valid.getText()).toContain('false');
  19305. });
  19306. it('should be invalid if not url', function() {
  19307. input.clear();
  19308. input.sendKeys('box');
  19309. expect(valid.getText()).toContain('false');
  19310. });
  19311. </file>
  19312. </example>
  19313. */
  19314. 'url': urlInputType,
  19315. /**
  19316. * @ngdoc input
  19317. * @name input[email]
  19318. *
  19319. * @description
  19320. * Text input with email validation. Sets the `email` validation error key if not a valid email
  19321. * address.
  19322. *
  19323. * <div class="alert alert-warning">
  19324. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  19325. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  19326. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  19327. * </div>
  19328. *
  19329. * @param {string} ngModel Assignable angular expression to data-bind to.
  19330. * @param {string=} name Property name of the form under which the control is published.
  19331. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19332. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19333. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19334. * `required` when you want to data-bind to the `required` attribute.
  19335. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19336. * minlength.
  19337. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19338. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19339. * any length.
  19340. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19341. * that contains the regular expression body that will be converted to a regular expression
  19342. * as in the ngPattern directive.
  19343. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19344. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19345. * If the expression evaluates to a RegExp object, then this is used directly.
  19346. * If the expression evaluates to a string, then it will be converted to a RegExp
  19347. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19348. * `new RegExp('^abc$')`.<br />
  19349. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19350. * start at the index of the last search's match, thus not taking the whole input value into
  19351. * account.
  19352. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19353. * interaction with the input element.
  19354. *
  19355. * @example
  19356. <example name="email-input-directive" module="emailExample">
  19357. <file name="index.html">
  19358. <script>
  19359. angular.module('emailExample', [])
  19360. .controller('ExampleController', ['$scope', function($scope) {
  19361. $scope.email = {
  19362. text: 'me@example.com'
  19363. };
  19364. }]);
  19365. </script>
  19366. <form name="myForm" ng-controller="ExampleController">
  19367. <label>Email:
  19368. <input type="email" name="input" ng-model="email.text" required>
  19369. </label>
  19370. <div role="alert">
  19371. <span class="error" ng-show="myForm.input.$error.required">
  19372. Required!</span>
  19373. <span class="error" ng-show="myForm.input.$error.email">
  19374. Not valid email!</span>
  19375. </div>
  19376. <tt>text = {{email.text}}</tt><br/>
  19377. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19378. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19379. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19380. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19381. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  19382. </form>
  19383. </file>
  19384. <file name="protractor.js" type="protractor">
  19385. var text = element(by.binding('email.text'));
  19386. var valid = element(by.binding('myForm.input.$valid'));
  19387. var input = element(by.model('email.text'));
  19388. it('should initialize to model', function() {
  19389. expect(text.getText()).toContain('me@example.com');
  19390. expect(valid.getText()).toContain('true');
  19391. });
  19392. it('should be invalid if empty', function() {
  19393. input.clear();
  19394. input.sendKeys('');
  19395. expect(text.getText()).toEqual('text =');
  19396. expect(valid.getText()).toContain('false');
  19397. });
  19398. it('should be invalid if not email', function() {
  19399. input.clear();
  19400. input.sendKeys('xxx');
  19401. expect(valid.getText()).toContain('false');
  19402. });
  19403. </file>
  19404. </example>
  19405. */
  19406. 'email': emailInputType,
  19407. /**
  19408. * @ngdoc input
  19409. * @name input[radio]
  19410. *
  19411. * @description
  19412. * HTML radio button.
  19413. *
  19414. * @param {string} ngModel Assignable angular expression to data-bind to.
  19415. * @param {string} value The value to which the `ngModel` expression should be set when selected.
  19416. * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
  19417. * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
  19418. * @param {string=} name Property name of the form under which the control is published.
  19419. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19420. * interaction with the input element.
  19421. * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
  19422. * is selected. Should be used instead of the `value` attribute if you need
  19423. * a non-string `ngModel` (`boolean`, `array`, ...).
  19424. *
  19425. * @example
  19426. <example name="radio-input-directive" module="radioExample">
  19427. <file name="index.html">
  19428. <script>
  19429. angular.module('radioExample', [])
  19430. .controller('ExampleController', ['$scope', function($scope) {
  19431. $scope.color = {
  19432. name: 'blue'
  19433. };
  19434. $scope.specialValue = {
  19435. "id": "12345",
  19436. "value": "green"
  19437. };
  19438. }]);
  19439. </script>
  19440. <form name="myForm" ng-controller="ExampleController">
  19441. <label>
  19442. <input type="radio" ng-model="color.name" value="red">
  19443. Red
  19444. </label><br/>
  19445. <label>
  19446. <input type="radio" ng-model="color.name" ng-value="specialValue">
  19447. Green
  19448. </label><br/>
  19449. <label>
  19450. <input type="radio" ng-model="color.name" value="blue">
  19451. Blue
  19452. </label><br/>
  19453. <tt>color = {{color.name | json}}</tt><br/>
  19454. </form>
  19455. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  19456. </file>
  19457. <file name="protractor.js" type="protractor">
  19458. it('should change state', function() {
  19459. var color = element(by.binding('color.name'));
  19460. expect(color.getText()).toContain('blue');
  19461. element.all(by.model('color.name')).get(0).click();
  19462. expect(color.getText()).toContain('red');
  19463. });
  19464. </file>
  19465. </example>
  19466. */
  19467. 'radio': radioInputType,
  19468. /**
  19469. * @ngdoc input
  19470. * @name input[checkbox]
  19471. *
  19472. * @description
  19473. * HTML checkbox.
  19474. *
  19475. * @param {string} ngModel Assignable angular expression to data-bind to.
  19476. * @param {string=} name Property name of the form under which the control is published.
  19477. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  19478. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  19479. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19480. * interaction with the input element.
  19481. *
  19482. * @example
  19483. <example name="checkbox-input-directive" module="checkboxExample">
  19484. <file name="index.html">
  19485. <script>
  19486. angular.module('checkboxExample', [])
  19487. .controller('ExampleController', ['$scope', function($scope) {
  19488. $scope.checkboxModel = {
  19489. value1 : true,
  19490. value2 : 'YES'
  19491. };
  19492. }]);
  19493. </script>
  19494. <form name="myForm" ng-controller="ExampleController">
  19495. <label>Value1:
  19496. <input type="checkbox" ng-model="checkboxModel.value1">
  19497. </label><br/>
  19498. <label>Value2:
  19499. <input type="checkbox" ng-model="checkboxModel.value2"
  19500. ng-true-value="'YES'" ng-false-value="'NO'">
  19501. </label><br/>
  19502. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  19503. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  19504. </form>
  19505. </file>
  19506. <file name="protractor.js" type="protractor">
  19507. it('should change state', function() {
  19508. var value1 = element(by.binding('checkboxModel.value1'));
  19509. var value2 = element(by.binding('checkboxModel.value2'));
  19510. expect(value1.getText()).toContain('true');
  19511. expect(value2.getText()).toContain('YES');
  19512. element(by.model('checkboxModel.value1')).click();
  19513. element(by.model('checkboxModel.value2')).click();
  19514. expect(value1.getText()).toContain('false');
  19515. expect(value2.getText()).toContain('NO');
  19516. });
  19517. </file>
  19518. </example>
  19519. */
  19520. 'checkbox': checkboxInputType,
  19521. 'hidden': noop,
  19522. 'button': noop,
  19523. 'submit': noop,
  19524. 'reset': noop,
  19525. 'file': noop
  19526. };
  19527. function stringBasedInputType(ctrl) {
  19528. ctrl.$formatters.push(function(value) {
  19529. return ctrl.$isEmpty(value) ? value : value.toString();
  19530. });
  19531. }
  19532. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19533. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19534. stringBasedInputType(ctrl);
  19535. }
  19536. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19537. var type = lowercase(element[0].type);
  19538. // In composition mode, users are still inputing intermediate text buffer,
  19539. // hold the listener until composition is done.
  19540. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  19541. if (!$sniffer.android) {
  19542. var composing = false;
  19543. element.on('compositionstart', function(data) {
  19544. composing = true;
  19545. });
  19546. element.on('compositionend', function() {
  19547. composing = false;
  19548. listener();
  19549. });
  19550. }
  19551. var listener = function(ev) {
  19552. if (timeout) {
  19553. $browser.defer.cancel(timeout);
  19554. timeout = null;
  19555. }
  19556. if (composing) return;
  19557. var value = element.val(),
  19558. event = ev && ev.type;
  19559. // By default we will trim the value
  19560. // If the attribute ng-trim exists we will avoid trimming
  19561. // If input type is 'password', the value is never trimmed
  19562. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  19563. value = trim(value);
  19564. }
  19565. // If a control is suffering from bad input (due to native validators), browsers discard its
  19566. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  19567. // control's value is the same empty value twice in a row.
  19568. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  19569. ctrl.$setViewValue(value, event);
  19570. }
  19571. };
  19572. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  19573. // input event on backspace, delete or cut
  19574. if ($sniffer.hasEvent('input')) {
  19575. element.on('input', listener);
  19576. } else {
  19577. var timeout;
  19578. var deferListener = function(ev, input, origValue) {
  19579. if (!timeout) {
  19580. timeout = $browser.defer(function() {
  19581. timeout = null;
  19582. if (!input || input.value !== origValue) {
  19583. listener(ev);
  19584. }
  19585. });
  19586. }
  19587. };
  19588. element.on('keydown', function(event) {
  19589. var key = event.keyCode;
  19590. // ignore
  19591. // command modifiers arrows
  19592. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  19593. deferListener(event, this, this.value);
  19594. });
  19595. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  19596. if ($sniffer.hasEvent('paste')) {
  19597. element.on('paste cut', deferListener);
  19598. }
  19599. }
  19600. // if user paste into input using mouse on older browser
  19601. // or form autocomplete on newer browser, we need "change" event to catch it
  19602. element.on('change', listener);
  19603. ctrl.$render = function() {
  19604. // Workaround for Firefox validation #12102.
  19605. var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
  19606. if (element.val() !== value) {
  19607. element.val(value);
  19608. }
  19609. };
  19610. }
  19611. function weekParser(isoWeek, existingDate) {
  19612. if (isDate(isoWeek)) {
  19613. return isoWeek;
  19614. }
  19615. if (isString(isoWeek)) {
  19616. WEEK_REGEXP.lastIndex = 0;
  19617. var parts = WEEK_REGEXP.exec(isoWeek);
  19618. if (parts) {
  19619. var year = +parts[1],
  19620. week = +parts[2],
  19621. hours = 0,
  19622. minutes = 0,
  19623. seconds = 0,
  19624. milliseconds = 0,
  19625. firstThurs = getFirstThursdayOfYear(year),
  19626. addDays = (week - 1) * 7;
  19627. if (existingDate) {
  19628. hours = existingDate.getHours();
  19629. minutes = existingDate.getMinutes();
  19630. seconds = existingDate.getSeconds();
  19631. milliseconds = existingDate.getMilliseconds();
  19632. }
  19633. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  19634. }
  19635. }
  19636. return NaN;
  19637. }
  19638. function createDateParser(regexp, mapping) {
  19639. return function(iso, date) {
  19640. var parts, map;
  19641. if (isDate(iso)) {
  19642. return iso;
  19643. }
  19644. if (isString(iso)) {
  19645. // When a date is JSON'ified to wraps itself inside of an extra
  19646. // set of double quotes. This makes the date parsing code unable
  19647. // to match the date string and parse it as a date.
  19648. if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
  19649. iso = iso.substring(1, iso.length - 1);
  19650. }
  19651. if (ISO_DATE_REGEXP.test(iso)) {
  19652. return new Date(iso);
  19653. }
  19654. regexp.lastIndex = 0;
  19655. parts = regexp.exec(iso);
  19656. if (parts) {
  19657. parts.shift();
  19658. if (date) {
  19659. map = {
  19660. yyyy: date.getFullYear(),
  19661. MM: date.getMonth() + 1,
  19662. dd: date.getDate(),
  19663. HH: date.getHours(),
  19664. mm: date.getMinutes(),
  19665. ss: date.getSeconds(),
  19666. sss: date.getMilliseconds() / 1000
  19667. };
  19668. } else {
  19669. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  19670. }
  19671. forEach(parts, function(part, index) {
  19672. if (index < mapping.length) {
  19673. map[mapping[index]] = +part;
  19674. }
  19675. });
  19676. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  19677. }
  19678. }
  19679. return NaN;
  19680. };
  19681. }
  19682. function createDateInputType(type, regexp, parseDate, format) {
  19683. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  19684. badInputChecker(scope, element, attr, ctrl);
  19685. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19686. var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
  19687. var previousDate;
  19688. ctrl.$$parserName = type;
  19689. ctrl.$parsers.push(function(value) {
  19690. if (ctrl.$isEmpty(value)) return null;
  19691. if (regexp.test(value)) {
  19692. // Note: We cannot read ctrl.$modelValue, as there might be a different
  19693. // parser/formatter in the processing chain so that the model
  19694. // contains some different data format!
  19695. var parsedDate = parseDate(value, previousDate);
  19696. if (timezone) {
  19697. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  19698. }
  19699. return parsedDate;
  19700. }
  19701. return undefined;
  19702. });
  19703. ctrl.$formatters.push(function(value) {
  19704. if (value && !isDate(value)) {
  19705. throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  19706. }
  19707. if (isValidDate(value)) {
  19708. previousDate = value;
  19709. if (previousDate && timezone) {
  19710. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  19711. }
  19712. return $filter('date')(value, format, timezone);
  19713. } else {
  19714. previousDate = null;
  19715. return '';
  19716. }
  19717. });
  19718. if (isDefined(attr.min) || attr.ngMin) {
  19719. var minVal;
  19720. ctrl.$validators.min = function(value) {
  19721. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  19722. };
  19723. attr.$observe('min', function(val) {
  19724. minVal = parseObservedDateValue(val);
  19725. ctrl.$validate();
  19726. });
  19727. }
  19728. if (isDefined(attr.max) || attr.ngMax) {
  19729. var maxVal;
  19730. ctrl.$validators.max = function(value) {
  19731. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  19732. };
  19733. attr.$observe('max', function(val) {
  19734. maxVal = parseObservedDateValue(val);
  19735. ctrl.$validate();
  19736. });
  19737. }
  19738. function isValidDate(value) {
  19739. // Invalid Date: getTime() returns NaN
  19740. return value && !(value.getTime && value.getTime() !== value.getTime());
  19741. }
  19742. function parseObservedDateValue(val) {
  19743. return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined;
  19744. }
  19745. };
  19746. }
  19747. function badInputChecker(scope, element, attr, ctrl) {
  19748. var node = element[0];
  19749. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  19750. if (nativeValidation) {
  19751. ctrl.$parsers.push(function(value) {
  19752. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  19753. // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):
  19754. // - also sets validity.badInput (should only be validity.typeMismatch).
  19755. // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)
  19756. // - can ignore this case as we can still read out the erroneous email...
  19757. return validity.badInput && !validity.typeMismatch ? undefined : value;
  19758. });
  19759. }
  19760. }
  19761. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19762. badInputChecker(scope, element, attr, ctrl);
  19763. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19764. ctrl.$$parserName = 'number';
  19765. ctrl.$parsers.push(function(value) {
  19766. if (ctrl.$isEmpty(value)) return null;
  19767. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  19768. return undefined;
  19769. });
  19770. ctrl.$formatters.push(function(value) {
  19771. if (!ctrl.$isEmpty(value)) {
  19772. if (!isNumber(value)) {
  19773. throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  19774. }
  19775. value = value.toString();
  19776. }
  19777. return value;
  19778. });
  19779. if (isDefined(attr.min) || attr.ngMin) {
  19780. var minVal;
  19781. ctrl.$validators.min = function(value) {
  19782. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  19783. };
  19784. attr.$observe('min', function(val) {
  19785. if (isDefined(val) && !isNumber(val)) {
  19786. val = parseFloat(val, 10);
  19787. }
  19788. minVal = isNumber(val) && !isNaN(val) ? val : undefined;
  19789. // TODO(matsko): implement validateLater to reduce number of validations
  19790. ctrl.$validate();
  19791. });
  19792. }
  19793. if (isDefined(attr.max) || attr.ngMax) {
  19794. var maxVal;
  19795. ctrl.$validators.max = function(value) {
  19796. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  19797. };
  19798. attr.$observe('max', function(val) {
  19799. if (isDefined(val) && !isNumber(val)) {
  19800. val = parseFloat(val, 10);
  19801. }
  19802. maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
  19803. // TODO(matsko): implement validateLater to reduce number of validations
  19804. ctrl.$validate();
  19805. });
  19806. }
  19807. }
  19808. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19809. // Note: no badInputChecker here by purpose as `url` is only a validation
  19810. // in browsers, i.e. we can always read out input.value even if it is not valid!
  19811. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19812. stringBasedInputType(ctrl);
  19813. ctrl.$$parserName = 'url';
  19814. ctrl.$validators.url = function(modelValue, viewValue) {
  19815. var value = modelValue || viewValue;
  19816. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  19817. };
  19818. }
  19819. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19820. // Note: no badInputChecker here by purpose as `url` is only a validation
  19821. // in browsers, i.e. we can always read out input.value even if it is not valid!
  19822. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19823. stringBasedInputType(ctrl);
  19824. ctrl.$$parserName = 'email';
  19825. ctrl.$validators.email = function(modelValue, viewValue) {
  19826. var value = modelValue || viewValue;
  19827. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  19828. };
  19829. }
  19830. function radioInputType(scope, element, attr, ctrl) {
  19831. // make the name unique, if not defined
  19832. if (isUndefined(attr.name)) {
  19833. element.attr('name', nextUid());
  19834. }
  19835. var listener = function(ev) {
  19836. if (element[0].checked) {
  19837. ctrl.$setViewValue(attr.value, ev && ev.type);
  19838. }
  19839. };
  19840. element.on('click', listener);
  19841. ctrl.$render = function() {
  19842. var value = attr.value;
  19843. element[0].checked = (value == ctrl.$viewValue);
  19844. };
  19845. attr.$observe('value', ctrl.$render);
  19846. }
  19847. function parseConstantExpr($parse, context, name, expression, fallback) {
  19848. var parseFn;
  19849. if (isDefined(expression)) {
  19850. parseFn = $parse(expression);
  19851. if (!parseFn.constant) {
  19852. throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  19853. '`{1}`.', name, expression);
  19854. }
  19855. return parseFn(context);
  19856. }
  19857. return fallback;
  19858. }
  19859. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  19860. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  19861. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  19862. var listener = function(ev) {
  19863. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  19864. };
  19865. element.on('click', listener);
  19866. ctrl.$render = function() {
  19867. element[0].checked = ctrl.$viewValue;
  19868. };
  19869. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  19870. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  19871. // it to a boolean.
  19872. ctrl.$isEmpty = function(value) {
  19873. return value === false;
  19874. };
  19875. ctrl.$formatters.push(function(value) {
  19876. return equals(value, trueValue);
  19877. });
  19878. ctrl.$parsers.push(function(value) {
  19879. return value ? trueValue : falseValue;
  19880. });
  19881. }
  19882. /**
  19883. * @ngdoc directive
  19884. * @name textarea
  19885. * @restrict E
  19886. *
  19887. * @description
  19888. * HTML textarea element control with angular data-binding. The data-binding and validation
  19889. * properties of this element are exactly the same as those of the
  19890. * {@link ng.directive:input input element}.
  19891. *
  19892. * @param {string} ngModel Assignable angular expression to data-bind to.
  19893. * @param {string=} name Property name of the form under which the control is published.
  19894. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19895. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19896. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19897. * `required` when you want to data-bind to the `required` attribute.
  19898. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19899. * minlength.
  19900. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19901. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  19902. * length.
  19903. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19904. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19905. * If the expression evaluates to a RegExp object, then this is used directly.
  19906. * If the expression evaluates to a string, then it will be converted to a RegExp
  19907. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19908. * `new RegExp('^abc$')`.<br />
  19909. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19910. * start at the index of the last search's match, thus not taking the whole input value into
  19911. * account.
  19912. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19913. * interaction with the input element.
  19914. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  19915. */
  19916. /**
  19917. * @ngdoc directive
  19918. * @name input
  19919. * @restrict E
  19920. *
  19921. * @description
  19922. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  19923. * input state control, and validation.
  19924. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  19925. *
  19926. * <div class="alert alert-warning">
  19927. * **Note:** Not every feature offered is available for all input types.
  19928. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  19929. * </div>
  19930. *
  19931. * @param {string} ngModel Assignable angular expression to data-bind to.
  19932. * @param {string=} name Property name of the form under which the control is published.
  19933. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19934. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  19935. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19936. * minlength.
  19937. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19938. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  19939. * length.
  19940. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19941. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19942. * If the expression evaluates to a RegExp object, then this is used directly.
  19943. * If the expression evaluates to a string, then it will be converted to a RegExp
  19944. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19945. * `new RegExp('^abc$')`.<br />
  19946. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19947. * start at the index of the last search's match, thus not taking the whole input value into
  19948. * account.
  19949. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19950. * interaction with the input element.
  19951. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  19952. * This parameter is ignored for input[type=password] controls, which will never trim the
  19953. * input.
  19954. *
  19955. * @example
  19956. <example name="input-directive" module="inputExample">
  19957. <file name="index.html">
  19958. <script>
  19959. angular.module('inputExample', [])
  19960. .controller('ExampleController', ['$scope', function($scope) {
  19961. $scope.user = {name: 'guest', last: 'visitor'};
  19962. }]);
  19963. </script>
  19964. <div ng-controller="ExampleController">
  19965. <form name="myForm">
  19966. <label>
  19967. User name:
  19968. <input type="text" name="userName" ng-model="user.name" required>
  19969. </label>
  19970. <div role="alert">
  19971. <span class="error" ng-show="myForm.userName.$error.required">
  19972. Required!</span>
  19973. </div>
  19974. <label>
  19975. Last name:
  19976. <input type="text" name="lastName" ng-model="user.last"
  19977. ng-minlength="3" ng-maxlength="10">
  19978. </label>
  19979. <div role="alert">
  19980. <span class="error" ng-show="myForm.lastName.$error.minlength">
  19981. Too short!</span>
  19982. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  19983. Too long!</span>
  19984. </div>
  19985. </form>
  19986. <hr>
  19987. <tt>user = {{user}}</tt><br/>
  19988. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  19989. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  19990. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  19991. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  19992. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19993. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19994. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  19995. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  19996. </div>
  19997. </file>
  19998. <file name="protractor.js" type="protractor">
  19999. var user = element(by.exactBinding('user'));
  20000. var userNameValid = element(by.binding('myForm.userName.$valid'));
  20001. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  20002. var lastNameError = element(by.binding('myForm.lastName.$error'));
  20003. var formValid = element(by.binding('myForm.$valid'));
  20004. var userNameInput = element(by.model('user.name'));
  20005. var userLastInput = element(by.model('user.last'));
  20006. it('should initialize to model', function() {
  20007. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  20008. expect(userNameValid.getText()).toContain('true');
  20009. expect(formValid.getText()).toContain('true');
  20010. });
  20011. it('should be invalid if empty when required', function() {
  20012. userNameInput.clear();
  20013. userNameInput.sendKeys('');
  20014. expect(user.getText()).toContain('{"last":"visitor"}');
  20015. expect(userNameValid.getText()).toContain('false');
  20016. expect(formValid.getText()).toContain('false');
  20017. });
  20018. it('should be valid if empty when min length is set', function() {
  20019. userLastInput.clear();
  20020. userLastInput.sendKeys('');
  20021. expect(user.getText()).toContain('{"name":"guest","last":""}');
  20022. expect(lastNameValid.getText()).toContain('true');
  20023. expect(formValid.getText()).toContain('true');
  20024. });
  20025. it('should be invalid if less than required min length', function() {
  20026. userLastInput.clear();
  20027. userLastInput.sendKeys('xx');
  20028. expect(user.getText()).toContain('{"name":"guest"}');
  20029. expect(lastNameValid.getText()).toContain('false');
  20030. expect(lastNameError.getText()).toContain('minlength');
  20031. expect(formValid.getText()).toContain('false');
  20032. });
  20033. it('should be invalid if longer than max length', function() {
  20034. userLastInput.clear();
  20035. userLastInput.sendKeys('some ridiculously long name');
  20036. expect(user.getText()).toContain('{"name":"guest"}');
  20037. expect(lastNameValid.getText()).toContain('false');
  20038. expect(lastNameError.getText()).toContain('maxlength');
  20039. expect(formValid.getText()).toContain('false');
  20040. });
  20041. </file>
  20042. </example>
  20043. */
  20044. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  20045. function($browser, $sniffer, $filter, $parse) {
  20046. return {
  20047. restrict: 'E',
  20048. require: ['?ngModel'],
  20049. link: {
  20050. pre: function(scope, element, attr, ctrls) {
  20051. if (ctrls[0]) {
  20052. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  20053. $browser, $filter, $parse);
  20054. }
  20055. }
  20056. }
  20057. };
  20058. }];
  20059. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  20060. /**
  20061. * @ngdoc directive
  20062. * @name ngValue
  20063. *
  20064. * @description
  20065. * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
  20066. * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
  20067. * the bound value.
  20068. *
  20069. * `ngValue` is useful when dynamically generating lists of radio buttons using
  20070. * {@link ngRepeat `ngRepeat`}, as shown below.
  20071. *
  20072. * Likewise, `ngValue` can be used to generate `<option>` elements for
  20073. * the {@link select `select`} element. In that case however, only strings are supported
  20074. * for the `value `attribute, so the resulting `ngModel` will always be a string.
  20075. * Support for `select` models with non-string values is available via `ngOptions`.
  20076. *
  20077. * @element input
  20078. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  20079. * of the `input` element
  20080. *
  20081. * @example
  20082. <example name="ngValue-directive" module="valueExample">
  20083. <file name="index.html">
  20084. <script>
  20085. angular.module('valueExample', [])
  20086. .controller('ExampleController', ['$scope', function($scope) {
  20087. $scope.names = ['pizza', 'unicorns', 'robots'];
  20088. $scope.my = { favorite: 'unicorns' };
  20089. }]);
  20090. </script>
  20091. <form ng-controller="ExampleController">
  20092. <h2>Which is your favorite?</h2>
  20093. <label ng-repeat="name in names" for="{{name}}">
  20094. {{name}}
  20095. <input type="radio"
  20096. ng-model="my.favorite"
  20097. ng-value="name"
  20098. id="{{name}}"
  20099. name="favorite">
  20100. </label>
  20101. <div>You chose {{my.favorite}}</div>
  20102. </form>
  20103. </file>
  20104. <file name="protractor.js" type="protractor">
  20105. var favorite = element(by.binding('my.favorite'));
  20106. it('should initialize to model', function() {
  20107. expect(favorite.getText()).toContain('unicorns');
  20108. });
  20109. it('should bind the values to the inputs', function() {
  20110. element.all(by.model('my.favorite')).get(0).click();
  20111. expect(favorite.getText()).toContain('pizza');
  20112. });
  20113. </file>
  20114. </example>
  20115. */
  20116. var ngValueDirective = function() {
  20117. return {
  20118. restrict: 'A',
  20119. priority: 100,
  20120. compile: function(tpl, tplAttr) {
  20121. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  20122. return function ngValueConstantLink(scope, elm, attr) {
  20123. attr.$set('value', scope.$eval(attr.ngValue));
  20124. };
  20125. } else {
  20126. return function ngValueLink(scope, elm, attr) {
  20127. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  20128. attr.$set('value', value);
  20129. });
  20130. };
  20131. }
  20132. }
  20133. };
  20134. };
  20135. /**
  20136. * @ngdoc directive
  20137. * @name ngBind
  20138. * @restrict AC
  20139. *
  20140. * @description
  20141. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  20142. * with the value of a given expression, and to update the text content when the value of that
  20143. * expression changes.
  20144. *
  20145. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  20146. * `{{ expression }}` which is similar but less verbose.
  20147. *
  20148. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  20149. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  20150. * element attribute, it makes the bindings invisible to the user while the page is loading.
  20151. *
  20152. * An alternative solution to this problem would be using the
  20153. * {@link ng.directive:ngCloak ngCloak} directive.
  20154. *
  20155. *
  20156. * @element ANY
  20157. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  20158. *
  20159. * @example
  20160. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  20161. <example module="bindExample">
  20162. <file name="index.html">
  20163. <script>
  20164. angular.module('bindExample', [])
  20165. .controller('ExampleController', ['$scope', function($scope) {
  20166. $scope.name = 'Whirled';
  20167. }]);
  20168. </script>
  20169. <div ng-controller="ExampleController">
  20170. <label>Enter name: <input type="text" ng-model="name"></label><br>
  20171. Hello <span ng-bind="name"></span>!
  20172. </div>
  20173. </file>
  20174. <file name="protractor.js" type="protractor">
  20175. it('should check ng-bind', function() {
  20176. var nameInput = element(by.model('name'));
  20177. expect(element(by.binding('name')).getText()).toBe('Whirled');
  20178. nameInput.clear();
  20179. nameInput.sendKeys('world');
  20180. expect(element(by.binding('name')).getText()).toBe('world');
  20181. });
  20182. </file>
  20183. </example>
  20184. */
  20185. var ngBindDirective = ['$compile', function($compile) {
  20186. return {
  20187. restrict: 'AC',
  20188. compile: function ngBindCompile(templateElement) {
  20189. $compile.$$addBindingClass(templateElement);
  20190. return function ngBindLink(scope, element, attr) {
  20191. $compile.$$addBindingInfo(element, attr.ngBind);
  20192. element = element[0];
  20193. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  20194. element.textContent = value === undefined ? '' : value;
  20195. });
  20196. };
  20197. }
  20198. };
  20199. }];
  20200. /**
  20201. * @ngdoc directive
  20202. * @name ngBindTemplate
  20203. *
  20204. * @description
  20205. * The `ngBindTemplate` directive specifies that the element
  20206. * text content should be replaced with the interpolation of the template
  20207. * in the `ngBindTemplate` attribute.
  20208. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  20209. * expressions. This directive is needed since some HTML elements
  20210. * (such as TITLE and OPTION) cannot contain SPAN elements.
  20211. *
  20212. * @element ANY
  20213. * @param {string} ngBindTemplate template of form
  20214. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  20215. *
  20216. * @example
  20217. * Try it here: enter text in text box and watch the greeting change.
  20218. <example module="bindExample">
  20219. <file name="index.html">
  20220. <script>
  20221. angular.module('bindExample', [])
  20222. .controller('ExampleController', ['$scope', function($scope) {
  20223. $scope.salutation = 'Hello';
  20224. $scope.name = 'World';
  20225. }]);
  20226. </script>
  20227. <div ng-controller="ExampleController">
  20228. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  20229. <label>Name: <input type="text" ng-model="name"></label><br>
  20230. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  20231. </div>
  20232. </file>
  20233. <file name="protractor.js" type="protractor">
  20234. it('should check ng-bind', function() {
  20235. var salutationElem = element(by.binding('salutation'));
  20236. var salutationInput = element(by.model('salutation'));
  20237. var nameInput = element(by.model('name'));
  20238. expect(salutationElem.getText()).toBe('Hello World!');
  20239. salutationInput.clear();
  20240. salutationInput.sendKeys('Greetings');
  20241. nameInput.clear();
  20242. nameInput.sendKeys('user');
  20243. expect(salutationElem.getText()).toBe('Greetings user!');
  20244. });
  20245. </file>
  20246. </example>
  20247. */
  20248. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  20249. return {
  20250. compile: function ngBindTemplateCompile(templateElement) {
  20251. $compile.$$addBindingClass(templateElement);
  20252. return function ngBindTemplateLink(scope, element, attr) {
  20253. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  20254. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  20255. element = element[0];
  20256. attr.$observe('ngBindTemplate', function(value) {
  20257. element.textContent = value === undefined ? '' : value;
  20258. });
  20259. };
  20260. }
  20261. };
  20262. }];
  20263. /**
  20264. * @ngdoc directive
  20265. * @name ngBindHtml
  20266. *
  20267. * @description
  20268. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  20269. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  20270. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  20271. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  20272. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  20273. *
  20274. * You may also bypass sanitization for values you know are safe. To do so, bind to
  20275. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  20276. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  20277. *
  20278. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  20279. * will have an exception (instead of an exploit.)
  20280. *
  20281. * @element ANY
  20282. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  20283. *
  20284. * @example
  20285. <example module="bindHtmlExample" deps="angular-sanitize.js">
  20286. <file name="index.html">
  20287. <div ng-controller="ExampleController">
  20288. <p ng-bind-html="myHTML"></p>
  20289. </div>
  20290. </file>
  20291. <file name="script.js">
  20292. angular.module('bindHtmlExample', ['ngSanitize'])
  20293. .controller('ExampleController', ['$scope', function($scope) {
  20294. $scope.myHTML =
  20295. 'I am an <code>HTML</code>string with ' +
  20296. '<a href="#">links!</a> and other <em>stuff</em>';
  20297. }]);
  20298. </file>
  20299. <file name="protractor.js" type="protractor">
  20300. it('should check ng-bind-html', function() {
  20301. expect(element(by.binding('myHTML')).getText()).toBe(
  20302. 'I am an HTMLstring with links! and other stuff');
  20303. });
  20304. </file>
  20305. </example>
  20306. */
  20307. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  20308. return {
  20309. restrict: 'A',
  20310. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  20311. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  20312. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
  20313. return (value || '').toString();
  20314. });
  20315. $compile.$$addBindingClass(tElement);
  20316. return function ngBindHtmlLink(scope, element, attr) {
  20317. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  20318. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  20319. // we re-evaluate the expr because we want a TrustedValueHolderType
  20320. // for $sce, not a string
  20321. element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
  20322. });
  20323. };
  20324. }
  20325. };
  20326. }];
  20327. /**
  20328. * @ngdoc directive
  20329. * @name ngChange
  20330. *
  20331. * @description
  20332. * Evaluate the given expression when the user changes the input.
  20333. * The expression is evaluated immediately, unlike the JavaScript onchange event
  20334. * which only triggers at the end of a change (usually, when the user leaves the
  20335. * form element or presses the return key).
  20336. *
  20337. * The `ngChange` expression is only evaluated when a change in the input value causes
  20338. * a new value to be committed to the model.
  20339. *
  20340. * It will not be evaluated:
  20341. * * if the value returned from the `$parsers` transformation pipeline has not changed
  20342. * * if the input has continued to be invalid since the model will stay `null`
  20343. * * if the model is changed programmatically and not by a change to the input value
  20344. *
  20345. *
  20346. * Note, this directive requires `ngModel` to be present.
  20347. *
  20348. * @element input
  20349. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  20350. * in input value.
  20351. *
  20352. * @example
  20353. * <example name="ngChange-directive" module="changeExample">
  20354. * <file name="index.html">
  20355. * <script>
  20356. * angular.module('changeExample', [])
  20357. * .controller('ExampleController', ['$scope', function($scope) {
  20358. * $scope.counter = 0;
  20359. * $scope.change = function() {
  20360. * $scope.counter++;
  20361. * };
  20362. * }]);
  20363. * </script>
  20364. * <div ng-controller="ExampleController">
  20365. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  20366. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  20367. * <label for="ng-change-example2">Confirmed</label><br />
  20368. * <tt>debug = {{confirmed}}</tt><br/>
  20369. * <tt>counter = {{counter}}</tt><br/>
  20370. * </div>
  20371. * </file>
  20372. * <file name="protractor.js" type="protractor">
  20373. * var counter = element(by.binding('counter'));
  20374. * var debug = element(by.binding('confirmed'));
  20375. *
  20376. * it('should evaluate the expression if changing from view', function() {
  20377. * expect(counter.getText()).toContain('0');
  20378. *
  20379. * element(by.id('ng-change-example1')).click();
  20380. *
  20381. * expect(counter.getText()).toContain('1');
  20382. * expect(debug.getText()).toContain('true');
  20383. * });
  20384. *
  20385. * it('should not evaluate the expression if changing from model', function() {
  20386. * element(by.id('ng-change-example2')).click();
  20387. * expect(counter.getText()).toContain('0');
  20388. * expect(debug.getText()).toContain('true');
  20389. * });
  20390. * </file>
  20391. * </example>
  20392. */
  20393. var ngChangeDirective = valueFn({
  20394. restrict: 'A',
  20395. require: 'ngModel',
  20396. link: function(scope, element, attr, ctrl) {
  20397. ctrl.$viewChangeListeners.push(function() {
  20398. scope.$eval(attr.ngChange);
  20399. });
  20400. }
  20401. });
  20402. function classDirective(name, selector) {
  20403. name = 'ngClass' + name;
  20404. return ['$animate', function($animate) {
  20405. return {
  20406. restrict: 'AC',
  20407. link: function(scope, element, attr) {
  20408. var oldVal;
  20409. scope.$watch(attr[name], ngClassWatchAction, true);
  20410. attr.$observe('class', function(value) {
  20411. ngClassWatchAction(scope.$eval(attr[name]));
  20412. });
  20413. if (name !== 'ngClass') {
  20414. scope.$watch('$index', function($index, old$index) {
  20415. // jshint bitwise: false
  20416. var mod = $index & 1;
  20417. if (mod !== (old$index & 1)) {
  20418. var classes = arrayClasses(scope.$eval(attr[name]));
  20419. mod === selector ?
  20420. addClasses(classes) :
  20421. removeClasses(classes);
  20422. }
  20423. });
  20424. }
  20425. function addClasses(classes) {
  20426. var newClasses = digestClassCounts(classes, 1);
  20427. attr.$addClass(newClasses);
  20428. }
  20429. function removeClasses(classes) {
  20430. var newClasses = digestClassCounts(classes, -1);
  20431. attr.$removeClass(newClasses);
  20432. }
  20433. function digestClassCounts(classes, count) {
  20434. // Use createMap() to prevent class assumptions involving property
  20435. // names in Object.prototype
  20436. var classCounts = element.data('$classCounts') || createMap();
  20437. var classesToUpdate = [];
  20438. forEach(classes, function(className) {
  20439. if (count > 0 || classCounts[className]) {
  20440. classCounts[className] = (classCounts[className] || 0) + count;
  20441. if (classCounts[className] === +(count > 0)) {
  20442. classesToUpdate.push(className);
  20443. }
  20444. }
  20445. });
  20446. element.data('$classCounts', classCounts);
  20447. return classesToUpdate.join(' ');
  20448. }
  20449. function updateClasses(oldClasses, newClasses) {
  20450. var toAdd = arrayDifference(newClasses, oldClasses);
  20451. var toRemove = arrayDifference(oldClasses, newClasses);
  20452. toAdd = digestClassCounts(toAdd, 1);
  20453. toRemove = digestClassCounts(toRemove, -1);
  20454. if (toAdd && toAdd.length) {
  20455. $animate.addClass(element, toAdd);
  20456. }
  20457. if (toRemove && toRemove.length) {
  20458. $animate.removeClass(element, toRemove);
  20459. }
  20460. }
  20461. function ngClassWatchAction(newVal) {
  20462. if (selector === true || scope.$index % 2 === selector) {
  20463. var newClasses = arrayClasses(newVal || []);
  20464. if (!oldVal) {
  20465. addClasses(newClasses);
  20466. } else if (!equals(newVal,oldVal)) {
  20467. var oldClasses = arrayClasses(oldVal);
  20468. updateClasses(oldClasses, newClasses);
  20469. }
  20470. }
  20471. oldVal = shallowCopy(newVal);
  20472. }
  20473. }
  20474. };
  20475. function arrayDifference(tokens1, tokens2) {
  20476. var values = [];
  20477. outer:
  20478. for (var i = 0; i < tokens1.length; i++) {
  20479. var token = tokens1[i];
  20480. for (var j = 0; j < tokens2.length; j++) {
  20481. if (token == tokens2[j]) continue outer;
  20482. }
  20483. values.push(token);
  20484. }
  20485. return values;
  20486. }
  20487. function arrayClasses(classVal) {
  20488. var classes = [];
  20489. if (isArray(classVal)) {
  20490. forEach(classVal, function(v) {
  20491. classes = classes.concat(arrayClasses(v));
  20492. });
  20493. return classes;
  20494. } else if (isString(classVal)) {
  20495. return classVal.split(' ');
  20496. } else if (isObject(classVal)) {
  20497. forEach(classVal, function(v, k) {
  20498. if (v) {
  20499. classes = classes.concat(k.split(' '));
  20500. }
  20501. });
  20502. return classes;
  20503. }
  20504. return classVal;
  20505. }
  20506. }];
  20507. }
  20508. /**
  20509. * @ngdoc directive
  20510. * @name ngClass
  20511. * @restrict AC
  20512. *
  20513. * @description
  20514. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  20515. * an expression that represents all classes to be added.
  20516. *
  20517. * The directive operates in three different ways, depending on which of three types the expression
  20518. * evaluates to:
  20519. *
  20520. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  20521. * names.
  20522. *
  20523. * 2. If the expression evaluates to an object, then for each key-value pair of the
  20524. * object with a truthy value the corresponding key is used as a class name.
  20525. *
  20526. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  20527. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  20528. * to give you more control over what CSS classes appear. See the code below for an example of this.
  20529. *
  20530. *
  20531. * The directive won't add duplicate classes if a particular class was already set.
  20532. *
  20533. * When the expression changes, the previously added classes are removed and only then are the
  20534. * new classes added.
  20535. *
  20536. * @animations
  20537. * **add** - happens just before the class is applied to the elements
  20538. *
  20539. * **remove** - happens just before the class is removed from the element
  20540. *
  20541. * @element ANY
  20542. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  20543. * of the evaluation can be a string representing space delimited class
  20544. * names, an array, or a map of class names to boolean values. In the case of a map, the
  20545. * names of the properties whose values are truthy will be added as css classes to the
  20546. * element.
  20547. *
  20548. * @example Example that demonstrates basic bindings via ngClass directive.
  20549. <example>
  20550. <file name="index.html">
  20551. <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
  20552. <label>
  20553. <input type="checkbox" ng-model="deleted">
  20554. deleted (apply "strike" class)
  20555. </label><br>
  20556. <label>
  20557. <input type="checkbox" ng-model="important">
  20558. important (apply "bold" class)
  20559. </label><br>
  20560. <label>
  20561. <input type="checkbox" ng-model="error">
  20562. error (apply "has-error" class)
  20563. </label>
  20564. <hr>
  20565. <p ng-class="style">Using String Syntax</p>
  20566. <input type="text" ng-model="style"
  20567. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  20568. <hr>
  20569. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  20570. <input ng-model="style1"
  20571. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  20572. <input ng-model="style2"
  20573. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  20574. <input ng-model="style3"
  20575. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  20576. <hr>
  20577. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  20578. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  20579. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  20580. </file>
  20581. <file name="style.css">
  20582. .strike {
  20583. text-decoration: line-through;
  20584. }
  20585. .bold {
  20586. font-weight: bold;
  20587. }
  20588. .red {
  20589. color: red;
  20590. }
  20591. .has-error {
  20592. color: red;
  20593. background-color: yellow;
  20594. }
  20595. .orange {
  20596. color: orange;
  20597. }
  20598. </file>
  20599. <file name="protractor.js" type="protractor">
  20600. var ps = element.all(by.css('p'));
  20601. it('should let you toggle the class', function() {
  20602. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  20603. expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
  20604. element(by.model('important')).click();
  20605. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  20606. element(by.model('error')).click();
  20607. expect(ps.first().getAttribute('class')).toMatch(/has-error/);
  20608. });
  20609. it('should let you toggle string example', function() {
  20610. expect(ps.get(1).getAttribute('class')).toBe('');
  20611. element(by.model('style')).clear();
  20612. element(by.model('style')).sendKeys('red');
  20613. expect(ps.get(1).getAttribute('class')).toBe('red');
  20614. });
  20615. it('array example should have 3 classes', function() {
  20616. expect(ps.get(2).getAttribute('class')).toBe('');
  20617. element(by.model('style1')).sendKeys('bold');
  20618. element(by.model('style2')).sendKeys('strike');
  20619. element(by.model('style3')).sendKeys('red');
  20620. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  20621. });
  20622. it('array with map example should have 2 classes', function() {
  20623. expect(ps.last().getAttribute('class')).toBe('');
  20624. element(by.model('style4')).sendKeys('bold');
  20625. element(by.model('warning')).click();
  20626. expect(ps.last().getAttribute('class')).toBe('bold orange');
  20627. });
  20628. </file>
  20629. </example>
  20630. ## Animations
  20631. The example below demonstrates how to perform animations using ngClass.
  20632. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  20633. <file name="index.html">
  20634. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  20635. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  20636. <br>
  20637. <span class="base-class" ng-class="myVar">Sample Text</span>
  20638. </file>
  20639. <file name="style.css">
  20640. .base-class {
  20641. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20642. }
  20643. .base-class.my-class {
  20644. color: red;
  20645. font-size:3em;
  20646. }
  20647. </file>
  20648. <file name="protractor.js" type="protractor">
  20649. it('should check ng-class', function() {
  20650. expect(element(by.css('.base-class')).getAttribute('class')).not.
  20651. toMatch(/my-class/);
  20652. element(by.id('setbtn')).click();
  20653. expect(element(by.css('.base-class')).getAttribute('class')).
  20654. toMatch(/my-class/);
  20655. element(by.id('clearbtn')).click();
  20656. expect(element(by.css('.base-class')).getAttribute('class')).not.
  20657. toMatch(/my-class/);
  20658. });
  20659. </file>
  20660. </example>
  20661. ## ngClass and pre-existing CSS3 Transitions/Animations
  20662. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  20663. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  20664. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  20665. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  20666. {@link $animate#removeClass $animate.removeClass}.
  20667. */
  20668. var ngClassDirective = classDirective('', true);
  20669. /**
  20670. * @ngdoc directive
  20671. * @name ngClassOdd
  20672. * @restrict AC
  20673. *
  20674. * @description
  20675. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  20676. * {@link ng.directive:ngClass ngClass}, except they work in
  20677. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  20678. *
  20679. * This directive can be applied only within the scope of an
  20680. * {@link ng.directive:ngRepeat ngRepeat}.
  20681. *
  20682. * @element ANY
  20683. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  20684. * of the evaluation can be a string representing space delimited class names or an array.
  20685. *
  20686. * @example
  20687. <example>
  20688. <file name="index.html">
  20689. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  20690. <li ng-repeat="name in names">
  20691. <span ng-class-odd="'odd'" ng-class-even="'even'">
  20692. {{name}}
  20693. </span>
  20694. </li>
  20695. </ol>
  20696. </file>
  20697. <file name="style.css">
  20698. .odd {
  20699. color: red;
  20700. }
  20701. .even {
  20702. color: blue;
  20703. }
  20704. </file>
  20705. <file name="protractor.js" type="protractor">
  20706. it('should check ng-class-odd and ng-class-even', function() {
  20707. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  20708. toMatch(/odd/);
  20709. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  20710. toMatch(/even/);
  20711. });
  20712. </file>
  20713. </example>
  20714. */
  20715. var ngClassOddDirective = classDirective('Odd', 0);
  20716. /**
  20717. * @ngdoc directive
  20718. * @name ngClassEven
  20719. * @restrict AC
  20720. *
  20721. * @description
  20722. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  20723. * {@link ng.directive:ngClass ngClass}, except they work in
  20724. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  20725. *
  20726. * This directive can be applied only within the scope of an
  20727. * {@link ng.directive:ngRepeat ngRepeat}.
  20728. *
  20729. * @element ANY
  20730. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  20731. * result of the evaluation can be a string representing space delimited class names or an array.
  20732. *
  20733. * @example
  20734. <example>
  20735. <file name="index.html">
  20736. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  20737. <li ng-repeat="name in names">
  20738. <span ng-class-odd="'odd'" ng-class-even="'even'">
  20739. {{name}} &nbsp; &nbsp; &nbsp;
  20740. </span>
  20741. </li>
  20742. </ol>
  20743. </file>
  20744. <file name="style.css">
  20745. .odd {
  20746. color: red;
  20747. }
  20748. .even {
  20749. color: blue;
  20750. }
  20751. </file>
  20752. <file name="protractor.js" type="protractor">
  20753. it('should check ng-class-odd and ng-class-even', function() {
  20754. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  20755. toMatch(/odd/);
  20756. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  20757. toMatch(/even/);
  20758. });
  20759. </file>
  20760. </example>
  20761. */
  20762. var ngClassEvenDirective = classDirective('Even', 1);
  20763. /**
  20764. * @ngdoc directive
  20765. * @name ngCloak
  20766. * @restrict AC
  20767. *
  20768. * @description
  20769. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  20770. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  20771. * directive to avoid the undesirable flicker effect caused by the html template display.
  20772. *
  20773. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  20774. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  20775. * of the browser view.
  20776. *
  20777. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  20778. * `angular.min.js`.
  20779. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  20780. *
  20781. * ```css
  20782. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  20783. * display: none !important;
  20784. * }
  20785. * ```
  20786. *
  20787. * When this css rule is loaded by the browser, all html elements (including their children) that
  20788. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  20789. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  20790. * the compiled element visible.
  20791. *
  20792. * For the best result, the `angular.js` script must be loaded in the head section of the html
  20793. * document; alternatively, the css rule above must be included in the external stylesheet of the
  20794. * application.
  20795. *
  20796. * @element ANY
  20797. *
  20798. * @example
  20799. <example>
  20800. <file name="index.html">
  20801. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  20802. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  20803. </file>
  20804. <file name="protractor.js" type="protractor">
  20805. it('should remove the template directive and css class', function() {
  20806. expect($('#template1').getAttribute('ng-cloak')).
  20807. toBeNull();
  20808. expect($('#template2').getAttribute('ng-cloak')).
  20809. toBeNull();
  20810. });
  20811. </file>
  20812. </example>
  20813. *
  20814. */
  20815. var ngCloakDirective = ngDirective({
  20816. compile: function(element, attr) {
  20817. attr.$set('ngCloak', undefined);
  20818. element.removeClass('ng-cloak');
  20819. }
  20820. });
  20821. /**
  20822. * @ngdoc directive
  20823. * @name ngController
  20824. *
  20825. * @description
  20826. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  20827. * supports the principles behind the Model-View-Controller design pattern.
  20828. *
  20829. * MVC components in angular:
  20830. *
  20831. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  20832. * are accessed through bindings.
  20833. * * View — The template (HTML with data bindings) that is rendered into the View.
  20834. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  20835. * logic behind the application to decorate the scope with functions and values
  20836. *
  20837. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  20838. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  20839. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  20840. * and executed twice.
  20841. *
  20842. * @element ANY
  20843. * @scope
  20844. * @priority 500
  20845. * @param {expression} ngController Name of a constructor function registered with the current
  20846. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  20847. * that on the current scope evaluates to a constructor function.
  20848. *
  20849. * The controller instance can be published into a scope property by specifying
  20850. * `ng-controller="as propertyName"`.
  20851. *
  20852. * If the current `$controllerProvider` is configured to use globals (via
  20853. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  20854. * also be the name of a globally accessible constructor function (not recommended).
  20855. *
  20856. * @example
  20857. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  20858. * greeting are methods declared on the controller (see source tab). These methods can
  20859. * easily be called from the angular markup. Any changes to the data are automatically reflected
  20860. * in the View without the need for a manual update.
  20861. *
  20862. * Two different declaration styles are included below:
  20863. *
  20864. * * one binds methods and properties directly onto the controller using `this`:
  20865. * `ng-controller="SettingsController1 as settings"`
  20866. * * one injects `$scope` into the controller:
  20867. * `ng-controller="SettingsController2"`
  20868. *
  20869. * The second option is more common in the Angular community, and is generally used in boilerplates
  20870. * and in this guide. However, there are advantages to binding properties directly to the controller
  20871. * and avoiding scope.
  20872. *
  20873. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  20874. * multiple controllers apply to an element.
  20875. * * If you are writing your controllers as classes you have easier access to the properties and
  20876. * methods, which will appear on the scope, from inside the controller code.
  20877. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  20878. * inheritance masking primitives.
  20879. *
  20880. * This example demonstrates the `controller as` syntax.
  20881. *
  20882. * <example name="ngControllerAs" module="controllerAsExample">
  20883. * <file name="index.html">
  20884. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  20885. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  20886. * <button ng-click="settings.greet()">greet</button><br/>
  20887. * Contact:
  20888. * <ul>
  20889. * <li ng-repeat="contact in settings.contacts">
  20890. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  20891. * <option>phone</option>
  20892. * <option>email</option>
  20893. * </select>
  20894. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  20895. * <button ng-click="settings.clearContact(contact)">clear</button>
  20896. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  20897. * </li>
  20898. * <li><button ng-click="settings.addContact()">add</button></li>
  20899. * </ul>
  20900. * </div>
  20901. * </file>
  20902. * <file name="app.js">
  20903. * angular.module('controllerAsExample', [])
  20904. * .controller('SettingsController1', SettingsController1);
  20905. *
  20906. * function SettingsController1() {
  20907. * this.name = "John Smith";
  20908. * this.contacts = [
  20909. * {type: 'phone', value: '408 555 1212'},
  20910. * {type: 'email', value: 'john.smith@example.org'} ];
  20911. * }
  20912. *
  20913. * SettingsController1.prototype.greet = function() {
  20914. * alert(this.name);
  20915. * };
  20916. *
  20917. * SettingsController1.prototype.addContact = function() {
  20918. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  20919. * };
  20920. *
  20921. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  20922. * var index = this.contacts.indexOf(contactToRemove);
  20923. * this.contacts.splice(index, 1);
  20924. * };
  20925. *
  20926. * SettingsController1.prototype.clearContact = function(contact) {
  20927. * contact.type = 'phone';
  20928. * contact.value = '';
  20929. * };
  20930. * </file>
  20931. * <file name="protractor.js" type="protractor">
  20932. * it('should check controller as', function() {
  20933. * var container = element(by.id('ctrl-as-exmpl'));
  20934. * expect(container.element(by.model('settings.name'))
  20935. * .getAttribute('value')).toBe('John Smith');
  20936. *
  20937. * var firstRepeat =
  20938. * container.element(by.repeater('contact in settings.contacts').row(0));
  20939. * var secondRepeat =
  20940. * container.element(by.repeater('contact in settings.contacts').row(1));
  20941. *
  20942. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20943. * .toBe('408 555 1212');
  20944. *
  20945. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  20946. * .toBe('john.smith@example.org');
  20947. *
  20948. * firstRepeat.element(by.buttonText('clear')).click();
  20949. *
  20950. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20951. * .toBe('');
  20952. *
  20953. * container.element(by.buttonText('add')).click();
  20954. *
  20955. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  20956. * .element(by.model('contact.value'))
  20957. * .getAttribute('value'))
  20958. * .toBe('yourname@example.org');
  20959. * });
  20960. * </file>
  20961. * </example>
  20962. *
  20963. * This example demonstrates the "attach to `$scope`" style of controller.
  20964. *
  20965. * <example name="ngController" module="controllerExample">
  20966. * <file name="index.html">
  20967. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  20968. * <label>Name: <input type="text" ng-model="name"/></label>
  20969. * <button ng-click="greet()">greet</button><br/>
  20970. * Contact:
  20971. * <ul>
  20972. * <li ng-repeat="contact in contacts">
  20973. * <select ng-model="contact.type" id="select_{{$index}}">
  20974. * <option>phone</option>
  20975. * <option>email</option>
  20976. * </select>
  20977. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  20978. * <button ng-click="clearContact(contact)">clear</button>
  20979. * <button ng-click="removeContact(contact)">X</button>
  20980. * </li>
  20981. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  20982. * </ul>
  20983. * </div>
  20984. * </file>
  20985. * <file name="app.js">
  20986. * angular.module('controllerExample', [])
  20987. * .controller('SettingsController2', ['$scope', SettingsController2]);
  20988. *
  20989. * function SettingsController2($scope) {
  20990. * $scope.name = "John Smith";
  20991. * $scope.contacts = [
  20992. * {type:'phone', value:'408 555 1212'},
  20993. * {type:'email', value:'john.smith@example.org'} ];
  20994. *
  20995. * $scope.greet = function() {
  20996. * alert($scope.name);
  20997. * };
  20998. *
  20999. * $scope.addContact = function() {
  21000. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  21001. * };
  21002. *
  21003. * $scope.removeContact = function(contactToRemove) {
  21004. * var index = $scope.contacts.indexOf(contactToRemove);
  21005. * $scope.contacts.splice(index, 1);
  21006. * };
  21007. *
  21008. * $scope.clearContact = function(contact) {
  21009. * contact.type = 'phone';
  21010. * contact.value = '';
  21011. * };
  21012. * }
  21013. * </file>
  21014. * <file name="protractor.js" type="protractor">
  21015. * it('should check controller', function() {
  21016. * var container = element(by.id('ctrl-exmpl'));
  21017. *
  21018. * expect(container.element(by.model('name'))
  21019. * .getAttribute('value')).toBe('John Smith');
  21020. *
  21021. * var firstRepeat =
  21022. * container.element(by.repeater('contact in contacts').row(0));
  21023. * var secondRepeat =
  21024. * container.element(by.repeater('contact in contacts').row(1));
  21025. *
  21026. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  21027. * .toBe('408 555 1212');
  21028. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  21029. * .toBe('john.smith@example.org');
  21030. *
  21031. * firstRepeat.element(by.buttonText('clear')).click();
  21032. *
  21033. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  21034. * .toBe('');
  21035. *
  21036. * container.element(by.buttonText('add')).click();
  21037. *
  21038. * expect(container.element(by.repeater('contact in contacts').row(2))
  21039. * .element(by.model('contact.value'))
  21040. * .getAttribute('value'))
  21041. * .toBe('yourname@example.org');
  21042. * });
  21043. * </file>
  21044. *</example>
  21045. */
  21046. var ngControllerDirective = [function() {
  21047. return {
  21048. restrict: 'A',
  21049. scope: true,
  21050. controller: '@',
  21051. priority: 500
  21052. };
  21053. }];
  21054. /**
  21055. * @ngdoc directive
  21056. * @name ngCsp
  21057. *
  21058. * @element html
  21059. * @description
  21060. *
  21061. * Angular has some features that can break certain
  21062. * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
  21063. *
  21064. * If you intend to implement these rules then you must tell Angular not to use these features.
  21065. *
  21066. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  21067. *
  21068. *
  21069. * The following rules affect Angular:
  21070. *
  21071. * * `unsafe-eval`: this rule forbids apps to use `eval` or `Function(string)` generated functions
  21072. * (among other things). Angular makes use of this in the {@link $parse} service to provide a 30%
  21073. * increase in the speed of evaluating Angular expressions.
  21074. *
  21075. * * `unsafe-inline`: this rule forbids apps from inject custom styles into the document. Angular
  21076. * makes use of this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}).
  21077. * To make these directives work when a CSP rule is blocking inline styles, you must link to the
  21078. * `angular-csp.css` in your HTML manually.
  21079. *
  21080. * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking unsafe-eval
  21081. * and automatically deactivates this feature in the {@link $parse} service. This autodetection,
  21082. * however, triggers a CSP error to be logged in the console:
  21083. *
  21084. * ```
  21085. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  21086. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  21087. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  21088. * ```
  21089. *
  21090. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  21091. * directive on an element of the HTML document that appears before the `<script>` tag that loads
  21092. * the `angular.js` file.
  21093. *
  21094. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  21095. *
  21096. * You can specify which of the CSP related Angular features should be deactivated by providing
  21097. * a value for the `ng-csp` attribute. The options are as follows:
  21098. *
  21099. * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
  21100. *
  21101. * * no-unsafe-eval: this stops Angular from optimising $parse with unsafe eval of strings
  21102. *
  21103. * You can use these values in the following combinations:
  21104. *
  21105. *
  21106. * * No declaration means that Angular will assume that you can do inline styles, but it will do
  21107. * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous versions
  21108. * of Angular.
  21109. *
  21110. * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
  21111. * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous versions
  21112. * of Angular.
  21113. *
  21114. * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can inject
  21115. * inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
  21116. *
  21117. * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
  21118. * run eval - no automcatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
  21119. *
  21120. * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
  21121. * styles nor use eval, which is the same as an empty: ng-csp.
  21122. * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
  21123. *
  21124. * @example
  21125. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  21126. ```html
  21127. <!doctype html>
  21128. <html ng-app ng-csp>
  21129. ...
  21130. ...
  21131. </html>
  21132. ```
  21133. * @example
  21134. // Note: the suffix `.csp` in the example name triggers
  21135. // csp mode in our http server!
  21136. <example name="example.csp" module="cspExample" ng-csp="true">
  21137. <file name="index.html">
  21138. <div ng-controller="MainController as ctrl">
  21139. <div>
  21140. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  21141. <span id="counter">
  21142. {{ctrl.counter}}
  21143. </span>
  21144. </div>
  21145. <div>
  21146. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  21147. <span id="evilError">
  21148. {{ctrl.evilError}}
  21149. </span>
  21150. </div>
  21151. </div>
  21152. </file>
  21153. <file name="script.js">
  21154. angular.module('cspExample', [])
  21155. .controller('MainController', function() {
  21156. this.counter = 0;
  21157. this.inc = function() {
  21158. this.counter++;
  21159. };
  21160. this.evil = function() {
  21161. // jshint evil:true
  21162. try {
  21163. eval('1+2');
  21164. } catch (e) {
  21165. this.evilError = e.message;
  21166. }
  21167. };
  21168. });
  21169. </file>
  21170. <file name="protractor.js" type="protractor">
  21171. var util, webdriver;
  21172. var incBtn = element(by.id('inc'));
  21173. var counter = element(by.id('counter'));
  21174. var evilBtn = element(by.id('evil'));
  21175. var evilError = element(by.id('evilError'));
  21176. function getAndClearSevereErrors() {
  21177. return browser.manage().logs().get('browser').then(function(browserLog) {
  21178. return browserLog.filter(function(logEntry) {
  21179. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  21180. });
  21181. });
  21182. }
  21183. function clearErrors() {
  21184. getAndClearSevereErrors();
  21185. }
  21186. function expectNoErrors() {
  21187. getAndClearSevereErrors().then(function(filteredLog) {
  21188. expect(filteredLog.length).toEqual(0);
  21189. if (filteredLog.length) {
  21190. console.log('browser console errors: ' + util.inspect(filteredLog));
  21191. }
  21192. });
  21193. }
  21194. function expectError(regex) {
  21195. getAndClearSevereErrors().then(function(filteredLog) {
  21196. var found = false;
  21197. filteredLog.forEach(function(log) {
  21198. if (log.message.match(regex)) {
  21199. found = true;
  21200. }
  21201. });
  21202. if (!found) {
  21203. throw new Error('expected an error that matches ' + regex);
  21204. }
  21205. });
  21206. }
  21207. beforeEach(function() {
  21208. util = require('util');
  21209. webdriver = require('protractor/node_modules/selenium-webdriver');
  21210. });
  21211. // For now, we only test on Chrome,
  21212. // as Safari does not load the page with Protractor's injected scripts,
  21213. // and Firefox webdriver always disables content security policy (#6358)
  21214. if (browser.params.browser !== 'chrome') {
  21215. return;
  21216. }
  21217. it('should not report errors when the page is loaded', function() {
  21218. // clear errors so we are not dependent on previous tests
  21219. clearErrors();
  21220. // Need to reload the page as the page is already loaded when
  21221. // we come here
  21222. browser.driver.getCurrentUrl().then(function(url) {
  21223. browser.get(url);
  21224. });
  21225. expectNoErrors();
  21226. });
  21227. it('should evaluate expressions', function() {
  21228. expect(counter.getText()).toEqual('0');
  21229. incBtn.click();
  21230. expect(counter.getText()).toEqual('1');
  21231. expectNoErrors();
  21232. });
  21233. it('should throw and report an error when using "eval"', function() {
  21234. evilBtn.click();
  21235. expect(evilError.getText()).toMatch(/Content Security Policy/);
  21236. expectError(/Content Security Policy/);
  21237. });
  21238. </file>
  21239. </example>
  21240. */
  21241. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  21242. // bootstrap the system (before $parse is instantiated), for this reason we just have
  21243. // the csp() fn that looks for the `ng-csp` attribute anywhere in the current doc
  21244. /**
  21245. * @ngdoc directive
  21246. * @name ngClick
  21247. *
  21248. * @description
  21249. * The ngClick directive allows you to specify custom behavior when
  21250. * an element is clicked.
  21251. *
  21252. * @element ANY
  21253. * @priority 0
  21254. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  21255. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  21256. *
  21257. * @example
  21258. <example>
  21259. <file name="index.html">
  21260. <button ng-click="count = count + 1" ng-init="count=0">
  21261. Increment
  21262. </button>
  21263. <span>
  21264. count: {{count}}
  21265. </span>
  21266. </file>
  21267. <file name="protractor.js" type="protractor">
  21268. it('should check ng-click', function() {
  21269. expect(element(by.binding('count')).getText()).toMatch('0');
  21270. element(by.css('button')).click();
  21271. expect(element(by.binding('count')).getText()).toMatch('1');
  21272. });
  21273. </file>
  21274. </example>
  21275. */
  21276. /*
  21277. * A collection of directives that allows creation of custom event handlers that are defined as
  21278. * angular expressions and are compiled and executed within the current scope.
  21279. */
  21280. var ngEventDirectives = {};
  21281. // For events that might fire synchronously during DOM manipulation
  21282. // we need to execute their event handlers asynchronously using $evalAsync,
  21283. // so that they are not executed in an inconsistent state.
  21284. var forceAsyncEvents = {
  21285. 'blur': true,
  21286. 'focus': true
  21287. };
  21288. forEach(
  21289. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  21290. function(eventName) {
  21291. var directiveName = directiveNormalize('ng-' + eventName);
  21292. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  21293. return {
  21294. restrict: 'A',
  21295. compile: function($element, attr) {
  21296. // We expose the powerful $event object on the scope that provides access to the Window,
  21297. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  21298. // checks at the cost of speed since event handler expressions are not executed as
  21299. // frequently as regular change detection.
  21300. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
  21301. return function ngEventHandler(scope, element) {
  21302. element.on(eventName, function(event) {
  21303. var callback = function() {
  21304. fn(scope, {$event:event});
  21305. };
  21306. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  21307. scope.$evalAsync(callback);
  21308. } else {
  21309. scope.$apply(callback);
  21310. }
  21311. });
  21312. };
  21313. }
  21314. };
  21315. }];
  21316. }
  21317. );
  21318. /**
  21319. * @ngdoc directive
  21320. * @name ngDblclick
  21321. *
  21322. * @description
  21323. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  21324. *
  21325. * @element ANY
  21326. * @priority 0
  21327. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  21328. * a dblclick. (The Event object is available as `$event`)
  21329. *
  21330. * @example
  21331. <example>
  21332. <file name="index.html">
  21333. <button ng-dblclick="count = count + 1" ng-init="count=0">
  21334. Increment (on double click)
  21335. </button>
  21336. count: {{count}}
  21337. </file>
  21338. </example>
  21339. */
  21340. /**
  21341. * @ngdoc directive
  21342. * @name ngMousedown
  21343. *
  21344. * @description
  21345. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  21346. *
  21347. * @element ANY
  21348. * @priority 0
  21349. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  21350. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  21351. *
  21352. * @example
  21353. <example>
  21354. <file name="index.html">
  21355. <button ng-mousedown="count = count + 1" ng-init="count=0">
  21356. Increment (on mouse down)
  21357. </button>
  21358. count: {{count}}
  21359. </file>
  21360. </example>
  21361. */
  21362. /**
  21363. * @ngdoc directive
  21364. * @name ngMouseup
  21365. *
  21366. * @description
  21367. * Specify custom behavior on mouseup event.
  21368. *
  21369. * @element ANY
  21370. * @priority 0
  21371. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  21372. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  21373. *
  21374. * @example
  21375. <example>
  21376. <file name="index.html">
  21377. <button ng-mouseup="count = count + 1" ng-init="count=0">
  21378. Increment (on mouse up)
  21379. </button>
  21380. count: {{count}}
  21381. </file>
  21382. </example>
  21383. */
  21384. /**
  21385. * @ngdoc directive
  21386. * @name ngMouseover
  21387. *
  21388. * @description
  21389. * Specify custom behavior on mouseover event.
  21390. *
  21391. * @element ANY
  21392. * @priority 0
  21393. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  21394. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  21395. *
  21396. * @example
  21397. <example>
  21398. <file name="index.html">
  21399. <button ng-mouseover="count = count + 1" ng-init="count=0">
  21400. Increment (when mouse is over)
  21401. </button>
  21402. count: {{count}}
  21403. </file>
  21404. </example>
  21405. */
  21406. /**
  21407. * @ngdoc directive
  21408. * @name ngMouseenter
  21409. *
  21410. * @description
  21411. * Specify custom behavior on mouseenter event.
  21412. *
  21413. * @element ANY
  21414. * @priority 0
  21415. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  21416. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  21417. *
  21418. * @example
  21419. <example>
  21420. <file name="index.html">
  21421. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  21422. Increment (when mouse enters)
  21423. </button>
  21424. count: {{count}}
  21425. </file>
  21426. </example>
  21427. */
  21428. /**
  21429. * @ngdoc directive
  21430. * @name ngMouseleave
  21431. *
  21432. * @description
  21433. * Specify custom behavior on mouseleave event.
  21434. *
  21435. * @element ANY
  21436. * @priority 0
  21437. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  21438. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  21439. *
  21440. * @example
  21441. <example>
  21442. <file name="index.html">
  21443. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  21444. Increment (when mouse leaves)
  21445. </button>
  21446. count: {{count}}
  21447. </file>
  21448. </example>
  21449. */
  21450. /**
  21451. * @ngdoc directive
  21452. * @name ngMousemove
  21453. *
  21454. * @description
  21455. * Specify custom behavior on mousemove event.
  21456. *
  21457. * @element ANY
  21458. * @priority 0
  21459. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  21460. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  21461. *
  21462. * @example
  21463. <example>
  21464. <file name="index.html">
  21465. <button ng-mousemove="count = count + 1" ng-init="count=0">
  21466. Increment (when mouse moves)
  21467. </button>
  21468. count: {{count}}
  21469. </file>
  21470. </example>
  21471. */
  21472. /**
  21473. * @ngdoc directive
  21474. * @name ngKeydown
  21475. *
  21476. * @description
  21477. * Specify custom behavior on keydown event.
  21478. *
  21479. * @element ANY
  21480. * @priority 0
  21481. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  21482. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  21483. *
  21484. * @example
  21485. <example>
  21486. <file name="index.html">
  21487. <input ng-keydown="count = count + 1" ng-init="count=0">
  21488. key down count: {{count}}
  21489. </file>
  21490. </example>
  21491. */
  21492. /**
  21493. * @ngdoc directive
  21494. * @name ngKeyup
  21495. *
  21496. * @description
  21497. * Specify custom behavior on keyup event.
  21498. *
  21499. * @element ANY
  21500. * @priority 0
  21501. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  21502. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  21503. *
  21504. * @example
  21505. <example>
  21506. <file name="index.html">
  21507. <p>Typing in the input box below updates the key count</p>
  21508. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  21509. <p>Typing in the input box below updates the keycode</p>
  21510. <input ng-keyup="event=$event">
  21511. <p>event keyCode: {{ event.keyCode }}</p>
  21512. <p>event altKey: {{ event.altKey }}</p>
  21513. </file>
  21514. </example>
  21515. */
  21516. /**
  21517. * @ngdoc directive
  21518. * @name ngKeypress
  21519. *
  21520. * @description
  21521. * Specify custom behavior on keypress event.
  21522. *
  21523. * @element ANY
  21524. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  21525. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  21526. * and can be interrogated for keyCode, altKey, etc.)
  21527. *
  21528. * @example
  21529. <example>
  21530. <file name="index.html">
  21531. <input ng-keypress="count = count + 1" ng-init="count=0">
  21532. key press count: {{count}}
  21533. </file>
  21534. </example>
  21535. */
  21536. /**
  21537. * @ngdoc directive
  21538. * @name ngSubmit
  21539. *
  21540. * @description
  21541. * Enables binding angular expressions to onsubmit events.
  21542. *
  21543. * Additionally it prevents the default action (which for form means sending the request to the
  21544. * server and reloading the current page), but only if the form does not contain `action`,
  21545. * `data-action`, or `x-action` attributes.
  21546. *
  21547. * <div class="alert alert-warning">
  21548. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  21549. * `ngSubmit` handlers together. See the
  21550. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  21551. * for a detailed discussion of when `ngSubmit` may be triggered.
  21552. * </div>
  21553. *
  21554. * @element form
  21555. * @priority 0
  21556. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  21557. * ({@link guide/expression#-event- Event object is available as `$event`})
  21558. *
  21559. * @example
  21560. <example module="submitExample">
  21561. <file name="index.html">
  21562. <script>
  21563. angular.module('submitExample', [])
  21564. .controller('ExampleController', ['$scope', function($scope) {
  21565. $scope.list = [];
  21566. $scope.text = 'hello';
  21567. $scope.submit = function() {
  21568. if ($scope.text) {
  21569. $scope.list.push(this.text);
  21570. $scope.text = '';
  21571. }
  21572. };
  21573. }]);
  21574. </script>
  21575. <form ng-submit="submit()" ng-controller="ExampleController">
  21576. Enter text and hit enter:
  21577. <input type="text" ng-model="text" name="text" />
  21578. <input type="submit" id="submit" value="Submit" />
  21579. <pre>list={{list}}</pre>
  21580. </form>
  21581. </file>
  21582. <file name="protractor.js" type="protractor">
  21583. it('should check ng-submit', function() {
  21584. expect(element(by.binding('list')).getText()).toBe('list=[]');
  21585. element(by.css('#submit')).click();
  21586. expect(element(by.binding('list')).getText()).toContain('hello');
  21587. expect(element(by.model('text')).getAttribute('value')).toBe('');
  21588. });
  21589. it('should ignore empty strings', function() {
  21590. expect(element(by.binding('list')).getText()).toBe('list=[]');
  21591. element(by.css('#submit')).click();
  21592. element(by.css('#submit')).click();
  21593. expect(element(by.binding('list')).getText()).toContain('hello');
  21594. });
  21595. </file>
  21596. </example>
  21597. */
  21598. /**
  21599. * @ngdoc directive
  21600. * @name ngFocus
  21601. *
  21602. * @description
  21603. * Specify custom behavior on focus event.
  21604. *
  21605. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  21606. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  21607. * during an `$apply` to ensure a consistent state.
  21608. *
  21609. * @element window, input, select, textarea, a
  21610. * @priority 0
  21611. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  21612. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  21613. *
  21614. * @example
  21615. * See {@link ng.directive:ngClick ngClick}
  21616. */
  21617. /**
  21618. * @ngdoc directive
  21619. * @name ngBlur
  21620. *
  21621. * @description
  21622. * Specify custom behavior on blur event.
  21623. *
  21624. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  21625. * an element has lost focus.
  21626. *
  21627. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  21628. * (e.g. removing a focussed input),
  21629. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  21630. * during an `$apply` to ensure a consistent state.
  21631. *
  21632. * @element window, input, select, textarea, a
  21633. * @priority 0
  21634. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  21635. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  21636. *
  21637. * @example
  21638. * See {@link ng.directive:ngClick ngClick}
  21639. */
  21640. /**
  21641. * @ngdoc directive
  21642. * @name ngCopy
  21643. *
  21644. * @description
  21645. * Specify custom behavior on copy event.
  21646. *
  21647. * @element window, input, select, textarea, a
  21648. * @priority 0
  21649. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  21650. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  21651. *
  21652. * @example
  21653. <example>
  21654. <file name="index.html">
  21655. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  21656. copied: {{copied}}
  21657. </file>
  21658. </example>
  21659. */
  21660. /**
  21661. * @ngdoc directive
  21662. * @name ngCut
  21663. *
  21664. * @description
  21665. * Specify custom behavior on cut event.
  21666. *
  21667. * @element window, input, select, textarea, a
  21668. * @priority 0
  21669. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  21670. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  21671. *
  21672. * @example
  21673. <example>
  21674. <file name="index.html">
  21675. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  21676. cut: {{cut}}
  21677. </file>
  21678. </example>
  21679. */
  21680. /**
  21681. * @ngdoc directive
  21682. * @name ngPaste
  21683. *
  21684. * @description
  21685. * Specify custom behavior on paste event.
  21686. *
  21687. * @element window, input, select, textarea, a
  21688. * @priority 0
  21689. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  21690. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  21691. *
  21692. * @example
  21693. <example>
  21694. <file name="index.html">
  21695. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  21696. pasted: {{paste}}
  21697. </file>
  21698. </example>
  21699. */
  21700. /**
  21701. * @ngdoc directive
  21702. * @name ngIf
  21703. * @restrict A
  21704. * @multiElement
  21705. *
  21706. * @description
  21707. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  21708. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  21709. * value then the element is removed from the DOM, otherwise a clone of the
  21710. * element is reinserted into the DOM.
  21711. *
  21712. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  21713. * element in the DOM rather than changing its visibility via the `display` css property. A common
  21714. * case when this difference is significant is when using css selectors that rely on an element's
  21715. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  21716. *
  21717. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  21718. * is created when the element is restored. The scope created within `ngIf` inherits from
  21719. * its parent scope using
  21720. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  21721. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  21722. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  21723. * variable within the child scope will override (hide) the value in the parent scope.
  21724. *
  21725. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  21726. * is if an element's class attribute is directly modified after it's compiled, using something like
  21727. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  21728. * the added class will be lost because the original compiled state is used to regenerate the element.
  21729. *
  21730. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  21731. * and `leave` effects.
  21732. *
  21733. * @animations
  21734. * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
  21735. * leave - happens just before the `ngIf` contents are removed from the DOM
  21736. *
  21737. * @element ANY
  21738. * @scope
  21739. * @priority 600
  21740. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  21741. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  21742. * element is added to the DOM tree.
  21743. *
  21744. * @example
  21745. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  21746. <file name="index.html">
  21747. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  21748. Show when checked:
  21749. <span ng-if="checked" class="animate-if">
  21750. This is removed when the checkbox is unchecked.
  21751. </span>
  21752. </file>
  21753. <file name="animations.css">
  21754. .animate-if {
  21755. background:white;
  21756. border:1px solid black;
  21757. padding:10px;
  21758. }
  21759. .animate-if.ng-enter, .animate-if.ng-leave {
  21760. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21761. }
  21762. .animate-if.ng-enter,
  21763. .animate-if.ng-leave.ng-leave-active {
  21764. opacity:0;
  21765. }
  21766. .animate-if.ng-leave,
  21767. .animate-if.ng-enter.ng-enter-active {
  21768. opacity:1;
  21769. }
  21770. </file>
  21771. </example>
  21772. */
  21773. var ngIfDirective = ['$animate', function($animate) {
  21774. return {
  21775. multiElement: true,
  21776. transclude: 'element',
  21777. priority: 600,
  21778. terminal: true,
  21779. restrict: 'A',
  21780. $$tlb: true,
  21781. link: function($scope, $element, $attr, ctrl, $transclude) {
  21782. var block, childScope, previousElements;
  21783. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  21784. if (value) {
  21785. if (!childScope) {
  21786. $transclude(function(clone, newScope) {
  21787. childScope = newScope;
  21788. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  21789. // Note: We only need the first/last node of the cloned nodes.
  21790. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  21791. // by a directive with templateUrl when its template arrives.
  21792. block = {
  21793. clone: clone
  21794. };
  21795. $animate.enter(clone, $element.parent(), $element);
  21796. });
  21797. }
  21798. } else {
  21799. if (previousElements) {
  21800. previousElements.remove();
  21801. previousElements = null;
  21802. }
  21803. if (childScope) {
  21804. childScope.$destroy();
  21805. childScope = null;
  21806. }
  21807. if (block) {
  21808. previousElements = getBlockNodes(block.clone);
  21809. $animate.leave(previousElements).then(function() {
  21810. previousElements = null;
  21811. });
  21812. block = null;
  21813. }
  21814. }
  21815. });
  21816. }
  21817. };
  21818. }];
  21819. /**
  21820. * @ngdoc directive
  21821. * @name ngInclude
  21822. * @restrict ECA
  21823. *
  21824. * @description
  21825. * Fetches, compiles and includes an external HTML fragment.
  21826. *
  21827. * By default, the template URL is restricted to the same domain and protocol as the
  21828. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  21829. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  21830. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  21831. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  21832. * ng.$sce Strict Contextual Escaping}.
  21833. *
  21834. * In addition, the browser's
  21835. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  21836. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  21837. * policy may further restrict whether the template is successfully loaded.
  21838. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  21839. * access on some browsers.
  21840. *
  21841. * @animations
  21842. * enter - animation is used to bring new content into the browser.
  21843. * leave - animation is used to animate existing content away.
  21844. *
  21845. * The enter and leave animation occur concurrently.
  21846. *
  21847. * @scope
  21848. * @priority 400
  21849. *
  21850. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  21851. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  21852. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  21853. *
  21854. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  21855. * $anchorScroll} to scroll the viewport after the content is loaded.
  21856. *
  21857. * - If the attribute is not set, disable scrolling.
  21858. * - If the attribute is set without value, enable scrolling.
  21859. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  21860. *
  21861. * @example
  21862. <example module="includeExample" deps="angular-animate.js" animations="true">
  21863. <file name="index.html">
  21864. <div ng-controller="ExampleController">
  21865. <select ng-model="template" ng-options="t.name for t in templates">
  21866. <option value="">(blank)</option>
  21867. </select>
  21868. url of the template: <code>{{template.url}}</code>
  21869. <hr/>
  21870. <div class="slide-animate-container">
  21871. <div class="slide-animate" ng-include="template.url"></div>
  21872. </div>
  21873. </div>
  21874. </file>
  21875. <file name="script.js">
  21876. angular.module('includeExample', ['ngAnimate'])
  21877. .controller('ExampleController', ['$scope', function($scope) {
  21878. $scope.templates =
  21879. [ { name: 'template1.html', url: 'template1.html'},
  21880. { name: 'template2.html', url: 'template2.html'} ];
  21881. $scope.template = $scope.templates[0];
  21882. }]);
  21883. </file>
  21884. <file name="template1.html">
  21885. Content of template1.html
  21886. </file>
  21887. <file name="template2.html">
  21888. Content of template2.html
  21889. </file>
  21890. <file name="animations.css">
  21891. .slide-animate-container {
  21892. position:relative;
  21893. background:white;
  21894. border:1px solid black;
  21895. height:40px;
  21896. overflow:hidden;
  21897. }
  21898. .slide-animate {
  21899. padding:10px;
  21900. }
  21901. .slide-animate.ng-enter, .slide-animate.ng-leave {
  21902. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21903. position:absolute;
  21904. top:0;
  21905. left:0;
  21906. right:0;
  21907. bottom:0;
  21908. display:block;
  21909. padding:10px;
  21910. }
  21911. .slide-animate.ng-enter {
  21912. top:-50px;
  21913. }
  21914. .slide-animate.ng-enter.ng-enter-active {
  21915. top:0;
  21916. }
  21917. .slide-animate.ng-leave {
  21918. top:0;
  21919. }
  21920. .slide-animate.ng-leave.ng-leave-active {
  21921. top:50px;
  21922. }
  21923. </file>
  21924. <file name="protractor.js" type="protractor">
  21925. var templateSelect = element(by.model('template'));
  21926. var includeElem = element(by.css('[ng-include]'));
  21927. it('should load template1.html', function() {
  21928. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  21929. });
  21930. it('should load template2.html', function() {
  21931. if (browser.params.browser == 'firefox') {
  21932. // Firefox can't handle using selects
  21933. // See https://github.com/angular/protractor/issues/480
  21934. return;
  21935. }
  21936. templateSelect.click();
  21937. templateSelect.all(by.css('option')).get(2).click();
  21938. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  21939. });
  21940. it('should change to blank', function() {
  21941. if (browser.params.browser == 'firefox') {
  21942. // Firefox can't handle using selects
  21943. return;
  21944. }
  21945. templateSelect.click();
  21946. templateSelect.all(by.css('option')).get(0).click();
  21947. expect(includeElem.isPresent()).toBe(false);
  21948. });
  21949. </file>
  21950. </example>
  21951. */
  21952. /**
  21953. * @ngdoc event
  21954. * @name ngInclude#$includeContentRequested
  21955. * @eventType emit on the scope ngInclude was declared in
  21956. * @description
  21957. * Emitted every time the ngInclude content is requested.
  21958. *
  21959. * @param {Object} angularEvent Synthetic event object.
  21960. * @param {String} src URL of content to load.
  21961. */
  21962. /**
  21963. * @ngdoc event
  21964. * @name ngInclude#$includeContentLoaded
  21965. * @eventType emit on the current ngInclude scope
  21966. * @description
  21967. * Emitted every time the ngInclude content is reloaded.
  21968. *
  21969. * @param {Object} angularEvent Synthetic event object.
  21970. * @param {String} src URL of content to load.
  21971. */
  21972. /**
  21973. * @ngdoc event
  21974. * @name ngInclude#$includeContentError
  21975. * @eventType emit on the scope ngInclude was declared in
  21976. * @description
  21977. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  21978. *
  21979. * @param {Object} angularEvent Synthetic event object.
  21980. * @param {String} src URL of content to load.
  21981. */
  21982. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
  21983. function($templateRequest, $anchorScroll, $animate) {
  21984. return {
  21985. restrict: 'ECA',
  21986. priority: 400,
  21987. terminal: true,
  21988. transclude: 'element',
  21989. controller: angular.noop,
  21990. compile: function(element, attr) {
  21991. var srcExp = attr.ngInclude || attr.src,
  21992. onloadExp = attr.onload || '',
  21993. autoScrollExp = attr.autoscroll;
  21994. return function(scope, $element, $attr, ctrl, $transclude) {
  21995. var changeCounter = 0,
  21996. currentScope,
  21997. previousElement,
  21998. currentElement;
  21999. var cleanupLastIncludeContent = function() {
  22000. if (previousElement) {
  22001. previousElement.remove();
  22002. previousElement = null;
  22003. }
  22004. if (currentScope) {
  22005. currentScope.$destroy();
  22006. currentScope = null;
  22007. }
  22008. if (currentElement) {
  22009. $animate.leave(currentElement).then(function() {
  22010. previousElement = null;
  22011. });
  22012. previousElement = currentElement;
  22013. currentElement = null;
  22014. }
  22015. };
  22016. scope.$watch(srcExp, function ngIncludeWatchAction(src) {
  22017. var afterAnimation = function() {
  22018. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  22019. $anchorScroll();
  22020. }
  22021. };
  22022. var thisChangeId = ++changeCounter;
  22023. if (src) {
  22024. //set the 2nd param to true to ignore the template request error so that the inner
  22025. //contents and scope can be cleaned up.
  22026. $templateRequest(src, true).then(function(response) {
  22027. if (thisChangeId !== changeCounter) return;
  22028. var newScope = scope.$new();
  22029. ctrl.template = response;
  22030. // Note: This will also link all children of ng-include that were contained in the original
  22031. // html. If that content contains controllers, ... they could pollute/change the scope.
  22032. // However, using ng-include on an element with additional content does not make sense...
  22033. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  22034. // function is called before linking the content, which would apply child
  22035. // directives to non existing elements.
  22036. var clone = $transclude(newScope, function(clone) {
  22037. cleanupLastIncludeContent();
  22038. $animate.enter(clone, null, $element).then(afterAnimation);
  22039. });
  22040. currentScope = newScope;
  22041. currentElement = clone;
  22042. currentScope.$emit('$includeContentLoaded', src);
  22043. scope.$eval(onloadExp);
  22044. }, function() {
  22045. if (thisChangeId === changeCounter) {
  22046. cleanupLastIncludeContent();
  22047. scope.$emit('$includeContentError', src);
  22048. }
  22049. });
  22050. scope.$emit('$includeContentRequested', src);
  22051. } else {
  22052. cleanupLastIncludeContent();
  22053. ctrl.template = null;
  22054. }
  22055. });
  22056. };
  22057. }
  22058. };
  22059. }];
  22060. // This directive is called during the $transclude call of the first `ngInclude` directive.
  22061. // It will replace and compile the content of the element with the loaded template.
  22062. // We need this directive so that the element content is already filled when
  22063. // the link function of another directive on the same element as ngInclude
  22064. // is called.
  22065. var ngIncludeFillContentDirective = ['$compile',
  22066. function($compile) {
  22067. return {
  22068. restrict: 'ECA',
  22069. priority: -400,
  22070. require: 'ngInclude',
  22071. link: function(scope, $element, $attr, ctrl) {
  22072. if (/SVG/.test($element[0].toString())) {
  22073. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  22074. // support innerHTML, so detect this here and try to generate the contents
  22075. // specially.
  22076. $element.empty();
  22077. $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
  22078. function namespaceAdaptedClone(clone) {
  22079. $element.append(clone);
  22080. }, {futureParentElement: $element});
  22081. return;
  22082. }
  22083. $element.html(ctrl.template);
  22084. $compile($element.contents())(scope);
  22085. }
  22086. };
  22087. }];
  22088. /**
  22089. * @ngdoc directive
  22090. * @name ngInit
  22091. * @restrict AC
  22092. *
  22093. * @description
  22094. * The `ngInit` directive allows you to evaluate an expression in the
  22095. * current scope.
  22096. *
  22097. * <div class="alert alert-danger">
  22098. * The only appropriate use of `ngInit` is for aliasing special properties of
  22099. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
  22100. * should use {@link guide/controller controllers} rather than `ngInit`
  22101. * to initialize values on a scope.
  22102. * </div>
  22103. * <div class="alert alert-warning">
  22104. * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
  22105. * sure you have parenthesis for correct precedence:
  22106. * <pre class="prettyprint">
  22107. * `<div ng-init="test1 = (data | orderBy:'name')"></div>`
  22108. * </pre>
  22109. * </div>
  22110. *
  22111. * @priority 450
  22112. *
  22113. * @element ANY
  22114. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  22115. *
  22116. * @example
  22117. <example module="initExample">
  22118. <file name="index.html">
  22119. <script>
  22120. angular.module('initExample', [])
  22121. .controller('ExampleController', ['$scope', function($scope) {
  22122. $scope.list = [['a', 'b'], ['c', 'd']];
  22123. }]);
  22124. </script>
  22125. <div ng-controller="ExampleController">
  22126. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  22127. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  22128. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  22129. </div>
  22130. </div>
  22131. </div>
  22132. </file>
  22133. <file name="protractor.js" type="protractor">
  22134. it('should alias index positions', function() {
  22135. var elements = element.all(by.css('.example-init'));
  22136. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  22137. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  22138. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  22139. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  22140. });
  22141. </file>
  22142. </example>
  22143. */
  22144. var ngInitDirective = ngDirective({
  22145. priority: 450,
  22146. compile: function() {
  22147. return {
  22148. pre: function(scope, element, attrs) {
  22149. scope.$eval(attrs.ngInit);
  22150. }
  22151. };
  22152. }
  22153. });
  22154. /**
  22155. * @ngdoc directive
  22156. * @name ngList
  22157. *
  22158. * @description
  22159. * Text input that converts between a delimited string and an array of strings. The default
  22160. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  22161. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  22162. *
  22163. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  22164. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  22165. * list item is respected. This implies that the user of the directive is responsible for
  22166. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  22167. * tab or newline character.
  22168. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  22169. * when joining the list items back together) and whitespace around each list item is stripped
  22170. * before it is added to the model.
  22171. *
  22172. * ### Example with Validation
  22173. *
  22174. * <example name="ngList-directive" module="listExample">
  22175. * <file name="app.js">
  22176. * angular.module('listExample', [])
  22177. * .controller('ExampleController', ['$scope', function($scope) {
  22178. * $scope.names = ['morpheus', 'neo', 'trinity'];
  22179. * }]);
  22180. * </file>
  22181. * <file name="index.html">
  22182. * <form name="myForm" ng-controller="ExampleController">
  22183. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  22184. * <span role="alert">
  22185. * <span class="error" ng-show="myForm.namesInput.$error.required">
  22186. * Required!</span>
  22187. * </span>
  22188. * <br>
  22189. * <tt>names = {{names}}</tt><br/>
  22190. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  22191. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  22192. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22193. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22194. * </form>
  22195. * </file>
  22196. * <file name="protractor.js" type="protractor">
  22197. * var listInput = element(by.model('names'));
  22198. * var names = element(by.exactBinding('names'));
  22199. * var valid = element(by.binding('myForm.namesInput.$valid'));
  22200. * var error = element(by.css('span.error'));
  22201. *
  22202. * it('should initialize to model', function() {
  22203. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  22204. * expect(valid.getText()).toContain('true');
  22205. * expect(error.getCssValue('display')).toBe('none');
  22206. * });
  22207. *
  22208. * it('should be invalid if empty', function() {
  22209. * listInput.clear();
  22210. * listInput.sendKeys('');
  22211. *
  22212. * expect(names.getText()).toContain('');
  22213. * expect(valid.getText()).toContain('false');
  22214. * expect(error.getCssValue('display')).not.toBe('none');
  22215. * });
  22216. * </file>
  22217. * </example>
  22218. *
  22219. * ### Example - splitting on whitespace
  22220. * <example name="ngList-directive-newlines">
  22221. * <file name="index.html">
  22222. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  22223. * <pre>{{ list | json }}</pre>
  22224. * </file>
  22225. * <file name="protractor.js" type="protractor">
  22226. * it("should split the text by newlines", function() {
  22227. * var listInput = element(by.model('list'));
  22228. * var output = element(by.binding('list | json'));
  22229. * listInput.sendKeys('abc\ndef\nghi');
  22230. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  22231. * });
  22232. * </file>
  22233. * </example>
  22234. *
  22235. * @element input
  22236. * @param {string=} ngList optional delimiter that should be used to split the value.
  22237. */
  22238. var ngListDirective = function() {
  22239. return {
  22240. restrict: 'A',
  22241. priority: 100,
  22242. require: 'ngModel',
  22243. link: function(scope, element, attr, ctrl) {
  22244. // We want to control whitespace trimming so we use this convoluted approach
  22245. // to access the ngList attribute, which doesn't pre-trim the attribute
  22246. var ngList = element.attr(attr.$attr.ngList) || ', ';
  22247. var trimValues = attr.ngTrim !== 'false';
  22248. var separator = trimValues ? trim(ngList) : ngList;
  22249. var parse = function(viewValue) {
  22250. // If the viewValue is invalid (say required but empty) it will be `undefined`
  22251. if (isUndefined(viewValue)) return;
  22252. var list = [];
  22253. if (viewValue) {
  22254. forEach(viewValue.split(separator), function(value) {
  22255. if (value) list.push(trimValues ? trim(value) : value);
  22256. });
  22257. }
  22258. return list;
  22259. };
  22260. ctrl.$parsers.push(parse);
  22261. ctrl.$formatters.push(function(value) {
  22262. if (isArray(value)) {
  22263. return value.join(ngList);
  22264. }
  22265. return undefined;
  22266. });
  22267. // Override the standard $isEmpty because an empty array means the input is empty.
  22268. ctrl.$isEmpty = function(value) {
  22269. return !value || !value.length;
  22270. };
  22271. }
  22272. };
  22273. };
  22274. /* global VALID_CLASS: true,
  22275. INVALID_CLASS: true,
  22276. PRISTINE_CLASS: true,
  22277. DIRTY_CLASS: true,
  22278. UNTOUCHED_CLASS: true,
  22279. TOUCHED_CLASS: true,
  22280. */
  22281. var VALID_CLASS = 'ng-valid',
  22282. INVALID_CLASS = 'ng-invalid',
  22283. PRISTINE_CLASS = 'ng-pristine',
  22284. DIRTY_CLASS = 'ng-dirty',
  22285. UNTOUCHED_CLASS = 'ng-untouched',
  22286. TOUCHED_CLASS = 'ng-touched',
  22287. PENDING_CLASS = 'ng-pending';
  22288. var ngModelMinErr = minErr('ngModel');
  22289. /**
  22290. * @ngdoc type
  22291. * @name ngModel.NgModelController
  22292. *
  22293. * @property {string} $viewValue Actual string value in the view.
  22294. * @property {*} $modelValue The value in the model that the control is bound to.
  22295. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  22296. the control reads value from the DOM. The functions are called in array order, each passing
  22297. its return value through to the next. The last return value is forwarded to the
  22298. {@link ngModel.NgModelController#$validators `$validators`} collection.
  22299. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  22300. `$viewValue`}.
  22301. Returning `undefined` from a parser means a parse error occurred. In that case,
  22302. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  22303. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  22304. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  22305. *
  22306. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  22307. the model value changes. The functions are called in reverse array order, each passing the value through to the
  22308. next. The last return value is used as the actual DOM value.
  22309. Used to format / convert values for display in the control.
  22310. * ```js
  22311. * function formatter(value) {
  22312. * if (value) {
  22313. * return value.toUpperCase();
  22314. * }
  22315. * }
  22316. * ngModel.$formatters.push(formatter);
  22317. * ```
  22318. *
  22319. * @property {Object.<string, function>} $validators A collection of validators that are applied
  22320. * whenever the model value changes. The key value within the object refers to the name of the
  22321. * validator while the function refers to the validation operation. The validation operation is
  22322. * provided with the model value as an argument and must return a true or false value depending
  22323. * on the response of that validation.
  22324. *
  22325. * ```js
  22326. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  22327. * var value = modelValue || viewValue;
  22328. * return /[0-9]+/.test(value) &&
  22329. * /[a-z]+/.test(value) &&
  22330. * /[A-Z]+/.test(value) &&
  22331. * /\W+/.test(value);
  22332. * };
  22333. * ```
  22334. *
  22335. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  22336. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  22337. * is expected to return a promise when it is run during the model validation process. Once the promise
  22338. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  22339. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  22340. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  22341. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  22342. * will only run once all synchronous validators have passed.
  22343. *
  22344. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  22345. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  22346. *
  22347. * ```js
  22348. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  22349. * var value = modelValue || viewValue;
  22350. *
  22351. * // Lookup user by username
  22352. * return $http.get('/api/users/' + value).
  22353. * then(function resolved() {
  22354. * //username exists, this means validation fails
  22355. * return $q.reject('exists');
  22356. * }, function rejected() {
  22357. * //username does not exist, therefore this validation passes
  22358. * return true;
  22359. * });
  22360. * };
  22361. * ```
  22362. *
  22363. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  22364. * view value has changed. It is called with no arguments, and its return value is ignored.
  22365. * This can be used in place of additional $watches against the model value.
  22366. *
  22367. * @property {Object} $error An object hash with all failing validator ids as keys.
  22368. * @property {Object} $pending An object hash with all pending validator ids as keys.
  22369. *
  22370. * @property {boolean} $untouched True if control has not lost focus yet.
  22371. * @property {boolean} $touched True if control has lost focus.
  22372. * @property {boolean} $pristine True if user has not interacted with the control yet.
  22373. * @property {boolean} $dirty True if user has already interacted with the control.
  22374. * @property {boolean} $valid True if there is no error.
  22375. * @property {boolean} $invalid True if at least one error on the control.
  22376. * @property {string} $name The name attribute of the control.
  22377. *
  22378. * @description
  22379. *
  22380. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  22381. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  22382. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  22383. * listening to DOM events.
  22384. * Such DOM related logic should be provided by other directives which make use of
  22385. * `NgModelController` for data-binding to control elements.
  22386. * Angular provides this DOM logic for most {@link input `input`} elements.
  22387. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  22388. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  22389. *
  22390. * @example
  22391. * ### Custom Control Example
  22392. * This example shows how to use `NgModelController` with a custom control to achieve
  22393. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  22394. * collaborate together to achieve the desired result.
  22395. *
  22396. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  22397. * contents be edited in place by the user.
  22398. *
  22399. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  22400. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  22401. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  22402. * that content using the `$sce` service.
  22403. *
  22404. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  22405. <file name="style.css">
  22406. [contenteditable] {
  22407. border: 1px solid black;
  22408. background-color: white;
  22409. min-height: 20px;
  22410. }
  22411. .ng-invalid {
  22412. border: 1px solid red;
  22413. }
  22414. </file>
  22415. <file name="script.js">
  22416. angular.module('customControl', ['ngSanitize']).
  22417. directive('contenteditable', ['$sce', function($sce) {
  22418. return {
  22419. restrict: 'A', // only activate on element attribute
  22420. require: '?ngModel', // get a hold of NgModelController
  22421. link: function(scope, element, attrs, ngModel) {
  22422. if (!ngModel) return; // do nothing if no ng-model
  22423. // Specify how UI should be updated
  22424. ngModel.$render = function() {
  22425. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  22426. };
  22427. // Listen for change events to enable binding
  22428. element.on('blur keyup change', function() {
  22429. scope.$evalAsync(read);
  22430. });
  22431. read(); // initialize
  22432. // Write data to the model
  22433. function read() {
  22434. var html = element.html();
  22435. // When we clear the content editable the browser leaves a <br> behind
  22436. // If strip-br attribute is provided then we strip this out
  22437. if ( attrs.stripBr && html == '<br>' ) {
  22438. html = '';
  22439. }
  22440. ngModel.$setViewValue(html);
  22441. }
  22442. }
  22443. };
  22444. }]);
  22445. </file>
  22446. <file name="index.html">
  22447. <form name="myForm">
  22448. <div contenteditable
  22449. name="myWidget" ng-model="userContent"
  22450. strip-br="true"
  22451. required>Change me!</div>
  22452. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  22453. <hr>
  22454. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  22455. </form>
  22456. </file>
  22457. <file name="protractor.js" type="protractor">
  22458. it('should data-bind and become invalid', function() {
  22459. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  22460. // SafariDriver can't handle contenteditable
  22461. // and Firefox driver can't clear contenteditables very well
  22462. return;
  22463. }
  22464. var contentEditable = element(by.css('[contenteditable]'));
  22465. var content = 'Change me!';
  22466. expect(contentEditable.getText()).toEqual(content);
  22467. contentEditable.clear();
  22468. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  22469. expect(contentEditable.getText()).toEqual('');
  22470. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  22471. });
  22472. </file>
  22473. * </example>
  22474. *
  22475. *
  22476. */
  22477. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
  22478. function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
  22479. this.$viewValue = Number.NaN;
  22480. this.$modelValue = Number.NaN;
  22481. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  22482. this.$validators = {};
  22483. this.$asyncValidators = {};
  22484. this.$parsers = [];
  22485. this.$formatters = [];
  22486. this.$viewChangeListeners = [];
  22487. this.$untouched = true;
  22488. this.$touched = false;
  22489. this.$pristine = true;
  22490. this.$dirty = false;
  22491. this.$valid = true;
  22492. this.$invalid = false;
  22493. this.$error = {}; // keep invalid keys here
  22494. this.$$success = {}; // keep valid keys here
  22495. this.$pending = undefined; // keep pending keys here
  22496. this.$name = $interpolate($attr.name || '', false)($scope);
  22497. var parsedNgModel = $parse($attr.ngModel),
  22498. parsedNgModelAssign = parsedNgModel.assign,
  22499. ngModelGet = parsedNgModel,
  22500. ngModelSet = parsedNgModelAssign,
  22501. pendingDebounce = null,
  22502. parserValid,
  22503. ctrl = this;
  22504. this.$$setOptions = function(options) {
  22505. ctrl.$options = options;
  22506. if (options && options.getterSetter) {
  22507. var invokeModelGetter = $parse($attr.ngModel + '()'),
  22508. invokeModelSetter = $parse($attr.ngModel + '($$$p)');
  22509. ngModelGet = function($scope) {
  22510. var modelValue = parsedNgModel($scope);
  22511. if (isFunction(modelValue)) {
  22512. modelValue = invokeModelGetter($scope);
  22513. }
  22514. return modelValue;
  22515. };
  22516. ngModelSet = function($scope, newValue) {
  22517. if (isFunction(parsedNgModel($scope))) {
  22518. invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
  22519. } else {
  22520. parsedNgModelAssign($scope, ctrl.$modelValue);
  22521. }
  22522. };
  22523. } else if (!parsedNgModel.assign) {
  22524. throw ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  22525. $attr.ngModel, startingTag($element));
  22526. }
  22527. };
  22528. /**
  22529. * @ngdoc method
  22530. * @name ngModel.NgModelController#$render
  22531. *
  22532. * @description
  22533. * Called when the view needs to be updated. It is expected that the user of the ng-model
  22534. * directive will implement this method.
  22535. *
  22536. * The `$render()` method is invoked in the following situations:
  22537. *
  22538. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  22539. * committed value then `$render()` is called to update the input control.
  22540. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  22541. * the `$viewValue` are different from last time.
  22542. *
  22543. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  22544. * `$modelValue` and `$viewValue` are actually different from their previous value. If `$modelValue`
  22545. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  22546. * invoked if you only change a property on the objects.
  22547. */
  22548. this.$render = noop;
  22549. /**
  22550. * @ngdoc method
  22551. * @name ngModel.NgModelController#$isEmpty
  22552. *
  22553. * @description
  22554. * This is called when we need to determine if the value of an input is empty.
  22555. *
  22556. * For instance, the required directive does this to work out if the input has data or not.
  22557. *
  22558. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  22559. *
  22560. * You can override this for input directives whose concept of being empty is different from the
  22561. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  22562. * implies empty.
  22563. *
  22564. * @param {*} value The value of the input to check for emptiness.
  22565. * @returns {boolean} True if `value` is "empty".
  22566. */
  22567. this.$isEmpty = function(value) {
  22568. return isUndefined(value) || value === '' || value === null || value !== value;
  22569. };
  22570. var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
  22571. currentValidationRunId = 0;
  22572. /**
  22573. * @ngdoc method
  22574. * @name ngModel.NgModelController#$setValidity
  22575. *
  22576. * @description
  22577. * Change the validity state, and notify the form.
  22578. *
  22579. * This method can be called within $parsers/$formatters or a custom validation implementation.
  22580. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  22581. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  22582. *
  22583. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  22584. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  22585. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  22586. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  22587. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  22588. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  22589. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  22590. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  22591. * Skipped is used by Angular when validators do not run because of parse errors and
  22592. * when `$asyncValidators` do not run because any of the `$validators` failed.
  22593. */
  22594. addSetValidityMethod({
  22595. ctrl: this,
  22596. $element: $element,
  22597. set: function(object, property) {
  22598. object[property] = true;
  22599. },
  22600. unset: function(object, property) {
  22601. delete object[property];
  22602. },
  22603. parentForm: parentForm,
  22604. $animate: $animate
  22605. });
  22606. /**
  22607. * @ngdoc method
  22608. * @name ngModel.NgModelController#$setPristine
  22609. *
  22610. * @description
  22611. * Sets the control to its pristine state.
  22612. *
  22613. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  22614. * state (`ng-pristine` class). A model is considered to be pristine when the control
  22615. * has not been changed from when first compiled.
  22616. */
  22617. this.$setPristine = function() {
  22618. ctrl.$dirty = false;
  22619. ctrl.$pristine = true;
  22620. $animate.removeClass($element, DIRTY_CLASS);
  22621. $animate.addClass($element, PRISTINE_CLASS);
  22622. };
  22623. /**
  22624. * @ngdoc method
  22625. * @name ngModel.NgModelController#$setDirty
  22626. *
  22627. * @description
  22628. * Sets the control to its dirty state.
  22629. *
  22630. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  22631. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  22632. * from when first compiled.
  22633. */
  22634. this.$setDirty = function() {
  22635. ctrl.$dirty = true;
  22636. ctrl.$pristine = false;
  22637. $animate.removeClass($element, PRISTINE_CLASS);
  22638. $animate.addClass($element, DIRTY_CLASS);
  22639. parentForm.$setDirty();
  22640. };
  22641. /**
  22642. * @ngdoc method
  22643. * @name ngModel.NgModelController#$setUntouched
  22644. *
  22645. * @description
  22646. * Sets the control to its untouched state.
  22647. *
  22648. * This method can be called to remove the `ng-touched` class and set the control to its
  22649. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  22650. * by default, however this function can be used to restore that state if the model has
  22651. * already been touched by the user.
  22652. */
  22653. this.$setUntouched = function() {
  22654. ctrl.$touched = false;
  22655. ctrl.$untouched = true;
  22656. $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  22657. };
  22658. /**
  22659. * @ngdoc method
  22660. * @name ngModel.NgModelController#$setTouched
  22661. *
  22662. * @description
  22663. * Sets the control to its touched state.
  22664. *
  22665. * This method can be called to remove the `ng-untouched` class and set the control to its
  22666. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  22667. * first focused the control element and then shifted focus away from the control (blur event).
  22668. */
  22669. this.$setTouched = function() {
  22670. ctrl.$touched = true;
  22671. ctrl.$untouched = false;
  22672. $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  22673. };
  22674. /**
  22675. * @ngdoc method
  22676. * @name ngModel.NgModelController#$rollbackViewValue
  22677. *
  22678. * @description
  22679. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  22680. * which may be caused by a pending debounced event or because the input is waiting for a some
  22681. * future event.
  22682. *
  22683. * If you have an input that uses `ng-model-options` to set up debounced events or events such
  22684. * as blur you can have a situation where there is a period when the `$viewValue`
  22685. * is out of synch with the ngModel's `$modelValue`.
  22686. *
  22687. * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`
  22688. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  22689. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  22690. *
  22691. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  22692. * input which may have such events pending. This is important in order to make sure that the
  22693. * input field will be updated with the new model value and any pending operations are cancelled.
  22694. *
  22695. * <example name="ng-model-cancel-update" module="cancel-update-example">
  22696. * <file name="app.js">
  22697. * angular.module('cancel-update-example', [])
  22698. *
  22699. * .controller('CancelUpdateController', ['$scope', function($scope) {
  22700. * $scope.resetWithCancel = function(e) {
  22701. * if (e.keyCode == 27) {
  22702. * $scope.myForm.myInput1.$rollbackViewValue();
  22703. * $scope.myValue = '';
  22704. * }
  22705. * };
  22706. * $scope.resetWithoutCancel = function(e) {
  22707. * if (e.keyCode == 27) {
  22708. * $scope.myValue = '';
  22709. * }
  22710. * };
  22711. * }]);
  22712. * </file>
  22713. * <file name="index.html">
  22714. * <div ng-controller="CancelUpdateController">
  22715. * <p>Try typing something in each input. See that the model only updates when you
  22716. * blur off the input.
  22717. * </p>
  22718. * <p>Now see what happens if you start typing then press the Escape key</p>
  22719. *
  22720. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  22721. * <p id="inputDescription1">With $rollbackViewValue()</p>
  22722. * <input name="myInput1" aria-describedby="inputDescription1" ng-model="myValue"
  22723. * ng-keydown="resetWithCancel($event)"><br/>
  22724. * myValue: "{{ myValue }}"
  22725. *
  22726. * <p id="inputDescription2">Without $rollbackViewValue()</p>
  22727. * <input name="myInput2" aria-describedby="inputDescription2" ng-model="myValue"
  22728. * ng-keydown="resetWithoutCancel($event)"><br/>
  22729. * myValue: "{{ myValue }}"
  22730. * </form>
  22731. * </div>
  22732. * </file>
  22733. * </example>
  22734. */
  22735. this.$rollbackViewValue = function() {
  22736. $timeout.cancel(pendingDebounce);
  22737. ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
  22738. ctrl.$render();
  22739. };
  22740. /**
  22741. * @ngdoc method
  22742. * @name ngModel.NgModelController#$validate
  22743. *
  22744. * @description
  22745. * Runs each of the registered validators (first synchronous validators and then
  22746. * asynchronous validators).
  22747. * If the validity changes to invalid, the model will be set to `undefined`,
  22748. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  22749. * If the validity changes to valid, it will set the model to the last available valid
  22750. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  22751. */
  22752. this.$validate = function() {
  22753. // ignore $validate before model is initialized
  22754. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  22755. return;
  22756. }
  22757. var viewValue = ctrl.$$lastCommittedViewValue;
  22758. // Note: we use the $$rawModelValue as $modelValue might have been
  22759. // set to undefined during a view -> model update that found validation
  22760. // errors. We can't parse the view here, since that could change
  22761. // the model although neither viewValue nor the model on the scope changed
  22762. var modelValue = ctrl.$$rawModelValue;
  22763. var prevValid = ctrl.$valid;
  22764. var prevModelValue = ctrl.$modelValue;
  22765. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  22766. ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
  22767. // If there was no change in validity, don't update the model
  22768. // This prevents changing an invalid modelValue to undefined
  22769. if (!allowInvalid && prevValid !== allValid) {
  22770. // Note: Don't check ctrl.$valid here, as we could have
  22771. // external validators (e.g. calculated on the server),
  22772. // that just call $setValidity and need the model value
  22773. // to calculate their validity.
  22774. ctrl.$modelValue = allValid ? modelValue : undefined;
  22775. if (ctrl.$modelValue !== prevModelValue) {
  22776. ctrl.$$writeModelToScope();
  22777. }
  22778. }
  22779. });
  22780. };
  22781. this.$$runValidators = function(modelValue, viewValue, doneCallback) {
  22782. currentValidationRunId++;
  22783. var localValidationRunId = currentValidationRunId;
  22784. // check parser error
  22785. if (!processParseErrors()) {
  22786. validationDone(false);
  22787. return;
  22788. }
  22789. if (!processSyncValidators()) {
  22790. validationDone(false);
  22791. return;
  22792. }
  22793. processAsyncValidators();
  22794. function processParseErrors() {
  22795. var errorKey = ctrl.$$parserName || 'parse';
  22796. if (parserValid === undefined) {
  22797. setValidity(errorKey, null);
  22798. } else {
  22799. if (!parserValid) {
  22800. forEach(ctrl.$validators, function(v, name) {
  22801. setValidity(name, null);
  22802. });
  22803. forEach(ctrl.$asyncValidators, function(v, name) {
  22804. setValidity(name, null);
  22805. });
  22806. }
  22807. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  22808. setValidity(errorKey, parserValid);
  22809. return parserValid;
  22810. }
  22811. return true;
  22812. }
  22813. function processSyncValidators() {
  22814. var syncValidatorsValid = true;
  22815. forEach(ctrl.$validators, function(validator, name) {
  22816. var result = validator(modelValue, viewValue);
  22817. syncValidatorsValid = syncValidatorsValid && result;
  22818. setValidity(name, result);
  22819. });
  22820. if (!syncValidatorsValid) {
  22821. forEach(ctrl.$asyncValidators, function(v, name) {
  22822. setValidity(name, null);
  22823. });
  22824. return false;
  22825. }
  22826. return true;
  22827. }
  22828. function processAsyncValidators() {
  22829. var validatorPromises = [];
  22830. var allValid = true;
  22831. forEach(ctrl.$asyncValidators, function(validator, name) {
  22832. var promise = validator(modelValue, viewValue);
  22833. if (!isPromiseLike(promise)) {
  22834. throw ngModelMinErr("$asyncValidators",
  22835. "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
  22836. }
  22837. setValidity(name, undefined);
  22838. validatorPromises.push(promise.then(function() {
  22839. setValidity(name, true);
  22840. }, function(error) {
  22841. allValid = false;
  22842. setValidity(name, false);
  22843. }));
  22844. });
  22845. if (!validatorPromises.length) {
  22846. validationDone(true);
  22847. } else {
  22848. $q.all(validatorPromises).then(function() {
  22849. validationDone(allValid);
  22850. }, noop);
  22851. }
  22852. }
  22853. function setValidity(name, isValid) {
  22854. if (localValidationRunId === currentValidationRunId) {
  22855. ctrl.$setValidity(name, isValid);
  22856. }
  22857. }
  22858. function validationDone(allValid) {
  22859. if (localValidationRunId === currentValidationRunId) {
  22860. doneCallback(allValid);
  22861. }
  22862. }
  22863. };
  22864. /**
  22865. * @ngdoc method
  22866. * @name ngModel.NgModelController#$commitViewValue
  22867. *
  22868. * @description
  22869. * Commit a pending update to the `$modelValue`.
  22870. *
  22871. * Updates may be pending by a debounced event or because the input is waiting for a some future
  22872. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  22873. * usually handles calling this in response to input events.
  22874. */
  22875. this.$commitViewValue = function() {
  22876. var viewValue = ctrl.$viewValue;
  22877. $timeout.cancel(pendingDebounce);
  22878. // If the view value has not changed then we should just exit, except in the case where there is
  22879. // a native validator on the element. In this case the validation state may have changed even though
  22880. // the viewValue has stayed empty.
  22881. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
  22882. return;
  22883. }
  22884. ctrl.$$lastCommittedViewValue = viewValue;
  22885. // change to dirty
  22886. if (ctrl.$pristine) {
  22887. this.$setDirty();
  22888. }
  22889. this.$$parseAndValidate();
  22890. };
  22891. this.$$parseAndValidate = function() {
  22892. var viewValue = ctrl.$$lastCommittedViewValue;
  22893. var modelValue = viewValue;
  22894. parserValid = isUndefined(modelValue) ? undefined : true;
  22895. if (parserValid) {
  22896. for (var i = 0; i < ctrl.$parsers.length; i++) {
  22897. modelValue = ctrl.$parsers[i](modelValue);
  22898. if (isUndefined(modelValue)) {
  22899. parserValid = false;
  22900. break;
  22901. }
  22902. }
  22903. }
  22904. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  22905. // ctrl.$modelValue has not been touched yet...
  22906. ctrl.$modelValue = ngModelGet($scope);
  22907. }
  22908. var prevModelValue = ctrl.$modelValue;
  22909. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  22910. ctrl.$$rawModelValue = modelValue;
  22911. if (allowInvalid) {
  22912. ctrl.$modelValue = modelValue;
  22913. writeToModelIfNeeded();
  22914. }
  22915. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  22916. // This can happen if e.g. $setViewValue is called from inside a parser
  22917. ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
  22918. if (!allowInvalid) {
  22919. // Note: Don't check ctrl.$valid here, as we could have
  22920. // external validators (e.g. calculated on the server),
  22921. // that just call $setValidity and need the model value
  22922. // to calculate their validity.
  22923. ctrl.$modelValue = allValid ? modelValue : undefined;
  22924. writeToModelIfNeeded();
  22925. }
  22926. });
  22927. function writeToModelIfNeeded() {
  22928. if (ctrl.$modelValue !== prevModelValue) {
  22929. ctrl.$$writeModelToScope();
  22930. }
  22931. }
  22932. };
  22933. this.$$writeModelToScope = function() {
  22934. ngModelSet($scope, ctrl.$modelValue);
  22935. forEach(ctrl.$viewChangeListeners, function(listener) {
  22936. try {
  22937. listener();
  22938. } catch (e) {
  22939. $exceptionHandler(e);
  22940. }
  22941. });
  22942. };
  22943. /**
  22944. * @ngdoc method
  22945. * @name ngModel.NgModelController#$setViewValue
  22946. *
  22947. * @description
  22948. * Update the view value.
  22949. *
  22950. * This method should be called when an input directive want to change the view value; typically,
  22951. * this is done from within a DOM event handler.
  22952. *
  22953. * For example {@link ng.directive:input input} calls it when the value of the input changes and
  22954. * {@link ng.directive:select select} calls it when an option is selected.
  22955. *
  22956. * If the new `value` is an object (rather than a string or a number), we should make a copy of the
  22957. * object before passing it to `$setViewValue`. This is because `ngModel` does not perform a deep
  22958. * watch of objects, it only looks for a change of identity. If you only change the property of
  22959. * the object then ngModel will not realise that the object has changed and will not invoke the
  22960. * `$parsers` and `$validators` pipelines.
  22961. *
  22962. * For this reason, you should not change properties of the copy once it has been passed to
  22963. * `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly.
  22964. *
  22965. * When this method is called, the new `value` will be staged for committing through the `$parsers`
  22966. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  22967. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  22968. * **expression** specified in the `ng-model` attribute.
  22969. *
  22970. * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
  22971. *
  22972. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  22973. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  22974. * `updateOn` events is triggered on the DOM element.
  22975. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  22976. * directive is used with a custom debounce for this particular event.
  22977. *
  22978. * Note that calling this function does not trigger a `$digest`.
  22979. *
  22980. * @param {string} value Value from the view.
  22981. * @param {string} trigger Event that triggered the update.
  22982. */
  22983. this.$setViewValue = function(value, trigger) {
  22984. ctrl.$viewValue = value;
  22985. if (!ctrl.$options || ctrl.$options.updateOnDefault) {
  22986. ctrl.$$debounceViewValueCommit(trigger);
  22987. }
  22988. };
  22989. this.$$debounceViewValueCommit = function(trigger) {
  22990. var debounceDelay = 0,
  22991. options = ctrl.$options,
  22992. debounce;
  22993. if (options && isDefined(options.debounce)) {
  22994. debounce = options.debounce;
  22995. if (isNumber(debounce)) {
  22996. debounceDelay = debounce;
  22997. } else if (isNumber(debounce[trigger])) {
  22998. debounceDelay = debounce[trigger];
  22999. } else if (isNumber(debounce['default'])) {
  23000. debounceDelay = debounce['default'];
  23001. }
  23002. }
  23003. $timeout.cancel(pendingDebounce);
  23004. if (debounceDelay) {
  23005. pendingDebounce = $timeout(function() {
  23006. ctrl.$commitViewValue();
  23007. }, debounceDelay);
  23008. } else if ($rootScope.$$phase) {
  23009. ctrl.$commitViewValue();
  23010. } else {
  23011. $scope.$apply(function() {
  23012. ctrl.$commitViewValue();
  23013. });
  23014. }
  23015. };
  23016. // model -> value
  23017. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  23018. // 1. scope value is 'a'
  23019. // 2. user enters 'b'
  23020. // 3. ng-change kicks in and reverts scope value to 'a'
  23021. // -> scope value did not change since the last digest as
  23022. // ng-change executes in apply phase
  23023. // 4. view should be changed back to 'a'
  23024. $scope.$watch(function ngModelWatch() {
  23025. var modelValue = ngModelGet($scope);
  23026. // if scope model value and ngModel value are out of sync
  23027. // TODO(perf): why not move this to the action fn?
  23028. if (modelValue !== ctrl.$modelValue &&
  23029. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  23030. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  23031. ) {
  23032. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  23033. parserValid = undefined;
  23034. var formatters = ctrl.$formatters,
  23035. idx = formatters.length;
  23036. var viewValue = modelValue;
  23037. while (idx--) {
  23038. viewValue = formatters[idx](viewValue);
  23039. }
  23040. if (ctrl.$viewValue !== viewValue) {
  23041. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  23042. ctrl.$render();
  23043. ctrl.$$runValidators(modelValue, viewValue, noop);
  23044. }
  23045. }
  23046. return modelValue;
  23047. });
  23048. }];
  23049. /**
  23050. * @ngdoc directive
  23051. * @name ngModel
  23052. *
  23053. * @element input
  23054. * @priority 1
  23055. *
  23056. * @description
  23057. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  23058. * property on the scope using {@link ngModel.NgModelController NgModelController},
  23059. * which is created and exposed by this directive.
  23060. *
  23061. * `ngModel` is responsible for:
  23062. *
  23063. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  23064. * require.
  23065. * - Providing validation behavior (i.e. required, number, email, url).
  23066. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  23067. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.
  23068. * - Registering the control with its parent {@link ng.directive:form form}.
  23069. *
  23070. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  23071. * current scope. If the property doesn't already exist on this scope, it will be created
  23072. * implicitly and added to the scope.
  23073. *
  23074. * For best practices on using `ngModel`, see:
  23075. *
  23076. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  23077. *
  23078. * For basic examples, how to use `ngModel`, see:
  23079. *
  23080. * - {@link ng.directive:input input}
  23081. * - {@link input[text] text}
  23082. * - {@link input[checkbox] checkbox}
  23083. * - {@link input[radio] radio}
  23084. * - {@link input[number] number}
  23085. * - {@link input[email] email}
  23086. * - {@link input[url] url}
  23087. * - {@link input[date] date}
  23088. * - {@link input[datetime-local] datetime-local}
  23089. * - {@link input[time] time}
  23090. * - {@link input[month] month}
  23091. * - {@link input[week] week}
  23092. * - {@link ng.directive:select select}
  23093. * - {@link ng.directive:textarea textarea}
  23094. *
  23095. * # CSS classes
  23096. * The following CSS classes are added and removed on the associated input/select/textarea element
  23097. * depending on the validity of the model.
  23098. *
  23099. * - `ng-valid`: the model is valid
  23100. * - `ng-invalid`: the model is invalid
  23101. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  23102. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  23103. * - `ng-pristine`: the control hasn't been interacted with yet
  23104. * - `ng-dirty`: the control has been interacted with
  23105. * - `ng-touched`: the control has been blurred
  23106. * - `ng-untouched`: the control hasn't been blurred
  23107. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  23108. *
  23109. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  23110. *
  23111. * ## Animation Hooks
  23112. *
  23113. * Animations within models are triggered when any of the associated CSS classes are added and removed
  23114. * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
  23115. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  23116. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  23117. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  23118. *
  23119. * The following example shows a simple way to utilize CSS transitions to style an input element
  23120. * that has been rendered as invalid after it has been validated:
  23121. *
  23122. * <pre>
  23123. * //be sure to include ngAnimate as a module to hook into more
  23124. * //advanced animations
  23125. * .my-input {
  23126. * transition:0.5s linear all;
  23127. * background: white;
  23128. * }
  23129. * .my-input.ng-invalid {
  23130. * background: red;
  23131. * color:white;
  23132. * }
  23133. * </pre>
  23134. *
  23135. * @example
  23136. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  23137. <file name="index.html">
  23138. <script>
  23139. angular.module('inputExample', [])
  23140. .controller('ExampleController', ['$scope', function($scope) {
  23141. $scope.val = '1';
  23142. }]);
  23143. </script>
  23144. <style>
  23145. .my-input {
  23146. transition:all linear 0.5s;
  23147. background: transparent;
  23148. }
  23149. .my-input.ng-invalid {
  23150. color:white;
  23151. background: red;
  23152. }
  23153. </style>
  23154. <p id="inputDescription">
  23155. Update input to see transitions when valid/invalid.
  23156. Integer is a valid value.
  23157. </p>
  23158. <form name="testForm" ng-controller="ExampleController">
  23159. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  23160. aria-describedby="inputDescription" />
  23161. </form>
  23162. </file>
  23163. * </example>
  23164. *
  23165. * ## Binding to a getter/setter
  23166. *
  23167. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  23168. * function that returns a representation of the model when called with zero arguments, and sets
  23169. * the internal state of a model when called with an argument. It's sometimes useful to use this
  23170. * for models that have an internal representation that's different from what the model exposes
  23171. * to the view.
  23172. *
  23173. * <div class="alert alert-success">
  23174. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  23175. * frequently than other parts of your code.
  23176. * </div>
  23177. *
  23178. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  23179. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  23180. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  23181. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  23182. *
  23183. * The following example shows how to use `ngModel` with a getter/setter:
  23184. *
  23185. * @example
  23186. * <example name="ngModel-getter-setter" module="getterSetterExample">
  23187. <file name="index.html">
  23188. <div ng-controller="ExampleController">
  23189. <form name="userForm">
  23190. <label>Name:
  23191. <input type="text" name="userName"
  23192. ng-model="user.name"
  23193. ng-model-options="{ getterSetter: true }" />
  23194. </label>
  23195. </form>
  23196. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  23197. </div>
  23198. </file>
  23199. <file name="app.js">
  23200. angular.module('getterSetterExample', [])
  23201. .controller('ExampleController', ['$scope', function($scope) {
  23202. var _name = 'Brian';
  23203. $scope.user = {
  23204. name: function(newName) {
  23205. // Note that newName can be undefined for two reasons:
  23206. // 1. Because it is called as a getter and thus called with no arguments
  23207. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  23208. // input is invalid
  23209. return arguments.length ? (_name = newName) : _name;
  23210. }
  23211. };
  23212. }]);
  23213. </file>
  23214. * </example>
  23215. */
  23216. var ngModelDirective = ['$rootScope', function($rootScope) {
  23217. return {
  23218. restrict: 'A',
  23219. require: ['ngModel', '^?form', '^?ngModelOptions'],
  23220. controller: NgModelController,
  23221. // Prelink needs to run before any input directive
  23222. // so that we can set the NgModelOptions in NgModelController
  23223. // before anyone else uses it.
  23224. priority: 1,
  23225. compile: function ngModelCompile(element) {
  23226. // Setup initial state of the control
  23227. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  23228. return {
  23229. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  23230. var modelCtrl = ctrls[0],
  23231. formCtrl = ctrls[1] || nullFormCtrl;
  23232. modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
  23233. // notify others, especially parent forms
  23234. formCtrl.$addControl(modelCtrl);
  23235. attr.$observe('name', function(newValue) {
  23236. if (modelCtrl.$name !== newValue) {
  23237. formCtrl.$$renameControl(modelCtrl, newValue);
  23238. }
  23239. });
  23240. scope.$on('$destroy', function() {
  23241. formCtrl.$removeControl(modelCtrl);
  23242. });
  23243. },
  23244. post: function ngModelPostLink(scope, element, attr, ctrls) {
  23245. var modelCtrl = ctrls[0];
  23246. if (modelCtrl.$options && modelCtrl.$options.updateOn) {
  23247. element.on(modelCtrl.$options.updateOn, function(ev) {
  23248. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  23249. });
  23250. }
  23251. element.on('blur', function(ev) {
  23252. if (modelCtrl.$touched) return;
  23253. if ($rootScope.$$phase) {
  23254. scope.$evalAsync(modelCtrl.$setTouched);
  23255. } else {
  23256. scope.$apply(modelCtrl.$setTouched);
  23257. }
  23258. });
  23259. }
  23260. };
  23261. }
  23262. };
  23263. }];
  23264. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  23265. /**
  23266. * @ngdoc directive
  23267. * @name ngModelOptions
  23268. *
  23269. * @description
  23270. * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
  23271. * events that will trigger a model update and/or a debouncing delay so that the actual update only
  23272. * takes place when a timer expires; this timer will be reset after another change takes place.
  23273. *
  23274. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  23275. * be different from the value in the actual model. This means that if you update the model you
  23276. * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
  23277. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  23278. *
  23279. * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
  23280. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  23281. * important because `form` controllers are published to the related scope under the name in their
  23282. * `name` attribute.
  23283. *
  23284. * Any pending changes will take place immediately when an enclosing form is submitted via the
  23285. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  23286. * to have access to the updated model.
  23287. *
  23288. * `ngModelOptions` has an effect on the element it's declared on and its descendants.
  23289. *
  23290. * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
  23291. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  23292. * events using an space delimited list. There is a special event called `default` that
  23293. * matches the default events belonging of the control.
  23294. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  23295. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  23296. * custom value for each event. For example:
  23297. * `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
  23298. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  23299. * not validate correctly instead of the default behavior of setting the model to undefined.
  23300. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  23301. `ngModel` as getters/setters.
  23302. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  23303. * `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
  23304. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  23305. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  23306. * If not specified, the timezone of the browser will be used.
  23307. *
  23308. * @example
  23309. The following example shows how to override immediate updates. Changes on the inputs within the
  23310. form will update the model only when the control loses focus (blur event). If `escape` key is
  23311. pressed while the input field is focused, the value is reset to the value in the current model.
  23312. <example name="ngModelOptions-directive-blur" module="optionsExample">
  23313. <file name="index.html">
  23314. <div ng-controller="ExampleController">
  23315. <form name="userForm">
  23316. <label>Name:
  23317. <input type="text" name="userName"
  23318. ng-model="user.name"
  23319. ng-model-options="{ updateOn: 'blur' }"
  23320. ng-keyup="cancel($event)" />
  23321. </label><br />
  23322. <label>Other data:
  23323. <input type="text" ng-model="user.data" />
  23324. </label><br />
  23325. </form>
  23326. <pre>user.name = <span ng-bind="user.name"></span></pre>
  23327. </div>
  23328. </file>
  23329. <file name="app.js">
  23330. angular.module('optionsExample', [])
  23331. .controller('ExampleController', ['$scope', function($scope) {
  23332. $scope.user = { name: 'say', data: '' };
  23333. $scope.cancel = function(e) {
  23334. if (e.keyCode == 27) {
  23335. $scope.userForm.userName.$rollbackViewValue();
  23336. }
  23337. };
  23338. }]);
  23339. </file>
  23340. <file name="protractor.js" type="protractor">
  23341. var model = element(by.binding('user.name'));
  23342. var input = element(by.model('user.name'));
  23343. var other = element(by.model('user.data'));
  23344. it('should allow custom events', function() {
  23345. input.sendKeys(' hello');
  23346. input.click();
  23347. expect(model.getText()).toEqual('say');
  23348. other.click();
  23349. expect(model.getText()).toEqual('say hello');
  23350. });
  23351. it('should $rollbackViewValue when model changes', function() {
  23352. input.sendKeys(' hello');
  23353. expect(input.getAttribute('value')).toEqual('say hello');
  23354. input.sendKeys(protractor.Key.ESCAPE);
  23355. expect(input.getAttribute('value')).toEqual('say');
  23356. other.click();
  23357. expect(model.getText()).toEqual('say');
  23358. });
  23359. </file>
  23360. </example>
  23361. This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
  23362. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  23363. <example name="ngModelOptions-directive-debounce" module="optionsExample">
  23364. <file name="index.html">
  23365. <div ng-controller="ExampleController">
  23366. <form name="userForm">
  23367. <label>Name:
  23368. <input type="text" name="userName"
  23369. ng-model="user.name"
  23370. ng-model-options="{ debounce: 1000 }" />
  23371. </label>
  23372. <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
  23373. <br />
  23374. </form>
  23375. <pre>user.name = <span ng-bind="user.name"></span></pre>
  23376. </div>
  23377. </file>
  23378. <file name="app.js">
  23379. angular.module('optionsExample', [])
  23380. .controller('ExampleController', ['$scope', function($scope) {
  23381. $scope.user = { name: 'say' };
  23382. }]);
  23383. </file>
  23384. </example>
  23385. This one shows how to bind to getter/setters:
  23386. <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  23387. <file name="index.html">
  23388. <div ng-controller="ExampleController">
  23389. <form name="userForm">
  23390. <label>Name:
  23391. <input type="text" name="userName"
  23392. ng-model="user.name"
  23393. ng-model-options="{ getterSetter: true }" />
  23394. </label>
  23395. </form>
  23396. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  23397. </div>
  23398. </file>
  23399. <file name="app.js">
  23400. angular.module('getterSetterExample', [])
  23401. .controller('ExampleController', ['$scope', function($scope) {
  23402. var _name = 'Brian';
  23403. $scope.user = {
  23404. name: function(newName) {
  23405. // Note that newName can be undefined for two reasons:
  23406. // 1. Because it is called as a getter and thus called with no arguments
  23407. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  23408. // input is invalid
  23409. return arguments.length ? (_name = newName) : _name;
  23410. }
  23411. };
  23412. }]);
  23413. </file>
  23414. </example>
  23415. */
  23416. var ngModelOptionsDirective = function() {
  23417. return {
  23418. restrict: 'A',
  23419. controller: ['$scope', '$attrs', function($scope, $attrs) {
  23420. var that = this;
  23421. this.$options = copy($scope.$eval($attrs.ngModelOptions));
  23422. // Allow adding/overriding bound events
  23423. if (this.$options.updateOn !== undefined) {
  23424. this.$options.updateOnDefault = false;
  23425. // extract "default" pseudo-event from list of events that can trigger a model update
  23426. this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
  23427. that.$options.updateOnDefault = true;
  23428. return ' ';
  23429. }));
  23430. } else {
  23431. this.$options.updateOnDefault = true;
  23432. }
  23433. }]
  23434. };
  23435. };
  23436. // helper methods
  23437. function addSetValidityMethod(context) {
  23438. var ctrl = context.ctrl,
  23439. $element = context.$element,
  23440. classCache = {},
  23441. set = context.set,
  23442. unset = context.unset,
  23443. parentForm = context.parentForm,
  23444. $animate = context.$animate;
  23445. classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
  23446. ctrl.$setValidity = setValidity;
  23447. function setValidity(validationErrorKey, state, controller) {
  23448. if (state === undefined) {
  23449. createAndSet('$pending', validationErrorKey, controller);
  23450. } else {
  23451. unsetAndCleanup('$pending', validationErrorKey, controller);
  23452. }
  23453. if (!isBoolean(state)) {
  23454. unset(ctrl.$error, validationErrorKey, controller);
  23455. unset(ctrl.$$success, validationErrorKey, controller);
  23456. } else {
  23457. if (state) {
  23458. unset(ctrl.$error, validationErrorKey, controller);
  23459. set(ctrl.$$success, validationErrorKey, controller);
  23460. } else {
  23461. set(ctrl.$error, validationErrorKey, controller);
  23462. unset(ctrl.$$success, validationErrorKey, controller);
  23463. }
  23464. }
  23465. if (ctrl.$pending) {
  23466. cachedToggleClass(PENDING_CLASS, true);
  23467. ctrl.$valid = ctrl.$invalid = undefined;
  23468. toggleValidationCss('', null);
  23469. } else {
  23470. cachedToggleClass(PENDING_CLASS, false);
  23471. ctrl.$valid = isObjectEmpty(ctrl.$error);
  23472. ctrl.$invalid = !ctrl.$valid;
  23473. toggleValidationCss('', ctrl.$valid);
  23474. }
  23475. // re-read the state as the set/unset methods could have
  23476. // combined state in ctrl.$error[validationError] (used for forms),
  23477. // where setting/unsetting only increments/decrements the value,
  23478. // and does not replace it.
  23479. var combinedState;
  23480. if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
  23481. combinedState = undefined;
  23482. } else if (ctrl.$error[validationErrorKey]) {
  23483. combinedState = false;
  23484. } else if (ctrl.$$success[validationErrorKey]) {
  23485. combinedState = true;
  23486. } else {
  23487. combinedState = null;
  23488. }
  23489. toggleValidationCss(validationErrorKey, combinedState);
  23490. parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
  23491. }
  23492. function createAndSet(name, value, controller) {
  23493. if (!ctrl[name]) {
  23494. ctrl[name] = {};
  23495. }
  23496. set(ctrl[name], value, controller);
  23497. }
  23498. function unsetAndCleanup(name, value, controller) {
  23499. if (ctrl[name]) {
  23500. unset(ctrl[name], value, controller);
  23501. }
  23502. if (isObjectEmpty(ctrl[name])) {
  23503. ctrl[name] = undefined;
  23504. }
  23505. }
  23506. function cachedToggleClass(className, switchValue) {
  23507. if (switchValue && !classCache[className]) {
  23508. $animate.addClass($element, className);
  23509. classCache[className] = true;
  23510. } else if (!switchValue && classCache[className]) {
  23511. $animate.removeClass($element, className);
  23512. classCache[className] = false;
  23513. }
  23514. }
  23515. function toggleValidationCss(validationErrorKey, isValid) {
  23516. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  23517. cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
  23518. cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
  23519. }
  23520. }
  23521. function isObjectEmpty(obj) {
  23522. if (obj) {
  23523. for (var prop in obj) {
  23524. if (obj.hasOwnProperty(prop)) {
  23525. return false;
  23526. }
  23527. }
  23528. }
  23529. return true;
  23530. }
  23531. /**
  23532. * @ngdoc directive
  23533. * @name ngNonBindable
  23534. * @restrict AC
  23535. * @priority 1000
  23536. *
  23537. * @description
  23538. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  23539. * DOM element. This is useful if the element contains what appears to be Angular directives and
  23540. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  23541. * displays snippets of code, for instance.
  23542. *
  23543. * @element ANY
  23544. *
  23545. * @example
  23546. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  23547. * but the one wrapped in `ngNonBindable` is left alone.
  23548. *
  23549. * @example
  23550. <example>
  23551. <file name="index.html">
  23552. <div>Normal: {{1 + 2}}</div>
  23553. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  23554. </file>
  23555. <file name="protractor.js" type="protractor">
  23556. it('should check ng-non-bindable', function() {
  23557. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  23558. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  23559. });
  23560. </file>
  23561. </example>
  23562. */
  23563. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  23564. /* global jqLiteRemove */
  23565. var ngOptionsMinErr = minErr('ngOptions');
  23566. /**
  23567. * @ngdoc directive
  23568. * @name ngOptions
  23569. * @restrict A
  23570. *
  23571. * @description
  23572. *
  23573. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  23574. * elements for the `<select>` element using the array or object obtained by evaluating the
  23575. * `ngOptions` comprehension expression.
  23576. *
  23577. * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
  23578. * similar result. However, `ngOptions` provides some benefits such as reducing memory and
  23579. * increasing speed by not creating a new scope for each repeated instance, as well as providing
  23580. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  23581. * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
  23582. * to a non-string value. This is because an option element can only be bound to string values at
  23583. * present.
  23584. *
  23585. * When an item in the `<select>` menu is selected, the array element or object property
  23586. * represented by the selected option will be bound to the model identified by the `ngModel`
  23587. * directive.
  23588. *
  23589. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  23590. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  23591. * option. See example below for demonstration.
  23592. *
  23593. * ## Complex Models (objects or collections)
  23594. *
  23595. * **Note:** By default, `ngModel` watches the model by reference, not value. This is important when
  23596. * binding any input directive to a model that is an object or a collection.
  23597. *
  23598. * Since this is a common situation for `ngOptions` the directive additionally watches the model using
  23599. * `$watchCollection` when the select has the `multiple` attribute or when there is a `track by` clause in
  23600. * the options expression. This allows ngOptions to trigger a re-rendering of the options even if the actual
  23601. * object/collection has not changed identity but only a property on the object or an item in the collection
  23602. * changes.
  23603. *
  23604. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  23605. * if the model is an array). This means that changing a property deeper inside the object/collection that the
  23606. * first level will not trigger a re-rendering.
  23607. *
  23608. *
  23609. * ## `select` **`as`**
  23610. *
  23611. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  23612. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  23613. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  23614. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  23615. *
  23616. *
  23617. * ### `select` **`as`** and **`track by`**
  23618. *
  23619. * <div class="alert alert-warning">
  23620. * Do not use `select` **`as`** and **`track by`** in the same expression. They are not designed to work together.
  23621. * </div>
  23622. *
  23623. * Consider the following example:
  23624. *
  23625. * ```html
  23626. * <select ng-options="item.subItem as item.label for item in values track by item.id" ng-model="selected"></select>
  23627. * ```
  23628. *
  23629. * ```js
  23630. * $scope.values = [{
  23631. * id: 1,
  23632. * label: 'aLabel',
  23633. * subItem: { name: 'aSubItem' }
  23634. * }, {
  23635. * id: 2,
  23636. * label: 'bLabel',
  23637. * subItem: { name: 'bSubItem' }
  23638. * }];
  23639. *
  23640. * $scope.selected = { name: 'aSubItem' };
  23641. * ```
  23642. *
  23643. * With the purpose of preserving the selection, the **`track by`** expression is always applied to the element
  23644. * of the data source (to `item` in this example). To calculate whether an element is selected, we do the
  23645. * following:
  23646. *
  23647. * 1. Apply **`track by`** to the elements in the array. In the example: `[1, 2]`
  23648. * 2. Apply **`track by`** to the already selected value in `ngModel`.
  23649. * In the example: this is not possible as **`track by`** refers to `item.id`, but the selected
  23650. * value from `ngModel` is `{name: 'aSubItem'}`, so the **`track by`** expression is applied to
  23651. * a wrong object, the selected element can't be found, `<select>` is always reset to the "not
  23652. * selected" option.
  23653. *
  23654. *
  23655. * @param {string} ngModel Assignable angular expression to data-bind to.
  23656. * @param {string=} name Property name of the form under which the control is published.
  23657. * @param {string=} required The control is considered valid only if value is entered.
  23658. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23659. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23660. * `required` when you want to data-bind to the `required` attribute.
  23661. * @param {comprehension_expression=} ngOptions in one of the following forms:
  23662. *
  23663. * * for array data sources:
  23664. * * `label` **`for`** `value` **`in`** `array`
  23665. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  23666. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  23667. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  23668. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  23669. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  23670. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  23671. * (for including a filter with `track by`)
  23672. * * for object data sources:
  23673. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  23674. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  23675. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  23676. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  23677. * * `select` **`as`** `label` **`group by`** `group`
  23678. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  23679. * * `select` **`as`** `label` **`disable when`** `disable`
  23680. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  23681. *
  23682. * Where:
  23683. *
  23684. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  23685. * * `value`: local variable which will refer to each item in the `array` or each property value
  23686. * of `object` during iteration.
  23687. * * `key`: local variable which will refer to a property name in `object` during iteration.
  23688. * * `label`: The result of this expression will be the label for `<option>` element. The
  23689. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  23690. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  23691. * element. If not specified, `select` expression will default to `value`.
  23692. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  23693. * DOM element.
  23694. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  23695. * element. Return `true` to disable.
  23696. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  23697. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  23698. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  23699. * even when the options are recreated (e.g. reloaded from the server).
  23700. *
  23701. * @example
  23702. <example module="selectExample">
  23703. <file name="index.html">
  23704. <script>
  23705. angular.module('selectExample', [])
  23706. .controller('ExampleController', ['$scope', function($scope) {
  23707. $scope.colors = [
  23708. {name:'black', shade:'dark'},
  23709. {name:'white', shade:'light', notAnOption: true},
  23710. {name:'red', shade:'dark'},
  23711. {name:'blue', shade:'dark', notAnOption: true},
  23712. {name:'yellow', shade:'light', notAnOption: false}
  23713. ];
  23714. $scope.myColor = $scope.colors[2]; // red
  23715. }]);
  23716. </script>
  23717. <div ng-controller="ExampleController">
  23718. <ul>
  23719. <li ng-repeat="color in colors">
  23720. <label>Name: <input ng-model="color.name"></label>
  23721. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  23722. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  23723. </li>
  23724. <li>
  23725. <button ng-click="colors.push({})">add</button>
  23726. </li>
  23727. </ul>
  23728. <hr/>
  23729. <label>Color (null not allowed):
  23730. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  23731. </label><br/>
  23732. <label>Color (null allowed):
  23733. <span class="nullable">
  23734. <select ng-model="myColor" ng-options="color.name for color in colors">
  23735. <option value="">-- choose color --</option>
  23736. </select>
  23737. </span></label><br/>
  23738. <label>Color grouped by shade:
  23739. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  23740. </select>
  23741. </label><br/>
  23742. <label>Color grouped by shade, with some disabled:
  23743. <select ng-model="myColor"
  23744. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  23745. </select>
  23746. </label><br/>
  23747. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  23748. <br/>
  23749. <hr/>
  23750. Currently selected: {{ {selected_color:myColor} }}
  23751. <div style="border:solid 1px black; height:20px"
  23752. ng-style="{'background-color':myColor.name}">
  23753. </div>
  23754. </div>
  23755. </file>
  23756. <file name="protractor.js" type="protractor">
  23757. it('should check ng-options', function() {
  23758. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  23759. element.all(by.model('myColor')).first().click();
  23760. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  23761. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  23762. element(by.css('.nullable select[ng-model="myColor"]')).click();
  23763. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  23764. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  23765. });
  23766. </file>
  23767. </example>
  23768. */
  23769. // jshint maxlen: false
  23770. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
  23771. 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]+?))?$/;
  23772. // 1: value expression (valueFn)
  23773. // 2: label expression (displayFn)
  23774. // 3: group by expression (groupByFn)
  23775. // 4: disable when expression (disableWhenFn)
  23776. // 5: array item variable name
  23777. // 6: object item key variable name
  23778. // 7: object item value variable name
  23779. // 8: collection expression
  23780. // 9: track by expression
  23781. // jshint maxlen: 100
  23782. var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
  23783. function parseOptionsExpression(optionsExp, selectElement, scope) {
  23784. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  23785. if (!(match)) {
  23786. throw ngOptionsMinErr('iexp',
  23787. "Expected expression in form of " +
  23788. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  23789. " but got '{0}'. Element: {1}",
  23790. optionsExp, startingTag(selectElement));
  23791. }
  23792. // Extract the parts from the ngOptions expression
  23793. // The variable name for the value of the item in the collection
  23794. var valueName = match[5] || match[7];
  23795. // The variable name for the key of the item in the collection
  23796. var keyName = match[6];
  23797. // An expression that generates the viewValue for an option if there is a label expression
  23798. var selectAs = / as /.test(match[0]) && match[1];
  23799. // An expression that is used to track the id of each object in the options collection
  23800. var trackBy = match[9];
  23801. // An expression that generates the viewValue for an option if there is no label expression
  23802. var valueFn = $parse(match[2] ? match[1] : valueName);
  23803. var selectAsFn = selectAs && $parse(selectAs);
  23804. var viewValueFn = selectAsFn || valueFn;
  23805. var trackByFn = trackBy && $parse(trackBy);
  23806. // Get the value by which we are going to track the option
  23807. // if we have a trackFn then use that (passing scope and locals)
  23808. // otherwise just hash the given viewValue
  23809. var getTrackByValueFn = trackBy ?
  23810. function(value, locals) { return trackByFn(scope, locals); } :
  23811. function getHashOfValue(value) { return hashKey(value); };
  23812. var getTrackByValue = function(value, key) {
  23813. return getTrackByValueFn(value, getLocals(value, key));
  23814. };
  23815. var displayFn = $parse(match[2] || match[1]);
  23816. var groupByFn = $parse(match[3] || '');
  23817. var disableWhenFn = $parse(match[4] || '');
  23818. var valuesFn = $parse(match[8]);
  23819. var locals = {};
  23820. var getLocals = keyName ? function(value, key) {
  23821. locals[keyName] = key;
  23822. locals[valueName] = value;
  23823. return locals;
  23824. } : function(value) {
  23825. locals[valueName] = value;
  23826. return locals;
  23827. };
  23828. function Option(selectValue, viewValue, label, group, disabled) {
  23829. this.selectValue = selectValue;
  23830. this.viewValue = viewValue;
  23831. this.label = label;
  23832. this.group = group;
  23833. this.disabled = disabled;
  23834. }
  23835. function getOptionValuesKeys(optionValues) {
  23836. var optionValuesKeys;
  23837. if (!keyName && isArrayLike(optionValues)) {
  23838. optionValuesKeys = optionValues;
  23839. } else {
  23840. // if object, extract keys, in enumeration order, unsorted
  23841. optionValuesKeys = [];
  23842. for (var itemKey in optionValues) {
  23843. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  23844. optionValuesKeys.push(itemKey);
  23845. }
  23846. }
  23847. }
  23848. return optionValuesKeys;
  23849. }
  23850. return {
  23851. trackBy: trackBy,
  23852. getTrackByValue: getTrackByValue,
  23853. getWatchables: $parse(valuesFn, function(optionValues) {
  23854. // Create a collection of things that we would like to watch (watchedArray)
  23855. // so that they can all be watched using a single $watchCollection
  23856. // that only runs the handler once if anything changes
  23857. var watchedArray = [];
  23858. optionValues = optionValues || [];
  23859. var optionValuesKeys = getOptionValuesKeys(optionValues);
  23860. var optionValuesLength = optionValuesKeys.length;
  23861. for (var index = 0; index < optionValuesLength; index++) {
  23862. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  23863. var value = optionValues[key];
  23864. var locals = getLocals(optionValues[key], key);
  23865. var selectValue = getTrackByValueFn(optionValues[key], locals);
  23866. watchedArray.push(selectValue);
  23867. // Only need to watch the displayFn if there is a specific label expression
  23868. if (match[2] || match[1]) {
  23869. var label = displayFn(scope, locals);
  23870. watchedArray.push(label);
  23871. }
  23872. // Only need to watch the disableWhenFn if there is a specific disable expression
  23873. if (match[4]) {
  23874. var disableWhen = disableWhenFn(scope, locals);
  23875. watchedArray.push(disableWhen);
  23876. }
  23877. }
  23878. return watchedArray;
  23879. }),
  23880. getOptions: function() {
  23881. var optionItems = [];
  23882. var selectValueMap = {};
  23883. // The option values were already computed in the `getWatchables` fn,
  23884. // which must have been called to trigger `getOptions`
  23885. var optionValues = valuesFn(scope) || [];
  23886. var optionValuesKeys = getOptionValuesKeys(optionValues);
  23887. var optionValuesLength = optionValuesKeys.length;
  23888. for (var index = 0; index < optionValuesLength; index++) {
  23889. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  23890. var value = optionValues[key];
  23891. var locals = getLocals(value, key);
  23892. var viewValue = viewValueFn(scope, locals);
  23893. var selectValue = getTrackByValueFn(viewValue, locals);
  23894. var label = displayFn(scope, locals);
  23895. var group = groupByFn(scope, locals);
  23896. var disabled = disableWhenFn(scope, locals);
  23897. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  23898. optionItems.push(optionItem);
  23899. selectValueMap[selectValue] = optionItem;
  23900. }
  23901. return {
  23902. items: optionItems,
  23903. selectValueMap: selectValueMap,
  23904. getOptionFromViewValue: function(value) {
  23905. return selectValueMap[getTrackByValue(value)];
  23906. },
  23907. getViewValueFromOption: function(option) {
  23908. // If the viewValue could be an object that may be mutated by the application,
  23909. // we need to make a copy and not return the reference to the value on the option.
  23910. return trackBy ? angular.copy(option.viewValue) : option.viewValue;
  23911. }
  23912. };
  23913. }
  23914. };
  23915. }
  23916. // we can't just jqLite('<option>') since jqLite is not smart enough
  23917. // to create it in <select> and IE barfs otherwise.
  23918. var optionTemplate = document.createElement('option'),
  23919. optGroupTemplate = document.createElement('optgroup');
  23920. return {
  23921. restrict: 'A',
  23922. terminal: true,
  23923. require: ['select', '?ngModel'],
  23924. link: function(scope, selectElement, attr, ctrls) {
  23925. // if ngModel is not defined, we don't need to do anything
  23926. var ngModelCtrl = ctrls[1];
  23927. if (!ngModelCtrl) return;
  23928. var selectCtrl = ctrls[0];
  23929. var multiple = attr.multiple;
  23930. // The emptyOption allows the application developer to provide their own custom "empty"
  23931. // option when the viewValue does not match any of the option values.
  23932. var emptyOption;
  23933. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  23934. if (children[i].value === '') {
  23935. emptyOption = children.eq(i);
  23936. break;
  23937. }
  23938. }
  23939. var providedEmptyOption = !!emptyOption;
  23940. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  23941. unknownOption.val('?');
  23942. var options;
  23943. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  23944. var renderEmptyOption = function() {
  23945. if (!providedEmptyOption) {
  23946. selectElement.prepend(emptyOption);
  23947. }
  23948. selectElement.val('');
  23949. emptyOption.prop('selected', true); // needed for IE
  23950. emptyOption.attr('selected', true);
  23951. };
  23952. var removeEmptyOption = function() {
  23953. if (!providedEmptyOption) {
  23954. emptyOption.remove();
  23955. }
  23956. };
  23957. var renderUnknownOption = function() {
  23958. selectElement.prepend(unknownOption);
  23959. selectElement.val('?');
  23960. unknownOption.prop('selected', true); // needed for IE
  23961. unknownOption.attr('selected', true);
  23962. };
  23963. var removeUnknownOption = function() {
  23964. unknownOption.remove();
  23965. };
  23966. // Update the controller methods for multiple selectable options
  23967. if (!multiple) {
  23968. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  23969. var option = options.getOptionFromViewValue(value);
  23970. if (option && !option.disabled) {
  23971. if (selectElement[0].value !== option.selectValue) {
  23972. removeUnknownOption();
  23973. removeEmptyOption();
  23974. selectElement[0].value = option.selectValue;
  23975. option.element.selected = true;
  23976. option.element.setAttribute('selected', 'selected');
  23977. }
  23978. } else {
  23979. if (value === null || providedEmptyOption) {
  23980. removeUnknownOption();
  23981. renderEmptyOption();
  23982. } else {
  23983. removeEmptyOption();
  23984. renderUnknownOption();
  23985. }
  23986. }
  23987. };
  23988. selectCtrl.readValue = function readNgOptionsValue() {
  23989. var selectedOption = options.selectValueMap[selectElement.val()];
  23990. if (selectedOption && !selectedOption.disabled) {
  23991. removeEmptyOption();
  23992. removeUnknownOption();
  23993. return options.getViewValueFromOption(selectedOption);
  23994. }
  23995. return null;
  23996. };
  23997. // If we are using `track by` then we must watch the tracked value on the model
  23998. // since ngModel only watches for object identity change
  23999. if (ngOptions.trackBy) {
  24000. scope.$watch(
  24001. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  24002. function() { ngModelCtrl.$render(); }
  24003. );
  24004. }
  24005. } else {
  24006. ngModelCtrl.$isEmpty = function(value) {
  24007. return !value || value.length === 0;
  24008. };
  24009. selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
  24010. options.items.forEach(function(option) {
  24011. option.element.selected = false;
  24012. });
  24013. if (value) {
  24014. value.forEach(function(item) {
  24015. var option = options.getOptionFromViewValue(item);
  24016. if (option && !option.disabled) option.element.selected = true;
  24017. });
  24018. }
  24019. };
  24020. selectCtrl.readValue = function readNgOptionsMultiple() {
  24021. var selectedValues = selectElement.val() || [],
  24022. selections = [];
  24023. forEach(selectedValues, function(value) {
  24024. var option = options.selectValueMap[value];
  24025. if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
  24026. });
  24027. return selections;
  24028. };
  24029. // If we are using `track by` then we must watch these tracked values on the model
  24030. // since ngModel only watches for object identity change
  24031. if (ngOptions.trackBy) {
  24032. scope.$watchCollection(function() {
  24033. if (isArray(ngModelCtrl.$viewValue)) {
  24034. return ngModelCtrl.$viewValue.map(function(value) {
  24035. return ngOptions.getTrackByValue(value);
  24036. });
  24037. }
  24038. }, function() {
  24039. ngModelCtrl.$render();
  24040. });
  24041. }
  24042. }
  24043. if (providedEmptyOption) {
  24044. // we need to remove it before calling selectElement.empty() because otherwise IE will
  24045. // remove the label from the element. wtf?
  24046. emptyOption.remove();
  24047. // compile the element since there might be bindings in it
  24048. $compile(emptyOption)(scope);
  24049. // remove the class, which is added automatically because we recompile the element and it
  24050. // becomes the compilation root
  24051. emptyOption.removeClass('ng-scope');
  24052. } else {
  24053. emptyOption = jqLite(optionTemplate.cloneNode(false));
  24054. }
  24055. // We need to do this here to ensure that the options object is defined
  24056. // when we first hit it in writeNgOptionsValue
  24057. updateOptions();
  24058. // We will re-render the option elements if the option values or labels change
  24059. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  24060. // ------------------------------------------------------------------ //
  24061. function updateOptionElement(option, element) {
  24062. option.element = element;
  24063. element.disabled = option.disabled;
  24064. if (option.value !== element.value) element.value = option.selectValue;
  24065. if (option.label !== element.label) {
  24066. element.label = option.label;
  24067. element.textContent = option.label;
  24068. }
  24069. }
  24070. function addOrReuseElement(parent, current, type, templateElement) {
  24071. var element;
  24072. // Check whether we can reuse the next element
  24073. if (current && lowercase(current.nodeName) === type) {
  24074. // The next element is the right type so reuse it
  24075. element = current;
  24076. } else {
  24077. // The next element is not the right type so create a new one
  24078. element = templateElement.cloneNode(false);
  24079. if (!current) {
  24080. // There are no more elements so just append it to the select
  24081. parent.appendChild(element);
  24082. } else {
  24083. // The next element is not a group so insert the new one
  24084. parent.insertBefore(element, current);
  24085. }
  24086. }
  24087. return element;
  24088. }
  24089. function removeExcessElements(current) {
  24090. var next;
  24091. while (current) {
  24092. next = current.nextSibling;
  24093. jqLiteRemove(current);
  24094. current = next;
  24095. }
  24096. }
  24097. function skipEmptyAndUnknownOptions(current) {
  24098. var emptyOption_ = emptyOption && emptyOption[0];
  24099. var unknownOption_ = unknownOption && unknownOption[0];
  24100. if (emptyOption_ || unknownOption_) {
  24101. while (current &&
  24102. (current === emptyOption_ ||
  24103. current === unknownOption_)) {
  24104. current = current.nextSibling;
  24105. }
  24106. }
  24107. return current;
  24108. }
  24109. function updateOptions() {
  24110. var previousValue = options && selectCtrl.readValue();
  24111. options = ngOptions.getOptions();
  24112. var groupMap = {};
  24113. var currentElement = selectElement[0].firstChild;
  24114. // Ensure that the empty option is always there if it was explicitly provided
  24115. if (providedEmptyOption) {
  24116. selectElement.prepend(emptyOption);
  24117. }
  24118. currentElement = skipEmptyAndUnknownOptions(currentElement);
  24119. options.items.forEach(function updateOption(option) {
  24120. var group;
  24121. var groupElement;
  24122. var optionElement;
  24123. if (option.group) {
  24124. // This option is to live in a group
  24125. // See if we have already created this group
  24126. group = groupMap[option.group];
  24127. if (!group) {
  24128. // We have not already created this group
  24129. groupElement = addOrReuseElement(selectElement[0],
  24130. currentElement,
  24131. 'optgroup',
  24132. optGroupTemplate);
  24133. // Move to the next element
  24134. currentElement = groupElement.nextSibling;
  24135. // Update the label on the group element
  24136. groupElement.label = option.group;
  24137. // Store it for use later
  24138. group = groupMap[option.group] = {
  24139. groupElement: groupElement,
  24140. currentOptionElement: groupElement.firstChild
  24141. };
  24142. }
  24143. // So now we have a group for this option we add the option to the group
  24144. optionElement = addOrReuseElement(group.groupElement,
  24145. group.currentOptionElement,
  24146. 'option',
  24147. optionTemplate);
  24148. updateOptionElement(option, optionElement);
  24149. // Move to the next element
  24150. group.currentOptionElement = optionElement.nextSibling;
  24151. } else {
  24152. // This option is not in a group
  24153. optionElement = addOrReuseElement(selectElement[0],
  24154. currentElement,
  24155. 'option',
  24156. optionTemplate);
  24157. updateOptionElement(option, optionElement);
  24158. // Move to the next element
  24159. currentElement = optionElement.nextSibling;
  24160. }
  24161. });
  24162. // Now remove all excess options and group
  24163. Object.keys(groupMap).forEach(function(key) {
  24164. removeExcessElements(groupMap[key].currentOptionElement);
  24165. });
  24166. removeExcessElements(currentElement);
  24167. ngModelCtrl.$render();
  24168. // Check to see if the value has changed due to the update to the options
  24169. if (!ngModelCtrl.$isEmpty(previousValue)) {
  24170. var nextValue = selectCtrl.readValue();
  24171. if (ngOptions.trackBy ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
  24172. ngModelCtrl.$setViewValue(nextValue);
  24173. ngModelCtrl.$render();
  24174. }
  24175. }
  24176. }
  24177. }
  24178. };
  24179. }];
  24180. /**
  24181. * @ngdoc directive
  24182. * @name ngPluralize
  24183. * @restrict EA
  24184. *
  24185. * @description
  24186. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  24187. * These rules are bundled with angular.js, but can be overridden
  24188. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  24189. * by specifying the mappings between
  24190. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  24191. * and the strings to be displayed.
  24192. *
  24193. * # Plural categories and explicit number rules
  24194. * There are two
  24195. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  24196. * in Angular's default en-US locale: "one" and "other".
  24197. *
  24198. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  24199. * any number that is not 1), an explicit number rule can only match one number. For example, the
  24200. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  24201. * and explicit number rules throughout the rest of this documentation.
  24202. *
  24203. * # Configuring ngPluralize
  24204. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  24205. * You can also provide an optional attribute, `offset`.
  24206. *
  24207. * The value of the `count` attribute can be either a string or an {@link guide/expression
  24208. * Angular expression}; these are evaluated on the current scope for its bound value.
  24209. *
  24210. * The `when` attribute specifies the mappings between plural categories and the actual
  24211. * string to be displayed. The value of the attribute should be a JSON object.
  24212. *
  24213. * The following example shows how to configure ngPluralize:
  24214. *
  24215. * ```html
  24216. * <ng-pluralize count="personCount"
  24217. when="{'0': 'Nobody is viewing.',
  24218. * 'one': '1 person is viewing.',
  24219. * 'other': '{} people are viewing.'}">
  24220. * </ng-pluralize>
  24221. *```
  24222. *
  24223. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  24224. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  24225. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  24226. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  24227. * show "a dozen people are viewing".
  24228. *
  24229. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  24230. * into pluralized strings. In the previous example, Angular will replace `{}` with
  24231. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  24232. * for <span ng-non-bindable>{{numberExpression}}</span>.
  24233. *
  24234. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  24235. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  24236. *
  24237. * # Configuring ngPluralize with offset
  24238. * The `offset` attribute allows further customization of pluralized text, which can result in
  24239. * a better user experience. For example, instead of the message "4 people are viewing this document",
  24240. * you might display "John, Kate and 2 others are viewing this document".
  24241. * The offset attribute allows you to offset a number by any desired value.
  24242. * Let's take a look at an example:
  24243. *
  24244. * ```html
  24245. * <ng-pluralize count="personCount" offset=2
  24246. * when="{'0': 'Nobody is viewing.',
  24247. * '1': '{{person1}} is viewing.',
  24248. * '2': '{{person1}} and {{person2}} are viewing.',
  24249. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  24250. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  24251. * </ng-pluralize>
  24252. * ```
  24253. *
  24254. * Notice that we are still using two plural categories(one, other), but we added
  24255. * three explicit number rules 0, 1 and 2.
  24256. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  24257. * When three people view the document, no explicit number rule is found, so
  24258. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  24259. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  24260. * is shown.
  24261. *
  24262. * Note that when you specify offsets, you must provide explicit number rules for
  24263. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  24264. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  24265. * plural categories "one" and "other".
  24266. *
  24267. * @param {string|expression} count The variable to be bound to.
  24268. * @param {string} when The mapping between plural category to its corresponding strings.
  24269. * @param {number=} offset Offset to deduct from the total number.
  24270. *
  24271. * @example
  24272. <example module="pluralizeExample">
  24273. <file name="index.html">
  24274. <script>
  24275. angular.module('pluralizeExample', [])
  24276. .controller('ExampleController', ['$scope', function($scope) {
  24277. $scope.person1 = 'Igor';
  24278. $scope.person2 = 'Misko';
  24279. $scope.personCount = 1;
  24280. }]);
  24281. </script>
  24282. <div ng-controller="ExampleController">
  24283. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  24284. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  24285. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  24286. <!--- Example with simple pluralization rules for en locale --->
  24287. Without Offset:
  24288. <ng-pluralize count="personCount"
  24289. when="{'0': 'Nobody is viewing.',
  24290. 'one': '1 person is viewing.',
  24291. 'other': '{} people are viewing.'}">
  24292. </ng-pluralize><br>
  24293. <!--- Example with offset --->
  24294. With Offset(2):
  24295. <ng-pluralize count="personCount" offset=2
  24296. when="{'0': 'Nobody is viewing.',
  24297. '1': '{{person1}} is viewing.',
  24298. '2': '{{person1}} and {{person2}} are viewing.',
  24299. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  24300. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  24301. </ng-pluralize>
  24302. </div>
  24303. </file>
  24304. <file name="protractor.js" type="protractor">
  24305. it('should show correct pluralized string', function() {
  24306. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  24307. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  24308. var countInput = element(by.model('personCount'));
  24309. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  24310. expect(withOffset.getText()).toEqual('Igor is viewing.');
  24311. countInput.clear();
  24312. countInput.sendKeys('0');
  24313. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  24314. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  24315. countInput.clear();
  24316. countInput.sendKeys('2');
  24317. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  24318. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  24319. countInput.clear();
  24320. countInput.sendKeys('3');
  24321. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  24322. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  24323. countInput.clear();
  24324. countInput.sendKeys('4');
  24325. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  24326. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  24327. });
  24328. it('should show data-bound names', function() {
  24329. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  24330. var personCount = element(by.model('personCount'));
  24331. var person1 = element(by.model('person1'));
  24332. var person2 = element(by.model('person2'));
  24333. personCount.clear();
  24334. personCount.sendKeys('4');
  24335. person1.clear();
  24336. person1.sendKeys('Di');
  24337. person2.clear();
  24338. person2.sendKeys('Vojta');
  24339. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  24340. });
  24341. </file>
  24342. </example>
  24343. */
  24344. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  24345. var BRACE = /{}/g,
  24346. IS_WHEN = /^when(Minus)?(.+)$/;
  24347. return {
  24348. link: function(scope, element, attr) {
  24349. var numberExp = attr.count,
  24350. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  24351. offset = attr.offset || 0,
  24352. whens = scope.$eval(whenExp) || {},
  24353. whensExpFns = {},
  24354. startSymbol = $interpolate.startSymbol(),
  24355. endSymbol = $interpolate.endSymbol(),
  24356. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  24357. watchRemover = angular.noop,
  24358. lastCount;
  24359. forEach(attr, function(expression, attributeName) {
  24360. var tmpMatch = IS_WHEN.exec(attributeName);
  24361. if (tmpMatch) {
  24362. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  24363. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  24364. }
  24365. });
  24366. forEach(whens, function(expression, key) {
  24367. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  24368. });
  24369. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  24370. var count = parseFloat(newVal);
  24371. var countIsNaN = isNaN(count);
  24372. if (!countIsNaN && !(count in whens)) {
  24373. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  24374. // Otherwise, check it against pluralization rules in $locale service.
  24375. count = $locale.pluralCat(count - offset);
  24376. }
  24377. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  24378. // In JS `NaN !== NaN`, so we have to exlicitly check.
  24379. if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {
  24380. watchRemover();
  24381. var whenExpFn = whensExpFns[count];
  24382. if (isUndefined(whenExpFn)) {
  24383. if (newVal != null) {
  24384. $log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp);
  24385. }
  24386. watchRemover = noop;
  24387. updateElementText();
  24388. } else {
  24389. watchRemover = scope.$watch(whenExpFn, updateElementText);
  24390. }
  24391. lastCount = count;
  24392. }
  24393. });
  24394. function updateElementText(newText) {
  24395. element.text(newText || '');
  24396. }
  24397. }
  24398. };
  24399. }];
  24400. /**
  24401. * @ngdoc directive
  24402. * @name ngRepeat
  24403. * @multiElement
  24404. *
  24405. * @description
  24406. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  24407. * instance gets its own scope, where the given loop variable is set to the current collection item,
  24408. * and `$index` is set to the item index or key.
  24409. *
  24410. * Special properties are exposed on the local scope of each template instance, including:
  24411. *
  24412. * | Variable | Type | Details |
  24413. * |-----------|-----------------|-----------------------------------------------------------------------------|
  24414. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  24415. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  24416. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  24417. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  24418. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  24419. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  24420. *
  24421. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  24422. * This may be useful when, for instance, nesting ngRepeats.
  24423. *
  24424. *
  24425. * # Iterating over object properties
  24426. *
  24427. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  24428. * syntax:
  24429. *
  24430. * ```js
  24431. * <div ng-repeat="(key, value) in myObj"> ... </div>
  24432. * ```
  24433. *
  24434. * You need to be aware that the JavaScript specification does not define the order of keys
  24435. * returned for an object. (To mitigate this in Angular 1.3 the `ngRepeat` directive
  24436. * used to sort the keys alphabetically.)
  24437. *
  24438. * Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser
  24439. * when running `for key in myObj`. It seems that browsers generally follow the strategy of providing
  24440. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  24441. * and reinstated. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_issues
  24442. *
  24443. * If this is not desired, the recommended workaround is to convert your object into an array
  24444. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  24445. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  24446. * or implement a `$watch` on the object yourself.
  24447. *
  24448. *
  24449. * # Tracking and Duplicates
  24450. *
  24451. * When the contents of the collection change, `ngRepeat` makes the corresponding changes to the DOM:
  24452. *
  24453. * * When an item is added, a new instance of the template is added to the DOM.
  24454. * * When an item is removed, its template instance is removed from the DOM.
  24455. * * When items are reordered, their respective templates are reordered in the DOM.
  24456. *
  24457. * By default, `ngRepeat` does not allow duplicate items in arrays. This is because when
  24458. * there are duplicates, it is not possible to maintain a one-to-one mapping between collection
  24459. * items and DOM elements.
  24460. *
  24461. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  24462. * with your own using the `track by` expression.
  24463. *
  24464. * For example, you may track items by the index of each item in the collection, using the
  24465. * special scope property `$index`:
  24466. * ```html
  24467. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  24468. * {{n}}
  24469. * </div>
  24470. * ```
  24471. *
  24472. * You may use arbitrary expressions in `track by`, including references to custom functions
  24473. * on the scope:
  24474. * ```html
  24475. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  24476. * {{n}}
  24477. * </div>
  24478. * ```
  24479. *
  24480. * If you are working with objects that have an identifier property, you can track
  24481. * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
  24482. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  24483. * JavaScript objects in the collection have been substituted for new ones:
  24484. * ```html
  24485. * <div ng-repeat="model in collection track by model.id">
  24486. * {{model.name}}
  24487. * </div>
  24488. * ```
  24489. *
  24490. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  24491. * `$id` function, which tracks items by their identity:
  24492. * ```html
  24493. * <div ng-repeat="obj in collection track by $id(obj)">
  24494. * {{obj.prop}}
  24495. * </div>
  24496. * ```
  24497. *
  24498. * <div class="alert alert-warning">
  24499. * **Note:** `track by` must always be the last expression:
  24500. * </div>
  24501. * ```
  24502. * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
  24503. * {{model.name}}
  24504. * </div>
  24505. * ```
  24506. *
  24507. * # Special repeat start and end points
  24508. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  24509. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  24510. * 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)
  24511. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  24512. *
  24513. * The example below makes use of this feature:
  24514. * ```html
  24515. * <header ng-repeat-start="item in items">
  24516. * Header {{ item }}
  24517. * </header>
  24518. * <div class="body">
  24519. * Body {{ item }}
  24520. * </div>
  24521. * <footer ng-repeat-end>
  24522. * Footer {{ item }}
  24523. * </footer>
  24524. * ```
  24525. *
  24526. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  24527. * ```html
  24528. * <header>
  24529. * Header A
  24530. * </header>
  24531. * <div class="body">
  24532. * Body A
  24533. * </div>
  24534. * <footer>
  24535. * Footer A
  24536. * </footer>
  24537. * <header>
  24538. * Header B
  24539. * </header>
  24540. * <div class="body">
  24541. * Body B
  24542. * </div>
  24543. * <footer>
  24544. * Footer B
  24545. * </footer>
  24546. * ```
  24547. *
  24548. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  24549. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  24550. *
  24551. * @animations
  24552. * **.enter** - when a new item is added to the list or when an item is revealed after a filter
  24553. *
  24554. * **.leave** - when an item is removed from the list or when an item is filtered out
  24555. *
  24556. * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
  24557. *
  24558. * @element ANY
  24559. * @scope
  24560. * @priority 1000
  24561. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  24562. * formats are currently supported:
  24563. *
  24564. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  24565. * is a scope expression giving the collection to enumerate.
  24566. *
  24567. * For example: `album in artist.albums`.
  24568. *
  24569. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  24570. * and `expression` is the scope expression giving the collection to enumerate.
  24571. *
  24572. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  24573. *
  24574. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  24575. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  24576. * is specified, ng-repeat associates elements by identity. It is an error to have
  24577. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  24578. * mapped to the same DOM element, which is not possible.)
  24579. *
  24580. * Note that the tracking expression must come last, after any filters, and the alias expression.
  24581. *
  24582. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  24583. * will be associated by item identity in the array.
  24584. *
  24585. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  24586. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  24587. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  24588. * element in the same way in the DOM.
  24589. *
  24590. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  24591. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  24592. * property is same.
  24593. *
  24594. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  24595. * to items in conjunction with a tracking expression.
  24596. *
  24597. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  24598. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  24599. * when a filter is active on the repeater, but the filtered result set is empty.
  24600. *
  24601. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  24602. * the items have been processed through the filter.
  24603. *
  24604. * 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
  24605. * (and not as operator, inside an expression).
  24606. *
  24607. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
  24608. *
  24609. * @example
  24610. * This example initializes the scope to a list of names and
  24611. * then uses `ngRepeat` to display every person:
  24612. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  24613. <file name="index.html">
  24614. <div ng-init="friends = [
  24615. {name:'John', age:25, gender:'boy'},
  24616. {name:'Jessie', age:30, gender:'girl'},
  24617. {name:'Johanna', age:28, gender:'girl'},
  24618. {name:'Joy', age:15, gender:'girl'},
  24619. {name:'Mary', age:28, gender:'girl'},
  24620. {name:'Peter', age:95, gender:'boy'},
  24621. {name:'Sebastian', age:50, gender:'boy'},
  24622. {name:'Erika', age:27, gender:'girl'},
  24623. {name:'Patrick', age:40, gender:'boy'},
  24624. {name:'Samantha', age:60, gender:'girl'}
  24625. ]">
  24626. I have {{friends.length}} friends. They are:
  24627. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  24628. <ul class="example-animate-container">
  24629. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  24630. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  24631. </li>
  24632. <li class="animate-repeat" ng-if="results.length == 0">
  24633. <strong>No results found...</strong>
  24634. </li>
  24635. </ul>
  24636. </div>
  24637. </file>
  24638. <file name="animations.css">
  24639. .example-animate-container {
  24640. background:white;
  24641. border:1px solid black;
  24642. list-style:none;
  24643. margin:0;
  24644. padding:0 10px;
  24645. }
  24646. .animate-repeat {
  24647. line-height:40px;
  24648. list-style:none;
  24649. box-sizing:border-box;
  24650. }
  24651. .animate-repeat.ng-move,
  24652. .animate-repeat.ng-enter,
  24653. .animate-repeat.ng-leave {
  24654. transition:all linear 0.5s;
  24655. }
  24656. .animate-repeat.ng-leave.ng-leave-active,
  24657. .animate-repeat.ng-move,
  24658. .animate-repeat.ng-enter {
  24659. opacity:0;
  24660. max-height:0;
  24661. }
  24662. .animate-repeat.ng-leave,
  24663. .animate-repeat.ng-move.ng-move-active,
  24664. .animate-repeat.ng-enter.ng-enter-active {
  24665. opacity:1;
  24666. max-height:40px;
  24667. }
  24668. </file>
  24669. <file name="protractor.js" type="protractor">
  24670. var friends = element.all(by.repeater('friend in friends'));
  24671. it('should render initial data set', function() {
  24672. expect(friends.count()).toBe(10);
  24673. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  24674. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  24675. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  24676. expect(element(by.binding('friends.length')).getText())
  24677. .toMatch("I have 10 friends. They are:");
  24678. });
  24679. it('should update repeater when filter predicate changes', function() {
  24680. expect(friends.count()).toBe(10);
  24681. element(by.model('q')).sendKeys('ma');
  24682. expect(friends.count()).toBe(2);
  24683. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  24684. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  24685. });
  24686. </file>
  24687. </example>
  24688. */
  24689. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  24690. var NG_REMOVED = '$$NG_REMOVED';
  24691. var ngRepeatMinErr = minErr('ngRepeat');
  24692. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  24693. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  24694. scope[valueIdentifier] = value;
  24695. if (keyIdentifier) scope[keyIdentifier] = key;
  24696. scope.$index = index;
  24697. scope.$first = (index === 0);
  24698. scope.$last = (index === (arrayLength - 1));
  24699. scope.$middle = !(scope.$first || scope.$last);
  24700. // jshint bitwise: false
  24701. scope.$odd = !(scope.$even = (index&1) === 0);
  24702. // jshint bitwise: true
  24703. };
  24704. var getBlockStart = function(block) {
  24705. return block.clone[0];
  24706. };
  24707. var getBlockEnd = function(block) {
  24708. return block.clone[block.clone.length - 1];
  24709. };
  24710. return {
  24711. restrict: 'A',
  24712. multiElement: true,
  24713. transclude: 'element',
  24714. priority: 1000,
  24715. terminal: true,
  24716. $$tlb: true,
  24717. compile: function ngRepeatCompile($element, $attr) {
  24718. var expression = $attr.ngRepeat;
  24719. var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
  24720. 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*$/);
  24721. if (!match) {
  24722. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  24723. expression);
  24724. }
  24725. var lhs = match[1];
  24726. var rhs = match[2];
  24727. var aliasAs = match[3];
  24728. var trackByExp = match[4];
  24729. match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
  24730. if (!match) {
  24731. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  24732. lhs);
  24733. }
  24734. var valueIdentifier = match[3] || match[1];
  24735. var keyIdentifier = match[2];
  24736. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  24737. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  24738. throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
  24739. aliasAs);
  24740. }
  24741. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  24742. var hashFnLocals = {$id: hashKey};
  24743. if (trackByExp) {
  24744. trackByExpGetter = $parse(trackByExp);
  24745. } else {
  24746. trackByIdArrayFn = function(key, value) {
  24747. return hashKey(value);
  24748. };
  24749. trackByIdObjFn = function(key) {
  24750. return key;
  24751. };
  24752. }
  24753. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  24754. if (trackByExpGetter) {
  24755. trackByIdExpFn = function(key, value, index) {
  24756. // assign key, value, and $index to the locals so that they can be used in hash functions
  24757. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  24758. hashFnLocals[valueIdentifier] = value;
  24759. hashFnLocals.$index = index;
  24760. return trackByExpGetter($scope, hashFnLocals);
  24761. };
  24762. }
  24763. // Store a list of elements from previous run. This is a hash where key is the item from the
  24764. // iterator, and the value is objects with following properties.
  24765. // - scope: bound scope
  24766. // - element: previous element.
  24767. // - index: position
  24768. //
  24769. // We are using no-proto object so that we don't need to guard against inherited props via
  24770. // hasOwnProperty.
  24771. var lastBlockMap = createMap();
  24772. //watch props
  24773. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  24774. var index, length,
  24775. previousNode = $element[0], // node that cloned nodes should be inserted after
  24776. // initialized to the comment node anchor
  24777. nextNode,
  24778. // Same as lastBlockMap but it has the current state. It will become the
  24779. // lastBlockMap on the next iteration.
  24780. nextBlockMap = createMap(),
  24781. collectionLength,
  24782. key, value, // key/value of iteration
  24783. trackById,
  24784. trackByIdFn,
  24785. collectionKeys,
  24786. block, // last object information {scope, element, id}
  24787. nextBlockOrder,
  24788. elementsToRemove;
  24789. if (aliasAs) {
  24790. $scope[aliasAs] = collection;
  24791. }
  24792. if (isArrayLike(collection)) {
  24793. collectionKeys = collection;
  24794. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  24795. } else {
  24796. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  24797. // if object, extract keys, in enumeration order, unsorted
  24798. collectionKeys = [];
  24799. for (var itemKey in collection) {
  24800. if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  24801. collectionKeys.push(itemKey);
  24802. }
  24803. }
  24804. }
  24805. collectionLength = collectionKeys.length;
  24806. nextBlockOrder = new Array(collectionLength);
  24807. // locate existing items
  24808. for (index = 0; index < collectionLength; index++) {
  24809. key = (collection === collectionKeys) ? index : collectionKeys[index];
  24810. value = collection[key];
  24811. trackById = trackByIdFn(key, value, index);
  24812. if (lastBlockMap[trackById]) {
  24813. // found previously seen block
  24814. block = lastBlockMap[trackById];
  24815. delete lastBlockMap[trackById];
  24816. nextBlockMap[trackById] = block;
  24817. nextBlockOrder[index] = block;
  24818. } else if (nextBlockMap[trackById]) {
  24819. // if collision detected. restore lastBlockMap and throw an error
  24820. forEach(nextBlockOrder, function(block) {
  24821. if (block && block.scope) lastBlockMap[block.id] = block;
  24822. });
  24823. throw ngRepeatMinErr('dupes',
  24824. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  24825. expression, trackById, value);
  24826. } else {
  24827. // new never before seen block
  24828. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  24829. nextBlockMap[trackById] = true;
  24830. }
  24831. }
  24832. // remove leftover items
  24833. for (var blockKey in lastBlockMap) {
  24834. block = lastBlockMap[blockKey];
  24835. elementsToRemove = getBlockNodes(block.clone);
  24836. $animate.leave(elementsToRemove);
  24837. if (elementsToRemove[0].parentNode) {
  24838. // if the element was not removed yet because of pending animation, mark it as deleted
  24839. // so that we can ignore it later
  24840. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  24841. elementsToRemove[index][NG_REMOVED] = true;
  24842. }
  24843. }
  24844. block.scope.$destroy();
  24845. }
  24846. // we are not using forEach for perf reasons (trying to avoid #call)
  24847. for (index = 0; index < collectionLength; index++) {
  24848. key = (collection === collectionKeys) ? index : collectionKeys[index];
  24849. value = collection[key];
  24850. block = nextBlockOrder[index];
  24851. if (block.scope) {
  24852. // if we have already seen this object, then we need to reuse the
  24853. // associated scope/element
  24854. nextNode = previousNode;
  24855. // skip nodes that are already pending removal via leave animation
  24856. do {
  24857. nextNode = nextNode.nextSibling;
  24858. } while (nextNode && nextNode[NG_REMOVED]);
  24859. if (getBlockStart(block) != nextNode) {
  24860. // existing item which got moved
  24861. $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
  24862. }
  24863. previousNode = getBlockEnd(block);
  24864. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  24865. } else {
  24866. // new item which we don't know about
  24867. $transclude(function ngRepeatTransclude(clone, scope) {
  24868. block.scope = scope;
  24869. // http://jsperf.com/clone-vs-createcomment
  24870. var endNode = ngRepeatEndComment.cloneNode(false);
  24871. clone[clone.length++] = endNode;
  24872. // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
  24873. $animate.enter(clone, null, jqLite(previousNode));
  24874. previousNode = endNode;
  24875. // Note: We only need the first/last node of the cloned nodes.
  24876. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  24877. // by a directive with templateUrl when its template arrives.
  24878. block.clone = clone;
  24879. nextBlockMap[block.id] = block;
  24880. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  24881. });
  24882. }
  24883. }
  24884. lastBlockMap = nextBlockMap;
  24885. });
  24886. };
  24887. }
  24888. };
  24889. }];
  24890. var NG_HIDE_CLASS = 'ng-hide';
  24891. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  24892. /**
  24893. * @ngdoc directive
  24894. * @name ngShow
  24895. * @multiElement
  24896. *
  24897. * @description
  24898. * The `ngShow` directive shows or hides the given HTML element based on the expression
  24899. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  24900. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  24901. * in AngularJS and sets the display style to none (using an !important flag).
  24902. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  24903. *
  24904. * ```html
  24905. * <!-- when $scope.myValue is truthy (element is visible) -->
  24906. * <div ng-show="myValue"></div>
  24907. *
  24908. * <!-- when $scope.myValue is falsy (element is hidden) -->
  24909. * <div ng-show="myValue" class="ng-hide"></div>
  24910. * ```
  24911. *
  24912. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
  24913. * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
  24914. * from the element causing the element not to appear hidden.
  24915. *
  24916. * ## Why is !important used?
  24917. *
  24918. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  24919. * can be easily overridden by heavier selectors. For example, something as simple
  24920. * as changing the display style on a HTML list item would make hidden elements appear visible.
  24921. * This also becomes a bigger issue when dealing with CSS frameworks.
  24922. *
  24923. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  24924. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  24925. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  24926. *
  24927. * ### Overriding `.ng-hide`
  24928. *
  24929. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  24930. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  24931. * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
  24932. * with extra animation classes that can be added.
  24933. *
  24934. * ```css
  24935. * .ng-hide:not(.ng-hide-animate) {
  24936. * /&#42; this is just another form of hiding an element &#42;/
  24937. * display: block!important;
  24938. * position: absolute;
  24939. * top: -9999px;
  24940. * left: -9999px;
  24941. * }
  24942. * ```
  24943. *
  24944. * By default you don't need to override in CSS anything and the animations will work around the display style.
  24945. *
  24946. * ## A note about animations with `ngShow`
  24947. *
  24948. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  24949. * is true and false. This system works like the animation system present with ngClass except that
  24950. * you must also include the !important flag to override the display property
  24951. * so that you can perform an animation when the element is hidden during the time of the animation.
  24952. *
  24953. * ```css
  24954. * //
  24955. * //a working example can be found at the bottom of this page
  24956. * //
  24957. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  24958. * /&#42; this is required as of 1.3x to properly
  24959. * apply all styling in a show/hide animation &#42;/
  24960. * transition: 0s linear all;
  24961. * }
  24962. *
  24963. * .my-element.ng-hide-add-active,
  24964. * .my-element.ng-hide-remove-active {
  24965. * /&#42; the transition is defined in the active class &#42;/
  24966. * transition: 1s linear all;
  24967. * }
  24968. *
  24969. * .my-element.ng-hide-add { ... }
  24970. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  24971. * .my-element.ng-hide-remove { ... }
  24972. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  24973. * ```
  24974. *
  24975. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  24976. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  24977. *
  24978. * @animations
  24979. * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
  24980. * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
  24981. *
  24982. * @element ANY
  24983. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  24984. * then the element is shown or hidden respectively.
  24985. *
  24986. * @example
  24987. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  24988. <file name="index.html">
  24989. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
  24990. <div>
  24991. Show:
  24992. <div class="check-element animate-show" ng-show="checked">
  24993. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  24994. </div>
  24995. </div>
  24996. <div>
  24997. Hide:
  24998. <div class="check-element animate-show" ng-hide="checked">
  24999. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  25000. </div>
  25001. </div>
  25002. </file>
  25003. <file name="glyphicons.css">
  25004. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  25005. </file>
  25006. <file name="animations.css">
  25007. .animate-show {
  25008. line-height: 20px;
  25009. opacity: 1;
  25010. padding: 10px;
  25011. border: 1px solid black;
  25012. background: white;
  25013. }
  25014. .animate-show.ng-hide-add, .animate-show.ng-hide-remove {
  25015. transition: all linear 0.5s;
  25016. }
  25017. .animate-show.ng-hide {
  25018. line-height: 0;
  25019. opacity: 0;
  25020. padding: 0 10px;
  25021. }
  25022. .check-element {
  25023. padding: 10px;
  25024. border: 1px solid black;
  25025. background: white;
  25026. }
  25027. </file>
  25028. <file name="protractor.js" type="protractor">
  25029. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  25030. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  25031. it('should check ng-show / ng-hide', function() {
  25032. expect(thumbsUp.isDisplayed()).toBeFalsy();
  25033. expect(thumbsDown.isDisplayed()).toBeTruthy();
  25034. element(by.model('checked')).click();
  25035. expect(thumbsUp.isDisplayed()).toBeTruthy();
  25036. expect(thumbsDown.isDisplayed()).toBeFalsy();
  25037. });
  25038. </file>
  25039. </example>
  25040. */
  25041. var ngShowDirective = ['$animate', function($animate) {
  25042. return {
  25043. restrict: 'A',
  25044. multiElement: true,
  25045. link: function(scope, element, attr) {
  25046. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  25047. // we're adding a temporary, animation-specific class for ng-hide since this way
  25048. // we can control when the element is actually displayed on screen without having
  25049. // to have a global/greedy CSS selector that breaks when other animations are run.
  25050. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  25051. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  25052. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  25053. });
  25054. });
  25055. }
  25056. };
  25057. }];
  25058. /**
  25059. * @ngdoc directive
  25060. * @name ngHide
  25061. * @multiElement
  25062. *
  25063. * @description
  25064. * The `ngHide` directive shows or hides the given HTML element based on the expression
  25065. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  25066. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  25067. * in AngularJS and sets the display style to none (using an !important flag).
  25068. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  25069. *
  25070. * ```html
  25071. * <!-- when $scope.myValue is truthy (element is hidden) -->
  25072. * <div ng-hide="myValue" class="ng-hide"></div>
  25073. *
  25074. * <!-- when $scope.myValue is falsy (element is visible) -->
  25075. * <div ng-hide="myValue"></div>
  25076. * ```
  25077. *
  25078. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
  25079. * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
  25080. * from the element causing the element not to appear hidden.
  25081. *
  25082. * ## Why is !important used?
  25083. *
  25084. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  25085. * can be easily overridden by heavier selectors. For example, something as simple
  25086. * as changing the display style on a HTML list item would make hidden elements appear visible.
  25087. * This also becomes a bigger issue when dealing with CSS frameworks.
  25088. *
  25089. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  25090. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  25091. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  25092. *
  25093. * ### Overriding `.ng-hide`
  25094. *
  25095. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  25096. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  25097. * class in CSS:
  25098. *
  25099. * ```css
  25100. * .ng-hide {
  25101. * /&#42; this is just another form of hiding an element &#42;/
  25102. * display: block!important;
  25103. * position: absolute;
  25104. * top: -9999px;
  25105. * left: -9999px;
  25106. * }
  25107. * ```
  25108. *
  25109. * By default you don't need to override in CSS anything and the animations will work around the display style.
  25110. *
  25111. * ## A note about animations with `ngHide`
  25112. *
  25113. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  25114. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  25115. * CSS class is added and removed for you instead of your own CSS class.
  25116. *
  25117. * ```css
  25118. * //
  25119. * //a working example can be found at the bottom of this page
  25120. * //
  25121. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  25122. * transition: 0.5s linear all;
  25123. * }
  25124. *
  25125. * .my-element.ng-hide-add { ... }
  25126. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  25127. * .my-element.ng-hide-remove { ... }
  25128. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  25129. * ```
  25130. *
  25131. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  25132. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  25133. *
  25134. * @animations
  25135. * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
  25136. * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
  25137. *
  25138. * @element ANY
  25139. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  25140. * the element is shown or hidden respectively.
  25141. *
  25142. * @example
  25143. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  25144. <file name="index.html">
  25145. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
  25146. <div>
  25147. Show:
  25148. <div class="check-element animate-hide" ng-show="checked">
  25149. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  25150. </div>
  25151. </div>
  25152. <div>
  25153. Hide:
  25154. <div class="check-element animate-hide" ng-hide="checked">
  25155. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  25156. </div>
  25157. </div>
  25158. </file>
  25159. <file name="glyphicons.css">
  25160. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  25161. </file>
  25162. <file name="animations.css">
  25163. .animate-hide {
  25164. transition: all linear 0.5s;
  25165. line-height: 20px;
  25166. opacity: 1;
  25167. padding: 10px;
  25168. border: 1px solid black;
  25169. background: white;
  25170. }
  25171. .animate-hide.ng-hide {
  25172. line-height: 0;
  25173. opacity: 0;
  25174. padding: 0 10px;
  25175. }
  25176. .check-element {
  25177. padding: 10px;
  25178. border: 1px solid black;
  25179. background: white;
  25180. }
  25181. </file>
  25182. <file name="protractor.js" type="protractor">
  25183. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  25184. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  25185. it('should check ng-show / ng-hide', function() {
  25186. expect(thumbsUp.isDisplayed()).toBeFalsy();
  25187. expect(thumbsDown.isDisplayed()).toBeTruthy();
  25188. element(by.model('checked')).click();
  25189. expect(thumbsUp.isDisplayed()).toBeTruthy();
  25190. expect(thumbsDown.isDisplayed()).toBeFalsy();
  25191. });
  25192. </file>
  25193. </example>
  25194. */
  25195. var ngHideDirective = ['$animate', function($animate) {
  25196. return {
  25197. restrict: 'A',
  25198. multiElement: true,
  25199. link: function(scope, element, attr) {
  25200. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  25201. // The comment inside of the ngShowDirective explains why we add and
  25202. // remove a temporary class for the show/hide animation
  25203. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  25204. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  25205. });
  25206. });
  25207. }
  25208. };
  25209. }];
  25210. /**
  25211. * @ngdoc directive
  25212. * @name ngStyle
  25213. * @restrict AC
  25214. *
  25215. * @description
  25216. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  25217. *
  25218. * @element ANY
  25219. * @param {expression} ngStyle
  25220. *
  25221. * {@link guide/expression Expression} which evals to an
  25222. * object whose keys are CSS style names and values are corresponding values for those CSS
  25223. * keys.
  25224. *
  25225. * Since some CSS style names are not valid keys for an object, they must be quoted.
  25226. * See the 'background-color' style in the example below.
  25227. *
  25228. * @example
  25229. <example>
  25230. <file name="index.html">
  25231. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  25232. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  25233. <input type="button" value="clear" ng-click="myStyle={}">
  25234. <br/>
  25235. <span ng-style="myStyle">Sample Text</span>
  25236. <pre>myStyle={{myStyle}}</pre>
  25237. </file>
  25238. <file name="style.css">
  25239. span {
  25240. color: black;
  25241. }
  25242. </file>
  25243. <file name="protractor.js" type="protractor">
  25244. var colorSpan = element(by.css('span'));
  25245. it('should check ng-style', function() {
  25246. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  25247. element(by.css('input[value=\'set color\']')).click();
  25248. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  25249. element(by.css('input[value=clear]')).click();
  25250. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  25251. });
  25252. </file>
  25253. </example>
  25254. */
  25255. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  25256. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  25257. if (oldStyles && (newStyles !== oldStyles)) {
  25258. forEach(oldStyles, function(val, style) { element.css(style, '');});
  25259. }
  25260. if (newStyles) element.css(newStyles);
  25261. }, true);
  25262. });
  25263. /**
  25264. * @ngdoc directive
  25265. * @name ngSwitch
  25266. * @restrict EA
  25267. *
  25268. * @description
  25269. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  25270. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  25271. * as specified in the template.
  25272. *
  25273. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  25274. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  25275. * matches the value obtained from the evaluated expression. In other words, you define a container element
  25276. * (where you place the directive), place an expression on the **`on="..."` attribute**
  25277. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  25278. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  25279. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  25280. * attribute is displayed.
  25281. *
  25282. * <div class="alert alert-info">
  25283. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  25284. * as literal string values to match against.
  25285. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  25286. * value of the expression `$scope.someVal`.
  25287. * </div>
  25288. * @animations
  25289. * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
  25290. * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
  25291. *
  25292. * @usage
  25293. *
  25294. * ```
  25295. * <ANY ng-switch="expression">
  25296. * <ANY ng-switch-when="matchValue1">...</ANY>
  25297. * <ANY ng-switch-when="matchValue2">...</ANY>
  25298. * <ANY ng-switch-default>...</ANY>
  25299. * </ANY>
  25300. * ```
  25301. *
  25302. *
  25303. * @scope
  25304. * @priority 1200
  25305. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  25306. * On child elements add:
  25307. *
  25308. * * `ngSwitchWhen`: the case statement to match against. If match then this
  25309. * case will be displayed. If the same match appears multiple times, all the
  25310. * elements will be displayed.
  25311. * * `ngSwitchDefault`: the default case when no other case match. If there
  25312. * are multiple default cases, all of them will be displayed when no other
  25313. * case match.
  25314. *
  25315. *
  25316. * @example
  25317. <example module="switchExample" deps="angular-animate.js" animations="true">
  25318. <file name="index.html">
  25319. <div ng-controller="ExampleController">
  25320. <select ng-model="selection" ng-options="item for item in items">
  25321. </select>
  25322. <code>selection={{selection}}</code>
  25323. <hr/>
  25324. <div class="animate-switch-container"
  25325. ng-switch on="selection">
  25326. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  25327. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  25328. <div class="animate-switch" ng-switch-default>default</div>
  25329. </div>
  25330. </div>
  25331. </file>
  25332. <file name="script.js">
  25333. angular.module('switchExample', ['ngAnimate'])
  25334. .controller('ExampleController', ['$scope', function($scope) {
  25335. $scope.items = ['settings', 'home', 'other'];
  25336. $scope.selection = $scope.items[0];
  25337. }]);
  25338. </file>
  25339. <file name="animations.css">
  25340. .animate-switch-container {
  25341. position:relative;
  25342. background:white;
  25343. border:1px solid black;
  25344. height:40px;
  25345. overflow:hidden;
  25346. }
  25347. .animate-switch {
  25348. padding:10px;
  25349. }
  25350. .animate-switch.ng-animate {
  25351. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  25352. position:absolute;
  25353. top:0;
  25354. left:0;
  25355. right:0;
  25356. bottom:0;
  25357. }
  25358. .animate-switch.ng-leave.ng-leave-active,
  25359. .animate-switch.ng-enter {
  25360. top:-50px;
  25361. }
  25362. .animate-switch.ng-leave,
  25363. .animate-switch.ng-enter.ng-enter-active {
  25364. top:0;
  25365. }
  25366. </file>
  25367. <file name="protractor.js" type="protractor">
  25368. var switchElem = element(by.css('[ng-switch]'));
  25369. var select = element(by.model('selection'));
  25370. it('should start in settings', function() {
  25371. expect(switchElem.getText()).toMatch(/Settings Div/);
  25372. });
  25373. it('should change to home', function() {
  25374. select.all(by.css('option')).get(1).click();
  25375. expect(switchElem.getText()).toMatch(/Home Span/);
  25376. });
  25377. it('should select default', function() {
  25378. select.all(by.css('option')).get(2).click();
  25379. expect(switchElem.getText()).toMatch(/default/);
  25380. });
  25381. </file>
  25382. </example>
  25383. */
  25384. var ngSwitchDirective = ['$animate', function($animate) {
  25385. return {
  25386. require: 'ngSwitch',
  25387. // asks for $scope to fool the BC controller module
  25388. controller: ['$scope', function ngSwitchController() {
  25389. this.cases = {};
  25390. }],
  25391. link: function(scope, element, attr, ngSwitchController) {
  25392. var watchExpr = attr.ngSwitch || attr.on,
  25393. selectedTranscludes = [],
  25394. selectedElements = [],
  25395. previousLeaveAnimations = [],
  25396. selectedScopes = [];
  25397. var spliceFactory = function(array, index) {
  25398. return function() { array.splice(index, 1); };
  25399. };
  25400. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  25401. var i, ii;
  25402. for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
  25403. $animate.cancel(previousLeaveAnimations[i]);
  25404. }
  25405. previousLeaveAnimations.length = 0;
  25406. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  25407. var selected = getBlockNodes(selectedElements[i].clone);
  25408. selectedScopes[i].$destroy();
  25409. var promise = previousLeaveAnimations[i] = $animate.leave(selected);
  25410. promise.then(spliceFactory(previousLeaveAnimations, i));
  25411. }
  25412. selectedElements.length = 0;
  25413. selectedScopes.length = 0;
  25414. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  25415. forEach(selectedTranscludes, function(selectedTransclude) {
  25416. selectedTransclude.transclude(function(caseElement, selectedScope) {
  25417. selectedScopes.push(selectedScope);
  25418. var anchor = selectedTransclude.element;
  25419. caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
  25420. var block = { clone: caseElement };
  25421. selectedElements.push(block);
  25422. $animate.enter(caseElement, anchor.parent(), anchor);
  25423. });
  25424. });
  25425. }
  25426. });
  25427. }
  25428. };
  25429. }];
  25430. var ngSwitchWhenDirective = ngDirective({
  25431. transclude: 'element',
  25432. priority: 1200,
  25433. require: '^ngSwitch',
  25434. multiElement: true,
  25435. link: function(scope, element, attrs, ctrl, $transclude) {
  25436. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  25437. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  25438. }
  25439. });
  25440. var ngSwitchDefaultDirective = ngDirective({
  25441. transclude: 'element',
  25442. priority: 1200,
  25443. require: '^ngSwitch',
  25444. multiElement: true,
  25445. link: function(scope, element, attr, ctrl, $transclude) {
  25446. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  25447. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  25448. }
  25449. });
  25450. /**
  25451. * @ngdoc directive
  25452. * @name ngTransclude
  25453. * @restrict EAC
  25454. *
  25455. * @description
  25456. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  25457. *
  25458. * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
  25459. *
  25460. * @element ANY
  25461. *
  25462. * @example
  25463. <example module="transcludeExample">
  25464. <file name="index.html">
  25465. <script>
  25466. angular.module('transcludeExample', [])
  25467. .directive('pane', function(){
  25468. return {
  25469. restrict: 'E',
  25470. transclude: true,
  25471. scope: { title:'@' },
  25472. template: '<div style="border: 1px solid black;">' +
  25473. '<div style="background-color: gray">{{title}}</div>' +
  25474. '<ng-transclude></ng-transclude>' +
  25475. '</div>'
  25476. };
  25477. })
  25478. .controller('ExampleController', ['$scope', function($scope) {
  25479. $scope.title = 'Lorem Ipsum';
  25480. $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  25481. }]);
  25482. </script>
  25483. <div ng-controller="ExampleController">
  25484. <input ng-model="title" aria-label="title"> <br/>
  25485. <textarea ng-model="text" aria-label="text"></textarea> <br/>
  25486. <pane title="{{title}}">{{text}}</pane>
  25487. </div>
  25488. </file>
  25489. <file name="protractor.js" type="protractor">
  25490. it('should have transcluded', function() {
  25491. var titleElement = element(by.model('title'));
  25492. titleElement.clear();
  25493. titleElement.sendKeys('TITLE');
  25494. var textElement = element(by.model('text'));
  25495. textElement.clear();
  25496. textElement.sendKeys('TEXT');
  25497. expect(element(by.binding('title')).getText()).toEqual('TITLE');
  25498. expect(element(by.binding('text')).getText()).toEqual('TEXT');
  25499. });
  25500. </file>
  25501. </example>
  25502. *
  25503. */
  25504. var ngTranscludeDirective = ngDirective({
  25505. restrict: 'EAC',
  25506. link: function($scope, $element, $attrs, controller, $transclude) {
  25507. if (!$transclude) {
  25508. throw minErr('ngTransclude')('orphan',
  25509. 'Illegal use of ngTransclude directive in the template! ' +
  25510. 'No parent directive that requires a transclusion found. ' +
  25511. 'Element: {0}',
  25512. startingTag($element));
  25513. }
  25514. $transclude(function(clone) {
  25515. $element.empty();
  25516. $element.append(clone);
  25517. });
  25518. }
  25519. });
  25520. /**
  25521. * @ngdoc directive
  25522. * @name script
  25523. * @restrict E
  25524. *
  25525. * @description
  25526. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  25527. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  25528. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  25529. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  25530. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  25531. *
  25532. * @param {string} type Must be set to `'text/ng-template'`.
  25533. * @param {string} id Cache name of the template.
  25534. *
  25535. * @example
  25536. <example>
  25537. <file name="index.html">
  25538. <script type="text/ng-template" id="/tpl.html">
  25539. Content of the template.
  25540. </script>
  25541. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  25542. <div id="tpl-content" ng-include src="currentTpl"></div>
  25543. </file>
  25544. <file name="protractor.js" type="protractor">
  25545. it('should load template defined inside script tag', function() {
  25546. element(by.css('#tpl-link')).click();
  25547. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  25548. });
  25549. </file>
  25550. </example>
  25551. */
  25552. var scriptDirective = ['$templateCache', function($templateCache) {
  25553. return {
  25554. restrict: 'E',
  25555. terminal: true,
  25556. compile: function(element, attr) {
  25557. if (attr.type == 'text/ng-template') {
  25558. var templateUrl = attr.id,
  25559. text = element[0].text;
  25560. $templateCache.put(templateUrl, text);
  25561. }
  25562. }
  25563. };
  25564. }];
  25565. var noopNgModelController = { $setViewValue: noop, $render: noop };
  25566. /**
  25567. * @ngdoc type
  25568. * @name select.SelectController
  25569. * @description
  25570. * The controller for the `<select>` directive. This provides support for reading
  25571. * and writing the selected value(s) of the control and also coordinates dynamically
  25572. * added `<option>` elements, perhaps by an `ngRepeat` directive.
  25573. */
  25574. var SelectController =
  25575. ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  25576. var self = this,
  25577. optionsMap = new HashMap();
  25578. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  25579. self.ngModelCtrl = noopNgModelController;
  25580. // The "unknown" option is one that is prepended to the list if the viewValue
  25581. // does not match any of the options. When it is rendered the value of the unknown
  25582. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  25583. //
  25584. // We can't just jqLite('<option>') since jqLite is not smart enough
  25585. // to create it in <select> and IE barfs otherwise.
  25586. self.unknownOption = jqLite(document.createElement('option'));
  25587. self.renderUnknownOption = function(val) {
  25588. var unknownVal = '? ' + hashKey(val) + ' ?';
  25589. self.unknownOption.val(unknownVal);
  25590. $element.prepend(self.unknownOption);
  25591. $element.val(unknownVal);
  25592. };
  25593. $scope.$on('$destroy', function() {
  25594. // disable unknown option so that we don't do work when the whole select is being destroyed
  25595. self.renderUnknownOption = noop;
  25596. });
  25597. self.removeUnknownOption = function() {
  25598. if (self.unknownOption.parent()) self.unknownOption.remove();
  25599. };
  25600. // Read the value of the select control, the implementation of this changes depending
  25601. // upon whether the select can have multiple values and whether ngOptions is at work.
  25602. self.readValue = function readSingleValue() {
  25603. self.removeUnknownOption();
  25604. return $element.val();
  25605. };
  25606. // Write the value to the select control, the implementation of this changes depending
  25607. // upon whether the select can have multiple values and whether ngOptions is at work.
  25608. self.writeValue = function writeSingleValue(value) {
  25609. if (self.hasOption(value)) {
  25610. self.removeUnknownOption();
  25611. $element.val(value);
  25612. if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy
  25613. } else {
  25614. if (value == null && self.emptyOption) {
  25615. self.removeUnknownOption();
  25616. $element.val('');
  25617. } else {
  25618. self.renderUnknownOption(value);
  25619. }
  25620. }
  25621. };
  25622. // Tell the select control that an option, with the given value, has been added
  25623. self.addOption = function(value, element) {
  25624. assertNotHasOwnProperty(value, '"option value"');
  25625. if (value === '') {
  25626. self.emptyOption = element;
  25627. }
  25628. var count = optionsMap.get(value) || 0;
  25629. optionsMap.put(value, count + 1);
  25630. };
  25631. // Tell the select control that an option, with the given value, has been removed
  25632. self.removeOption = function(value) {
  25633. var count = optionsMap.get(value);
  25634. if (count) {
  25635. if (count === 1) {
  25636. optionsMap.remove(value);
  25637. if (value === '') {
  25638. self.emptyOption = undefined;
  25639. }
  25640. } else {
  25641. optionsMap.put(value, count - 1);
  25642. }
  25643. }
  25644. };
  25645. // Check whether the select control has an option matching the given value
  25646. self.hasOption = function(value) {
  25647. return !!optionsMap.get(value);
  25648. };
  25649. }];
  25650. /**
  25651. * @ngdoc directive
  25652. * @name select
  25653. * @restrict E
  25654. *
  25655. * @description
  25656. * HTML `SELECT` element with angular data-binding.
  25657. *
  25658. * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
  25659. * between the scope and the `<select>` control (including setting default values).
  25660. * Ìt also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
  25661. * {@link ngOptions `ngOptions`} directives.
  25662. *
  25663. * When an item in the `<select>` menu is selected, the value of the selected option will be bound
  25664. * to the model identified by the `ngModel` directive. With static or repeated options, this is
  25665. * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
  25666. * If you want dynamic value attributes, you can use interpolation inside the value attribute.
  25667. *
  25668. * <div class="alert alert-warning">
  25669. * Note that the value of a `select` directive used without `ngOptions` is always a string.
  25670. * When the model needs to be bound to a non-string value, you must either explictly convert it
  25671. * using a directive (see example below) or use `ngOptions` to specify the set of options.
  25672. * This is because an option element can only be bound to string values at present.
  25673. * </div>
  25674. *
  25675. * If the viewValue of `ngModel` does not match any of the options, then the control
  25676. * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
  25677. *
  25678. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  25679. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  25680. * option. See example below for demonstration.
  25681. *
  25682. * <div class="alert alert-info">
  25683. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  25684. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits, such as
  25685. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  25686. * comprehension expression, and additionally in reducing memory and increasing speed by not creating
  25687. * a new scope for each repeated instance.
  25688. * </div>
  25689. *
  25690. *
  25691. * @param {string} ngModel Assignable angular expression to data-bind to.
  25692. * @param {string=} name Property name of the form under which the control is published.
  25693. * @param {string=} required Sets `required` validation error key if the value is not entered.
  25694. * @param {string=} ngRequired Adds required attribute and required validation constraint to
  25695. * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
  25696. * when you want to data-bind to the required attribute.
  25697. * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
  25698. * interaction with the select element.
  25699. * @param {string=} ngOptions sets the options that the select is populated with and defines what is
  25700. * set on the model on selection. See {@link ngOptions `ngOptions`}.
  25701. *
  25702. * @example
  25703. * ### Simple `select` elements with static options
  25704. *
  25705. * <example name="static-select" module="staticSelect">
  25706. * <file name="index.html">
  25707. * <div ng-controller="ExampleController">
  25708. * <form name="myForm">
  25709. * <label for="singleSelect"> Single select: </label><br>
  25710. * <select name="singleSelect" ng-model="data.singleSelect">
  25711. * <option value="option-1">Option 1</option>
  25712. * <option value="option-2">Option 2</option>
  25713. * </select><br>
  25714. *
  25715. * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
  25716. * <select name="singleSelect" ng-model="data.singleSelect">
  25717. * <option value="">---Please select---</option> <!-- not selected / blank option -->
  25718. * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
  25719. * <option value="option-2">Option 2</option>
  25720. * </select><br>
  25721. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  25722. * <tt>singleSelect = {{data.singleSelect}}</tt>
  25723. *
  25724. * <hr>
  25725. * <label for="multipleSelect"> Multiple select: </label><br>
  25726. * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
  25727. * <option value="option-1">Option 1</option>
  25728. * <option value="option-2">Option 2</option>
  25729. * <option value="option-3">Option 3</option>
  25730. * </select><br>
  25731. * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
  25732. * </form>
  25733. * </div>
  25734. * </file>
  25735. * <file name="app.js">
  25736. * angular.module('staticSelect', [])
  25737. * .controller('ExampleController', ['$scope', function($scope) {
  25738. * $scope.data = {
  25739. * singleSelect: null,
  25740. * multipleSelect: [],
  25741. * option1: 'option-1',
  25742. * };
  25743. *
  25744. * $scope.forceUnknownOption = function() {
  25745. * $scope.data.singleSelect = 'nonsense';
  25746. * };
  25747. * }]);
  25748. * </file>
  25749. *</example>
  25750. *
  25751. * ### Using `ngRepeat` to generate `select` options
  25752. * <example name="ngrepeat-select" module="ngrepeatSelect">
  25753. * <file name="index.html">
  25754. * <div ng-controller="ExampleController">
  25755. * <form name="myForm">
  25756. * <label for="repeatSelect"> Repeat select: </label>
  25757. * <select name="repeatSelect" ng-model="data.repeatSelect">
  25758. * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
  25759. * </select>
  25760. * </form>
  25761. * <hr>
  25762. * <tt>repeatSelect = {{data.repeatSelect}}</tt><br/>
  25763. * </div>
  25764. * </file>
  25765. * <file name="app.js">
  25766. * angular.module('ngrepeatSelect', [])
  25767. * .controller('ExampleController', ['$scope', function($scope) {
  25768. * $scope.data = {
  25769. * singleSelect: null,
  25770. * availableOptions: [
  25771. * {id: '1', name: 'Option A'},
  25772. * {id: '2', name: 'Option B'},
  25773. * {id: '3', name: 'Option C'}
  25774. * ],
  25775. * };
  25776. * }]);
  25777. * </file>
  25778. *</example>
  25779. *
  25780. *
  25781. * ### Using `select` with `ngOptions` and setting a default value
  25782. * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
  25783. *
  25784. * <example name="select-with-default-values" module="defaultValueSelect">
  25785. * <file name="index.html">
  25786. * <div ng-controller="ExampleController">
  25787. * <form name="myForm">
  25788. * <label for="mySelect">Make a choice:</label>
  25789. * <select name="mySelect" id="mySelect"
  25790. * ng-options="option.name for option in data.availableOptions track by option.id"
  25791. * ng-model="data.selectedOption"></select>
  25792. * </form>
  25793. * <hr>
  25794. * <tt>option = {{data.selectedOption}}</tt><br/>
  25795. * </div>
  25796. * </file>
  25797. * <file name="app.js">
  25798. * angular.module('defaultValueSelect', [])
  25799. * .controller('ExampleController', ['$scope', function($scope) {
  25800. * $scope.data = {
  25801. * availableOptions: [
  25802. * {id: '1', name: 'Option A'},
  25803. * {id: '2', name: 'Option B'},
  25804. * {id: '3', name: 'Option C'}
  25805. * ],
  25806. * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
  25807. * };
  25808. * }]);
  25809. * </file>
  25810. *</example>
  25811. *
  25812. *
  25813. * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
  25814. *
  25815. * <example name="select-with-non-string-options" module="nonStringSelect">
  25816. * <file name="index.html">
  25817. * <select ng-model="model.id" convert-to-number>
  25818. * <option value="0">Zero</option>
  25819. * <option value="1">One</option>
  25820. * <option value="2">Two</option>
  25821. * </select>
  25822. * {{ model }}
  25823. * </file>
  25824. * <file name="app.js">
  25825. * angular.module('nonStringSelect', [])
  25826. * .run(function($rootScope) {
  25827. * $rootScope.model = { id: 2 };
  25828. * })
  25829. * .directive('convertToNumber', function() {
  25830. * return {
  25831. * require: 'ngModel',
  25832. * link: function(scope, element, attrs, ngModel) {
  25833. * ngModel.$parsers.push(function(val) {
  25834. * return parseInt(val, 10);
  25835. * });
  25836. * ngModel.$formatters.push(function(val) {
  25837. * return '' + val;
  25838. * });
  25839. * }
  25840. * };
  25841. * });
  25842. * </file>
  25843. * <file name="protractor.js" type="protractor">
  25844. * it('should initialize to model', function() {
  25845. * var select = element(by.css('select'));
  25846. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  25847. * });
  25848. * </file>
  25849. * </example>
  25850. *
  25851. */
  25852. var selectDirective = function() {
  25853. return {
  25854. restrict: 'E',
  25855. require: ['select', '?ngModel'],
  25856. controller: SelectController,
  25857. link: function(scope, element, attr, ctrls) {
  25858. // if ngModel is not defined, we don't need to do anything
  25859. var ngModelCtrl = ctrls[1];
  25860. if (!ngModelCtrl) return;
  25861. var selectCtrl = ctrls[0];
  25862. selectCtrl.ngModelCtrl = ngModelCtrl;
  25863. // We delegate rendering to the `writeValue` method, which can be changed
  25864. // if the select can have multiple selected values or if the options are being
  25865. // generated by `ngOptions`
  25866. ngModelCtrl.$render = function() {
  25867. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  25868. };
  25869. // When the selected item(s) changes we delegate getting the value of the select control
  25870. // to the `readValue` method, which can be changed if the select can have multiple
  25871. // selected values or if the options are being generated by `ngOptions`
  25872. element.on('change', function() {
  25873. scope.$apply(function() {
  25874. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  25875. });
  25876. });
  25877. // If the select allows multiple values then we need to modify how we read and write
  25878. // values from and to the control; also what it means for the value to be empty and
  25879. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  25880. // doesn't trigger rendering if only an item in the array changes.
  25881. if (attr.multiple) {
  25882. // Read value now needs to check each option to see if it is selected
  25883. selectCtrl.readValue = function readMultipleValue() {
  25884. var array = [];
  25885. forEach(element.find('option'), function(option) {
  25886. if (option.selected) {
  25887. array.push(option.value);
  25888. }
  25889. });
  25890. return array;
  25891. };
  25892. // Write value now needs to set the selected property of each matching option
  25893. selectCtrl.writeValue = function writeMultipleValue(value) {
  25894. var items = new HashMap(value);
  25895. forEach(element.find('option'), function(option) {
  25896. option.selected = isDefined(items.get(option.value));
  25897. });
  25898. };
  25899. // we have to do it on each watch since ngModel watches reference, but
  25900. // we need to work of an array, so we need to see if anything was inserted/removed
  25901. var lastView, lastViewRef = NaN;
  25902. scope.$watch(function selectMultipleWatch() {
  25903. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  25904. lastView = shallowCopy(ngModelCtrl.$viewValue);
  25905. ngModelCtrl.$render();
  25906. }
  25907. lastViewRef = ngModelCtrl.$viewValue;
  25908. });
  25909. // If we are a multiple select then value is now a collection
  25910. // so the meaning of $isEmpty changes
  25911. ngModelCtrl.$isEmpty = function(value) {
  25912. return !value || value.length === 0;
  25913. };
  25914. }
  25915. }
  25916. };
  25917. };
  25918. // The option directive is purely designed to communicate the existence (or lack of)
  25919. // of dynamically created (and destroyed) option elements to their containing select
  25920. // directive via its controller.
  25921. var optionDirective = ['$interpolate', function($interpolate) {
  25922. function chromeHack(optionElement) {
  25923. // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
  25924. // Adding an <option selected="selected"> element to a <select required="required"> should
  25925. // automatically select the new element
  25926. if (optionElement[0].hasAttribute('selected')) {
  25927. optionElement[0].selected = true;
  25928. }
  25929. }
  25930. return {
  25931. restrict: 'E',
  25932. priority: 100,
  25933. compile: function(element, attr) {
  25934. // If the value attribute is not defined then we fall back to the
  25935. // text content of the option element, which may be interpolated
  25936. if (isUndefined(attr.value)) {
  25937. var interpolateFn = $interpolate(element.text(), true);
  25938. if (!interpolateFn) {
  25939. attr.$set('value', element.text());
  25940. }
  25941. }
  25942. return function(scope, element, attr) {
  25943. // This is an optimization over using ^^ since we don't want to have to search
  25944. // all the way to the root of the DOM for every single option element
  25945. var selectCtrlName = '$selectController',
  25946. parent = element.parent(),
  25947. selectCtrl = parent.data(selectCtrlName) ||
  25948. parent.parent().data(selectCtrlName); // in case we are in optgroup
  25949. // Only update trigger option updates if this is an option within a `select`
  25950. // that also has `ngModel` attached
  25951. if (selectCtrl && selectCtrl.ngModelCtrl) {
  25952. if (interpolateFn) {
  25953. scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
  25954. attr.$set('value', newVal);
  25955. if (oldVal !== newVal) {
  25956. selectCtrl.removeOption(oldVal);
  25957. }
  25958. selectCtrl.addOption(newVal, element);
  25959. selectCtrl.ngModelCtrl.$render();
  25960. chromeHack(element);
  25961. });
  25962. } else {
  25963. selectCtrl.addOption(attr.value, element);
  25964. selectCtrl.ngModelCtrl.$render();
  25965. chromeHack(element);
  25966. }
  25967. element.on('$destroy', function() {
  25968. selectCtrl.removeOption(attr.value);
  25969. selectCtrl.ngModelCtrl.$render();
  25970. });
  25971. }
  25972. };
  25973. }
  25974. };
  25975. }];
  25976. var styleDirective = valueFn({
  25977. restrict: 'E',
  25978. terminal: false
  25979. });
  25980. var requiredDirective = function() {
  25981. return {
  25982. restrict: 'A',
  25983. require: '?ngModel',
  25984. link: function(scope, elm, attr, ctrl) {
  25985. if (!ctrl) return;
  25986. attr.required = true; // force truthy in case we are on non input element
  25987. ctrl.$validators.required = function(modelValue, viewValue) {
  25988. return !attr.required || !ctrl.$isEmpty(viewValue);
  25989. };
  25990. attr.$observe('required', function() {
  25991. ctrl.$validate();
  25992. });
  25993. }
  25994. };
  25995. };
  25996. var patternDirective = function() {
  25997. return {
  25998. restrict: 'A',
  25999. require: '?ngModel',
  26000. link: function(scope, elm, attr, ctrl) {
  26001. if (!ctrl) return;
  26002. var regexp, patternExp = attr.ngPattern || attr.pattern;
  26003. attr.$observe('pattern', function(regex) {
  26004. if (isString(regex) && regex.length > 0) {
  26005. regex = new RegExp('^' + regex + '$');
  26006. }
  26007. if (regex && !regex.test) {
  26008. throw minErr('ngPattern')('noregexp',
  26009. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  26010. regex, startingTag(elm));
  26011. }
  26012. regexp = regex || undefined;
  26013. ctrl.$validate();
  26014. });
  26015. ctrl.$validators.pattern = function(modelValue, viewValue) {
  26016. // HTML5 pattern constraint validates the input value, so we validate the viewValue
  26017. return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
  26018. };
  26019. }
  26020. };
  26021. };
  26022. var maxlengthDirective = function() {
  26023. return {
  26024. restrict: 'A',
  26025. require: '?ngModel',
  26026. link: function(scope, elm, attr, ctrl) {
  26027. if (!ctrl) return;
  26028. var maxlength = -1;
  26029. attr.$observe('maxlength', function(value) {
  26030. var intVal = toInt(value);
  26031. maxlength = isNaN(intVal) ? -1 : intVal;
  26032. ctrl.$validate();
  26033. });
  26034. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  26035. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  26036. };
  26037. }
  26038. };
  26039. };
  26040. var minlengthDirective = function() {
  26041. return {
  26042. restrict: 'A',
  26043. require: '?ngModel',
  26044. link: function(scope, elm, attr, ctrl) {
  26045. if (!ctrl) return;
  26046. var minlength = 0;
  26047. attr.$observe('minlength', function(value) {
  26048. minlength = toInt(value) || 0;
  26049. ctrl.$validate();
  26050. });
  26051. ctrl.$validators.minlength = function(modelValue, viewValue) {
  26052. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  26053. };
  26054. }
  26055. };
  26056. };
  26057. if (window.angular.bootstrap) {
  26058. //AngularJS is already loaded, so we can return here...
  26059. console.log('WARNING: Tried to load angular more than once.');
  26060. return;
  26061. }
  26062. //try to bind to jquery now so that one can write jqLite(document).ready()
  26063. //but we will rebind on bootstrap again.
  26064. bindJQuery();
  26065. publishExternalAPI(angular);
  26066. angular.module("ngLocale", [], ["$provide", function($provide) {
  26067. var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
  26068. function getDecimals(n) {
  26069. n = n + '';
  26070. var i = n.indexOf('.');
  26071. return (i == -1) ? 0 : n.length - i - 1;
  26072. }
  26073. function getVF(n, opt_precision) {
  26074. var v = opt_precision;
  26075. if (undefined === v) {
  26076. v = Math.min(getDecimals(n), 3);
  26077. }
  26078. var base = Math.pow(10, v);
  26079. var f = ((n * base) | 0) % base;
  26080. return {v: v, f: f};
  26081. }
  26082. $provide.value("$locale", {
  26083. "DATETIME_FORMATS": {
  26084. "AMPMS": [
  26085. "AM",
  26086. "PM"
  26087. ],
  26088. "DAY": [
  26089. "Sunday",
  26090. "Monday",
  26091. "Tuesday",
  26092. "Wednesday",
  26093. "Thursday",
  26094. "Friday",
  26095. "Saturday"
  26096. ],
  26097. "ERANAMES": [
  26098. "Before Christ",
  26099. "Anno Domini"
  26100. ],
  26101. "ERAS": [
  26102. "BC",
  26103. "AD"
  26104. ],
  26105. "FIRSTDAYOFWEEK": 6,
  26106. "MONTH": [
  26107. "January",
  26108. "February",
  26109. "March",
  26110. "April",
  26111. "May",
  26112. "June",
  26113. "July",
  26114. "August",
  26115. "September",
  26116. "October",
  26117. "November",
  26118. "December"
  26119. ],
  26120. "SHORTDAY": [
  26121. "Sun",
  26122. "Mon",
  26123. "Tue",
  26124. "Wed",
  26125. "Thu",
  26126. "Fri",
  26127. "Sat"
  26128. ],
  26129. "SHORTMONTH": [
  26130. "Jan",
  26131. "Feb",
  26132. "Mar",
  26133. "Apr",
  26134. "May",
  26135. "Jun",
  26136. "Jul",
  26137. "Aug",
  26138. "Sep",
  26139. "Oct",
  26140. "Nov",
  26141. "Dec"
  26142. ],
  26143. "WEEKENDRANGE": [
  26144. 5,
  26145. 6
  26146. ],
  26147. "fullDate": "EEEE, MMMM d, y",
  26148. "longDate": "MMMM d, y",
  26149. "medium": "MMM d, y h:mm:ss a",
  26150. "mediumDate": "MMM d, y",
  26151. "mediumTime": "h:mm:ss a",
  26152. "short": "M/d/yy h:mm a",
  26153. "shortDate": "M/d/yy",
  26154. "shortTime": "h:mm a"
  26155. },
  26156. "NUMBER_FORMATS": {
  26157. "CURRENCY_SYM": "$",
  26158. "DECIMAL_SEP": ".",
  26159. "GROUP_SEP": ",",
  26160. "PATTERNS": [
  26161. {
  26162. "gSize": 3,
  26163. "lgSize": 3,
  26164. "maxFrac": 3,
  26165. "minFrac": 0,
  26166. "minInt": 1,
  26167. "negPre": "-",
  26168. "negSuf": "",
  26169. "posPre": "",
  26170. "posSuf": ""
  26171. },
  26172. {
  26173. "gSize": 3,
  26174. "lgSize": 3,
  26175. "maxFrac": 2,
  26176. "minFrac": 2,
  26177. "minInt": 1,
  26178. "negPre": "-\u00a4",
  26179. "negSuf": "",
  26180. "posPre": "\u00a4",
  26181. "posSuf": ""
  26182. }
  26183. ]
  26184. },
  26185. "id": "en-us",
  26186. "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;}
  26187. });
  26188. }]);
  26189. jqLite(document).ready(function() {
  26190. angularInit(document, bootstrap);
  26191. });
  26192. })(window, document);
  26193. !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>');