angular.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714
  1. /**
  2. * @license AngularJS v1.5.3
  3. * (c) 2010-2016 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window, document, undefined) {'use strict';
  7. /**
  8. * @description
  9. *
  10. * This object provides a utility for producing rich Error messages within
  11. * Angular. It can be called as follows:
  12. *
  13. * var exampleMinErr = minErr('example');
  14. * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
  15. *
  16. * The above creates an instance of minErr in the example namespace. The
  17. * resulting error will have a namespaced error code of example.one. The
  18. * resulting error will replace {0} with the value of foo, and {1} with the
  19. * value of bar. The object is not restricted in the number of arguments it can
  20. * take.
  21. *
  22. * If fewer arguments are specified than necessary for interpolation, the extra
  23. * interpolation markers will be preserved in the final string.
  24. *
  25. * Since data will be parsed statically during a build step, some restrictions
  26. * are applied with respect to how minErr instances are created and called.
  27. * Instances should have names of the form namespaceMinErr for a minErr created
  28. * using minErr('namespace') . Error codes, namespaces and template strings
  29. * should all be static strings, not variables or general expressions.
  30. *
  31. * @param {string} module The namespace to use for the new minErr instance.
  32. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
  33. * error from returned function, for cases when a particular type of error is useful.
  34. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
  35. */
  36. function minErr(module, ErrorConstructor) {
  37. ErrorConstructor = ErrorConstructor || Error;
  38. return function() {
  39. var SKIP_INDEXES = 2;
  40. var templateArgs = arguments,
  41. code = templateArgs[0],
  42. message = '[' + (module ? module + ':' : '') + code + '] ',
  43. template = templateArgs[1],
  44. paramPrefix, i;
  45. message += template.replace(/\{\d+\}/g, function(match) {
  46. var index = +match.slice(1, -1),
  47. shiftedIndex = index + SKIP_INDEXES;
  48. if (shiftedIndex < templateArgs.length) {
  49. return toDebugString(templateArgs[shiftedIndex]);
  50. }
  51. return match;
  52. });
  53. message += '\nhttp://errors.angularjs.org/1.5.3/' +
  54. (module ? module + '/' : '') + code;
  55. for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
  56. message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
  57. encodeURIComponent(toDebugString(templateArgs[i]));
  58. }
  59. return new ErrorConstructor(message);
  60. };
  61. }
  62. /* We need to tell jshint what variables are being exported */
  63. /* global angular: true,
  64. msie: true,
  65. jqLite: true,
  66. jQuery: true,
  67. slice: true,
  68. splice: true,
  69. push: true,
  70. toString: true,
  71. ngMinErr: true,
  72. angularModule: true,
  73. uid: true,
  74. REGEX_STRING_REGEXP: true,
  75. VALIDITY_STATE_PROPERTY: true,
  76. lowercase: true,
  77. uppercase: true,
  78. manualLowercase: true,
  79. manualUppercase: true,
  80. nodeName_: true,
  81. isArrayLike: true,
  82. forEach: true,
  83. forEachSorted: true,
  84. reverseParams: true,
  85. nextUid: true,
  86. setHashKey: true,
  87. extend: true,
  88. toInt: true,
  89. inherit: true,
  90. merge: true,
  91. noop: true,
  92. identity: true,
  93. valueFn: true,
  94. isUndefined: true,
  95. isDefined: true,
  96. isObject: true,
  97. isBlankObject: true,
  98. isString: true,
  99. isNumber: true,
  100. isDate: true,
  101. isArray: true,
  102. isFunction: true,
  103. isRegExp: true,
  104. isWindow: true,
  105. isScope: true,
  106. isFile: true,
  107. isFormData: true,
  108. isBlob: true,
  109. isBoolean: true,
  110. isPromiseLike: true,
  111. trim: true,
  112. escapeForRegexp: true,
  113. isElement: true,
  114. makeMap: true,
  115. includes: true,
  116. arrayRemove: true,
  117. copy: true,
  118. shallowCopy: true,
  119. equals: true,
  120. csp: true,
  121. jq: true,
  122. concat: true,
  123. sliceArgs: true,
  124. bind: true,
  125. toJsonReplacer: true,
  126. toJson: true,
  127. fromJson: true,
  128. convertTimezoneToLocal: true,
  129. timezoneToOffset: true,
  130. startingTag: true,
  131. tryDecodeURIComponent: true,
  132. parseKeyValue: true,
  133. toKeyValue: true,
  134. encodeUriSegment: true,
  135. encodeUriQuery: true,
  136. angularInit: true,
  137. bootstrap: true,
  138. getTestability: true,
  139. snake_case: true,
  140. bindJQuery: true,
  141. assertArg: true,
  142. assertArgFn: true,
  143. assertNotHasOwnProperty: true,
  144. getter: true,
  145. getBlockNodes: true,
  146. hasOwnProperty: true,
  147. createMap: true,
  148. NODE_TYPE_ELEMENT: true,
  149. NODE_TYPE_ATTRIBUTE: true,
  150. NODE_TYPE_TEXT: true,
  151. NODE_TYPE_COMMENT: true,
  152. NODE_TYPE_DOCUMENT: true,
  153. NODE_TYPE_DOCUMENT_FRAGMENT: true,
  154. */
  155. ////////////////////////////////////
  156. /**
  157. * @ngdoc module
  158. * @name ng
  159. * @module ng
  160. * @description
  161. *
  162. * # ng (core module)
  163. * The ng module is loaded by default when an AngularJS application is started. The module itself
  164. * contains the essential components for an AngularJS application to function. The table below
  165. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  166. * components available within this core module.
  167. *
  168. * <div doc-module-components="ng"></div>
  169. */
  170. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  171. // The name of a form control's ValidityState property.
  172. // This is used so that it's possible for internal tests to create mock ValidityStates.
  173. var VALIDITY_STATE_PROPERTY = 'validity';
  174. var hasOwnProperty = Object.prototype.hasOwnProperty;
  175. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  176. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  177. var manualLowercase = function(s) {
  178. /* jshint bitwise: false */
  179. return isString(s)
  180. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  181. : s;
  182. };
  183. var manualUppercase = function(s) {
  184. /* jshint bitwise: false */
  185. return isString(s)
  186. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  187. : s;
  188. };
  189. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  190. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  191. // with correct but slower alternatives. See https://github.com/angular/angular.js/issues/11387
  192. if ('i' !== 'I'.toLowerCase()) {
  193. lowercase = manualLowercase;
  194. uppercase = manualUppercase;
  195. }
  196. var
  197. msie, // holds major version number for IE, or NaN if UA is not IE.
  198. jqLite, // delay binding since jQuery could be loaded after us.
  199. jQuery, // delay binding
  200. slice = [].slice,
  201. splice = [].splice,
  202. push = [].push,
  203. toString = Object.prototype.toString,
  204. getPrototypeOf = Object.getPrototypeOf,
  205. ngMinErr = minErr('ng'),
  206. /** @name angular */
  207. angular = window.angular || (window.angular = {}),
  208. angularModule,
  209. uid = 0;
  210. /**
  211. * documentMode is an IE-only property
  212. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  213. */
  214. msie = document.documentMode;
  215. /**
  216. * @private
  217. * @param {*} obj
  218. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  219. * String ...)
  220. */
  221. function isArrayLike(obj) {
  222. // `null`, `undefined` and `window` are not array-like
  223. if (obj == null || isWindow(obj)) return false;
  224. // arrays, strings and jQuery/jqLite objects are array like
  225. // * jqLite is either the jQuery or jqLite constructor function
  226. // * we have to check the existence of jqLite first as this method is called
  227. // via the forEach method when constructing the jqLite object in the first place
  228. if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
  229. // Support: iOS 8.2 (not reproducible in simulator)
  230. // "length" in obj used to prevent JIT error (gh-11508)
  231. var length = "length" in Object(obj) && obj.length;
  232. // NodeList objects (with `item` method) and
  233. // other objects with suitable length characteristics are array-like
  234. return isNumber(length) &&
  235. (length >= 0 && ((length - 1) in obj || obj instanceof Array) || typeof obj.item == 'function');
  236. }
  237. /**
  238. * @ngdoc function
  239. * @name angular.forEach
  240. * @module ng
  241. * @kind function
  242. *
  243. * @description
  244. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  245. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  246. * is the value of an object property or an array element, `key` is the object property key or
  247. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  248. *
  249. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  250. * using the `hasOwnProperty` method.
  251. *
  252. * Unlike ES262's
  253. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  254. * providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  255. * return the value provided.
  256. *
  257. ```js
  258. var values = {name: 'misko', gender: 'male'};
  259. var log = [];
  260. angular.forEach(values, function(value, key) {
  261. this.push(key + ': ' + value);
  262. }, log);
  263. expect(log).toEqual(['name: misko', 'gender: male']);
  264. ```
  265. *
  266. * @param {Object|Array} obj Object to iterate over.
  267. * @param {Function} iterator Iterator function.
  268. * @param {Object=} context Object to become context (`this`) for the iterator function.
  269. * @returns {Object|Array} Reference to `obj`.
  270. */
  271. function forEach(obj, iterator, context) {
  272. var key, length;
  273. if (obj) {
  274. if (isFunction(obj)) {
  275. for (key in obj) {
  276. // Need to check if hasOwnProperty exists,
  277. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  278. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  279. iterator.call(context, obj[key], key, obj);
  280. }
  281. }
  282. } else if (isArray(obj) || isArrayLike(obj)) {
  283. var isPrimitive = typeof obj !== 'object';
  284. for (key = 0, length = obj.length; key < length; key++) {
  285. if (isPrimitive || key in obj) {
  286. iterator.call(context, obj[key], key, obj);
  287. }
  288. }
  289. } else if (obj.forEach && obj.forEach !== forEach) {
  290. obj.forEach(iterator, context, obj);
  291. } else if (isBlankObject(obj)) {
  292. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  293. for (key in obj) {
  294. iterator.call(context, obj[key], key, obj);
  295. }
  296. } else if (typeof obj.hasOwnProperty === 'function') {
  297. // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
  298. for (key in obj) {
  299. if (obj.hasOwnProperty(key)) {
  300. iterator.call(context, obj[key], key, obj);
  301. }
  302. }
  303. } else {
  304. // Slow path for objects which do not have a method `hasOwnProperty`
  305. for (key in obj) {
  306. if (hasOwnProperty.call(obj, key)) {
  307. iterator.call(context, obj[key], key, obj);
  308. }
  309. }
  310. }
  311. }
  312. return obj;
  313. }
  314. function forEachSorted(obj, iterator, context) {
  315. var keys = Object.keys(obj).sort();
  316. for (var i = 0; i < keys.length; i++) {
  317. iterator.call(context, obj[keys[i]], keys[i]);
  318. }
  319. return keys;
  320. }
  321. /**
  322. * when using forEach the params are value, key, but it is often useful to have key, value.
  323. * @param {function(string, *)} iteratorFn
  324. * @returns {function(*, string)}
  325. */
  326. function reverseParams(iteratorFn) {
  327. return function(value, key) {iteratorFn(key, value);};
  328. }
  329. /**
  330. * A consistent way of creating unique IDs in angular.
  331. *
  332. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  333. * we hit number precision issues in JavaScript.
  334. *
  335. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  336. *
  337. * @returns {number} an unique alpha-numeric string
  338. */
  339. function nextUid() {
  340. return ++uid;
  341. }
  342. /**
  343. * Set or clear the hashkey for an object.
  344. * @param obj object
  345. * @param h the hashkey (!truthy to delete the hashkey)
  346. */
  347. function setHashKey(obj, h) {
  348. if (h) {
  349. obj.$$hashKey = h;
  350. } else {
  351. delete obj.$$hashKey;
  352. }
  353. }
  354. function baseExtend(dst, objs, deep) {
  355. var h = dst.$$hashKey;
  356. for (var i = 0, ii = objs.length; i < ii; ++i) {
  357. var obj = objs[i];
  358. if (!isObject(obj) && !isFunction(obj)) continue;
  359. var keys = Object.keys(obj);
  360. for (var j = 0, jj = keys.length; j < jj; j++) {
  361. var key = keys[j];
  362. var src = obj[key];
  363. if (deep && isObject(src)) {
  364. if (isDate(src)) {
  365. dst[key] = new Date(src.valueOf());
  366. } else if (isRegExp(src)) {
  367. dst[key] = new RegExp(src);
  368. } else if (src.nodeName) {
  369. dst[key] = src.cloneNode(true);
  370. } else if (isElement(src)) {
  371. dst[key] = src.clone();
  372. } else {
  373. if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
  374. baseExtend(dst[key], [src], true);
  375. }
  376. } else {
  377. dst[key] = src;
  378. }
  379. }
  380. }
  381. setHashKey(dst, h);
  382. return dst;
  383. }
  384. /**
  385. * @ngdoc function
  386. * @name angular.extend
  387. * @module ng
  388. * @kind function
  389. *
  390. * @description
  391. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  392. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  393. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  394. *
  395. * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
  396. * {@link angular.merge} for this.
  397. *
  398. * @param {Object} dst Destination object.
  399. * @param {...Object} src Source object(s).
  400. * @returns {Object} Reference to `dst`.
  401. */
  402. function extend(dst) {
  403. return baseExtend(dst, slice.call(arguments, 1), false);
  404. }
  405. /**
  406. * @ngdoc function
  407. * @name angular.merge
  408. * @module ng
  409. * @kind function
  410. *
  411. * @description
  412. * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  413. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  414. * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
  415. *
  416. * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
  417. * objects, performing a deep copy.
  418. *
  419. * @param {Object} dst Destination object.
  420. * @param {...Object} src Source object(s).
  421. * @returns {Object} Reference to `dst`.
  422. */
  423. function merge(dst) {
  424. return baseExtend(dst, slice.call(arguments, 1), true);
  425. }
  426. function toInt(str) {
  427. return parseInt(str, 10);
  428. }
  429. function inherit(parent, extra) {
  430. return extend(Object.create(parent), extra);
  431. }
  432. /**
  433. * @ngdoc function
  434. * @name angular.noop
  435. * @module ng
  436. * @kind function
  437. *
  438. * @description
  439. * A function that performs no operations. This function can be useful when writing code in the
  440. * functional style.
  441. ```js
  442. function foo(callback) {
  443. var result = calculateResult();
  444. (callback || angular.noop)(result);
  445. }
  446. ```
  447. */
  448. function noop() {}
  449. noop.$inject = [];
  450. /**
  451. * @ngdoc function
  452. * @name angular.identity
  453. * @module ng
  454. * @kind function
  455. *
  456. * @description
  457. * A function that returns its first argument. This function is useful when writing code in the
  458. * functional style.
  459. *
  460. ```js
  461. function transformer(transformationFn, value) {
  462. return (transformationFn || angular.identity)(value);
  463. };
  464. ```
  465. * @param {*} value to be returned.
  466. * @returns {*} the value passed in.
  467. */
  468. function identity($) {return $;}
  469. identity.$inject = [];
  470. function valueFn(value) {return function valueRef() {return value;};}
  471. function hasCustomToString(obj) {
  472. return isFunction(obj.toString) && obj.toString !== toString;
  473. }
  474. /**
  475. * @ngdoc function
  476. * @name angular.isUndefined
  477. * @module ng
  478. * @kind function
  479. *
  480. * @description
  481. * Determines if a reference is undefined.
  482. *
  483. * @param {*} value Reference to check.
  484. * @returns {boolean} True if `value` is undefined.
  485. */
  486. function isUndefined(value) {return typeof value === 'undefined';}
  487. /**
  488. * @ngdoc function
  489. * @name angular.isDefined
  490. * @module ng
  491. * @kind function
  492. *
  493. * @description
  494. * Determines if a reference is defined.
  495. *
  496. * @param {*} value Reference to check.
  497. * @returns {boolean} True if `value` is defined.
  498. */
  499. function isDefined(value) {return typeof value !== 'undefined';}
  500. /**
  501. * @ngdoc function
  502. * @name angular.isObject
  503. * @module ng
  504. * @kind function
  505. *
  506. * @description
  507. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  508. * considered to be objects. Note that JavaScript arrays are objects.
  509. *
  510. * @param {*} value Reference to check.
  511. * @returns {boolean} True if `value` is an `Object` but not `null`.
  512. */
  513. function isObject(value) {
  514. // http://jsperf.com/isobject4
  515. return value !== null && typeof value === 'object';
  516. }
  517. /**
  518. * Determine if a value is an object with a null prototype
  519. *
  520. * @returns {boolean} True if `value` is an `Object` with a null prototype
  521. */
  522. function isBlankObject(value) {
  523. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  524. }
  525. /**
  526. * @ngdoc function
  527. * @name angular.isString
  528. * @module ng
  529. * @kind function
  530. *
  531. * @description
  532. * Determines if a reference is a `String`.
  533. *
  534. * @param {*} value Reference to check.
  535. * @returns {boolean} True if `value` is a `String`.
  536. */
  537. function isString(value) {return typeof value === 'string';}
  538. /**
  539. * @ngdoc function
  540. * @name angular.isNumber
  541. * @module ng
  542. * @kind function
  543. *
  544. * @description
  545. * Determines if a reference is a `Number`.
  546. *
  547. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  548. *
  549. * If you wish to exclude these then you can use the native
  550. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  551. * method.
  552. *
  553. * @param {*} value Reference to check.
  554. * @returns {boolean} True if `value` is a `Number`.
  555. */
  556. function isNumber(value) {return typeof value === 'number';}
  557. /**
  558. * @ngdoc function
  559. * @name angular.isDate
  560. * @module ng
  561. * @kind function
  562. *
  563. * @description
  564. * Determines if a value is a date.
  565. *
  566. * @param {*} value Reference to check.
  567. * @returns {boolean} True if `value` is a `Date`.
  568. */
  569. function isDate(value) {
  570. return toString.call(value) === '[object Date]';
  571. }
  572. /**
  573. * @ngdoc function
  574. * @name angular.isArray
  575. * @module ng
  576. * @kind function
  577. *
  578. * @description
  579. * Determines if a reference is an `Array`.
  580. *
  581. * @param {*} value Reference to check.
  582. * @returns {boolean} True if `value` is an `Array`.
  583. */
  584. var isArray = Array.isArray;
  585. /**
  586. * @ngdoc function
  587. * @name angular.isFunction
  588. * @module ng
  589. * @kind function
  590. *
  591. * @description
  592. * Determines if a reference is a `Function`.
  593. *
  594. * @param {*} value Reference to check.
  595. * @returns {boolean} True if `value` is a `Function`.
  596. */
  597. function isFunction(value) {return typeof value === 'function';}
  598. /**
  599. * Determines if a value is a regular expression object.
  600. *
  601. * @private
  602. * @param {*} value Reference to check.
  603. * @returns {boolean} True if `value` is a `RegExp`.
  604. */
  605. function isRegExp(value) {
  606. return toString.call(value) === '[object RegExp]';
  607. }
  608. /**
  609. * Checks if `obj` is a window object.
  610. *
  611. * @private
  612. * @param {*} obj Object to check
  613. * @returns {boolean} True if `obj` is a window obj.
  614. */
  615. function isWindow(obj) {
  616. return obj && obj.window === obj;
  617. }
  618. function isScope(obj) {
  619. return obj && obj.$evalAsync && obj.$watch;
  620. }
  621. function isFile(obj) {
  622. return toString.call(obj) === '[object File]';
  623. }
  624. function isFormData(obj) {
  625. return toString.call(obj) === '[object FormData]';
  626. }
  627. function isBlob(obj) {
  628. return toString.call(obj) === '[object Blob]';
  629. }
  630. function isBoolean(value) {
  631. return typeof value === 'boolean';
  632. }
  633. function isPromiseLike(obj) {
  634. return obj && isFunction(obj.then);
  635. }
  636. var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array\]$/;
  637. function isTypedArray(value) {
  638. return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
  639. }
  640. function isArrayBuffer(obj) {
  641. return toString.call(obj) === '[object ArrayBuffer]';
  642. }
  643. var trim = function(value) {
  644. return isString(value) ? value.trim() : value;
  645. };
  646. // Copied from:
  647. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  648. // Prereq: s is a string.
  649. var escapeForRegexp = function(s) {
  650. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  651. replace(/\x08/g, '\\x08');
  652. };
  653. /**
  654. * @ngdoc function
  655. * @name angular.isElement
  656. * @module ng
  657. * @kind function
  658. *
  659. * @description
  660. * Determines if a reference is a DOM element (or wrapped jQuery element).
  661. *
  662. * @param {*} value Reference to check.
  663. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  664. */
  665. function isElement(node) {
  666. return !!(node &&
  667. (node.nodeName // we are a direct element
  668. || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
  669. }
  670. /**
  671. * @param str 'key1,key2,...'
  672. * @returns {object} in the form of {key1:true, key2:true, ...}
  673. */
  674. function makeMap(str) {
  675. var obj = {}, items = str.split(','), i;
  676. for (i = 0; i < items.length; i++) {
  677. obj[items[i]] = true;
  678. }
  679. return obj;
  680. }
  681. function nodeName_(element) {
  682. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  683. }
  684. function includes(array, obj) {
  685. return Array.prototype.indexOf.call(array, obj) != -1;
  686. }
  687. function arrayRemove(array, value) {
  688. var index = array.indexOf(value);
  689. if (index >= 0) {
  690. array.splice(index, 1);
  691. }
  692. return index;
  693. }
  694. /**
  695. * @ngdoc function
  696. * @name angular.copy
  697. * @module ng
  698. * @kind function
  699. *
  700. * @description
  701. * Creates a deep copy of `source`, which should be an object or an array.
  702. *
  703. * * If no destination is supplied, a copy of the object or array is created.
  704. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  705. * are deleted and then all elements/properties from the source are copied to it.
  706. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  707. * * If `source` is identical to 'destination' an exception will be thrown.
  708. *
  709. * @param {*} source The source that will be used to make a copy.
  710. * Can be any type, including primitives, `null`, and `undefined`.
  711. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  712. * provided, must be of the same type as `source`.
  713. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  714. *
  715. * @example
  716. <example module="copyExample">
  717. <file name="index.html">
  718. <div ng-controller="ExampleController">
  719. <form novalidate class="simple-form">
  720. Name: <input type="text" ng-model="user.name" /><br />
  721. E-mail: <input type="email" ng-model="user.email" /><br />
  722. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  723. <input type="radio" ng-model="user.gender" value="female" />female<br />
  724. <button ng-click="reset()">RESET</button>
  725. <button ng-click="update(user)">SAVE</button>
  726. </form>
  727. <pre>form = {{user | json}}</pre>
  728. <pre>master = {{master | json}}</pre>
  729. </div>
  730. <script>
  731. angular.module('copyExample', [])
  732. .controller('ExampleController', ['$scope', function($scope) {
  733. $scope.master= {};
  734. $scope.update = function(user) {
  735. // Example with 1 argument
  736. $scope.master= angular.copy(user);
  737. };
  738. $scope.reset = function() {
  739. // Example with 2 arguments
  740. angular.copy($scope.master, $scope.user);
  741. };
  742. $scope.reset();
  743. }]);
  744. </script>
  745. </file>
  746. </example>
  747. */
  748. function copy(source, destination) {
  749. var stackSource = [];
  750. var stackDest = [];
  751. if (destination) {
  752. if (isTypedArray(destination) || isArrayBuffer(destination)) {
  753. throw ngMinErr('cpta', "Can't copy! TypedArray destination cannot be mutated.");
  754. }
  755. if (source === destination) {
  756. throw ngMinErr('cpi', "Can't copy! Source and destination are identical.");
  757. }
  758. // Empty the destination object
  759. if (isArray(destination)) {
  760. destination.length = 0;
  761. } else {
  762. forEach(destination, function(value, key) {
  763. if (key !== '$$hashKey') {
  764. delete destination[key];
  765. }
  766. });
  767. }
  768. stackSource.push(source);
  769. stackDest.push(destination);
  770. return copyRecurse(source, destination);
  771. }
  772. return copyElement(source);
  773. function copyRecurse(source, destination) {
  774. var h = destination.$$hashKey;
  775. var key;
  776. if (isArray(source)) {
  777. for (var i = 0, ii = source.length; i < ii; i++) {
  778. destination.push(copyElement(source[i]));
  779. }
  780. } else if (isBlankObject(source)) {
  781. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  782. for (key in source) {
  783. destination[key] = copyElement(source[key]);
  784. }
  785. } else if (source && typeof source.hasOwnProperty === 'function') {
  786. // Slow path, which must rely on hasOwnProperty
  787. for (key in source) {
  788. if (source.hasOwnProperty(key)) {
  789. destination[key] = copyElement(source[key]);
  790. }
  791. }
  792. } else {
  793. // Slowest path --- hasOwnProperty can't be called as a method
  794. for (key in source) {
  795. if (hasOwnProperty.call(source, key)) {
  796. destination[key] = copyElement(source[key]);
  797. }
  798. }
  799. }
  800. setHashKey(destination, h);
  801. return destination;
  802. }
  803. function copyElement(source) {
  804. // Simple values
  805. if (!isObject(source)) {
  806. return source;
  807. }
  808. // Already copied values
  809. var index = stackSource.indexOf(source);
  810. if (index !== -1) {
  811. return stackDest[index];
  812. }
  813. if (isWindow(source) || isScope(source)) {
  814. throw ngMinErr('cpws',
  815. "Can't copy! Making copies of Window or Scope instances is not supported.");
  816. }
  817. var needsRecurse = false;
  818. var destination = copyType(source);
  819. if (destination === undefined) {
  820. destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
  821. needsRecurse = true;
  822. }
  823. stackSource.push(source);
  824. stackDest.push(destination);
  825. return needsRecurse
  826. ? copyRecurse(source, destination)
  827. : destination;
  828. }
  829. function copyType(source) {
  830. switch (toString.call(source)) {
  831. case '[object Int8Array]':
  832. case '[object Int16Array]':
  833. case '[object Int32Array]':
  834. case '[object Float32Array]':
  835. case '[object Float64Array]':
  836. case '[object Uint8Array]':
  837. case '[object Uint8ClampedArray]':
  838. case '[object Uint16Array]':
  839. case '[object Uint32Array]':
  840. return new source.constructor(copyElement(source.buffer));
  841. case '[object ArrayBuffer]':
  842. //Support: IE10
  843. if (!source.slice) {
  844. var copied = new ArrayBuffer(source.byteLength);
  845. new Uint8Array(copied).set(new Uint8Array(source));
  846. return copied;
  847. }
  848. return source.slice(0);
  849. case '[object Boolean]':
  850. case '[object Number]':
  851. case '[object String]':
  852. case '[object Date]':
  853. return new source.constructor(source.valueOf());
  854. case '[object RegExp]':
  855. var re = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  856. re.lastIndex = source.lastIndex;
  857. return re;
  858. case '[object Blob]':
  859. return new source.constructor([source], {type: source.type});
  860. }
  861. if (isFunction(source.cloneNode)) {
  862. return source.cloneNode(true);
  863. }
  864. }
  865. }
  866. /**
  867. * Creates a shallow copy of an object, an array or a primitive.
  868. *
  869. * Assumes that there are no proto properties for objects.
  870. */
  871. function shallowCopy(src, dst) {
  872. if (isArray(src)) {
  873. dst = dst || [];
  874. for (var i = 0, ii = src.length; i < ii; i++) {
  875. dst[i] = src[i];
  876. }
  877. } else if (isObject(src)) {
  878. dst = dst || {};
  879. for (var key in src) {
  880. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  881. dst[key] = src[key];
  882. }
  883. }
  884. }
  885. return dst || src;
  886. }
  887. /**
  888. * @ngdoc function
  889. * @name angular.equals
  890. * @module ng
  891. * @kind function
  892. *
  893. * @description
  894. * Determines if two objects or two values are equivalent. Supports value types, regular
  895. * expressions, arrays and objects.
  896. *
  897. * Two objects or values are considered equivalent if at least one of the following is true:
  898. *
  899. * * Both objects or values pass `===` comparison.
  900. * * Both objects or values are of the same type and all of their properties are equal by
  901. * comparing them with `angular.equals`.
  902. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  903. * * Both values represent the same regular expression (In JavaScript,
  904. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  905. * representation matches).
  906. *
  907. * During a property comparison, properties of `function` type and properties with names
  908. * that begin with `$` are ignored.
  909. *
  910. * Scope and DOMWindow objects are being compared only by identify (`===`).
  911. *
  912. * @param {*} o1 Object or value to compare.
  913. * @param {*} o2 Object or value to compare.
  914. * @returns {boolean} True if arguments are equal.
  915. */
  916. function equals(o1, o2) {
  917. if (o1 === o2) return true;
  918. if (o1 === null || o2 === null) return false;
  919. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  920. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  921. if (t1 == t2 && t1 == 'object') {
  922. if (isArray(o1)) {
  923. if (!isArray(o2)) return false;
  924. if ((length = o1.length) == o2.length) {
  925. for (key = 0; key < length; key++) {
  926. if (!equals(o1[key], o2[key])) return false;
  927. }
  928. return true;
  929. }
  930. } else if (isDate(o1)) {
  931. if (!isDate(o2)) return false;
  932. return equals(o1.getTime(), o2.getTime());
  933. } else if (isRegExp(o1)) {
  934. if (!isRegExp(o2)) return false;
  935. return o1.toString() == o2.toString();
  936. } else {
  937. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  938. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  939. keySet = createMap();
  940. for (key in o1) {
  941. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  942. if (!equals(o1[key], o2[key])) return false;
  943. keySet[key] = true;
  944. }
  945. for (key in o2) {
  946. if (!(key in keySet) &&
  947. key.charAt(0) !== '$' &&
  948. isDefined(o2[key]) &&
  949. !isFunction(o2[key])) return false;
  950. }
  951. return true;
  952. }
  953. }
  954. return false;
  955. }
  956. var csp = function() {
  957. if (!isDefined(csp.rules)) {
  958. var ngCspElement = (document.querySelector('[ng-csp]') ||
  959. document.querySelector('[data-ng-csp]'));
  960. if (ngCspElement) {
  961. var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
  962. ngCspElement.getAttribute('data-ng-csp');
  963. csp.rules = {
  964. noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
  965. noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
  966. };
  967. } else {
  968. csp.rules = {
  969. noUnsafeEval: noUnsafeEval(),
  970. noInlineStyle: false
  971. };
  972. }
  973. }
  974. return csp.rules;
  975. function noUnsafeEval() {
  976. try {
  977. /* jshint -W031, -W054 */
  978. new Function('');
  979. /* jshint +W031, +W054 */
  980. return false;
  981. } catch (e) {
  982. return true;
  983. }
  984. }
  985. };
  986. /**
  987. * @ngdoc directive
  988. * @module ng
  989. * @name ngJq
  990. *
  991. * @element ANY
  992. * @param {string=} ngJq the name of the library available under `window`
  993. * to be used for angular.element
  994. * @description
  995. * Use this directive to force the angular.element library. This should be
  996. * used to force either jqLite by leaving ng-jq blank or setting the name of
  997. * the jquery variable under window (eg. jQuery).
  998. *
  999. * Since angular looks for this directive when it is loaded (doesn't wait for the
  1000. * DOMContentLoaded event), it must be placed on an element that comes before the script
  1001. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  1002. * others ignored.
  1003. *
  1004. * @example
  1005. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  1006. ```html
  1007. <!doctype html>
  1008. <html ng-app ng-jq>
  1009. ...
  1010. ...
  1011. </html>
  1012. ```
  1013. * @example
  1014. * This example shows how to use a jQuery based library of a different name.
  1015. * The library name must be available at the top most 'window'.
  1016. ```html
  1017. <!doctype html>
  1018. <html ng-app ng-jq="jQueryLib">
  1019. ...
  1020. ...
  1021. </html>
  1022. ```
  1023. */
  1024. var jq = function() {
  1025. if (isDefined(jq.name_)) return jq.name_;
  1026. var el;
  1027. var i, ii = ngAttrPrefixes.length, prefix, name;
  1028. for (i = 0; i < ii; ++i) {
  1029. prefix = ngAttrPrefixes[i];
  1030. if (el = document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]')) {
  1031. name = el.getAttribute(prefix + 'jq');
  1032. break;
  1033. }
  1034. }
  1035. return (jq.name_ = name);
  1036. };
  1037. function concat(array1, array2, index) {
  1038. return array1.concat(slice.call(array2, index));
  1039. }
  1040. function sliceArgs(args, startIndex) {
  1041. return slice.call(args, startIndex || 0);
  1042. }
  1043. /* jshint -W101 */
  1044. /**
  1045. * @ngdoc function
  1046. * @name angular.bind
  1047. * @module ng
  1048. * @kind function
  1049. *
  1050. * @description
  1051. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  1052. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  1053. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  1054. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  1055. *
  1056. * @param {Object} self Context which `fn` should be evaluated in.
  1057. * @param {function()} fn Function to be bound.
  1058. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  1059. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  1060. */
  1061. /* jshint +W101 */
  1062. function bind(self, fn) {
  1063. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  1064. if (isFunction(fn) && !(fn instanceof RegExp)) {
  1065. return curryArgs.length
  1066. ? function() {
  1067. return arguments.length
  1068. ? fn.apply(self, concat(curryArgs, arguments, 0))
  1069. : fn.apply(self, curryArgs);
  1070. }
  1071. : function() {
  1072. return arguments.length
  1073. ? fn.apply(self, arguments)
  1074. : fn.call(self);
  1075. };
  1076. } else {
  1077. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  1078. return fn;
  1079. }
  1080. }
  1081. function toJsonReplacer(key, value) {
  1082. var val = value;
  1083. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  1084. val = undefined;
  1085. } else if (isWindow(value)) {
  1086. val = '$WINDOW';
  1087. } else if (value && document === value) {
  1088. val = '$DOCUMENT';
  1089. } else if (isScope(value)) {
  1090. val = '$SCOPE';
  1091. }
  1092. return val;
  1093. }
  1094. /**
  1095. * @ngdoc function
  1096. * @name angular.toJson
  1097. * @module ng
  1098. * @kind function
  1099. *
  1100. * @description
  1101. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  1102. * stripped since angular uses this notation internally.
  1103. *
  1104. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  1105. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  1106. * If set to an integer, the JSON output will contain that many spaces per indentation.
  1107. * @returns {string|undefined} JSON-ified string representing `obj`.
  1108. */
  1109. function toJson(obj, pretty) {
  1110. if (isUndefined(obj)) return undefined;
  1111. if (!isNumber(pretty)) {
  1112. pretty = pretty ? 2 : null;
  1113. }
  1114. return JSON.stringify(obj, toJsonReplacer, pretty);
  1115. }
  1116. /**
  1117. * @ngdoc function
  1118. * @name angular.fromJson
  1119. * @module ng
  1120. * @kind function
  1121. *
  1122. * @description
  1123. * Deserializes a JSON string.
  1124. *
  1125. * @param {string} json JSON string to deserialize.
  1126. * @returns {Object|Array|string|number} Deserialized JSON string.
  1127. */
  1128. function fromJson(json) {
  1129. return isString(json)
  1130. ? JSON.parse(json)
  1131. : json;
  1132. }
  1133. var ALL_COLONS = /:/g;
  1134. function timezoneToOffset(timezone, fallback) {
  1135. // IE/Edge do not "understand" colon (`:`) in timezone
  1136. timezone = timezone.replace(ALL_COLONS, '');
  1137. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  1138. return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  1139. }
  1140. function addDateMinutes(date, minutes) {
  1141. date = new Date(date.getTime());
  1142. date.setMinutes(date.getMinutes() + minutes);
  1143. return date;
  1144. }
  1145. function convertTimezoneToLocal(date, timezone, reverse) {
  1146. reverse = reverse ? -1 : 1;
  1147. var dateTimezoneOffset = date.getTimezoneOffset();
  1148. var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  1149. return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));
  1150. }
  1151. /**
  1152. * @returns {string} Returns the string representation of the element.
  1153. */
  1154. function startingTag(element) {
  1155. element = jqLite(element).clone();
  1156. try {
  1157. // turns out IE does not let you set .html() on elements which
  1158. // are not allowed to have children. So we just ignore it.
  1159. element.empty();
  1160. } catch (e) {}
  1161. var elemHtml = jqLite('<div>').append(element).html();
  1162. try {
  1163. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  1164. elemHtml.
  1165. match(/^(<[^>]+>)/)[1].
  1166. replace(/^<([\w\-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
  1167. } catch (e) {
  1168. return lowercase(elemHtml);
  1169. }
  1170. }
  1171. /////////////////////////////////////////////////
  1172. /**
  1173. * Tries to decode the URI component without throwing an exception.
  1174. *
  1175. * @private
  1176. * @param str value potential URI component to check.
  1177. * @returns {boolean} True if `value` can be decoded
  1178. * with the decodeURIComponent function.
  1179. */
  1180. function tryDecodeURIComponent(value) {
  1181. try {
  1182. return decodeURIComponent(value);
  1183. } catch (e) {
  1184. // Ignore any invalid uri component
  1185. }
  1186. }
  1187. /**
  1188. * Parses an escaped url query string into key-value pairs.
  1189. * @returns {Object.<string,boolean|Array>}
  1190. */
  1191. function parseKeyValue(/**string*/keyValue) {
  1192. var obj = {};
  1193. forEach((keyValue || "").split('&'), function(keyValue) {
  1194. var splitPoint, key, val;
  1195. if (keyValue) {
  1196. key = keyValue = keyValue.replace(/\+/g,'%20');
  1197. splitPoint = keyValue.indexOf('=');
  1198. if (splitPoint !== -1) {
  1199. key = keyValue.substring(0, splitPoint);
  1200. val = keyValue.substring(splitPoint + 1);
  1201. }
  1202. key = tryDecodeURIComponent(key);
  1203. if (isDefined(key)) {
  1204. val = isDefined(val) ? tryDecodeURIComponent(val) : true;
  1205. if (!hasOwnProperty.call(obj, key)) {
  1206. obj[key] = val;
  1207. } else if (isArray(obj[key])) {
  1208. obj[key].push(val);
  1209. } else {
  1210. obj[key] = [obj[key],val];
  1211. }
  1212. }
  1213. }
  1214. });
  1215. return obj;
  1216. }
  1217. function toKeyValue(obj) {
  1218. var parts = [];
  1219. forEach(obj, function(value, key) {
  1220. if (isArray(value)) {
  1221. forEach(value, function(arrayValue) {
  1222. parts.push(encodeUriQuery(key, true) +
  1223. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1224. });
  1225. } else {
  1226. parts.push(encodeUriQuery(key, true) +
  1227. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1228. }
  1229. });
  1230. return parts.length ? parts.join('&') : '';
  1231. }
  1232. /**
  1233. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1234. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1235. * segments:
  1236. * segment = *pchar
  1237. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1238. * pct-encoded = "%" HEXDIG HEXDIG
  1239. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1240. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1241. * / "*" / "+" / "," / ";" / "="
  1242. */
  1243. function encodeUriSegment(val) {
  1244. return encodeUriQuery(val, true).
  1245. replace(/%26/gi, '&').
  1246. replace(/%3D/gi, '=').
  1247. replace(/%2B/gi, '+');
  1248. }
  1249. /**
  1250. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1251. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1252. * encoded per http://tools.ietf.org/html/rfc3986:
  1253. * query = *( pchar / "/" / "?" )
  1254. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1255. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1256. * pct-encoded = "%" HEXDIG HEXDIG
  1257. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1258. * / "*" / "+" / "," / ";" / "="
  1259. */
  1260. function encodeUriQuery(val, pctEncodeSpaces) {
  1261. return encodeURIComponent(val).
  1262. replace(/%40/gi, '@').
  1263. replace(/%3A/gi, ':').
  1264. replace(/%24/g, '$').
  1265. replace(/%2C/gi, ',').
  1266. replace(/%3B/gi, ';').
  1267. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1268. }
  1269. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1270. function getNgAttribute(element, ngAttr) {
  1271. var attr, i, ii = ngAttrPrefixes.length;
  1272. for (i = 0; i < ii; ++i) {
  1273. attr = ngAttrPrefixes[i] + ngAttr;
  1274. if (isString(attr = element.getAttribute(attr))) {
  1275. return attr;
  1276. }
  1277. }
  1278. return null;
  1279. }
  1280. /**
  1281. * @ngdoc directive
  1282. * @name ngApp
  1283. * @module ng
  1284. *
  1285. * @element ANY
  1286. * @param {angular.Module} ngApp an optional application
  1287. * {@link angular.module module} name to load.
  1288. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1289. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1290. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1291. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1292. * tracking down the root of these bugs.
  1293. *
  1294. * @description
  1295. *
  1296. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1297. * designates the **root element** of the application and is typically placed near the root element
  1298. * of the page - e.g. on the `<body>` or `<html>` tags.
  1299. *
  1300. * There are a few things to keep in mind when using `ngApp`:
  1301. * - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1302. * found in the document will be used to define the root element to auto-bootstrap as an
  1303. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1304. * {@link angular.bootstrap} instead.
  1305. * - AngularJS applications cannot be nested within each other.
  1306. * - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`.
  1307. * This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and
  1308. * {@link ngRoute.ngView `ngView`}.
  1309. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1310. * causing animations to stop working and making the injector inaccessible from outside the app.
  1311. *
  1312. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1313. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1314. * should contain the application code needed or have dependencies on other modules that will
  1315. * contain the code. See {@link angular.module} for more information.
  1316. *
  1317. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1318. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1319. * would not be resolved to `3`.
  1320. *
  1321. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1322. *
  1323. <example module="ngAppDemo">
  1324. <file name="index.html">
  1325. <div ng-controller="ngAppDemoController">
  1326. I can add: {{a}} + {{b}} = {{ a+b }}
  1327. </div>
  1328. </file>
  1329. <file name="script.js">
  1330. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1331. $scope.a = 1;
  1332. $scope.b = 2;
  1333. });
  1334. </file>
  1335. </example>
  1336. *
  1337. * Using `ngStrictDi`, you would see something like this:
  1338. *
  1339. <example ng-app-included="true">
  1340. <file name="index.html">
  1341. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1342. <div ng-controller="GoodController1">
  1343. I can add: {{a}} + {{b}} = {{ a+b }}
  1344. <p>This renders because the controller does not fail to
  1345. instantiate, by using explicit annotation style (see
  1346. script.js for details)
  1347. </p>
  1348. </div>
  1349. <div ng-controller="GoodController2">
  1350. Name: <input ng-model="name"><br />
  1351. Hello, {{name}}!
  1352. <p>This renders because the controller does not fail to
  1353. instantiate, by using explicit annotation style
  1354. (see script.js for details)
  1355. </p>
  1356. </div>
  1357. <div ng-controller="BadController">
  1358. I can add: {{a}} + {{b}} = {{ a+b }}
  1359. <p>The controller could not be instantiated, due to relying
  1360. on automatic function annotations (which are disabled in
  1361. strict mode). As such, the content of this section is not
  1362. interpolated, and there should be an error in your web console.
  1363. </p>
  1364. </div>
  1365. </div>
  1366. </file>
  1367. <file name="script.js">
  1368. angular.module('ngAppStrictDemo', [])
  1369. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1370. // rather than an explicit annotation
  1371. .controller('BadController', function($scope) {
  1372. $scope.a = 1;
  1373. $scope.b = 2;
  1374. })
  1375. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1376. // due to using explicit annotations using the array style and $inject property, respectively.
  1377. .controller('GoodController1', ['$scope', function($scope) {
  1378. $scope.a = 1;
  1379. $scope.b = 2;
  1380. }])
  1381. .controller('GoodController2', GoodController2);
  1382. function GoodController2($scope) {
  1383. $scope.name = "World";
  1384. }
  1385. GoodController2.$inject = ['$scope'];
  1386. </file>
  1387. <file name="style.css">
  1388. div[ng-controller] {
  1389. margin-bottom: 1em;
  1390. -webkit-border-radius: 4px;
  1391. border-radius: 4px;
  1392. border: 1px solid;
  1393. padding: .5em;
  1394. }
  1395. div[ng-controller^=Good] {
  1396. border-color: #d6e9c6;
  1397. background-color: #dff0d8;
  1398. color: #3c763d;
  1399. }
  1400. div[ng-controller^=Bad] {
  1401. border-color: #ebccd1;
  1402. background-color: #f2dede;
  1403. color: #a94442;
  1404. margin-bottom: 0;
  1405. }
  1406. </file>
  1407. </example>
  1408. */
  1409. function angularInit(element, bootstrap) {
  1410. var appElement,
  1411. module,
  1412. config = {};
  1413. // The element `element` has priority over any other element
  1414. forEach(ngAttrPrefixes, function(prefix) {
  1415. var name = prefix + 'app';
  1416. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1417. appElement = element;
  1418. module = element.getAttribute(name);
  1419. }
  1420. });
  1421. forEach(ngAttrPrefixes, function(prefix) {
  1422. var name = prefix + 'app';
  1423. var candidate;
  1424. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1425. appElement = candidate;
  1426. module = candidate.getAttribute(name);
  1427. }
  1428. });
  1429. if (appElement) {
  1430. config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
  1431. bootstrap(appElement, module ? [module] : [], config);
  1432. }
  1433. }
  1434. /**
  1435. * @ngdoc function
  1436. * @name angular.bootstrap
  1437. * @module ng
  1438. * @description
  1439. * Use this function to manually start up angular application.
  1440. *
  1441. * For more information, see the {@link guide/bootstrap Bootstrap guide}.
  1442. *
  1443. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1444. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1445. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1446. * multiple instances of Angular try to work on the DOM.
  1447. *
  1448. * <div class="alert alert-warning">
  1449. * **Note:** Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1450. * They must use {@link ng.directive:ngApp ngApp}.
  1451. * </div>
  1452. *
  1453. * <div class="alert alert-warning">
  1454. * **Note:** Do not bootstrap the app on an element with a directive that uses {@link ng.$compile#transclusion transclusion},
  1455. * such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and {@link ngRoute.ngView `ngView`}.
  1456. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1457. * causing animations to stop working and making the injector inaccessible from outside the app.
  1458. * </div>
  1459. *
  1460. * ```html
  1461. * <!doctype html>
  1462. * <html>
  1463. * <body>
  1464. * <div ng-controller="WelcomeController">
  1465. * {{greeting}}
  1466. * </div>
  1467. *
  1468. * <script src="angular.js"></script>
  1469. * <script>
  1470. * var app = angular.module('demo', [])
  1471. * .controller('WelcomeController', function($scope) {
  1472. * $scope.greeting = 'Welcome!';
  1473. * });
  1474. * angular.bootstrap(document, ['demo']);
  1475. * </script>
  1476. * </body>
  1477. * </html>
  1478. * ```
  1479. *
  1480. * @param {DOMElement} element DOM element which is the root of angular application.
  1481. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1482. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1483. * function that will be invoked by the injector as a `config` block.
  1484. * See: {@link angular.module modules}
  1485. * @param {Object=} config an object for defining configuration options for the application. The
  1486. * following keys are supported:
  1487. *
  1488. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1489. * assist in finding bugs which break minified code. Defaults to `false`.
  1490. *
  1491. * @returns {auto.$injector} Returns the newly created injector for this app.
  1492. */
  1493. function bootstrap(element, modules, config) {
  1494. if (!isObject(config)) config = {};
  1495. var defaultConfig = {
  1496. strictDi: false
  1497. };
  1498. config = extend(defaultConfig, config);
  1499. var doBootstrap = function() {
  1500. element = jqLite(element);
  1501. if (element.injector()) {
  1502. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1503. //Encode angle brackets to prevent input from being sanitized to empty string #8683
  1504. throw ngMinErr(
  1505. 'btstrpd',
  1506. "App Already Bootstrapped with this Element '{0}'",
  1507. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1508. }
  1509. modules = modules || [];
  1510. modules.unshift(['$provide', function($provide) {
  1511. $provide.value('$rootElement', element);
  1512. }]);
  1513. if (config.debugInfoEnabled) {
  1514. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1515. modules.push(['$compileProvider', function($compileProvider) {
  1516. $compileProvider.debugInfoEnabled(true);
  1517. }]);
  1518. }
  1519. modules.unshift('ng');
  1520. var injector = createInjector(modules, config.strictDi);
  1521. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1522. function bootstrapApply(scope, element, compile, injector) {
  1523. scope.$apply(function() {
  1524. element.data('$injector', injector);
  1525. compile(element)(scope);
  1526. });
  1527. }]
  1528. );
  1529. return injector;
  1530. };
  1531. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1532. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1533. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1534. config.debugInfoEnabled = true;
  1535. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1536. }
  1537. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1538. return doBootstrap();
  1539. }
  1540. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1541. angular.resumeBootstrap = function(extraModules) {
  1542. forEach(extraModules, function(module) {
  1543. modules.push(module);
  1544. });
  1545. return doBootstrap();
  1546. };
  1547. if (isFunction(angular.resumeDeferredBootstrap)) {
  1548. angular.resumeDeferredBootstrap();
  1549. }
  1550. }
  1551. /**
  1552. * @ngdoc function
  1553. * @name angular.reloadWithDebugInfo
  1554. * @module ng
  1555. * @description
  1556. * Use this function to reload the current application with debug information turned on.
  1557. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1558. *
  1559. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1560. */
  1561. function reloadWithDebugInfo() {
  1562. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1563. window.location.reload();
  1564. }
  1565. /**
  1566. * @name angular.getTestability
  1567. * @module ng
  1568. * @description
  1569. * Get the testability service for the instance of Angular on the given
  1570. * element.
  1571. * @param {DOMElement} element DOM element which is the root of angular application.
  1572. */
  1573. function getTestability(rootElement) {
  1574. var injector = angular.element(rootElement).injector();
  1575. if (!injector) {
  1576. throw ngMinErr('test',
  1577. 'no injector found for element argument to getTestability');
  1578. }
  1579. return injector.get('$$testability');
  1580. }
  1581. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1582. function snake_case(name, separator) {
  1583. separator = separator || '_';
  1584. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1585. return (pos ? separator : '') + letter.toLowerCase();
  1586. });
  1587. }
  1588. var bindJQueryFired = false;
  1589. function bindJQuery() {
  1590. var originalCleanData;
  1591. if (bindJQueryFired) {
  1592. return;
  1593. }
  1594. // bind to jQuery if present;
  1595. var jqName = jq();
  1596. jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
  1597. !jqName ? undefined : // use jqLite
  1598. window[jqName]; // use jQuery specified by `ngJq`
  1599. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1600. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1601. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1602. // versions. It will not work for sure with jQuery <1.7, though.
  1603. if (jQuery && jQuery.fn.on) {
  1604. jqLite = jQuery;
  1605. extend(jQuery.fn, {
  1606. scope: JQLitePrototype.scope,
  1607. isolateScope: JQLitePrototype.isolateScope,
  1608. controller: JQLitePrototype.controller,
  1609. injector: JQLitePrototype.injector,
  1610. inheritedData: JQLitePrototype.inheritedData
  1611. });
  1612. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1613. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1614. // the $destroy event on all removed nodes.
  1615. originalCleanData = jQuery.cleanData;
  1616. jQuery.cleanData = function(elems) {
  1617. var events;
  1618. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1619. events = jQuery._data(elem, "events");
  1620. if (events && events.$destroy) {
  1621. jQuery(elem).triggerHandler('$destroy');
  1622. }
  1623. }
  1624. originalCleanData(elems);
  1625. };
  1626. } else {
  1627. jqLite = JQLite;
  1628. }
  1629. angular.element = jqLite;
  1630. // Prevent double-proxying.
  1631. bindJQueryFired = true;
  1632. }
  1633. /**
  1634. * throw error if the argument is falsy.
  1635. */
  1636. function assertArg(arg, name, reason) {
  1637. if (!arg) {
  1638. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1639. }
  1640. return arg;
  1641. }
  1642. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1643. if (acceptArrayAnnotation && isArray(arg)) {
  1644. arg = arg[arg.length - 1];
  1645. }
  1646. assertArg(isFunction(arg), name, 'not a function, got ' +
  1647. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1648. return arg;
  1649. }
  1650. /**
  1651. * throw error if the name given is hasOwnProperty
  1652. * @param {String} name the name to test
  1653. * @param {String} context the context in which the name is used, such as module or directive
  1654. */
  1655. function assertNotHasOwnProperty(name, context) {
  1656. if (name === 'hasOwnProperty') {
  1657. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1658. }
  1659. }
  1660. /**
  1661. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1662. * @param {Object} obj starting object
  1663. * @param {String} path path to traverse
  1664. * @param {boolean} [bindFnToScope=true]
  1665. * @returns {Object} value as accessible by path
  1666. */
  1667. //TODO(misko): this function needs to be removed
  1668. function getter(obj, path, bindFnToScope) {
  1669. if (!path) return obj;
  1670. var keys = path.split('.');
  1671. var key;
  1672. var lastInstance = obj;
  1673. var len = keys.length;
  1674. for (var i = 0; i < len; i++) {
  1675. key = keys[i];
  1676. if (obj) {
  1677. obj = (lastInstance = obj)[key];
  1678. }
  1679. }
  1680. if (!bindFnToScope && isFunction(obj)) {
  1681. return bind(lastInstance, obj);
  1682. }
  1683. return obj;
  1684. }
  1685. /**
  1686. * Return the DOM siblings between the first and last node in the given array.
  1687. * @param {Array} array like object
  1688. * @returns {Array} the inputted object or a jqLite collection containing the nodes
  1689. */
  1690. function getBlockNodes(nodes) {
  1691. // TODO(perf): update `nodes` instead of creating a new object?
  1692. var node = nodes[0];
  1693. var endNode = nodes[nodes.length - 1];
  1694. var blockNodes;
  1695. for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
  1696. if (blockNodes || nodes[i] !== node) {
  1697. if (!blockNodes) {
  1698. blockNodes = jqLite(slice.call(nodes, 0, i));
  1699. }
  1700. blockNodes.push(node);
  1701. }
  1702. }
  1703. return blockNodes || nodes;
  1704. }
  1705. /**
  1706. * Creates a new object without a prototype. This object is useful for lookup without having to
  1707. * guard against prototypically inherited properties via hasOwnProperty.
  1708. *
  1709. * Related micro-benchmarks:
  1710. * - http://jsperf.com/object-create2
  1711. * - http://jsperf.com/proto-map-lookup/2
  1712. * - http://jsperf.com/for-in-vs-object-keys2
  1713. *
  1714. * @returns {Object}
  1715. */
  1716. function createMap() {
  1717. return Object.create(null);
  1718. }
  1719. var NODE_TYPE_ELEMENT = 1;
  1720. var NODE_TYPE_ATTRIBUTE = 2;
  1721. var NODE_TYPE_TEXT = 3;
  1722. var NODE_TYPE_COMMENT = 8;
  1723. var NODE_TYPE_DOCUMENT = 9;
  1724. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1725. /**
  1726. * @ngdoc type
  1727. * @name angular.Module
  1728. * @module ng
  1729. * @description
  1730. *
  1731. * Interface for configuring angular {@link angular.module modules}.
  1732. */
  1733. function setupModuleLoader(window) {
  1734. var $injectorMinErr = minErr('$injector');
  1735. var ngMinErr = minErr('ng');
  1736. function ensure(obj, name, factory) {
  1737. return obj[name] || (obj[name] = factory());
  1738. }
  1739. var angular = ensure(window, 'angular', Object);
  1740. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1741. angular.$$minErr = angular.$$minErr || minErr;
  1742. return ensure(angular, 'module', function() {
  1743. /** @type {Object.<string, angular.Module>} */
  1744. var modules = {};
  1745. /**
  1746. * @ngdoc function
  1747. * @name angular.module
  1748. * @module ng
  1749. * @description
  1750. *
  1751. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1752. * modules.
  1753. * All modules (angular core or 3rd party) that should be available to an application must be
  1754. * registered using this mechanism.
  1755. *
  1756. * Passing one argument retrieves an existing {@link angular.Module},
  1757. * whereas passing more than one argument creates a new {@link angular.Module}
  1758. *
  1759. *
  1760. * # Module
  1761. *
  1762. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1763. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1764. *
  1765. * ```js
  1766. * // Create a new module
  1767. * var myModule = angular.module('myModule', []);
  1768. *
  1769. * // register a new service
  1770. * myModule.value('appName', 'MyCoolApp');
  1771. *
  1772. * // configure existing services inside initialization blocks.
  1773. * myModule.config(['$locationProvider', function($locationProvider) {
  1774. * // Configure existing providers
  1775. * $locationProvider.hashPrefix('!');
  1776. * }]);
  1777. * ```
  1778. *
  1779. * Then you can create an injector and load your modules like this:
  1780. *
  1781. * ```js
  1782. * var injector = angular.injector(['ng', 'myModule'])
  1783. * ```
  1784. *
  1785. * However it's more likely that you'll just use
  1786. * {@link ng.directive:ngApp ngApp} or
  1787. * {@link angular.bootstrap} to simplify this process for you.
  1788. *
  1789. * @param {!string} name The name of the module to create or retrieve.
  1790. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1791. * unspecified then the module is being retrieved for further configuration.
  1792. * @param {Function=} configFn Optional configuration function for the module. Same as
  1793. * {@link angular.Module#config Module#config()}.
  1794. * @returns {angular.Module} new module with the {@link angular.Module} api.
  1795. */
  1796. return function module(name, requires, configFn) {
  1797. var assertNotHasOwnProperty = function(name, context) {
  1798. if (name === 'hasOwnProperty') {
  1799. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1800. }
  1801. };
  1802. assertNotHasOwnProperty(name, 'module');
  1803. if (requires && modules.hasOwnProperty(name)) {
  1804. modules[name] = null;
  1805. }
  1806. return ensure(modules, name, function() {
  1807. if (!requires) {
  1808. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1809. "the module name or forgot to load it. If registering a module ensure that you " +
  1810. "specify the dependencies as the second argument.", name);
  1811. }
  1812. /** @type {!Array.<Array.<*>>} */
  1813. var invokeQueue = [];
  1814. /** @type {!Array.<Function>} */
  1815. var configBlocks = [];
  1816. /** @type {!Array.<Function>} */
  1817. var runBlocks = [];
  1818. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  1819. /** @type {angular.Module} */
  1820. var moduleInstance = {
  1821. // Private state
  1822. _invokeQueue: invokeQueue,
  1823. _configBlocks: configBlocks,
  1824. _runBlocks: runBlocks,
  1825. /**
  1826. * @ngdoc property
  1827. * @name angular.Module#requires
  1828. * @module ng
  1829. *
  1830. * @description
  1831. * Holds the list of modules which the injector will load before the current module is
  1832. * loaded.
  1833. */
  1834. requires: requires,
  1835. /**
  1836. * @ngdoc property
  1837. * @name angular.Module#name
  1838. * @module ng
  1839. *
  1840. * @description
  1841. * Name of the module.
  1842. */
  1843. name: name,
  1844. /**
  1845. * @ngdoc method
  1846. * @name angular.Module#provider
  1847. * @module ng
  1848. * @param {string} name service name
  1849. * @param {Function} providerType Construction function for creating new instance of the
  1850. * service.
  1851. * @description
  1852. * See {@link auto.$provide#provider $provide.provider()}.
  1853. */
  1854. provider: invokeLaterAndSetModuleName('$provide', 'provider'),
  1855. /**
  1856. * @ngdoc method
  1857. * @name angular.Module#factory
  1858. * @module ng
  1859. * @param {string} name service name
  1860. * @param {Function} providerFunction Function for creating new instance of the service.
  1861. * @description
  1862. * See {@link auto.$provide#factory $provide.factory()}.
  1863. */
  1864. factory: invokeLaterAndSetModuleName('$provide', 'factory'),
  1865. /**
  1866. * @ngdoc method
  1867. * @name angular.Module#service
  1868. * @module ng
  1869. * @param {string} name service name
  1870. * @param {Function} constructor A constructor function that will be instantiated.
  1871. * @description
  1872. * See {@link auto.$provide#service $provide.service()}.
  1873. */
  1874. service: invokeLaterAndSetModuleName('$provide', 'service'),
  1875. /**
  1876. * @ngdoc method
  1877. * @name angular.Module#value
  1878. * @module ng
  1879. * @param {string} name service name
  1880. * @param {*} object Service instance object.
  1881. * @description
  1882. * See {@link auto.$provide#value $provide.value()}.
  1883. */
  1884. value: invokeLater('$provide', 'value'),
  1885. /**
  1886. * @ngdoc method
  1887. * @name angular.Module#constant
  1888. * @module ng
  1889. * @param {string} name constant name
  1890. * @param {*} object Constant value.
  1891. * @description
  1892. * Because the constants are fixed, they get applied before other provide methods.
  1893. * See {@link auto.$provide#constant $provide.constant()}.
  1894. */
  1895. constant: invokeLater('$provide', 'constant', 'unshift'),
  1896. /**
  1897. * @ngdoc method
  1898. * @name angular.Module#decorator
  1899. * @module ng
  1900. * @param {string} The name of the service to decorate.
  1901. * @param {Function} This function will be invoked when the service needs to be
  1902. * instantiated and should return the decorated service instance.
  1903. * @description
  1904. * See {@link auto.$provide#decorator $provide.decorator()}.
  1905. */
  1906. decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
  1907. /**
  1908. * @ngdoc method
  1909. * @name angular.Module#animation
  1910. * @module ng
  1911. * @param {string} name animation name
  1912. * @param {Function} animationFactory Factory function for creating new instance of an
  1913. * animation.
  1914. * @description
  1915. *
  1916. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1917. *
  1918. *
  1919. * Defines an animation hook that can be later used with
  1920. * {@link $animate $animate} service and directives that use this service.
  1921. *
  1922. * ```js
  1923. * module.animation('.animation-name', function($inject1, $inject2) {
  1924. * return {
  1925. * eventName : function(element, done) {
  1926. * //code to run the animation
  1927. * //once complete, then run done()
  1928. * return function cancellationFunction(element) {
  1929. * //code to cancel the animation
  1930. * }
  1931. * }
  1932. * }
  1933. * })
  1934. * ```
  1935. *
  1936. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  1937. * {@link ngAnimate ngAnimate module} for more information.
  1938. */
  1939. animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
  1940. /**
  1941. * @ngdoc method
  1942. * @name angular.Module#filter
  1943. * @module ng
  1944. * @param {string} name Filter name - this must be a valid angular expression identifier
  1945. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1946. * @description
  1947. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1948. *
  1949. * <div class="alert alert-warning">
  1950. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  1951. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  1952. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  1953. * (`myapp_subsection_filterx`).
  1954. * </div>
  1955. */
  1956. filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
  1957. /**
  1958. * @ngdoc method
  1959. * @name angular.Module#controller
  1960. * @module ng
  1961. * @param {string|Object} name Controller name, or an object map of controllers where the
  1962. * keys are the names and the values are the constructors.
  1963. * @param {Function} constructor Controller constructor function.
  1964. * @description
  1965. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1966. */
  1967. controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
  1968. /**
  1969. * @ngdoc method
  1970. * @name angular.Module#directive
  1971. * @module ng
  1972. * @param {string|Object} name Directive name, or an object map of directives where the
  1973. * keys are the names and the values are the factories.
  1974. * @param {Function} directiveFactory Factory function for creating new instance of
  1975. * directives.
  1976. * @description
  1977. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  1978. */
  1979. directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
  1980. /**
  1981. * @ngdoc method
  1982. * @name angular.Module#component
  1983. * @module ng
  1984. * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp)
  1985. * @param {Object} options Component definition object (a simplified
  1986. * {@link ng.$compile#directive-definition-object directive definition object})
  1987. *
  1988. * @description
  1989. * See {@link ng.$compileProvider#component $compileProvider.component()}.
  1990. */
  1991. component: invokeLaterAndSetModuleName('$compileProvider', 'component'),
  1992. /**
  1993. * @ngdoc method
  1994. * @name angular.Module#config
  1995. * @module ng
  1996. * @param {Function} configFn Execute this function on module load. Useful for service
  1997. * configuration.
  1998. * @description
  1999. * Use this method to register work which needs to be performed on module loading.
  2000. * For more about how to configure services, see
  2001. * {@link providers#provider-recipe Provider Recipe}.
  2002. */
  2003. config: config,
  2004. /**
  2005. * @ngdoc method
  2006. * @name angular.Module#run
  2007. * @module ng
  2008. * @param {Function} initializationFn Execute this function after injector creation.
  2009. * Useful for application initialization.
  2010. * @description
  2011. * Use this method to register work which should be performed when the injector is done
  2012. * loading all modules.
  2013. */
  2014. run: function(block) {
  2015. runBlocks.push(block);
  2016. return this;
  2017. }
  2018. };
  2019. if (configFn) {
  2020. config(configFn);
  2021. }
  2022. return moduleInstance;
  2023. /**
  2024. * @param {string} provider
  2025. * @param {string} method
  2026. * @param {String=} insertMethod
  2027. * @returns {angular.Module}
  2028. */
  2029. function invokeLater(provider, method, insertMethod, queue) {
  2030. if (!queue) queue = invokeQueue;
  2031. return function() {
  2032. queue[insertMethod || 'push']([provider, method, arguments]);
  2033. return moduleInstance;
  2034. };
  2035. }
  2036. /**
  2037. * @param {string} provider
  2038. * @param {string} method
  2039. * @returns {angular.Module}
  2040. */
  2041. function invokeLaterAndSetModuleName(provider, method) {
  2042. return function(recipeName, factoryFunction) {
  2043. if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
  2044. invokeQueue.push([provider, method, arguments]);
  2045. return moduleInstance;
  2046. };
  2047. }
  2048. });
  2049. };
  2050. });
  2051. }
  2052. /* global: toDebugString: true */
  2053. function serializeObject(obj) {
  2054. var seen = [];
  2055. return JSON.stringify(obj, function(key, val) {
  2056. val = toJsonReplacer(key, val);
  2057. if (isObject(val)) {
  2058. if (seen.indexOf(val) >= 0) return '...';
  2059. seen.push(val);
  2060. }
  2061. return val;
  2062. });
  2063. }
  2064. function toDebugString(obj) {
  2065. if (typeof obj === 'function') {
  2066. return obj.toString().replace(/ \{[\s\S]*$/, '');
  2067. } else if (isUndefined(obj)) {
  2068. return 'undefined';
  2069. } else if (typeof obj !== 'string') {
  2070. return serializeObject(obj);
  2071. }
  2072. return obj;
  2073. }
  2074. /* global angularModule: true,
  2075. version: true,
  2076. $CompileProvider,
  2077. htmlAnchorDirective,
  2078. inputDirective,
  2079. inputDirective,
  2080. formDirective,
  2081. scriptDirective,
  2082. selectDirective,
  2083. styleDirective,
  2084. optionDirective,
  2085. ngBindDirective,
  2086. ngBindHtmlDirective,
  2087. ngBindTemplateDirective,
  2088. ngClassDirective,
  2089. ngClassEvenDirective,
  2090. ngClassOddDirective,
  2091. ngCloakDirective,
  2092. ngControllerDirective,
  2093. ngFormDirective,
  2094. ngHideDirective,
  2095. ngIfDirective,
  2096. ngIncludeDirective,
  2097. ngIncludeFillContentDirective,
  2098. ngInitDirective,
  2099. ngNonBindableDirective,
  2100. ngPluralizeDirective,
  2101. ngRepeatDirective,
  2102. ngShowDirective,
  2103. ngStyleDirective,
  2104. ngSwitchDirective,
  2105. ngSwitchWhenDirective,
  2106. ngSwitchDefaultDirective,
  2107. ngOptionsDirective,
  2108. ngTranscludeDirective,
  2109. ngModelDirective,
  2110. ngListDirective,
  2111. ngChangeDirective,
  2112. patternDirective,
  2113. patternDirective,
  2114. requiredDirective,
  2115. requiredDirective,
  2116. minlengthDirective,
  2117. minlengthDirective,
  2118. maxlengthDirective,
  2119. maxlengthDirective,
  2120. ngValueDirective,
  2121. ngModelOptionsDirective,
  2122. ngAttributeAliasDirectives,
  2123. ngEventDirectives,
  2124. $AnchorScrollProvider,
  2125. $AnimateProvider,
  2126. $CoreAnimateCssProvider,
  2127. $$CoreAnimateJsProvider,
  2128. $$CoreAnimateQueueProvider,
  2129. $$AnimateRunnerFactoryProvider,
  2130. $$AnimateAsyncRunFactoryProvider,
  2131. $BrowserProvider,
  2132. $CacheFactoryProvider,
  2133. $ControllerProvider,
  2134. $DateProvider,
  2135. $DocumentProvider,
  2136. $ExceptionHandlerProvider,
  2137. $FilterProvider,
  2138. $$ForceReflowProvider,
  2139. $InterpolateProvider,
  2140. $IntervalProvider,
  2141. $$HashMapProvider,
  2142. $HttpProvider,
  2143. $HttpParamSerializerProvider,
  2144. $HttpParamSerializerJQLikeProvider,
  2145. $HttpBackendProvider,
  2146. $xhrFactoryProvider,
  2147. $LocationProvider,
  2148. $LogProvider,
  2149. $ParseProvider,
  2150. $RootScopeProvider,
  2151. $QProvider,
  2152. $$QProvider,
  2153. $$SanitizeUriProvider,
  2154. $SceProvider,
  2155. $SceDelegateProvider,
  2156. $SnifferProvider,
  2157. $TemplateCacheProvider,
  2158. $TemplateRequestProvider,
  2159. $$TestabilityProvider,
  2160. $TimeoutProvider,
  2161. $$RAFProvider,
  2162. $WindowProvider,
  2163. $$jqLiteProvider,
  2164. $$CookieReaderProvider
  2165. */
  2166. /**
  2167. * @ngdoc object
  2168. * @name angular.version
  2169. * @module ng
  2170. * @description
  2171. * An object that contains information about the current AngularJS version.
  2172. *
  2173. * This object has the following properties:
  2174. *
  2175. * - `full` – `{string}` – Full version string, such as "0.9.18".
  2176. * - `major` – `{number}` – Major version number, such as "0".
  2177. * - `minor` – `{number}` – Minor version number, such as "9".
  2178. * - `dot` – `{number}` – Dot version number, such as "18".
  2179. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  2180. */
  2181. var version = {
  2182. full: '1.5.3', // all of these placeholder strings will be replaced by grunt's
  2183. major: 1, // package task
  2184. minor: 5,
  2185. dot: 3,
  2186. codeName: 'diplohaplontic-meiosis'
  2187. };
  2188. function publishExternalAPI(angular) {
  2189. extend(angular, {
  2190. 'bootstrap': bootstrap,
  2191. 'copy': copy,
  2192. 'extend': extend,
  2193. 'merge': merge,
  2194. 'equals': equals,
  2195. 'element': jqLite,
  2196. 'forEach': forEach,
  2197. 'injector': createInjector,
  2198. 'noop': noop,
  2199. 'bind': bind,
  2200. 'toJson': toJson,
  2201. 'fromJson': fromJson,
  2202. 'identity': identity,
  2203. 'isUndefined': isUndefined,
  2204. 'isDefined': isDefined,
  2205. 'isString': isString,
  2206. 'isFunction': isFunction,
  2207. 'isObject': isObject,
  2208. 'isNumber': isNumber,
  2209. 'isElement': isElement,
  2210. 'isArray': isArray,
  2211. 'version': version,
  2212. 'isDate': isDate,
  2213. 'lowercase': lowercase,
  2214. 'uppercase': uppercase,
  2215. 'callbacks': {counter: 0},
  2216. 'getTestability': getTestability,
  2217. '$$minErr': minErr,
  2218. '$$csp': csp,
  2219. 'reloadWithDebugInfo': reloadWithDebugInfo
  2220. });
  2221. angularModule = setupModuleLoader(window);
  2222. angularModule('ng', ['ngLocale'], ['$provide',
  2223. function ngModule($provide) {
  2224. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  2225. $provide.provider({
  2226. $$sanitizeUri: $$SanitizeUriProvider
  2227. });
  2228. $provide.provider('$compile', $CompileProvider).
  2229. directive({
  2230. a: htmlAnchorDirective,
  2231. input: inputDirective,
  2232. textarea: inputDirective,
  2233. form: formDirective,
  2234. script: scriptDirective,
  2235. select: selectDirective,
  2236. style: styleDirective,
  2237. option: optionDirective,
  2238. ngBind: ngBindDirective,
  2239. ngBindHtml: ngBindHtmlDirective,
  2240. ngBindTemplate: ngBindTemplateDirective,
  2241. ngClass: ngClassDirective,
  2242. ngClassEven: ngClassEvenDirective,
  2243. ngClassOdd: ngClassOddDirective,
  2244. ngCloak: ngCloakDirective,
  2245. ngController: ngControllerDirective,
  2246. ngForm: ngFormDirective,
  2247. ngHide: ngHideDirective,
  2248. ngIf: ngIfDirective,
  2249. ngInclude: ngIncludeDirective,
  2250. ngInit: ngInitDirective,
  2251. ngNonBindable: ngNonBindableDirective,
  2252. ngPluralize: ngPluralizeDirective,
  2253. ngRepeat: ngRepeatDirective,
  2254. ngShow: ngShowDirective,
  2255. ngStyle: ngStyleDirective,
  2256. ngSwitch: ngSwitchDirective,
  2257. ngSwitchWhen: ngSwitchWhenDirective,
  2258. ngSwitchDefault: ngSwitchDefaultDirective,
  2259. ngOptions: ngOptionsDirective,
  2260. ngTransclude: ngTranscludeDirective,
  2261. ngModel: ngModelDirective,
  2262. ngList: ngListDirective,
  2263. ngChange: ngChangeDirective,
  2264. pattern: patternDirective,
  2265. ngPattern: patternDirective,
  2266. required: requiredDirective,
  2267. ngRequired: requiredDirective,
  2268. minlength: minlengthDirective,
  2269. ngMinlength: minlengthDirective,
  2270. maxlength: maxlengthDirective,
  2271. ngMaxlength: maxlengthDirective,
  2272. ngValue: ngValueDirective,
  2273. ngModelOptions: ngModelOptionsDirective
  2274. }).
  2275. directive({
  2276. ngInclude: ngIncludeFillContentDirective
  2277. }).
  2278. directive(ngAttributeAliasDirectives).
  2279. directive(ngEventDirectives);
  2280. $provide.provider({
  2281. $anchorScroll: $AnchorScrollProvider,
  2282. $animate: $AnimateProvider,
  2283. $animateCss: $CoreAnimateCssProvider,
  2284. $$animateJs: $$CoreAnimateJsProvider,
  2285. $$animateQueue: $$CoreAnimateQueueProvider,
  2286. $$AnimateRunner: $$AnimateRunnerFactoryProvider,
  2287. $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,
  2288. $browser: $BrowserProvider,
  2289. $cacheFactory: $CacheFactoryProvider,
  2290. $controller: $ControllerProvider,
  2291. $document: $DocumentProvider,
  2292. $exceptionHandler: $ExceptionHandlerProvider,
  2293. $filter: $FilterProvider,
  2294. $$forceReflow: $$ForceReflowProvider,
  2295. $interpolate: $InterpolateProvider,
  2296. $interval: $IntervalProvider,
  2297. $http: $HttpProvider,
  2298. $httpParamSerializer: $HttpParamSerializerProvider,
  2299. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  2300. $httpBackend: $HttpBackendProvider,
  2301. $xhrFactory: $xhrFactoryProvider,
  2302. $location: $LocationProvider,
  2303. $log: $LogProvider,
  2304. $parse: $ParseProvider,
  2305. $rootScope: $RootScopeProvider,
  2306. $q: $QProvider,
  2307. $$q: $$QProvider,
  2308. $sce: $SceProvider,
  2309. $sceDelegate: $SceDelegateProvider,
  2310. $sniffer: $SnifferProvider,
  2311. $templateCache: $TemplateCacheProvider,
  2312. $templateRequest: $TemplateRequestProvider,
  2313. $$testability: $$TestabilityProvider,
  2314. $timeout: $TimeoutProvider,
  2315. $window: $WindowProvider,
  2316. $$rAF: $$RAFProvider,
  2317. $$jqLite: $$jqLiteProvider,
  2318. $$HashMap: $$HashMapProvider,
  2319. $$cookieReader: $$CookieReaderProvider
  2320. });
  2321. }
  2322. ]);
  2323. }
  2324. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2325. * Any commits to this file should be reviewed with security in mind. *
  2326. * Changes to this file can potentially create security vulnerabilities. *
  2327. * An approval from 2 Core members with history of modifying *
  2328. * this file is required. *
  2329. * *
  2330. * Does the change somehow allow for arbitrary javascript to be executed? *
  2331. * Or allows for someone to change the prototype of built-in objects? *
  2332. * Or gives undesired access to variables likes document or window? *
  2333. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2334. /* global JQLitePrototype: true,
  2335. addEventListenerFn: true,
  2336. removeEventListenerFn: true,
  2337. BOOLEAN_ATTR: true,
  2338. ALIASED_ATTR: true,
  2339. */
  2340. //////////////////////////////////
  2341. //JQLite
  2342. //////////////////////////////////
  2343. /**
  2344. * @ngdoc function
  2345. * @name angular.element
  2346. * @module ng
  2347. * @kind function
  2348. *
  2349. * @description
  2350. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2351. *
  2352. * If jQuery is available, `angular.element` is an alias for the
  2353. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2354. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
  2355. *
  2356. * jqLite is a tiny, API-compatible subset of jQuery that allows
  2357. * Angular to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
  2358. * commonly needed functionality with the goal of having a very small footprint.
  2359. *
  2360. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
  2361. * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
  2362. * specific version of jQuery if multiple versions exist on the page.
  2363. *
  2364. * <div class="alert alert-info">**Note:** All element references in Angular are always wrapped with jQuery or
  2365. * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div>
  2366. *
  2367. * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements
  2368. * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
  2369. * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.</div>
  2370. *
  2371. * ## Angular's jqLite
  2372. * jqLite provides only the following jQuery methods:
  2373. *
  2374. * - [`addClass()`](http://api.jquery.com/addClass/)
  2375. * - [`after()`](http://api.jquery.com/after/)
  2376. * - [`append()`](http://api.jquery.com/append/)
  2377. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2378. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  2379. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2380. * - [`clone()`](http://api.jquery.com/clone/)
  2381. * - [`contents()`](http://api.jquery.com/contents/)
  2382. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
  2383. * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
  2384. * - [`data()`](http://api.jquery.com/data/)
  2385. * - [`detach()`](http://api.jquery.com/detach/)
  2386. * - [`empty()`](http://api.jquery.com/empty/)
  2387. * - [`eq()`](http://api.jquery.com/eq/)
  2388. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2389. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2390. * - [`html()`](http://api.jquery.com/html/)
  2391. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2392. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2393. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
  2394. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2395. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2396. * - [`prepend()`](http://api.jquery.com/prepend/)
  2397. * - [`prop()`](http://api.jquery.com/prop/)
  2398. * - [`ready()`](http://api.jquery.com/ready/)
  2399. * - [`remove()`](http://api.jquery.com/remove/)
  2400. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  2401. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  2402. * - [`removeData()`](http://api.jquery.com/removeData/)
  2403. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2404. * - [`text()`](http://api.jquery.com/text/)
  2405. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  2406. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  2407. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces or event object as parameter
  2408. * - [`val()`](http://api.jquery.com/val/)
  2409. * - [`wrap()`](http://api.jquery.com/wrap/)
  2410. *
  2411. * ## jQuery/jqLite Extras
  2412. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2413. *
  2414. * ### Events
  2415. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2416. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2417. * element before it is removed.
  2418. *
  2419. * ### Methods
  2420. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2421. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2422. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2423. * `'ngModel'`).
  2424. * - `injector()` - retrieves the injector of the current element or its parent.
  2425. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2426. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2427. * be enabled.
  2428. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2429. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2430. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2431. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2432. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2433. * parent element is reached.
  2434. *
  2435. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2436. * @returns {Object} jQuery object.
  2437. */
  2438. JQLite.expando = 'ng339';
  2439. var jqCache = JQLite.cache = {},
  2440. jqId = 1,
  2441. addEventListenerFn = function(element, type, fn) {
  2442. element.addEventListener(type, fn, false);
  2443. },
  2444. removeEventListenerFn = function(element, type, fn) {
  2445. element.removeEventListener(type, fn, false);
  2446. };
  2447. /*
  2448. * !!! This is an undocumented "private" function !!!
  2449. */
  2450. JQLite._data = function(node) {
  2451. //jQuery always returns an object on cache miss
  2452. return this.cache[node[this.expando]] || {};
  2453. };
  2454. function jqNextId() { return ++jqId; }
  2455. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  2456. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  2457. var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
  2458. var jqLiteMinErr = minErr('jqLite');
  2459. /**
  2460. * Converts snake_case to camelCase.
  2461. * Also there is special case for Moz prefix starting with upper case letter.
  2462. * @param name Name to normalize
  2463. */
  2464. function camelCase(name) {
  2465. return name.
  2466. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2467. return offset ? letter.toUpperCase() : letter;
  2468. }).
  2469. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2470. }
  2471. var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
  2472. var HTML_REGEXP = /<|&#?\w+;/;
  2473. var TAG_NAME_REGEXP = /<([\w:-]+)/;
  2474. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
  2475. var wrapMap = {
  2476. 'option': [1, '<select multiple="multiple">', '</select>'],
  2477. 'thead': [1, '<table>', '</table>'],
  2478. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2479. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2480. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2481. '_default': [0, "", ""]
  2482. };
  2483. wrapMap.optgroup = wrapMap.option;
  2484. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2485. wrapMap.th = wrapMap.td;
  2486. function jqLiteIsTextNode(html) {
  2487. return !HTML_REGEXP.test(html);
  2488. }
  2489. function jqLiteAcceptsData(node) {
  2490. // The window object can accept data but has no nodeType
  2491. // Otherwise we are only interested in elements (1) and documents (9)
  2492. var nodeType = node.nodeType;
  2493. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2494. }
  2495. function jqLiteHasData(node) {
  2496. for (var key in jqCache[node.ng339]) {
  2497. return true;
  2498. }
  2499. return false;
  2500. }
  2501. function jqLiteCleanData(nodes) {
  2502. for (var i = 0, ii = nodes.length; i < ii; i++) {
  2503. jqLiteRemoveData(nodes[i]);
  2504. }
  2505. }
  2506. function jqLiteBuildFragment(html, context) {
  2507. var tmp, tag, wrap,
  2508. fragment = context.createDocumentFragment(),
  2509. nodes = [], i;
  2510. if (jqLiteIsTextNode(html)) {
  2511. // Convert non-html into a text node
  2512. nodes.push(context.createTextNode(html));
  2513. } else {
  2514. // Convert html into DOM nodes
  2515. tmp = tmp || fragment.appendChild(context.createElement("div"));
  2516. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2517. wrap = wrapMap[tag] || wrapMap._default;
  2518. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2519. // Descend through wrappers to the right content
  2520. i = wrap[0];
  2521. while (i--) {
  2522. tmp = tmp.lastChild;
  2523. }
  2524. nodes = concat(nodes, tmp.childNodes);
  2525. tmp = fragment.firstChild;
  2526. tmp.textContent = "";
  2527. }
  2528. // Remove wrapper from fragment
  2529. fragment.textContent = "";
  2530. fragment.innerHTML = ""; // Clear inner HTML
  2531. forEach(nodes, function(node) {
  2532. fragment.appendChild(node);
  2533. });
  2534. return fragment;
  2535. }
  2536. function jqLiteParseHTML(html, context) {
  2537. context = context || document;
  2538. var parsed;
  2539. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2540. return [context.createElement(parsed[1])];
  2541. }
  2542. if ((parsed = jqLiteBuildFragment(html, context))) {
  2543. return parsed.childNodes;
  2544. }
  2545. return [];
  2546. }
  2547. function jqLiteWrapNode(node, wrapper) {
  2548. var parent = node.parentNode;
  2549. if (parent) {
  2550. parent.replaceChild(wrapper, node);
  2551. }
  2552. wrapper.appendChild(node);
  2553. }
  2554. // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
  2555. var jqLiteContains = Node.prototype.contains || function(arg) {
  2556. // jshint bitwise: false
  2557. return !!(this.compareDocumentPosition(arg) & 16);
  2558. // jshint bitwise: true
  2559. };
  2560. /////////////////////////////////////////////
  2561. function JQLite(element) {
  2562. if (element instanceof JQLite) {
  2563. return element;
  2564. }
  2565. var argIsString;
  2566. if (isString(element)) {
  2567. element = trim(element);
  2568. argIsString = true;
  2569. }
  2570. if (!(this instanceof JQLite)) {
  2571. if (argIsString && element.charAt(0) != '<') {
  2572. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2573. }
  2574. return new JQLite(element);
  2575. }
  2576. if (argIsString) {
  2577. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2578. } else {
  2579. jqLiteAddNodes(this, element);
  2580. }
  2581. }
  2582. function jqLiteClone(element) {
  2583. return element.cloneNode(true);
  2584. }
  2585. function jqLiteDealoc(element, onlyDescendants) {
  2586. if (!onlyDescendants) jqLiteRemoveData(element);
  2587. if (element.querySelectorAll) {
  2588. var descendants = element.querySelectorAll('*');
  2589. for (var i = 0, l = descendants.length; i < l; i++) {
  2590. jqLiteRemoveData(descendants[i]);
  2591. }
  2592. }
  2593. }
  2594. function jqLiteOff(element, type, fn, unsupported) {
  2595. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2596. var expandoStore = jqLiteExpandoStore(element);
  2597. var events = expandoStore && expandoStore.events;
  2598. var handle = expandoStore && expandoStore.handle;
  2599. if (!handle) return; //no listeners registered
  2600. if (!type) {
  2601. for (type in events) {
  2602. if (type !== '$destroy') {
  2603. removeEventListenerFn(element, type, handle);
  2604. }
  2605. delete events[type];
  2606. }
  2607. } else {
  2608. var removeHandler = function(type) {
  2609. var listenerFns = events[type];
  2610. if (isDefined(fn)) {
  2611. arrayRemove(listenerFns || [], fn);
  2612. }
  2613. if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
  2614. removeEventListenerFn(element, type, handle);
  2615. delete events[type];
  2616. }
  2617. };
  2618. forEach(type.split(' '), function(type) {
  2619. removeHandler(type);
  2620. if (MOUSE_EVENT_MAP[type]) {
  2621. removeHandler(MOUSE_EVENT_MAP[type]);
  2622. }
  2623. });
  2624. }
  2625. }
  2626. function jqLiteRemoveData(element, name) {
  2627. var expandoId = element.ng339;
  2628. var expandoStore = expandoId && jqCache[expandoId];
  2629. if (expandoStore) {
  2630. if (name) {
  2631. delete expandoStore.data[name];
  2632. return;
  2633. }
  2634. if (expandoStore.handle) {
  2635. if (expandoStore.events.$destroy) {
  2636. expandoStore.handle({}, '$destroy');
  2637. }
  2638. jqLiteOff(element);
  2639. }
  2640. delete jqCache[expandoId];
  2641. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2642. }
  2643. }
  2644. function jqLiteExpandoStore(element, createIfNecessary) {
  2645. var expandoId = element.ng339,
  2646. expandoStore = expandoId && jqCache[expandoId];
  2647. if (createIfNecessary && !expandoStore) {
  2648. element.ng339 = expandoId = jqNextId();
  2649. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2650. }
  2651. return expandoStore;
  2652. }
  2653. function jqLiteData(element, key, value) {
  2654. if (jqLiteAcceptsData(element)) {
  2655. var isSimpleSetter = isDefined(value);
  2656. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2657. var massGetter = !key;
  2658. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2659. var data = expandoStore && expandoStore.data;
  2660. if (isSimpleSetter) { // data('key', value)
  2661. data[key] = value;
  2662. } else {
  2663. if (massGetter) { // data()
  2664. return data;
  2665. } else {
  2666. if (isSimpleGetter) { // data('key')
  2667. // don't force creation of expandoStore if it doesn't exist yet
  2668. return data && data[key];
  2669. } else { // mass-setter: data({key1: val1, key2: val2})
  2670. extend(data, key);
  2671. }
  2672. }
  2673. }
  2674. }
  2675. }
  2676. function jqLiteHasClass(element, selector) {
  2677. if (!element.getAttribute) return false;
  2678. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2679. indexOf(" " + selector + " ") > -1);
  2680. }
  2681. function jqLiteRemoveClass(element, cssClasses) {
  2682. if (cssClasses && element.setAttribute) {
  2683. forEach(cssClasses.split(' '), function(cssClass) {
  2684. element.setAttribute('class', trim(
  2685. (" " + (element.getAttribute('class') || '') + " ")
  2686. .replace(/[\n\t]/g, " ")
  2687. .replace(" " + trim(cssClass) + " ", " "))
  2688. );
  2689. });
  2690. }
  2691. }
  2692. function jqLiteAddClass(element, cssClasses) {
  2693. if (cssClasses && element.setAttribute) {
  2694. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2695. .replace(/[\n\t]/g, " ");
  2696. forEach(cssClasses.split(' '), function(cssClass) {
  2697. cssClass = trim(cssClass);
  2698. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2699. existingClasses += cssClass + ' ';
  2700. }
  2701. });
  2702. element.setAttribute('class', trim(existingClasses));
  2703. }
  2704. }
  2705. function jqLiteAddNodes(root, elements) {
  2706. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2707. if (elements) {
  2708. // if a Node (the most common case)
  2709. if (elements.nodeType) {
  2710. root[root.length++] = elements;
  2711. } else {
  2712. var length = elements.length;
  2713. // if an Array or NodeList and not a Window
  2714. if (typeof length === 'number' && elements.window !== elements) {
  2715. if (length) {
  2716. for (var i = 0; i < length; i++) {
  2717. root[root.length++] = elements[i];
  2718. }
  2719. }
  2720. } else {
  2721. root[root.length++] = elements;
  2722. }
  2723. }
  2724. }
  2725. }
  2726. function jqLiteController(element, name) {
  2727. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  2728. }
  2729. function jqLiteInheritedData(element, name, value) {
  2730. // if element is the document object work with the html element instead
  2731. // this makes $(document).scope() possible
  2732. if (element.nodeType == NODE_TYPE_DOCUMENT) {
  2733. element = element.documentElement;
  2734. }
  2735. var names = isArray(name) ? name : [name];
  2736. while (element) {
  2737. for (var i = 0, ii = names.length; i < ii; i++) {
  2738. if (isDefined(value = jqLite.data(element, names[i]))) return value;
  2739. }
  2740. // If dealing with a document fragment node with a host element, and no parent, use the host
  2741. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2742. // to lookup parent controllers.
  2743. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  2744. }
  2745. }
  2746. function jqLiteEmpty(element) {
  2747. jqLiteDealoc(element, true);
  2748. while (element.firstChild) {
  2749. element.removeChild(element.firstChild);
  2750. }
  2751. }
  2752. function jqLiteRemove(element, keepData) {
  2753. if (!keepData) jqLiteDealoc(element);
  2754. var parent = element.parentNode;
  2755. if (parent) parent.removeChild(element);
  2756. }
  2757. function jqLiteDocumentLoaded(action, win) {
  2758. win = win || window;
  2759. if (win.document.readyState === 'complete') {
  2760. // Force the action to be run async for consistent behavior
  2761. // from the action's point of view
  2762. // i.e. it will definitely not be in a $apply
  2763. win.setTimeout(action);
  2764. } else {
  2765. // No need to unbind this handler as load is only ever called once
  2766. jqLite(win).on('load', action);
  2767. }
  2768. }
  2769. //////////////////////////////////////////
  2770. // Functions which are declared directly.
  2771. //////////////////////////////////////////
  2772. var JQLitePrototype = JQLite.prototype = {
  2773. ready: function(fn) {
  2774. var fired = false;
  2775. function trigger() {
  2776. if (fired) return;
  2777. fired = true;
  2778. fn();
  2779. }
  2780. // check if document is already loaded
  2781. if (document.readyState === 'complete') {
  2782. setTimeout(trigger);
  2783. } else {
  2784. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2785. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2786. // jshint -W064
  2787. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2788. // jshint +W064
  2789. }
  2790. },
  2791. toString: function() {
  2792. var value = [];
  2793. forEach(this, function(e) { value.push('' + e);});
  2794. return '[' + value.join(', ') + ']';
  2795. },
  2796. eq: function(index) {
  2797. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2798. },
  2799. length: 0,
  2800. push: push,
  2801. sort: [].sort,
  2802. splice: [].splice
  2803. };
  2804. //////////////////////////////////////////
  2805. // Functions iterating getter/setters.
  2806. // these functions return self on setter and
  2807. // value on get.
  2808. //////////////////////////////////////////
  2809. var BOOLEAN_ATTR = {};
  2810. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2811. BOOLEAN_ATTR[lowercase(value)] = value;
  2812. });
  2813. var BOOLEAN_ELEMENTS = {};
  2814. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2815. BOOLEAN_ELEMENTS[value] = true;
  2816. });
  2817. var ALIASED_ATTR = {
  2818. 'ngMinlength': 'minlength',
  2819. 'ngMaxlength': 'maxlength',
  2820. 'ngMin': 'min',
  2821. 'ngMax': 'max',
  2822. 'ngPattern': 'pattern'
  2823. };
  2824. function getBooleanAttrName(element, name) {
  2825. // check dom last since we will most likely fail on name
  2826. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2827. // booleanAttr is here twice to minimize DOM access
  2828. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  2829. }
  2830. function getAliasedAttrName(name) {
  2831. return ALIASED_ATTR[name];
  2832. }
  2833. forEach({
  2834. data: jqLiteData,
  2835. removeData: jqLiteRemoveData,
  2836. hasData: jqLiteHasData,
  2837. cleanData: jqLiteCleanData
  2838. }, function(fn, name) {
  2839. JQLite[name] = fn;
  2840. });
  2841. forEach({
  2842. data: jqLiteData,
  2843. inheritedData: jqLiteInheritedData,
  2844. scope: function(element) {
  2845. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2846. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2847. },
  2848. isolateScope: function(element) {
  2849. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2850. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  2851. },
  2852. controller: jqLiteController,
  2853. injector: function(element) {
  2854. return jqLiteInheritedData(element, '$injector');
  2855. },
  2856. removeAttr: function(element, name) {
  2857. element.removeAttribute(name);
  2858. },
  2859. hasClass: jqLiteHasClass,
  2860. css: function(element, name, value) {
  2861. name = camelCase(name);
  2862. if (isDefined(value)) {
  2863. element.style[name] = value;
  2864. } else {
  2865. return element.style[name];
  2866. }
  2867. },
  2868. attr: function(element, name, value) {
  2869. var nodeType = element.nodeType;
  2870. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
  2871. return;
  2872. }
  2873. var lowercasedName = lowercase(name);
  2874. if (BOOLEAN_ATTR[lowercasedName]) {
  2875. if (isDefined(value)) {
  2876. if (!!value) {
  2877. element[name] = true;
  2878. element.setAttribute(name, lowercasedName);
  2879. } else {
  2880. element[name] = false;
  2881. element.removeAttribute(lowercasedName);
  2882. }
  2883. } else {
  2884. return (element[name] ||
  2885. (element.attributes.getNamedItem(name) || noop).specified)
  2886. ? lowercasedName
  2887. : undefined;
  2888. }
  2889. } else if (isDefined(value)) {
  2890. element.setAttribute(name, value);
  2891. } else if (element.getAttribute) {
  2892. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2893. // some elements (e.g. Document) don't have get attribute, so return undefined
  2894. var ret = element.getAttribute(name, 2);
  2895. // normalize non-existing attributes to undefined (as jQuery)
  2896. return ret === null ? undefined : ret;
  2897. }
  2898. },
  2899. prop: function(element, name, value) {
  2900. if (isDefined(value)) {
  2901. element[name] = value;
  2902. } else {
  2903. return element[name];
  2904. }
  2905. },
  2906. text: (function() {
  2907. getText.$dv = '';
  2908. return getText;
  2909. function getText(element, value) {
  2910. if (isUndefined(value)) {
  2911. var nodeType = element.nodeType;
  2912. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  2913. }
  2914. element.textContent = value;
  2915. }
  2916. })(),
  2917. val: function(element, value) {
  2918. if (isUndefined(value)) {
  2919. if (element.multiple && nodeName_(element) === 'select') {
  2920. var result = [];
  2921. forEach(element.options, function(option) {
  2922. if (option.selected) {
  2923. result.push(option.value || option.text);
  2924. }
  2925. });
  2926. return result.length === 0 ? null : result;
  2927. }
  2928. return element.value;
  2929. }
  2930. element.value = value;
  2931. },
  2932. html: function(element, value) {
  2933. if (isUndefined(value)) {
  2934. return element.innerHTML;
  2935. }
  2936. jqLiteDealoc(element, true);
  2937. element.innerHTML = value;
  2938. },
  2939. empty: jqLiteEmpty
  2940. }, function(fn, name) {
  2941. /**
  2942. * Properties: writes return selection, reads return first value
  2943. */
  2944. JQLite.prototype[name] = function(arg1, arg2) {
  2945. var i, key;
  2946. var nodeCount = this.length;
  2947. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  2948. // in a way that survives minification.
  2949. // jqLiteEmpty takes no arguments but is a setter.
  2950. if (fn !== jqLiteEmpty &&
  2951. (isUndefined((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
  2952. if (isObject(arg1)) {
  2953. // we are a write, but the object properties are the key/values
  2954. for (i = 0; i < nodeCount; i++) {
  2955. if (fn === jqLiteData) {
  2956. // data() takes the whole object in jQuery
  2957. fn(this[i], arg1);
  2958. } else {
  2959. for (key in arg1) {
  2960. fn(this[i], key, arg1[key]);
  2961. }
  2962. }
  2963. }
  2964. // return self for chaining
  2965. return this;
  2966. } else {
  2967. // we are a read, so read the first child.
  2968. // TODO: do we still need this?
  2969. var value = fn.$dv;
  2970. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  2971. var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
  2972. for (var j = 0; j < jj; j++) {
  2973. var nodeValue = fn(this[j], arg1, arg2);
  2974. value = value ? value + nodeValue : nodeValue;
  2975. }
  2976. return value;
  2977. }
  2978. } else {
  2979. // we are a write, so apply to all children
  2980. for (i = 0; i < nodeCount; i++) {
  2981. fn(this[i], arg1, arg2);
  2982. }
  2983. // return self for chaining
  2984. return this;
  2985. }
  2986. };
  2987. });
  2988. function createEventHandler(element, events) {
  2989. var eventHandler = function(event, type) {
  2990. // jQuery specific api
  2991. event.isDefaultPrevented = function() {
  2992. return event.defaultPrevented;
  2993. };
  2994. var eventFns = events[type || event.type];
  2995. var eventFnsLength = eventFns ? eventFns.length : 0;
  2996. if (!eventFnsLength) return;
  2997. if (isUndefined(event.immediatePropagationStopped)) {
  2998. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  2999. event.stopImmediatePropagation = function() {
  3000. event.immediatePropagationStopped = true;
  3001. if (event.stopPropagation) {
  3002. event.stopPropagation();
  3003. }
  3004. if (originalStopImmediatePropagation) {
  3005. originalStopImmediatePropagation.call(event);
  3006. }
  3007. };
  3008. }
  3009. event.isImmediatePropagationStopped = function() {
  3010. return event.immediatePropagationStopped === true;
  3011. };
  3012. // Some events have special handlers that wrap the real handler
  3013. var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
  3014. // Copy event handlers in case event handlers array is modified during execution.
  3015. if ((eventFnsLength > 1)) {
  3016. eventFns = shallowCopy(eventFns);
  3017. }
  3018. for (var i = 0; i < eventFnsLength; i++) {
  3019. if (!event.isImmediatePropagationStopped()) {
  3020. handlerWrapper(element, event, eventFns[i]);
  3021. }
  3022. }
  3023. };
  3024. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  3025. // events on `element`
  3026. eventHandler.elem = element;
  3027. return eventHandler;
  3028. }
  3029. function defaultHandlerWrapper(element, event, handler) {
  3030. handler.call(element, event);
  3031. }
  3032. function specialMouseHandlerWrapper(target, event, handler) {
  3033. // Refer to jQuery's implementation of mouseenter & mouseleave
  3034. // Read about mouseenter and mouseleave:
  3035. // http://www.quirksmode.org/js/events_mouse.html#link8
  3036. var related = event.relatedTarget;
  3037. // For mousenter/leave call the handler if related is outside the target.
  3038. // NB: No relatedTarget if the mouse left/entered the browser window
  3039. if (!related || (related !== target && !jqLiteContains.call(target, related))) {
  3040. handler.call(target, event);
  3041. }
  3042. }
  3043. //////////////////////////////////////////
  3044. // Functions iterating traversal.
  3045. // These functions chain results into a single
  3046. // selector.
  3047. //////////////////////////////////////////
  3048. forEach({
  3049. removeData: jqLiteRemoveData,
  3050. on: function jqLiteOn(element, type, fn, unsupported) {
  3051. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  3052. // Do not add event handlers to non-elements because they will not be cleaned up.
  3053. if (!jqLiteAcceptsData(element)) {
  3054. return;
  3055. }
  3056. var expandoStore = jqLiteExpandoStore(element, true);
  3057. var events = expandoStore.events;
  3058. var handle = expandoStore.handle;
  3059. if (!handle) {
  3060. handle = expandoStore.handle = createEventHandler(element, events);
  3061. }
  3062. // http://jsperf.com/string-indexof-vs-split
  3063. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  3064. var i = types.length;
  3065. var addHandler = function(type, specialHandlerWrapper, noEventListener) {
  3066. var eventFns = events[type];
  3067. if (!eventFns) {
  3068. eventFns = events[type] = [];
  3069. eventFns.specialHandlerWrapper = specialHandlerWrapper;
  3070. if (type !== '$destroy' && !noEventListener) {
  3071. addEventListenerFn(element, type, handle);
  3072. }
  3073. }
  3074. eventFns.push(fn);
  3075. };
  3076. while (i--) {
  3077. type = types[i];
  3078. if (MOUSE_EVENT_MAP[type]) {
  3079. addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
  3080. addHandler(type, undefined, true);
  3081. } else {
  3082. addHandler(type);
  3083. }
  3084. }
  3085. },
  3086. off: jqLiteOff,
  3087. one: function(element, type, fn) {
  3088. element = jqLite(element);
  3089. //add the listener twice so that when it is called
  3090. //you can remove the original function and still be
  3091. //able to call element.off(ev, fn) normally
  3092. element.on(type, function onFn() {
  3093. element.off(type, fn);
  3094. element.off(type, onFn);
  3095. });
  3096. element.on(type, fn);
  3097. },
  3098. replaceWith: function(element, replaceNode) {
  3099. var index, parent = element.parentNode;
  3100. jqLiteDealoc(element);
  3101. forEach(new JQLite(replaceNode), function(node) {
  3102. if (index) {
  3103. parent.insertBefore(node, index.nextSibling);
  3104. } else {
  3105. parent.replaceChild(node, element);
  3106. }
  3107. index = node;
  3108. });
  3109. },
  3110. children: function(element) {
  3111. var children = [];
  3112. forEach(element.childNodes, function(element) {
  3113. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3114. children.push(element);
  3115. }
  3116. });
  3117. return children;
  3118. },
  3119. contents: function(element) {
  3120. return element.contentDocument || element.childNodes || [];
  3121. },
  3122. append: function(element, node) {
  3123. var nodeType = element.nodeType;
  3124. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  3125. node = new JQLite(node);
  3126. for (var i = 0, ii = node.length; i < ii; i++) {
  3127. var child = node[i];
  3128. element.appendChild(child);
  3129. }
  3130. },
  3131. prepend: function(element, node) {
  3132. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3133. var index = element.firstChild;
  3134. forEach(new JQLite(node), function(child) {
  3135. element.insertBefore(child, index);
  3136. });
  3137. }
  3138. },
  3139. wrap: function(element, wrapNode) {
  3140. jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);
  3141. },
  3142. remove: jqLiteRemove,
  3143. detach: function(element) {
  3144. jqLiteRemove(element, true);
  3145. },
  3146. after: function(element, newElement) {
  3147. var index = element, parent = element.parentNode;
  3148. newElement = new JQLite(newElement);
  3149. for (var i = 0, ii = newElement.length; i < ii; i++) {
  3150. var node = newElement[i];
  3151. parent.insertBefore(node, index.nextSibling);
  3152. index = node;
  3153. }
  3154. },
  3155. addClass: jqLiteAddClass,
  3156. removeClass: jqLiteRemoveClass,
  3157. toggleClass: function(element, selector, condition) {
  3158. if (selector) {
  3159. forEach(selector.split(' '), function(className) {
  3160. var classCondition = condition;
  3161. if (isUndefined(classCondition)) {
  3162. classCondition = !jqLiteHasClass(element, className);
  3163. }
  3164. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  3165. });
  3166. }
  3167. },
  3168. parent: function(element) {
  3169. var parent = element.parentNode;
  3170. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  3171. },
  3172. next: function(element) {
  3173. return element.nextElementSibling;
  3174. },
  3175. find: function(element, selector) {
  3176. if (element.getElementsByTagName) {
  3177. return element.getElementsByTagName(selector);
  3178. } else {
  3179. return [];
  3180. }
  3181. },
  3182. clone: jqLiteClone,
  3183. triggerHandler: function(element, event, extraParameters) {
  3184. var dummyEvent, eventFnsCopy, handlerArgs;
  3185. var eventName = event.type || event;
  3186. var expandoStore = jqLiteExpandoStore(element);
  3187. var events = expandoStore && expandoStore.events;
  3188. var eventFns = events && events[eventName];
  3189. if (eventFns) {
  3190. // Create a dummy event to pass to the handlers
  3191. dummyEvent = {
  3192. preventDefault: function() { this.defaultPrevented = true; },
  3193. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  3194. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  3195. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  3196. stopPropagation: noop,
  3197. type: eventName,
  3198. target: element
  3199. };
  3200. // If a custom event was provided then extend our dummy event with it
  3201. if (event.type) {
  3202. dummyEvent = extend(dummyEvent, event);
  3203. }
  3204. // Copy event handlers in case event handlers array is modified during execution.
  3205. eventFnsCopy = shallowCopy(eventFns);
  3206. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  3207. forEach(eventFnsCopy, function(fn) {
  3208. if (!dummyEvent.isImmediatePropagationStopped()) {
  3209. fn.apply(element, handlerArgs);
  3210. }
  3211. });
  3212. }
  3213. }
  3214. }, function(fn, name) {
  3215. /**
  3216. * chaining functions
  3217. */
  3218. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  3219. var value;
  3220. for (var i = 0, ii = this.length; i < ii; i++) {
  3221. if (isUndefined(value)) {
  3222. value = fn(this[i], arg1, arg2, arg3);
  3223. if (isDefined(value)) {
  3224. // any function which returns a value needs to be wrapped
  3225. value = jqLite(value);
  3226. }
  3227. } else {
  3228. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  3229. }
  3230. }
  3231. return isDefined(value) ? value : this;
  3232. };
  3233. // bind legacy bind/unbind to on/off
  3234. JQLite.prototype.bind = JQLite.prototype.on;
  3235. JQLite.prototype.unbind = JQLite.prototype.off;
  3236. });
  3237. // Provider for private $$jqLite service
  3238. function $$jqLiteProvider() {
  3239. this.$get = function $$jqLite() {
  3240. return extend(JQLite, {
  3241. hasClass: function(node, classes) {
  3242. if (node.attr) node = node[0];
  3243. return jqLiteHasClass(node, classes);
  3244. },
  3245. addClass: function(node, classes) {
  3246. if (node.attr) node = node[0];
  3247. return jqLiteAddClass(node, classes);
  3248. },
  3249. removeClass: function(node, classes) {
  3250. if (node.attr) node = node[0];
  3251. return jqLiteRemoveClass(node, classes);
  3252. }
  3253. });
  3254. };
  3255. }
  3256. /**
  3257. * Computes a hash of an 'obj'.
  3258. * Hash of a:
  3259. * string is string
  3260. * number is number as string
  3261. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  3262. * that is also assigned to the $$hashKey property of the object.
  3263. *
  3264. * @param obj
  3265. * @returns {string} hash string such that the same input will have the same hash string.
  3266. * The resulting string key is in 'type:hashKey' format.
  3267. */
  3268. function hashKey(obj, nextUidFn) {
  3269. var key = obj && obj.$$hashKey;
  3270. if (key) {
  3271. if (typeof key === 'function') {
  3272. key = obj.$$hashKey();
  3273. }
  3274. return key;
  3275. }
  3276. var objType = typeof obj;
  3277. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  3278. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  3279. } else {
  3280. key = objType + ':' + obj;
  3281. }
  3282. return key;
  3283. }
  3284. /**
  3285. * HashMap which can use objects as keys
  3286. */
  3287. function HashMap(array, isolatedUid) {
  3288. if (isolatedUid) {
  3289. var uid = 0;
  3290. this.nextUid = function() {
  3291. return ++uid;
  3292. };
  3293. }
  3294. forEach(array, this.put, this);
  3295. }
  3296. HashMap.prototype = {
  3297. /**
  3298. * Store key value pair
  3299. * @param key key to store can be any type
  3300. * @param value value to store can be any type
  3301. */
  3302. put: function(key, value) {
  3303. this[hashKey(key, this.nextUid)] = value;
  3304. },
  3305. /**
  3306. * @param key
  3307. * @returns {Object} the value for the key
  3308. */
  3309. get: function(key) {
  3310. return this[hashKey(key, this.nextUid)];
  3311. },
  3312. /**
  3313. * Remove the key/value pair
  3314. * @param key
  3315. */
  3316. remove: function(key) {
  3317. var value = this[key = hashKey(key, this.nextUid)];
  3318. delete this[key];
  3319. return value;
  3320. }
  3321. };
  3322. var $$HashMapProvider = [function() {
  3323. this.$get = [function() {
  3324. return HashMap;
  3325. }];
  3326. }];
  3327. /**
  3328. * @ngdoc function
  3329. * @module ng
  3330. * @name angular.injector
  3331. * @kind function
  3332. *
  3333. * @description
  3334. * Creates an injector object that can be used for retrieving services as well as for
  3335. * dependency injection (see {@link guide/di dependency injection}).
  3336. *
  3337. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3338. * {@link angular.module}. The `ng` module must be explicitly added.
  3339. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3340. * disallows argument name annotation inference.
  3341. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3342. *
  3343. * @example
  3344. * Typical usage
  3345. * ```js
  3346. * // create an injector
  3347. * var $injector = angular.injector(['ng']);
  3348. *
  3349. * // use the injector to kick off your application
  3350. * // use the type inference to auto inject arguments, or use implicit injection
  3351. * $injector.invoke(function($rootScope, $compile, $document) {
  3352. * $compile($document)($rootScope);
  3353. * $rootScope.$digest();
  3354. * });
  3355. * ```
  3356. *
  3357. * Sometimes you want to get access to the injector of a currently running Angular app
  3358. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  3359. * application has been bootstrapped. You can do this using the extra `injector()` added
  3360. * to JQuery/jqLite elements. See {@link angular.element}.
  3361. *
  3362. * *This is fairly rare but could be the case if a third party library is injecting the
  3363. * markup.*
  3364. *
  3365. * In the following example a new block of HTML containing a `ng-controller`
  3366. * directive is added to the end of the document body by JQuery. We then compile and link
  3367. * it into the current AngularJS scope.
  3368. *
  3369. * ```js
  3370. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3371. * $(document.body).append($div);
  3372. *
  3373. * angular.element(document).injector().invoke(function($compile) {
  3374. * var scope = angular.element($div).scope();
  3375. * $compile($div)(scope);
  3376. * });
  3377. * ```
  3378. */
  3379. /**
  3380. * @ngdoc module
  3381. * @name auto
  3382. * @description
  3383. *
  3384. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3385. */
  3386. var ARROW_ARG = /^([^\(]+?)=>/;
  3387. var FN_ARGS = /^[^\(]*\(\s*([^\)]*)\)/m;
  3388. var FN_ARG_SPLIT = /,/;
  3389. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3390. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3391. var $injectorMinErr = minErr('$injector');
  3392. function extractArgs(fn) {
  3393. var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
  3394. args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
  3395. return args;
  3396. }
  3397. function anonFn(fn) {
  3398. // For anonymous functions, showing at the very least the function signature can help in
  3399. // debugging.
  3400. var args = extractArgs(fn);
  3401. if (args) {
  3402. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3403. }
  3404. return 'fn';
  3405. }
  3406. function annotate(fn, strictDi, name) {
  3407. var $inject,
  3408. argDecl,
  3409. last;
  3410. if (typeof fn === 'function') {
  3411. if (!($inject = fn.$inject)) {
  3412. $inject = [];
  3413. if (fn.length) {
  3414. if (strictDi) {
  3415. if (!isString(name) || !name) {
  3416. name = fn.name || anonFn(fn);
  3417. }
  3418. throw $injectorMinErr('strictdi',
  3419. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3420. }
  3421. argDecl = extractArgs(fn);
  3422. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3423. arg.replace(FN_ARG, function(all, underscore, name) {
  3424. $inject.push(name);
  3425. });
  3426. });
  3427. }
  3428. fn.$inject = $inject;
  3429. }
  3430. } else if (isArray(fn)) {
  3431. last = fn.length - 1;
  3432. assertArgFn(fn[last], 'fn');
  3433. $inject = fn.slice(0, last);
  3434. } else {
  3435. assertArgFn(fn, 'fn', true);
  3436. }
  3437. return $inject;
  3438. }
  3439. ///////////////////////////////////////
  3440. /**
  3441. * @ngdoc service
  3442. * @name $injector
  3443. *
  3444. * @description
  3445. *
  3446. * `$injector` is used to retrieve object instances as defined by
  3447. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3448. * and load modules.
  3449. *
  3450. * The following always holds true:
  3451. *
  3452. * ```js
  3453. * var $injector = angular.injector();
  3454. * expect($injector.get('$injector')).toBe($injector);
  3455. * expect($injector.invoke(function($injector) {
  3456. * return $injector;
  3457. * })).toBe($injector);
  3458. * ```
  3459. *
  3460. * # Injection Function Annotation
  3461. *
  3462. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3463. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3464. *
  3465. * ```js
  3466. * // inferred (only works if code not minified/obfuscated)
  3467. * $injector.invoke(function(serviceA){});
  3468. *
  3469. * // annotated
  3470. * function explicit(serviceA) {};
  3471. * explicit.$inject = ['serviceA'];
  3472. * $injector.invoke(explicit);
  3473. *
  3474. * // inline
  3475. * $injector.invoke(['serviceA', function(serviceA){}]);
  3476. * ```
  3477. *
  3478. * ## Inference
  3479. *
  3480. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3481. * can then be parsed and the function arguments can be extracted. This method of discovering
  3482. * annotations is disallowed when the injector is in strict mode.
  3483. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3484. * argument names.
  3485. *
  3486. * ## `$inject` Annotation
  3487. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3488. *
  3489. * ## Inline
  3490. * As an array of injection names, where the last item in the array is the function to call.
  3491. */
  3492. /**
  3493. * @ngdoc method
  3494. * @name $injector#get
  3495. *
  3496. * @description
  3497. * Return an instance of the service.
  3498. *
  3499. * @param {string} name The name of the instance to retrieve.
  3500. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  3501. * @return {*} The instance.
  3502. */
  3503. /**
  3504. * @ngdoc method
  3505. * @name $injector#invoke
  3506. *
  3507. * @description
  3508. * Invoke the method and supply the method arguments from the `$injector`.
  3509. *
  3510. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  3511. * injected according to the {@link guide/di $inject Annotation} rules.
  3512. * @param {Object=} self The `this` for the invoked method.
  3513. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3514. * object first, before the `$injector` is consulted.
  3515. * @returns {*} the value returned by the invoked `fn` function.
  3516. */
  3517. /**
  3518. * @ngdoc method
  3519. * @name $injector#has
  3520. *
  3521. * @description
  3522. * Allows the user to query if the particular service exists.
  3523. *
  3524. * @param {string} name Name of the service to query.
  3525. * @returns {boolean} `true` if injector has given service.
  3526. */
  3527. /**
  3528. * @ngdoc method
  3529. * @name $injector#instantiate
  3530. * @description
  3531. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3532. * operator, and supplies all of the arguments to the constructor function as specified by the
  3533. * constructor annotation.
  3534. *
  3535. * @param {Function} Type Annotated constructor function.
  3536. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3537. * object first, before the `$injector` is consulted.
  3538. * @returns {Object} new instance of `Type`.
  3539. */
  3540. /**
  3541. * @ngdoc method
  3542. * @name $injector#annotate
  3543. *
  3544. * @description
  3545. * Returns an array of service names which the function is requesting for injection. This API is
  3546. * used by the injector to determine which services need to be injected into the function when the
  3547. * function is invoked. There are three ways in which the function can be annotated with the needed
  3548. * dependencies.
  3549. *
  3550. * # Argument names
  3551. *
  3552. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3553. * by converting the function into a string using `toString()` method and extracting the argument
  3554. * names.
  3555. * ```js
  3556. * // Given
  3557. * function MyController($scope, $route) {
  3558. * // ...
  3559. * }
  3560. *
  3561. * // Then
  3562. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3563. * ```
  3564. *
  3565. * You can disallow this method by using strict injection mode.
  3566. *
  3567. * This method does not work with code minification / obfuscation. For this reason the following
  3568. * annotation strategies are supported.
  3569. *
  3570. * # The `$inject` property
  3571. *
  3572. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3573. * represent names of services to be injected into the function.
  3574. * ```js
  3575. * // Given
  3576. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3577. * // ...
  3578. * }
  3579. * // Define function dependencies
  3580. * MyController['$inject'] = ['$scope', '$route'];
  3581. *
  3582. * // Then
  3583. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3584. * ```
  3585. *
  3586. * # The array notation
  3587. *
  3588. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3589. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3590. * a way that survives minification is a better choice:
  3591. *
  3592. * ```js
  3593. * // We wish to write this (not minification / obfuscation safe)
  3594. * injector.invoke(function($compile, $rootScope) {
  3595. * // ...
  3596. * });
  3597. *
  3598. * // We are forced to write break inlining
  3599. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3600. * // ...
  3601. * };
  3602. * tmpFn.$inject = ['$compile', '$rootScope'];
  3603. * injector.invoke(tmpFn);
  3604. *
  3605. * // To better support inline function the inline annotation is supported
  3606. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3607. * // ...
  3608. * }]);
  3609. *
  3610. * // Therefore
  3611. * expect(injector.annotate(
  3612. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3613. * ).toEqual(['$compile', '$rootScope']);
  3614. * ```
  3615. *
  3616. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3617. * be retrieved as described above.
  3618. *
  3619. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3620. *
  3621. * @returns {Array.<string>} The names of the services which the function requires.
  3622. */
  3623. /**
  3624. * @ngdoc service
  3625. * @name $provide
  3626. *
  3627. * @description
  3628. *
  3629. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3630. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3631. * {@link angular.Module}.
  3632. *
  3633. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3634. * factories** are functions which, in turn, are created by a **service provider**.
  3635. * The **service providers** are constructor functions. When instantiated they must contain a
  3636. * property called `$get`, which holds the **service factory** function.
  3637. *
  3638. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3639. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3640. * function to get the instance of the **service**.
  3641. *
  3642. * Often services have no configuration options and there is no need to add methods to the service
  3643. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3644. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3645. * services without specifying a provider.
  3646. *
  3647. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  3648. * {@link auto.$injector $injector}
  3649. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  3650. * providers and services.
  3651. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  3652. * services, not providers.
  3653. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  3654. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3655. * given factory function.
  3656. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  3657. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3658. * a new object using the given constructor function.
  3659. *
  3660. * See the individual methods for more information and examples.
  3661. */
  3662. /**
  3663. * @ngdoc method
  3664. * @name $provide#provider
  3665. * @description
  3666. *
  3667. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3668. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3669. * service.
  3670. *
  3671. * Service provider names start with the name of the service they provide followed by `Provider`.
  3672. * For example, the {@link ng.$log $log} service has a provider called
  3673. * {@link ng.$logProvider $logProvider}.
  3674. *
  3675. * Service provider objects can have additional methods which allow configuration of the provider
  3676. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3677. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3678. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3679. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3680. * console or not.
  3681. *
  3682. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3683. 'Provider'` key.
  3684. * @param {(Object|function())} provider If the provider is:
  3685. *
  3686. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3687. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3688. * - `Constructor`: a new instance of the provider will be created using
  3689. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3690. *
  3691. * @returns {Object} registered provider instance
  3692. * @example
  3693. *
  3694. * The following example shows how to create a simple event tracking service and register it using
  3695. * {@link auto.$provide#provider $provide.provider()}.
  3696. *
  3697. * ```js
  3698. * // Define the eventTracker provider
  3699. * function EventTrackerProvider() {
  3700. * var trackingUrl = '/track';
  3701. *
  3702. * // A provider method for configuring where the tracked events should been saved
  3703. * this.setTrackingUrl = function(url) {
  3704. * trackingUrl = url;
  3705. * };
  3706. *
  3707. * // The service factory function
  3708. * this.$get = ['$http', function($http) {
  3709. * var trackedEvents = {};
  3710. * return {
  3711. * // Call this to track an event
  3712. * event: function(event) {
  3713. * var count = trackedEvents[event] || 0;
  3714. * count += 1;
  3715. * trackedEvents[event] = count;
  3716. * return count;
  3717. * },
  3718. * // Call this to save the tracked events to the trackingUrl
  3719. * save: function() {
  3720. * $http.post(trackingUrl, trackedEvents);
  3721. * }
  3722. * };
  3723. * }];
  3724. * }
  3725. *
  3726. * describe('eventTracker', function() {
  3727. * var postSpy;
  3728. *
  3729. * beforeEach(module(function($provide) {
  3730. * // Register the eventTracker provider
  3731. * $provide.provider('eventTracker', EventTrackerProvider);
  3732. * }));
  3733. *
  3734. * beforeEach(module(function(eventTrackerProvider) {
  3735. * // Configure eventTracker provider
  3736. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3737. * }));
  3738. *
  3739. * it('tracks events', inject(function(eventTracker) {
  3740. * expect(eventTracker.event('login')).toEqual(1);
  3741. * expect(eventTracker.event('login')).toEqual(2);
  3742. * }));
  3743. *
  3744. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3745. * postSpy = spyOn($http, 'post');
  3746. * eventTracker.event('login');
  3747. * eventTracker.save();
  3748. * expect(postSpy).toHaveBeenCalled();
  3749. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3750. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3751. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3752. * }));
  3753. * });
  3754. * ```
  3755. */
  3756. /**
  3757. * @ngdoc method
  3758. * @name $provide#factory
  3759. * @description
  3760. *
  3761. * Register a **service factory**, which will be called to return the service instance.
  3762. * This is short for registering a service where its provider consists of only a `$get` property,
  3763. * which is the given service factory function.
  3764. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3765. * configure your service in a provider.
  3766. *
  3767. * @param {string} name The name of the instance.
  3768. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  3769. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  3770. * @returns {Object} registered provider instance
  3771. *
  3772. * @example
  3773. * Here is an example of registering a service
  3774. * ```js
  3775. * $provide.factory('ping', ['$http', function($http) {
  3776. * return function ping() {
  3777. * return $http.send('/ping');
  3778. * };
  3779. * }]);
  3780. * ```
  3781. * You would then inject and use this service like this:
  3782. * ```js
  3783. * someModule.controller('Ctrl', ['ping', function(ping) {
  3784. * ping();
  3785. * }]);
  3786. * ```
  3787. */
  3788. /**
  3789. * @ngdoc method
  3790. * @name $provide#service
  3791. * @description
  3792. *
  3793. * Register a **service constructor**, which will be invoked with `new` to create the service
  3794. * instance.
  3795. * This is short for registering a service where its provider's `$get` property is a factory
  3796. * function that returns an instance instantiated by the injector from the service constructor
  3797. * function.
  3798. *
  3799. * Internally it looks a bit like this:
  3800. *
  3801. * ```
  3802. * {
  3803. * $get: function() {
  3804. * return $injector.instantiate(constructor);
  3805. * }
  3806. * }
  3807. * ```
  3808. *
  3809. *
  3810. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3811. * as a type/class.
  3812. *
  3813. * @param {string} name The name of the instance.
  3814. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  3815. * that will be instantiated.
  3816. * @returns {Object} registered provider instance
  3817. *
  3818. * @example
  3819. * Here is an example of registering a service using
  3820. * {@link auto.$provide#service $provide.service(class)}.
  3821. * ```js
  3822. * var Ping = function($http) {
  3823. * this.$http = $http;
  3824. * };
  3825. *
  3826. * Ping.$inject = ['$http'];
  3827. *
  3828. * Ping.prototype.send = function() {
  3829. * return this.$http.get('/ping');
  3830. * };
  3831. * $provide.service('ping', Ping);
  3832. * ```
  3833. * You would then inject and use this service like this:
  3834. * ```js
  3835. * someModule.controller('Ctrl', ['ping', function(ping) {
  3836. * ping.send();
  3837. * }]);
  3838. * ```
  3839. */
  3840. /**
  3841. * @ngdoc method
  3842. * @name $provide#value
  3843. * @description
  3844. *
  3845. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3846. * number, an array, an object or a function. This is short for registering a service where its
  3847. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3848. * service**. That also means it is not possible to inject other services into a value service.
  3849. *
  3850. * Value services are similar to constant services, except that they cannot be injected into a
  3851. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3852. * an Angular {@link auto.$provide#decorator decorator}.
  3853. *
  3854. * @param {string} name The name of the instance.
  3855. * @param {*} value The value.
  3856. * @returns {Object} registered provider instance
  3857. *
  3858. * @example
  3859. * Here are some examples of creating value services.
  3860. * ```js
  3861. * $provide.value('ADMIN_USER', 'admin');
  3862. *
  3863. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3864. *
  3865. * $provide.value('halfOf', function(value) {
  3866. * return value / 2;
  3867. * });
  3868. * ```
  3869. */
  3870. /**
  3871. * @ngdoc method
  3872. * @name $provide#constant
  3873. * @description
  3874. *
  3875. * Register a **constant service** with the {@link auto.$injector $injector}, such as a string,
  3876. * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not
  3877. * possible to inject other services into a constant.
  3878. *
  3879. * But unlike {@link auto.$provide#value value}, a constant can be
  3880. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3881. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3882. *
  3883. * @param {string} name The name of the constant.
  3884. * @param {*} value The constant value.
  3885. * @returns {Object} registered instance
  3886. *
  3887. * @example
  3888. * Here a some examples of creating constants:
  3889. * ```js
  3890. * $provide.constant('SHARD_HEIGHT', 306);
  3891. *
  3892. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3893. *
  3894. * $provide.constant('double', function(value) {
  3895. * return value * 2;
  3896. * });
  3897. * ```
  3898. */
  3899. /**
  3900. * @ngdoc method
  3901. * @name $provide#decorator
  3902. * @description
  3903. *
  3904. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  3905. * intercepts the creation of a service, allowing it to override or modify the behavior of the
  3906. * service. The object returned by the decorator may be the original service, or a new service
  3907. * object which replaces or wraps and delegates to the original service.
  3908. *
  3909. * @param {string} name The name of the service to decorate.
  3910. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  3911. * instantiated and should return the decorated service instance. The function is called using
  3912. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3913. * Local injection arguments:
  3914. *
  3915. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3916. * decorated or delegated to.
  3917. *
  3918. * @example
  3919. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3920. * calls to {@link ng.$log#error $log.warn()}.
  3921. * ```js
  3922. * $provide.decorator('$log', ['$delegate', function($delegate) {
  3923. * $delegate.warn = $delegate.error;
  3924. * return $delegate;
  3925. * }]);
  3926. * ```
  3927. */
  3928. function createInjector(modulesToLoad, strictDi) {
  3929. strictDi = (strictDi === true);
  3930. var INSTANTIATING = {},
  3931. providerSuffix = 'Provider',
  3932. path = [],
  3933. loadedModules = new HashMap([], true),
  3934. providerCache = {
  3935. $provide: {
  3936. provider: supportObject(provider),
  3937. factory: supportObject(factory),
  3938. service: supportObject(service),
  3939. value: supportObject(value),
  3940. constant: supportObject(constant),
  3941. decorator: decorator
  3942. }
  3943. },
  3944. providerInjector = (providerCache.$injector =
  3945. createInternalInjector(providerCache, function(serviceName, caller) {
  3946. if (angular.isString(caller)) {
  3947. path.push(caller);
  3948. }
  3949. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  3950. })),
  3951. instanceCache = {},
  3952. protoInstanceInjector =
  3953. createInternalInjector(instanceCache, function(serviceName, caller) {
  3954. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  3955. return instanceInjector.invoke(
  3956. provider.$get, provider, undefined, serviceName);
  3957. }),
  3958. instanceInjector = protoInstanceInjector;
  3959. providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
  3960. var runBlocks = loadModules(modulesToLoad);
  3961. instanceInjector = protoInstanceInjector.get('$injector');
  3962. instanceInjector.strictDi = strictDi;
  3963. forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
  3964. return instanceInjector;
  3965. ////////////////////////////////////
  3966. // $provider
  3967. ////////////////////////////////////
  3968. function supportObject(delegate) {
  3969. return function(key, value) {
  3970. if (isObject(key)) {
  3971. forEach(key, reverseParams(delegate));
  3972. } else {
  3973. return delegate(key, value);
  3974. }
  3975. };
  3976. }
  3977. function provider(name, provider_) {
  3978. assertNotHasOwnProperty(name, 'service');
  3979. if (isFunction(provider_) || isArray(provider_)) {
  3980. provider_ = providerInjector.instantiate(provider_);
  3981. }
  3982. if (!provider_.$get) {
  3983. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  3984. }
  3985. return providerCache[name + providerSuffix] = provider_;
  3986. }
  3987. function enforceReturnValue(name, factory) {
  3988. return function enforcedReturnValue() {
  3989. var result = instanceInjector.invoke(factory, this);
  3990. if (isUndefined(result)) {
  3991. throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
  3992. }
  3993. return result;
  3994. };
  3995. }
  3996. function factory(name, factoryFn, enforce) {
  3997. return provider(name, {
  3998. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  3999. });
  4000. }
  4001. function service(name, constructor) {
  4002. return factory(name, ['$injector', function($injector) {
  4003. return $injector.instantiate(constructor);
  4004. }]);
  4005. }
  4006. function value(name, val) { return factory(name, valueFn(val), false); }
  4007. function constant(name, value) {
  4008. assertNotHasOwnProperty(name, 'constant');
  4009. providerCache[name] = value;
  4010. instanceCache[name] = value;
  4011. }
  4012. function decorator(serviceName, decorFn) {
  4013. var origProvider = providerInjector.get(serviceName + providerSuffix),
  4014. orig$get = origProvider.$get;
  4015. origProvider.$get = function() {
  4016. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  4017. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  4018. };
  4019. }
  4020. ////////////////////////////////////
  4021. // Module Loading
  4022. ////////////////////////////////////
  4023. function loadModules(modulesToLoad) {
  4024. assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
  4025. var runBlocks = [], moduleFn;
  4026. forEach(modulesToLoad, function(module) {
  4027. if (loadedModules.get(module)) return;
  4028. loadedModules.put(module, true);
  4029. function runInvokeQueue(queue) {
  4030. var i, ii;
  4031. for (i = 0, ii = queue.length; i < ii; i++) {
  4032. var invokeArgs = queue[i],
  4033. provider = providerInjector.get(invokeArgs[0]);
  4034. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  4035. }
  4036. }
  4037. try {
  4038. if (isString(module)) {
  4039. moduleFn = angularModule(module);
  4040. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  4041. runInvokeQueue(moduleFn._invokeQueue);
  4042. runInvokeQueue(moduleFn._configBlocks);
  4043. } else if (isFunction(module)) {
  4044. runBlocks.push(providerInjector.invoke(module));
  4045. } else if (isArray(module)) {
  4046. runBlocks.push(providerInjector.invoke(module));
  4047. } else {
  4048. assertArgFn(module, 'module');
  4049. }
  4050. } catch (e) {
  4051. if (isArray(module)) {
  4052. module = module[module.length - 1];
  4053. }
  4054. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  4055. // Safari & FF's stack traces don't contain error.message content
  4056. // unlike those of Chrome and IE
  4057. // So if stack doesn't contain message, we create a new string that contains both.
  4058. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  4059. /* jshint -W022 */
  4060. e = e.message + '\n' + e.stack;
  4061. }
  4062. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  4063. module, e.stack || e.message || e);
  4064. }
  4065. });
  4066. return runBlocks;
  4067. }
  4068. ////////////////////////////////////
  4069. // internal Injector
  4070. ////////////////////////////////////
  4071. function createInternalInjector(cache, factory) {
  4072. function getService(serviceName, caller) {
  4073. if (cache.hasOwnProperty(serviceName)) {
  4074. if (cache[serviceName] === INSTANTIATING) {
  4075. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  4076. serviceName + ' <- ' + path.join(' <- '));
  4077. }
  4078. return cache[serviceName];
  4079. } else {
  4080. try {
  4081. path.unshift(serviceName);
  4082. cache[serviceName] = INSTANTIATING;
  4083. return cache[serviceName] = factory(serviceName, caller);
  4084. } catch (err) {
  4085. if (cache[serviceName] === INSTANTIATING) {
  4086. delete cache[serviceName];
  4087. }
  4088. throw err;
  4089. } finally {
  4090. path.shift();
  4091. }
  4092. }
  4093. }
  4094. function injectionArgs(fn, locals, serviceName) {
  4095. var args = [],
  4096. $inject = createInjector.$$annotate(fn, strictDi, serviceName);
  4097. for (var i = 0, length = $inject.length; i < length; i++) {
  4098. var key = $inject[i];
  4099. if (typeof key !== 'string') {
  4100. throw $injectorMinErr('itkn',
  4101. 'Incorrect injection token! Expected service name as string, got {0}', key);
  4102. }
  4103. args.push(locals && locals.hasOwnProperty(key) ? locals[key] :
  4104. getService(key, serviceName));
  4105. }
  4106. return args;
  4107. }
  4108. function isClass(func) {
  4109. // IE 9-11 do not support classes and IE9 leaks with the code below.
  4110. if (msie <= 11) {
  4111. return false;
  4112. }
  4113. // Workaround for MS Edge.
  4114. // Check https://connect.microsoft.com/IE/Feedback/Details/2211653
  4115. return typeof func === 'function'
  4116. && /^(?:class\s|constructor\()/.test(Function.prototype.toString.call(func));
  4117. }
  4118. function invoke(fn, self, locals, serviceName) {
  4119. if (typeof locals === 'string') {
  4120. serviceName = locals;
  4121. locals = null;
  4122. }
  4123. var args = injectionArgs(fn, locals, serviceName);
  4124. if (isArray(fn)) {
  4125. fn = fn[fn.length - 1];
  4126. }
  4127. if (!isClass(fn)) {
  4128. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  4129. // #5388
  4130. return fn.apply(self, args);
  4131. } else {
  4132. args.unshift(null);
  4133. return new (Function.prototype.bind.apply(fn, args))();
  4134. }
  4135. }
  4136. function instantiate(Type, locals, serviceName) {
  4137. // Check if Type is annotated and use just the given function at n-1 as parameter
  4138. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  4139. var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
  4140. var args = injectionArgs(Type, locals, serviceName);
  4141. // Empty object at position 0 is ignored for invocation with `new`, but required.
  4142. args.unshift(null);
  4143. return new (Function.prototype.bind.apply(ctor, args))();
  4144. }
  4145. return {
  4146. invoke: invoke,
  4147. instantiate: instantiate,
  4148. get: getService,
  4149. annotate: createInjector.$$annotate,
  4150. has: function(name) {
  4151. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  4152. }
  4153. };
  4154. }
  4155. }
  4156. createInjector.$$annotate = annotate;
  4157. /**
  4158. * @ngdoc provider
  4159. * @name $anchorScrollProvider
  4160. *
  4161. * @description
  4162. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  4163. * {@link ng.$location#hash $location.hash()} changes.
  4164. */
  4165. function $AnchorScrollProvider() {
  4166. var autoScrollingEnabled = true;
  4167. /**
  4168. * @ngdoc method
  4169. * @name $anchorScrollProvider#disableAutoScrolling
  4170. *
  4171. * @description
  4172. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  4173. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  4174. * Use this method to disable automatic scrolling.
  4175. *
  4176. * If automatic scrolling is disabled, one must explicitly call
  4177. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  4178. * current hash.
  4179. */
  4180. this.disableAutoScrolling = function() {
  4181. autoScrollingEnabled = false;
  4182. };
  4183. /**
  4184. * @ngdoc service
  4185. * @name $anchorScroll
  4186. * @kind function
  4187. * @requires $window
  4188. * @requires $location
  4189. * @requires $rootScope
  4190. *
  4191. * @description
  4192. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  4193. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  4194. * in the
  4195. * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#the-indicated-part-of-the-document).
  4196. *
  4197. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  4198. * match any anchor whenever it changes. This can be disabled by calling
  4199. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  4200. *
  4201. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  4202. * vertical scroll-offset (either fixed or dynamic).
  4203. *
  4204. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  4205. * {@link ng.$location#hash $location.hash()} will be used.
  4206. *
  4207. * @property {(number|function|jqLite)} yOffset
  4208. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  4209. * positioned elements at the top of the page, such as navbars, headers etc.
  4210. *
  4211. * `yOffset` can be specified in various ways:
  4212. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  4213. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  4214. * a number representing the offset (in pixels).<br /><br />
  4215. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  4216. * the top of the page to the element's bottom will be used as offset.<br />
  4217. * **Note**: The element will be taken into account only as long as its `position` is set to
  4218. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  4219. * their height and/or positioning according to the viewport's size.
  4220. *
  4221. * <br />
  4222. * <div class="alert alert-warning">
  4223. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  4224. * not some child element.
  4225. * </div>
  4226. *
  4227. * @example
  4228. <example module="anchorScrollExample">
  4229. <file name="index.html">
  4230. <div id="scrollArea" ng-controller="ScrollController">
  4231. <a ng-click="gotoBottom()">Go to bottom</a>
  4232. <a id="bottom"></a> You're at the bottom!
  4233. </div>
  4234. </file>
  4235. <file name="script.js">
  4236. angular.module('anchorScrollExample', [])
  4237. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  4238. function ($scope, $location, $anchorScroll) {
  4239. $scope.gotoBottom = function() {
  4240. // set the location.hash to the id of
  4241. // the element you wish to scroll to.
  4242. $location.hash('bottom');
  4243. // call $anchorScroll()
  4244. $anchorScroll();
  4245. };
  4246. }]);
  4247. </file>
  4248. <file name="style.css">
  4249. #scrollArea {
  4250. height: 280px;
  4251. overflow: auto;
  4252. }
  4253. #bottom {
  4254. display: block;
  4255. margin-top: 2000px;
  4256. }
  4257. </file>
  4258. </example>
  4259. *
  4260. * <hr />
  4261. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  4262. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  4263. *
  4264. * @example
  4265. <example module="anchorScrollOffsetExample">
  4266. <file name="index.html">
  4267. <div class="fixed-header" ng-controller="headerCtrl">
  4268. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  4269. Go to anchor {{x}}
  4270. </a>
  4271. </div>
  4272. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  4273. Anchor {{x}} of 5
  4274. </div>
  4275. </file>
  4276. <file name="script.js">
  4277. angular.module('anchorScrollOffsetExample', [])
  4278. .run(['$anchorScroll', function($anchorScroll) {
  4279. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  4280. }])
  4281. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  4282. function ($anchorScroll, $location, $scope) {
  4283. $scope.gotoAnchor = function(x) {
  4284. var newHash = 'anchor' + x;
  4285. if ($location.hash() !== newHash) {
  4286. // set the $location.hash to `newHash` and
  4287. // $anchorScroll will automatically scroll to it
  4288. $location.hash('anchor' + x);
  4289. } else {
  4290. // call $anchorScroll() explicitly,
  4291. // since $location.hash hasn't changed
  4292. $anchorScroll();
  4293. }
  4294. };
  4295. }
  4296. ]);
  4297. </file>
  4298. <file name="style.css">
  4299. body {
  4300. padding-top: 50px;
  4301. }
  4302. .anchor {
  4303. border: 2px dashed DarkOrchid;
  4304. padding: 10px 10px 200px 10px;
  4305. }
  4306. .fixed-header {
  4307. background-color: rgba(0, 0, 0, 0.2);
  4308. height: 50px;
  4309. position: fixed;
  4310. top: 0; left: 0; right: 0;
  4311. }
  4312. .fixed-header > a {
  4313. display: inline-block;
  4314. margin: 5px 15px;
  4315. }
  4316. </file>
  4317. </example>
  4318. */
  4319. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  4320. var document = $window.document;
  4321. // Helper function to get first anchor from a NodeList
  4322. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  4323. // and working in all supported browsers.)
  4324. function getFirstAnchor(list) {
  4325. var result = null;
  4326. Array.prototype.some.call(list, function(element) {
  4327. if (nodeName_(element) === 'a') {
  4328. result = element;
  4329. return true;
  4330. }
  4331. });
  4332. return result;
  4333. }
  4334. function getYOffset() {
  4335. var offset = scroll.yOffset;
  4336. if (isFunction(offset)) {
  4337. offset = offset();
  4338. } else if (isElement(offset)) {
  4339. var elem = offset[0];
  4340. var style = $window.getComputedStyle(elem);
  4341. if (style.position !== 'fixed') {
  4342. offset = 0;
  4343. } else {
  4344. offset = elem.getBoundingClientRect().bottom;
  4345. }
  4346. } else if (!isNumber(offset)) {
  4347. offset = 0;
  4348. }
  4349. return offset;
  4350. }
  4351. function scrollTo(elem) {
  4352. if (elem) {
  4353. elem.scrollIntoView();
  4354. var offset = getYOffset();
  4355. if (offset) {
  4356. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  4357. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  4358. // top of the viewport.
  4359. //
  4360. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  4361. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  4362. // way down the page.
  4363. //
  4364. // This is often the case for elements near the bottom of the page.
  4365. //
  4366. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  4367. // the top of the element and the offset, which is enough to align the top of `elem` at the
  4368. // desired position.
  4369. var elemTop = elem.getBoundingClientRect().top;
  4370. $window.scrollBy(0, elemTop - offset);
  4371. }
  4372. } else {
  4373. $window.scrollTo(0, 0);
  4374. }
  4375. }
  4376. function scroll(hash) {
  4377. hash = isString(hash) ? hash : $location.hash();
  4378. var elm;
  4379. // empty hash, scroll to the top of the page
  4380. if (!hash) scrollTo(null);
  4381. // element with given id
  4382. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4383. // first anchor with given name :-D
  4384. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4385. // no element and hash == 'top', scroll to the top of the page
  4386. else if (hash === 'top') scrollTo(null);
  4387. }
  4388. // does not scroll when user clicks on anchor link that is currently on
  4389. // (no url change, no $location.hash() change), browser native does scroll
  4390. if (autoScrollingEnabled) {
  4391. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4392. function autoScrollWatchAction(newVal, oldVal) {
  4393. // skip the initial scroll if $location.hash is empty
  4394. if (newVal === oldVal && newVal === '') return;
  4395. jqLiteDocumentLoaded(function() {
  4396. $rootScope.$evalAsync(scroll);
  4397. });
  4398. });
  4399. }
  4400. return scroll;
  4401. }];
  4402. }
  4403. var $animateMinErr = minErr('$animate');
  4404. var ELEMENT_NODE = 1;
  4405. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  4406. function mergeClasses(a,b) {
  4407. if (!a && !b) return '';
  4408. if (!a) return b;
  4409. if (!b) return a;
  4410. if (isArray(a)) a = a.join(' ');
  4411. if (isArray(b)) b = b.join(' ');
  4412. return a + ' ' + b;
  4413. }
  4414. function extractElementNode(element) {
  4415. for (var i = 0; i < element.length; i++) {
  4416. var elm = element[i];
  4417. if (elm.nodeType === ELEMENT_NODE) {
  4418. return elm;
  4419. }
  4420. }
  4421. }
  4422. function splitClasses(classes) {
  4423. if (isString(classes)) {
  4424. classes = classes.split(' ');
  4425. }
  4426. // Use createMap() to prevent class assumptions involving property names in
  4427. // Object.prototype
  4428. var obj = createMap();
  4429. forEach(classes, function(klass) {
  4430. // sometimes the split leaves empty string values
  4431. // incase extra spaces were applied to the options
  4432. if (klass.length) {
  4433. obj[klass] = true;
  4434. }
  4435. });
  4436. return obj;
  4437. }
  4438. // if any other type of options value besides an Object value is
  4439. // passed into the $animate.method() animation then this helper code
  4440. // will be run which will ignore it. While this patch is not the
  4441. // greatest solution to this, a lot of existing plugins depend on
  4442. // $animate to either call the callback (< 1.2) or return a promise
  4443. // that can be changed. This helper function ensures that the options
  4444. // are wiped clean incase a callback function is provided.
  4445. function prepareAnimateOptions(options) {
  4446. return isObject(options)
  4447. ? options
  4448. : {};
  4449. }
  4450. var $$CoreAnimateJsProvider = function() {
  4451. this.$get = noop;
  4452. };
  4453. // this is prefixed with Core since it conflicts with
  4454. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  4455. var $$CoreAnimateQueueProvider = function() {
  4456. var postDigestQueue = new HashMap();
  4457. var postDigestElements = [];
  4458. this.$get = ['$$AnimateRunner', '$rootScope',
  4459. function($$AnimateRunner, $rootScope) {
  4460. return {
  4461. enabled: noop,
  4462. on: noop,
  4463. off: noop,
  4464. pin: noop,
  4465. push: function(element, event, options, domOperation) {
  4466. domOperation && domOperation();
  4467. options = options || {};
  4468. options.from && element.css(options.from);
  4469. options.to && element.css(options.to);
  4470. if (options.addClass || options.removeClass) {
  4471. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  4472. }
  4473. var runner = new $$AnimateRunner(); // jshint ignore:line
  4474. // since there are no animations to run the runner needs to be
  4475. // notified that the animation call is complete.
  4476. runner.complete();
  4477. return runner;
  4478. }
  4479. };
  4480. function updateData(data, classes, value) {
  4481. var changed = false;
  4482. if (classes) {
  4483. classes = isString(classes) ? classes.split(' ') :
  4484. isArray(classes) ? classes : [];
  4485. forEach(classes, function(className) {
  4486. if (className) {
  4487. changed = true;
  4488. data[className] = value;
  4489. }
  4490. });
  4491. }
  4492. return changed;
  4493. }
  4494. function handleCSSClassChanges() {
  4495. forEach(postDigestElements, function(element) {
  4496. var data = postDigestQueue.get(element);
  4497. if (data) {
  4498. var existing = splitClasses(element.attr('class'));
  4499. var toAdd = '';
  4500. var toRemove = '';
  4501. forEach(data, function(status, className) {
  4502. var hasClass = !!existing[className];
  4503. if (status !== hasClass) {
  4504. if (status) {
  4505. toAdd += (toAdd.length ? ' ' : '') + className;
  4506. } else {
  4507. toRemove += (toRemove.length ? ' ' : '') + className;
  4508. }
  4509. }
  4510. });
  4511. forEach(element, function(elm) {
  4512. toAdd && jqLiteAddClass(elm, toAdd);
  4513. toRemove && jqLiteRemoveClass(elm, toRemove);
  4514. });
  4515. postDigestQueue.remove(element);
  4516. }
  4517. });
  4518. postDigestElements.length = 0;
  4519. }
  4520. function addRemoveClassesPostDigest(element, add, remove) {
  4521. var data = postDigestQueue.get(element) || {};
  4522. var classesAdded = updateData(data, add, true);
  4523. var classesRemoved = updateData(data, remove, false);
  4524. if (classesAdded || classesRemoved) {
  4525. postDigestQueue.put(element, data);
  4526. postDigestElements.push(element);
  4527. if (postDigestElements.length === 1) {
  4528. $rootScope.$$postDigest(handleCSSClassChanges);
  4529. }
  4530. }
  4531. }
  4532. }];
  4533. };
  4534. /**
  4535. * @ngdoc provider
  4536. * @name $animateProvider
  4537. *
  4538. * @description
  4539. * Default implementation of $animate that doesn't perform any animations, instead just
  4540. * synchronously performs DOM updates and resolves the returned runner promise.
  4541. *
  4542. * In order to enable animations the `ngAnimate` module has to be loaded.
  4543. *
  4544. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  4545. */
  4546. var $AnimateProvider = ['$provide', function($provide) {
  4547. var provider = this;
  4548. this.$$registeredAnimations = Object.create(null);
  4549. /**
  4550. * @ngdoc method
  4551. * @name $animateProvider#register
  4552. *
  4553. * @description
  4554. * Registers a new injectable animation factory function. The factory function produces the
  4555. * animation object which contains callback functions for each event that is expected to be
  4556. * animated.
  4557. *
  4558. * * `eventFn`: `function(element, ... , doneFunction, options)`
  4559. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  4560. * on the type of animation additional arguments will be injected into the animation function. The
  4561. * list below explains the function signatures for the different animation methods:
  4562. *
  4563. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  4564. * - addClass: function(element, addedClasses, doneFunction, options)
  4565. * - removeClass: function(element, removedClasses, doneFunction, options)
  4566. * - enter, leave, move: function(element, doneFunction, options)
  4567. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  4568. *
  4569. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  4570. *
  4571. * ```js
  4572. * return {
  4573. * //enter, leave, move signature
  4574. * eventFn : function(element, done, options) {
  4575. * //code to run the animation
  4576. * //once complete, then run done()
  4577. * return function endFunction(wasCancelled) {
  4578. * //code to cancel the animation
  4579. * }
  4580. * }
  4581. * }
  4582. * ```
  4583. *
  4584. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  4585. * @param {Function} factory The factory function that will be executed to return the animation
  4586. * object.
  4587. */
  4588. this.register = function(name, factory) {
  4589. if (name && name.charAt(0) !== '.') {
  4590. throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name);
  4591. }
  4592. var key = name + '-animation';
  4593. provider.$$registeredAnimations[name.substr(1)] = key;
  4594. $provide.factory(key, factory);
  4595. };
  4596. /**
  4597. * @ngdoc method
  4598. * @name $animateProvider#classNameFilter
  4599. *
  4600. * @description
  4601. * Sets and/or returns the CSS class regular expression that is checked when performing
  4602. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4603. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  4604. * When setting the `classNameFilter` value, animations will only be performed on elements
  4605. * that successfully match the filter expression. This in turn can boost performance
  4606. * for low-powered devices as well as applications containing a lot of structural operations.
  4607. * @param {RegExp=} expression The className expression which will be checked against all animations
  4608. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4609. */
  4610. this.classNameFilter = function(expression) {
  4611. if (arguments.length === 1) {
  4612. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  4613. if (this.$$classNameFilter) {
  4614. var reservedRegex = new RegExp("(\\s+|\\/)" + NG_ANIMATE_CLASSNAME + "(\\s+|\\/)");
  4615. if (reservedRegex.test(this.$$classNameFilter.toString())) {
  4616. throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  4617. }
  4618. }
  4619. }
  4620. return this.$$classNameFilter;
  4621. };
  4622. this.$get = ['$$animateQueue', function($$animateQueue) {
  4623. function domInsert(element, parentElement, afterElement) {
  4624. // if for some reason the previous element was removed
  4625. // from the dom sometime before this code runs then let's
  4626. // just stick to using the parent element as the anchor
  4627. if (afterElement) {
  4628. var afterNode = extractElementNode(afterElement);
  4629. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  4630. afterElement = null;
  4631. }
  4632. }
  4633. afterElement ? afterElement.after(element) : parentElement.prepend(element);
  4634. }
  4635. /**
  4636. * @ngdoc service
  4637. * @name $animate
  4638. * @description The $animate service exposes a series of DOM utility methods that provide support
  4639. * for animation hooks. The default behavior is the application of DOM operations, however,
  4640. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  4641. * to ensure that animation runs with the triggered DOM operation.
  4642. *
  4643. * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
  4644. * included and only when it is active then the animation hooks that `$animate` triggers will be
  4645. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  4646. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  4647. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  4648. *
  4649. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  4650. *
  4651. * To learn more about enabling animation support, click here to visit the
  4652. * {@link ngAnimate ngAnimate module page}.
  4653. */
  4654. return {
  4655. // we don't call it directly since non-existant arguments may
  4656. // be interpreted as null within the sub enabled function
  4657. /**
  4658. *
  4659. * @ngdoc method
  4660. * @name $animate#on
  4661. * @kind function
  4662. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  4663. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  4664. * is fired with the following params:
  4665. *
  4666. * ```js
  4667. * $animate.on('enter', container,
  4668. * function callback(element, phase) {
  4669. * // cool we detected an enter animation within the container
  4670. * }
  4671. * );
  4672. * ```
  4673. *
  4674. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  4675. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  4676. * as well as among its children
  4677. * @param {Function} callback the callback function that will be fired when the listener is triggered
  4678. *
  4679. * The arguments present in the callback function are:
  4680. * * `element` - The captured DOM element that the animation was fired on.
  4681. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  4682. */
  4683. on: $$animateQueue.on,
  4684. /**
  4685. *
  4686. * @ngdoc method
  4687. * @name $animate#off
  4688. * @kind function
  4689. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  4690. * can be used in three different ways depending on the arguments:
  4691. *
  4692. * ```js
  4693. * // remove all the animation event listeners listening for `enter`
  4694. * $animate.off('enter');
  4695. *
  4696. * // remove all the animation event listeners listening for `enter` on the given element and its children
  4697. * $animate.off('enter', container);
  4698. *
  4699. * // remove the event listener function provided by `callback` that is set
  4700. * // to listen for `enter` on the given `container` as well as its children
  4701. * $animate.off('enter', container, callback);
  4702. * ```
  4703. *
  4704. * @param {string} event the animation event (e.g. enter, leave, move, addClass, removeClass, etc...)
  4705. * @param {DOMElement=} container the container element the event listener was placed on
  4706. * @param {Function=} callback the callback function that was registered as the listener
  4707. */
  4708. off: $$animateQueue.off,
  4709. /**
  4710. * @ngdoc method
  4711. * @name $animate#pin
  4712. * @kind function
  4713. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  4714. * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
  4715. * element despite being outside the realm of the application or within another application. Say for example if the application
  4716. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  4717. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  4718. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  4719. *
  4720. * Note that this feature is only active when the `ngAnimate` module is used.
  4721. *
  4722. * @param {DOMElement} element the external element that will be pinned
  4723. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  4724. */
  4725. pin: $$animateQueue.pin,
  4726. /**
  4727. *
  4728. * @ngdoc method
  4729. * @name $animate#enabled
  4730. * @kind function
  4731. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  4732. * function can be called in four ways:
  4733. *
  4734. * ```js
  4735. * // returns true or false
  4736. * $animate.enabled();
  4737. *
  4738. * // changes the enabled state for all animations
  4739. * $animate.enabled(false);
  4740. * $animate.enabled(true);
  4741. *
  4742. * // returns true or false if animations are enabled for an element
  4743. * $animate.enabled(element);
  4744. *
  4745. * // changes the enabled state for an element and its children
  4746. * $animate.enabled(element, true);
  4747. * $animate.enabled(element, false);
  4748. * ```
  4749. *
  4750. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  4751. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  4752. *
  4753. * @return {boolean} whether or not animations are enabled
  4754. */
  4755. enabled: $$animateQueue.enabled,
  4756. /**
  4757. * @ngdoc method
  4758. * @name $animate#cancel
  4759. * @kind function
  4760. * @description Cancels the provided animation.
  4761. *
  4762. * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
  4763. */
  4764. cancel: function(runner) {
  4765. runner.end && runner.end();
  4766. },
  4767. /**
  4768. *
  4769. * @ngdoc method
  4770. * @name $animate#enter
  4771. * @kind function
  4772. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  4773. * as the first child within the `parent` element and then triggers an animation.
  4774. * A promise is returned that will be resolved during the next digest once the animation
  4775. * has completed.
  4776. *
  4777. * @param {DOMElement} element the element which will be inserted into the DOM
  4778. * @param {DOMElement} parent the parent element which will append the element as
  4779. * a child (so long as the after element is not present)
  4780. * @param {DOMElement=} after the sibling element after which the element will be appended
  4781. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4782. *
  4783. * @return {Promise} the animation callback promise
  4784. */
  4785. enter: function(element, parent, after, options) {
  4786. parent = parent && jqLite(parent);
  4787. after = after && jqLite(after);
  4788. parent = parent || after.parent();
  4789. domInsert(element, parent, after);
  4790. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  4791. },
  4792. /**
  4793. *
  4794. * @ngdoc method
  4795. * @name $animate#move
  4796. * @kind function
  4797. * @description Inserts (moves) the element into its new position in the DOM either after
  4798. * the `after` element (if provided) or as the first child within the `parent` element
  4799. * and then triggers an animation. A promise is returned that will be resolved
  4800. * during the next digest once the animation has completed.
  4801. *
  4802. * @param {DOMElement} element the element which will be moved into the new DOM position
  4803. * @param {DOMElement} parent the parent element which will append the element as
  4804. * a child (so long as the after element is not present)
  4805. * @param {DOMElement=} after the sibling element after which the element will be appended
  4806. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4807. *
  4808. * @return {Promise} the animation callback promise
  4809. */
  4810. move: function(element, parent, after, options) {
  4811. parent = parent && jqLite(parent);
  4812. after = after && jqLite(after);
  4813. parent = parent || after.parent();
  4814. domInsert(element, parent, after);
  4815. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  4816. },
  4817. /**
  4818. * @ngdoc method
  4819. * @name $animate#leave
  4820. * @kind function
  4821. * @description Triggers an animation and then removes the element from the DOM.
  4822. * When the function is called a promise is returned that will be resolved during the next
  4823. * digest once the animation has completed.
  4824. *
  4825. * @param {DOMElement} element the element which will be removed from the DOM
  4826. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4827. *
  4828. * @return {Promise} the animation callback promise
  4829. */
  4830. leave: function(element, options) {
  4831. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  4832. element.remove();
  4833. });
  4834. },
  4835. /**
  4836. * @ngdoc method
  4837. * @name $animate#addClass
  4838. * @kind function
  4839. *
  4840. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  4841. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  4842. * animation if element already contains the CSS class or if the class is removed at a later step.
  4843. * Note that class-based animations are treated differently compared to structural animations
  4844. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4845. * depending if CSS or JavaScript animations are used.
  4846. *
  4847. * @param {DOMElement} element the element which the CSS classes will be applied to
  4848. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  4849. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4850. *
  4851. * @return {Promise} the animation callback promise
  4852. */
  4853. addClass: function(element, className, options) {
  4854. options = prepareAnimateOptions(options);
  4855. options.addClass = mergeClasses(options.addclass, className);
  4856. return $$animateQueue.push(element, 'addClass', options);
  4857. },
  4858. /**
  4859. * @ngdoc method
  4860. * @name $animate#removeClass
  4861. * @kind function
  4862. *
  4863. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  4864. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  4865. * animation if element does not contain the CSS class or if the class is added at a later step.
  4866. * Note that class-based animations are treated differently compared to structural animations
  4867. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4868. * depending if CSS or JavaScript animations are used.
  4869. *
  4870. * @param {DOMElement} element the element which the CSS classes will be applied to
  4871. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  4872. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4873. *
  4874. * @return {Promise} the animation callback promise
  4875. */
  4876. removeClass: function(element, className, options) {
  4877. options = prepareAnimateOptions(options);
  4878. options.removeClass = mergeClasses(options.removeClass, className);
  4879. return $$animateQueue.push(element, 'removeClass', options);
  4880. },
  4881. /**
  4882. * @ngdoc method
  4883. * @name $animate#setClass
  4884. * @kind function
  4885. *
  4886. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  4887. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  4888. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  4889. * passed. Note that class-based animations are treated differently compared to structural animations
  4890. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4891. * depending if CSS or JavaScript animations are used.
  4892. *
  4893. * @param {DOMElement} element the element which the CSS classes will be applied to
  4894. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  4895. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  4896. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4897. *
  4898. * @return {Promise} the animation callback promise
  4899. */
  4900. setClass: function(element, add, remove, options) {
  4901. options = prepareAnimateOptions(options);
  4902. options.addClass = mergeClasses(options.addClass, add);
  4903. options.removeClass = mergeClasses(options.removeClass, remove);
  4904. return $$animateQueue.push(element, 'setClass', options);
  4905. },
  4906. /**
  4907. * @ngdoc method
  4908. * @name $animate#animate
  4909. * @kind function
  4910. *
  4911. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  4912. * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take
  4913. * on the provided styles. For example, if a transition animation is set for the given classNamem, then the provided `from` and
  4914. * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding
  4915. * style in `to`, the style in `from` is applied immediately, and no animation is run.
  4916. * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`
  4917. * method (or as part of the `options` parameter):
  4918. *
  4919. * ```js
  4920. * ngModule.animation('.my-inline-animation', function() {
  4921. * return {
  4922. * animate : function(element, from, to, done, options) {
  4923. * //animation
  4924. * done();
  4925. * }
  4926. * }
  4927. * });
  4928. * ```
  4929. *
  4930. * @param {DOMElement} element the element which the CSS styles will be applied to
  4931. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  4932. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  4933. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  4934. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  4935. * (Note that if no animation is detected then this value will not be applied to the element.)
  4936. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4937. *
  4938. * @return {Promise} the animation callback promise
  4939. */
  4940. animate: function(element, from, to, className, options) {
  4941. options = prepareAnimateOptions(options);
  4942. options.from = options.from ? extend(options.from, from) : from;
  4943. options.to = options.to ? extend(options.to, to) : to;
  4944. className = className || 'ng-inline-animate';
  4945. options.tempClasses = mergeClasses(options.tempClasses, className);
  4946. return $$animateQueue.push(element, 'animate', options);
  4947. }
  4948. };
  4949. }];
  4950. }];
  4951. var $$AnimateAsyncRunFactoryProvider = function() {
  4952. this.$get = ['$$rAF', function($$rAF) {
  4953. var waitQueue = [];
  4954. function waitForTick(fn) {
  4955. waitQueue.push(fn);
  4956. if (waitQueue.length > 1) return;
  4957. $$rAF(function() {
  4958. for (var i = 0; i < waitQueue.length; i++) {
  4959. waitQueue[i]();
  4960. }
  4961. waitQueue = [];
  4962. });
  4963. }
  4964. return function() {
  4965. var passed = false;
  4966. waitForTick(function() {
  4967. passed = true;
  4968. });
  4969. return function(callback) {
  4970. passed ? callback() : waitForTick(callback);
  4971. };
  4972. };
  4973. }];
  4974. };
  4975. var $$AnimateRunnerFactoryProvider = function() {
  4976. this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$document', '$timeout',
  4977. function($q, $sniffer, $$animateAsyncRun, $document, $timeout) {
  4978. var INITIAL_STATE = 0;
  4979. var DONE_PENDING_STATE = 1;
  4980. var DONE_COMPLETE_STATE = 2;
  4981. AnimateRunner.chain = function(chain, callback) {
  4982. var index = 0;
  4983. next();
  4984. function next() {
  4985. if (index === chain.length) {
  4986. callback(true);
  4987. return;
  4988. }
  4989. chain[index](function(response) {
  4990. if (response === false) {
  4991. callback(false);
  4992. return;
  4993. }
  4994. index++;
  4995. next();
  4996. });
  4997. }
  4998. };
  4999. AnimateRunner.all = function(runners, callback) {
  5000. var count = 0;
  5001. var status = true;
  5002. forEach(runners, function(runner) {
  5003. runner.done(onProgress);
  5004. });
  5005. function onProgress(response) {
  5006. status = status && response;
  5007. if (++count === runners.length) {
  5008. callback(status);
  5009. }
  5010. }
  5011. };
  5012. function AnimateRunner(host) {
  5013. this.setHost(host);
  5014. var rafTick = $$animateAsyncRun();
  5015. var timeoutTick = function(fn) {
  5016. $timeout(fn, 0, false);
  5017. };
  5018. this._doneCallbacks = [];
  5019. this._tick = function(fn) {
  5020. var doc = $document[0];
  5021. // the document may not be ready or attached
  5022. // to the module for some internal tests
  5023. if (doc && doc.hidden) {
  5024. timeoutTick(fn);
  5025. } else {
  5026. rafTick(fn);
  5027. }
  5028. };
  5029. this._state = 0;
  5030. }
  5031. AnimateRunner.prototype = {
  5032. setHost: function(host) {
  5033. this.host = host || {};
  5034. },
  5035. done: function(fn) {
  5036. if (this._state === DONE_COMPLETE_STATE) {
  5037. fn();
  5038. } else {
  5039. this._doneCallbacks.push(fn);
  5040. }
  5041. },
  5042. progress: noop,
  5043. getPromise: function() {
  5044. if (!this.promise) {
  5045. var self = this;
  5046. this.promise = $q(function(resolve, reject) {
  5047. self.done(function(status) {
  5048. status === false ? reject() : resolve();
  5049. });
  5050. });
  5051. }
  5052. return this.promise;
  5053. },
  5054. then: function(resolveHandler, rejectHandler) {
  5055. return this.getPromise().then(resolveHandler, rejectHandler);
  5056. },
  5057. 'catch': function(handler) {
  5058. return this.getPromise()['catch'](handler);
  5059. },
  5060. 'finally': function(handler) {
  5061. return this.getPromise()['finally'](handler);
  5062. },
  5063. pause: function() {
  5064. if (this.host.pause) {
  5065. this.host.pause();
  5066. }
  5067. },
  5068. resume: function() {
  5069. if (this.host.resume) {
  5070. this.host.resume();
  5071. }
  5072. },
  5073. end: function() {
  5074. if (this.host.end) {
  5075. this.host.end();
  5076. }
  5077. this._resolve(true);
  5078. },
  5079. cancel: function() {
  5080. if (this.host.cancel) {
  5081. this.host.cancel();
  5082. }
  5083. this._resolve(false);
  5084. },
  5085. complete: function(response) {
  5086. var self = this;
  5087. if (self._state === INITIAL_STATE) {
  5088. self._state = DONE_PENDING_STATE;
  5089. self._tick(function() {
  5090. self._resolve(response);
  5091. });
  5092. }
  5093. },
  5094. _resolve: function(response) {
  5095. if (this._state !== DONE_COMPLETE_STATE) {
  5096. forEach(this._doneCallbacks, function(fn) {
  5097. fn(response);
  5098. });
  5099. this._doneCallbacks.length = 0;
  5100. this._state = DONE_COMPLETE_STATE;
  5101. }
  5102. }
  5103. };
  5104. return AnimateRunner;
  5105. }];
  5106. };
  5107. /**
  5108. * @ngdoc service
  5109. * @name $animateCss
  5110. * @kind object
  5111. *
  5112. * @description
  5113. * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
  5114. * then the `$animateCss` service will actually perform animations.
  5115. *
  5116. * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
  5117. */
  5118. var $CoreAnimateCssProvider = function() {
  5119. this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
  5120. return function(element, initialOptions) {
  5121. // all of the animation functions should create
  5122. // a copy of the options data, however, if a
  5123. // parent service has already created a copy then
  5124. // we should stick to using that
  5125. var options = initialOptions || {};
  5126. if (!options.$$prepared) {
  5127. options = copy(options);
  5128. }
  5129. // there is no point in applying the styles since
  5130. // there is no animation that goes on at all in
  5131. // this version of $animateCss.
  5132. if (options.cleanupStyles) {
  5133. options.from = options.to = null;
  5134. }
  5135. if (options.from) {
  5136. element.css(options.from);
  5137. options.from = null;
  5138. }
  5139. /* jshint newcap: false */
  5140. var closed, runner = new $$AnimateRunner();
  5141. return {
  5142. start: run,
  5143. end: run
  5144. };
  5145. function run() {
  5146. $$rAF(function() {
  5147. applyAnimationContents();
  5148. if (!closed) {
  5149. runner.complete();
  5150. }
  5151. closed = true;
  5152. });
  5153. return runner;
  5154. }
  5155. function applyAnimationContents() {
  5156. if (options.addClass) {
  5157. element.addClass(options.addClass);
  5158. options.addClass = null;
  5159. }
  5160. if (options.removeClass) {
  5161. element.removeClass(options.removeClass);
  5162. options.removeClass = null;
  5163. }
  5164. if (options.to) {
  5165. element.css(options.to);
  5166. options.to = null;
  5167. }
  5168. }
  5169. };
  5170. }];
  5171. };
  5172. /* global stripHash: true */
  5173. /**
  5174. * ! This is a private undocumented service !
  5175. *
  5176. * @name $browser
  5177. * @requires $log
  5178. * @description
  5179. * This object has two goals:
  5180. *
  5181. * - hide all the global state in the browser caused by the window object
  5182. * - abstract away all the browser specific features and inconsistencies
  5183. *
  5184. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  5185. * service, which can be used for convenient testing of the application without the interaction with
  5186. * the real browser apis.
  5187. */
  5188. /**
  5189. * @param {object} window The global window object.
  5190. * @param {object} document jQuery wrapped document.
  5191. * @param {object} $log window.console or an object with the same interface.
  5192. * @param {object} $sniffer $sniffer service
  5193. */
  5194. function Browser(window, document, $log, $sniffer) {
  5195. var self = this,
  5196. location = window.location,
  5197. history = window.history,
  5198. setTimeout = window.setTimeout,
  5199. clearTimeout = window.clearTimeout,
  5200. pendingDeferIds = {};
  5201. self.isMock = false;
  5202. var outstandingRequestCount = 0;
  5203. var outstandingRequestCallbacks = [];
  5204. // TODO(vojta): remove this temporary api
  5205. self.$$completeOutstandingRequest = completeOutstandingRequest;
  5206. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  5207. /**
  5208. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  5209. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  5210. */
  5211. function completeOutstandingRequest(fn) {
  5212. try {
  5213. fn.apply(null, sliceArgs(arguments, 1));
  5214. } finally {
  5215. outstandingRequestCount--;
  5216. if (outstandingRequestCount === 0) {
  5217. while (outstandingRequestCallbacks.length) {
  5218. try {
  5219. outstandingRequestCallbacks.pop()();
  5220. } catch (e) {
  5221. $log.error(e);
  5222. }
  5223. }
  5224. }
  5225. }
  5226. }
  5227. function getHash(url) {
  5228. var index = url.indexOf('#');
  5229. return index === -1 ? '' : url.substr(index);
  5230. }
  5231. /**
  5232. * @private
  5233. * Note: this method is used only by scenario runner
  5234. * TODO(vojta): prefix this method with $$ ?
  5235. * @param {function()} callback Function that will be called when no outstanding request
  5236. */
  5237. self.notifyWhenNoOutstandingRequests = function(callback) {
  5238. if (outstandingRequestCount === 0) {
  5239. callback();
  5240. } else {
  5241. outstandingRequestCallbacks.push(callback);
  5242. }
  5243. };
  5244. //////////////////////////////////////////////////////////////
  5245. // URL API
  5246. //////////////////////////////////////////////////////////////
  5247. var cachedState, lastHistoryState,
  5248. lastBrowserUrl = location.href,
  5249. baseElement = document.find('base'),
  5250. pendingLocation = null,
  5251. getCurrentState = !$sniffer.history ? noop : function getCurrentState() {
  5252. try {
  5253. return history.state;
  5254. } catch (e) {
  5255. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  5256. }
  5257. };
  5258. cacheState();
  5259. lastHistoryState = cachedState;
  5260. /**
  5261. * @name $browser#url
  5262. *
  5263. * @description
  5264. * GETTER:
  5265. * Without any argument, this method just returns current value of location.href.
  5266. *
  5267. * SETTER:
  5268. * With at least one argument, this method sets url to new value.
  5269. * If html5 history api supported, pushState/replaceState is used, otherwise
  5270. * location.href/location.replace is used.
  5271. * Returns its own instance to allow chaining
  5272. *
  5273. * NOTE: this api is intended for use only by the $location service. Please use the
  5274. * {@link ng.$location $location service} to change url.
  5275. *
  5276. * @param {string} url New url (when used as setter)
  5277. * @param {boolean=} replace Should new url replace current history record?
  5278. * @param {object=} state object to use with pushState/replaceState
  5279. */
  5280. self.url = function(url, replace, state) {
  5281. // In modern browsers `history.state` is `null` by default; treating it separately
  5282. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  5283. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  5284. if (isUndefined(state)) {
  5285. state = null;
  5286. }
  5287. // Android Browser BFCache causes location, history reference to become stale.
  5288. if (location !== window.location) location = window.location;
  5289. if (history !== window.history) history = window.history;
  5290. // setter
  5291. if (url) {
  5292. var sameState = lastHistoryState === state;
  5293. // Don't change anything if previous and current URLs and states match. This also prevents
  5294. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  5295. // See https://github.com/angular/angular.js/commit/ffb2701
  5296. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  5297. return self;
  5298. }
  5299. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  5300. lastBrowserUrl = url;
  5301. lastHistoryState = state;
  5302. // Don't use history API if only the hash changed
  5303. // due to a bug in IE10/IE11 which leads
  5304. // to not firing a `hashchange` nor `popstate` event
  5305. // in some cases (see #9143).
  5306. if ($sniffer.history && (!sameBase || !sameState)) {
  5307. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  5308. cacheState();
  5309. // Do the assignment again so that those two variables are referentially identical.
  5310. lastHistoryState = cachedState;
  5311. } else {
  5312. if (!sameBase || pendingLocation) {
  5313. pendingLocation = url;
  5314. }
  5315. if (replace) {
  5316. location.replace(url);
  5317. } else if (!sameBase) {
  5318. location.href = url;
  5319. } else {
  5320. location.hash = getHash(url);
  5321. }
  5322. if (location.href !== url) {
  5323. pendingLocation = url;
  5324. }
  5325. }
  5326. return self;
  5327. // getter
  5328. } else {
  5329. // - pendingLocation is needed as browsers don't allow to read out
  5330. // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
  5331. // https://openradar.appspot.com/22186109).
  5332. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  5333. return pendingLocation || location.href.replace(/%27/g,"'");
  5334. }
  5335. };
  5336. /**
  5337. * @name $browser#state
  5338. *
  5339. * @description
  5340. * This method is a getter.
  5341. *
  5342. * Return history.state or null if history.state is undefined.
  5343. *
  5344. * @returns {object} state
  5345. */
  5346. self.state = function() {
  5347. return cachedState;
  5348. };
  5349. var urlChangeListeners = [],
  5350. urlChangeInit = false;
  5351. function cacheStateAndFireUrlChange() {
  5352. pendingLocation = null;
  5353. cacheState();
  5354. fireUrlChange();
  5355. }
  5356. // This variable should be used *only* inside the cacheState function.
  5357. var lastCachedState = null;
  5358. function cacheState() {
  5359. // This should be the only place in $browser where `history.state` is read.
  5360. cachedState = getCurrentState();
  5361. cachedState = isUndefined(cachedState) ? null : cachedState;
  5362. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  5363. if (equals(cachedState, lastCachedState)) {
  5364. cachedState = lastCachedState;
  5365. }
  5366. lastCachedState = cachedState;
  5367. }
  5368. function fireUrlChange() {
  5369. if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
  5370. return;
  5371. }
  5372. lastBrowserUrl = self.url();
  5373. lastHistoryState = cachedState;
  5374. forEach(urlChangeListeners, function(listener) {
  5375. listener(self.url(), cachedState);
  5376. });
  5377. }
  5378. /**
  5379. * @name $browser#onUrlChange
  5380. *
  5381. * @description
  5382. * Register callback function that will be called, when url changes.
  5383. *
  5384. * It's only called when the url is changed from outside of angular:
  5385. * - user types different url into address bar
  5386. * - user clicks on history (forward/back) button
  5387. * - user clicks on a link
  5388. *
  5389. * It's not called when url is changed by $browser.url() method
  5390. *
  5391. * The listener gets called with new url as parameter.
  5392. *
  5393. * NOTE: this api is intended for use only by the $location service. Please use the
  5394. * {@link ng.$location $location service} to monitor url changes in angular apps.
  5395. *
  5396. * @param {function(string)} listener Listener function to be called when url changes.
  5397. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  5398. */
  5399. self.onUrlChange = function(callback) {
  5400. // TODO(vojta): refactor to use node's syntax for events
  5401. if (!urlChangeInit) {
  5402. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  5403. // don't fire popstate when user change the address bar and don't fire hashchange when url
  5404. // changed by push/replaceState
  5405. // html5 history api - popstate event
  5406. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  5407. // hashchange event
  5408. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  5409. urlChangeInit = true;
  5410. }
  5411. urlChangeListeners.push(callback);
  5412. return callback;
  5413. };
  5414. /**
  5415. * @private
  5416. * Remove popstate and hashchange handler from window.
  5417. *
  5418. * NOTE: this api is intended for use only by $rootScope.
  5419. */
  5420. self.$$applicationDestroyed = function() {
  5421. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  5422. };
  5423. /**
  5424. * Checks whether the url has changed outside of Angular.
  5425. * Needs to be exported to be able to check for changes that have been done in sync,
  5426. * as hashchange/popstate events fire in async.
  5427. */
  5428. self.$$checkUrlChange = fireUrlChange;
  5429. //////////////////////////////////////////////////////////////
  5430. // Misc API
  5431. //////////////////////////////////////////////////////////////
  5432. /**
  5433. * @name $browser#baseHref
  5434. *
  5435. * @description
  5436. * Returns current <base href>
  5437. * (always relative - without domain)
  5438. *
  5439. * @returns {string} The current base href
  5440. */
  5441. self.baseHref = function() {
  5442. var href = baseElement.attr('href');
  5443. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  5444. };
  5445. /**
  5446. * @name $browser#defer
  5447. * @param {function()} fn A function, who's execution should be deferred.
  5448. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  5449. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  5450. *
  5451. * @description
  5452. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  5453. *
  5454. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  5455. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  5456. * via `$browser.defer.flush()`.
  5457. *
  5458. */
  5459. self.defer = function(fn, delay) {
  5460. var timeoutId;
  5461. outstandingRequestCount++;
  5462. timeoutId = setTimeout(function() {
  5463. delete pendingDeferIds[timeoutId];
  5464. completeOutstandingRequest(fn);
  5465. }, delay || 0);
  5466. pendingDeferIds[timeoutId] = true;
  5467. return timeoutId;
  5468. };
  5469. /**
  5470. * @name $browser#defer.cancel
  5471. *
  5472. * @description
  5473. * Cancels a deferred task identified with `deferId`.
  5474. *
  5475. * @param {*} deferId Token returned by the `$browser.defer` function.
  5476. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  5477. * canceled.
  5478. */
  5479. self.defer.cancel = function(deferId) {
  5480. if (pendingDeferIds[deferId]) {
  5481. delete pendingDeferIds[deferId];
  5482. clearTimeout(deferId);
  5483. completeOutstandingRequest(noop);
  5484. return true;
  5485. }
  5486. return false;
  5487. };
  5488. }
  5489. function $BrowserProvider() {
  5490. this.$get = ['$window', '$log', '$sniffer', '$document',
  5491. function($window, $log, $sniffer, $document) {
  5492. return new Browser($window, $document, $log, $sniffer);
  5493. }];
  5494. }
  5495. /**
  5496. * @ngdoc service
  5497. * @name $cacheFactory
  5498. *
  5499. * @description
  5500. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  5501. * them.
  5502. *
  5503. * ```js
  5504. *
  5505. * var cache = $cacheFactory('cacheId');
  5506. * expect($cacheFactory.get('cacheId')).toBe(cache);
  5507. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  5508. *
  5509. * cache.put("key", "value");
  5510. * cache.put("another key", "another value");
  5511. *
  5512. * // We've specified no options on creation
  5513. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  5514. *
  5515. * ```
  5516. *
  5517. *
  5518. * @param {string} cacheId Name or id of the newly created cache.
  5519. * @param {object=} options Options object that specifies the cache behavior. Properties:
  5520. *
  5521. * - `{number=}` `capacity` — turns the cache into LRU cache.
  5522. *
  5523. * @returns {object} Newly created cache object with the following set of methods:
  5524. *
  5525. * - `{object}` `info()` — Returns id, size, and options of cache.
  5526. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  5527. * it.
  5528. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  5529. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  5530. * - `{void}` `removeAll()` — Removes all cached values.
  5531. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  5532. *
  5533. * @example
  5534. <example module="cacheExampleApp">
  5535. <file name="index.html">
  5536. <div ng-controller="CacheController">
  5537. <input ng-model="newCacheKey" placeholder="Key">
  5538. <input ng-model="newCacheValue" placeholder="Value">
  5539. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  5540. <p ng-if="keys.length">Cached Values</p>
  5541. <div ng-repeat="key in keys">
  5542. <span ng-bind="key"></span>
  5543. <span>: </span>
  5544. <b ng-bind="cache.get(key)"></b>
  5545. </div>
  5546. <p>Cache Info</p>
  5547. <div ng-repeat="(key, value) in cache.info()">
  5548. <span ng-bind="key"></span>
  5549. <span>: </span>
  5550. <b ng-bind="value"></b>
  5551. </div>
  5552. </div>
  5553. </file>
  5554. <file name="script.js">
  5555. angular.module('cacheExampleApp', []).
  5556. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  5557. $scope.keys = [];
  5558. $scope.cache = $cacheFactory('cacheId');
  5559. $scope.put = function(key, value) {
  5560. if (angular.isUndefined($scope.cache.get(key))) {
  5561. $scope.keys.push(key);
  5562. }
  5563. $scope.cache.put(key, angular.isUndefined(value) ? null : value);
  5564. };
  5565. }]);
  5566. </file>
  5567. <file name="style.css">
  5568. p {
  5569. margin: 10px 0 3px;
  5570. }
  5571. </file>
  5572. </example>
  5573. */
  5574. function $CacheFactoryProvider() {
  5575. this.$get = function() {
  5576. var caches = {};
  5577. function cacheFactory(cacheId, options) {
  5578. if (cacheId in caches) {
  5579. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  5580. }
  5581. var size = 0,
  5582. stats = extend({}, options, {id: cacheId}),
  5583. data = createMap(),
  5584. capacity = (options && options.capacity) || Number.MAX_VALUE,
  5585. lruHash = createMap(),
  5586. freshEnd = null,
  5587. staleEnd = null;
  5588. /**
  5589. * @ngdoc type
  5590. * @name $cacheFactory.Cache
  5591. *
  5592. * @description
  5593. * A cache object used to store and retrieve data, primarily used by
  5594. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  5595. * templates and other data.
  5596. *
  5597. * ```js
  5598. * angular.module('superCache')
  5599. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  5600. * return $cacheFactory('super-cache');
  5601. * }]);
  5602. * ```
  5603. *
  5604. * Example test:
  5605. *
  5606. * ```js
  5607. * it('should behave like a cache', inject(function(superCache) {
  5608. * superCache.put('key', 'value');
  5609. * superCache.put('another key', 'another value');
  5610. *
  5611. * expect(superCache.info()).toEqual({
  5612. * id: 'super-cache',
  5613. * size: 2
  5614. * });
  5615. *
  5616. * superCache.remove('another key');
  5617. * expect(superCache.get('another key')).toBeUndefined();
  5618. *
  5619. * superCache.removeAll();
  5620. * expect(superCache.info()).toEqual({
  5621. * id: 'super-cache',
  5622. * size: 0
  5623. * });
  5624. * }));
  5625. * ```
  5626. */
  5627. return caches[cacheId] = {
  5628. /**
  5629. * @ngdoc method
  5630. * @name $cacheFactory.Cache#put
  5631. * @kind function
  5632. *
  5633. * @description
  5634. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  5635. * retrieved later, and incrementing the size of the cache if the key was not already
  5636. * present in the cache. If behaving like an LRU cache, it will also remove stale
  5637. * entries from the set.
  5638. *
  5639. * It will not insert undefined values into the cache.
  5640. *
  5641. * @param {string} key the key under which the cached data is stored.
  5642. * @param {*} value the value to store alongside the key. If it is undefined, the key
  5643. * will not be stored.
  5644. * @returns {*} the value stored.
  5645. */
  5646. put: function(key, value) {
  5647. if (isUndefined(value)) return;
  5648. if (capacity < Number.MAX_VALUE) {
  5649. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  5650. refresh(lruEntry);
  5651. }
  5652. if (!(key in data)) size++;
  5653. data[key] = value;
  5654. if (size > capacity) {
  5655. this.remove(staleEnd.key);
  5656. }
  5657. return value;
  5658. },
  5659. /**
  5660. * @ngdoc method
  5661. * @name $cacheFactory.Cache#get
  5662. * @kind function
  5663. *
  5664. * @description
  5665. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  5666. *
  5667. * @param {string} key the key of the data to be retrieved
  5668. * @returns {*} the value stored.
  5669. */
  5670. get: function(key) {
  5671. if (capacity < Number.MAX_VALUE) {
  5672. var lruEntry = lruHash[key];
  5673. if (!lruEntry) return;
  5674. refresh(lruEntry);
  5675. }
  5676. return data[key];
  5677. },
  5678. /**
  5679. * @ngdoc method
  5680. * @name $cacheFactory.Cache#remove
  5681. * @kind function
  5682. *
  5683. * @description
  5684. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  5685. *
  5686. * @param {string} key the key of the entry to be removed
  5687. */
  5688. remove: function(key) {
  5689. if (capacity < Number.MAX_VALUE) {
  5690. var lruEntry = lruHash[key];
  5691. if (!lruEntry) return;
  5692. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  5693. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  5694. link(lruEntry.n,lruEntry.p);
  5695. delete lruHash[key];
  5696. }
  5697. if (!(key in data)) return;
  5698. delete data[key];
  5699. size--;
  5700. },
  5701. /**
  5702. * @ngdoc method
  5703. * @name $cacheFactory.Cache#removeAll
  5704. * @kind function
  5705. *
  5706. * @description
  5707. * Clears the cache object of any entries.
  5708. */
  5709. removeAll: function() {
  5710. data = createMap();
  5711. size = 0;
  5712. lruHash = createMap();
  5713. freshEnd = staleEnd = null;
  5714. },
  5715. /**
  5716. * @ngdoc method
  5717. * @name $cacheFactory.Cache#destroy
  5718. * @kind function
  5719. *
  5720. * @description
  5721. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  5722. * removing it from the {@link $cacheFactory $cacheFactory} set.
  5723. */
  5724. destroy: function() {
  5725. data = null;
  5726. stats = null;
  5727. lruHash = null;
  5728. delete caches[cacheId];
  5729. },
  5730. /**
  5731. * @ngdoc method
  5732. * @name $cacheFactory.Cache#info
  5733. * @kind function
  5734. *
  5735. * @description
  5736. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  5737. *
  5738. * @returns {object} an object with the following properties:
  5739. * <ul>
  5740. * <li>**id**: the id of the cache instance</li>
  5741. * <li>**size**: the number of entries kept in the cache instance</li>
  5742. * <li>**...**: any additional properties from the options object when creating the
  5743. * cache.</li>
  5744. * </ul>
  5745. */
  5746. info: function() {
  5747. return extend({}, stats, {size: size});
  5748. }
  5749. };
  5750. /**
  5751. * makes the `entry` the freshEnd of the LRU linked list
  5752. */
  5753. function refresh(entry) {
  5754. if (entry != freshEnd) {
  5755. if (!staleEnd) {
  5756. staleEnd = entry;
  5757. } else if (staleEnd == entry) {
  5758. staleEnd = entry.n;
  5759. }
  5760. link(entry.n, entry.p);
  5761. link(entry, freshEnd);
  5762. freshEnd = entry;
  5763. freshEnd.n = null;
  5764. }
  5765. }
  5766. /**
  5767. * bidirectionally links two entries of the LRU linked list
  5768. */
  5769. function link(nextEntry, prevEntry) {
  5770. if (nextEntry != prevEntry) {
  5771. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  5772. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  5773. }
  5774. }
  5775. }
  5776. /**
  5777. * @ngdoc method
  5778. * @name $cacheFactory#info
  5779. *
  5780. * @description
  5781. * Get information about all the caches that have been created
  5782. *
  5783. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  5784. */
  5785. cacheFactory.info = function() {
  5786. var info = {};
  5787. forEach(caches, function(cache, cacheId) {
  5788. info[cacheId] = cache.info();
  5789. });
  5790. return info;
  5791. };
  5792. /**
  5793. * @ngdoc method
  5794. * @name $cacheFactory#get
  5795. *
  5796. * @description
  5797. * Get access to a cache object by the `cacheId` used when it was created.
  5798. *
  5799. * @param {string} cacheId Name or id of a cache to access.
  5800. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  5801. */
  5802. cacheFactory.get = function(cacheId) {
  5803. return caches[cacheId];
  5804. };
  5805. return cacheFactory;
  5806. };
  5807. }
  5808. /**
  5809. * @ngdoc service
  5810. * @name $templateCache
  5811. *
  5812. * @description
  5813. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  5814. * can load templates directly into the cache in a `script` tag, or by consuming the
  5815. * `$templateCache` service directly.
  5816. *
  5817. * Adding via the `script` tag:
  5818. *
  5819. * ```html
  5820. * <script type="text/ng-template" id="templateId.html">
  5821. * <p>This is the content of the template</p>
  5822. * </script>
  5823. * ```
  5824. *
  5825. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  5826. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  5827. * element with ng-app attribute), otherwise the template will be ignored.
  5828. *
  5829. * Adding via the `$templateCache` service:
  5830. *
  5831. * ```js
  5832. * var myApp = angular.module('myApp', []);
  5833. * myApp.run(function($templateCache) {
  5834. * $templateCache.put('templateId.html', 'This is the content of the template');
  5835. * });
  5836. * ```
  5837. *
  5838. * To retrieve the template later, simply use it in your HTML:
  5839. * ```html
  5840. * <div ng-include=" 'templateId.html' "></div>
  5841. * ```
  5842. *
  5843. * or get it via Javascript:
  5844. * ```js
  5845. * $templateCache.get('templateId.html')
  5846. * ```
  5847. *
  5848. * See {@link ng.$cacheFactory $cacheFactory}.
  5849. *
  5850. */
  5851. function $TemplateCacheProvider() {
  5852. this.$get = ['$cacheFactory', function($cacheFactory) {
  5853. return $cacheFactory('templates');
  5854. }];
  5855. }
  5856. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  5857. * Any commits to this file should be reviewed with security in mind. *
  5858. * Changes to this file can potentially create security vulnerabilities. *
  5859. * An approval from 2 Core members with history of modifying *
  5860. * this file is required. *
  5861. * *
  5862. * Does the change somehow allow for arbitrary javascript to be executed? *
  5863. * Or allows for someone to change the prototype of built-in objects? *
  5864. * Or gives undesired access to variables likes document or window? *
  5865. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  5866. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  5867. *
  5868. * DOM-related variables:
  5869. *
  5870. * - "node" - DOM Node
  5871. * - "element" - DOM Element or Node
  5872. * - "$node" or "$element" - jqLite-wrapped node or element
  5873. *
  5874. *
  5875. * Compiler related stuff:
  5876. *
  5877. * - "linkFn" - linking fn of a single directive
  5878. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  5879. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  5880. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  5881. */
  5882. /**
  5883. * @ngdoc service
  5884. * @name $compile
  5885. * @kind function
  5886. *
  5887. * @description
  5888. * Compiles an HTML string or DOM into a template and produces a template function, which
  5889. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  5890. *
  5891. * The compilation is a process of walking the DOM tree and matching DOM elements to
  5892. * {@link ng.$compileProvider#directive directives}.
  5893. *
  5894. * <div class="alert alert-warning">
  5895. * **Note:** This document is an in-depth reference of all directive options.
  5896. * For a gentle introduction to directives with examples of common use cases,
  5897. * see the {@link guide/directive directive guide}.
  5898. * </div>
  5899. *
  5900. * ## Comprehensive Directive API
  5901. *
  5902. * There are many different options for a directive.
  5903. *
  5904. * The difference resides in the return value of the factory function.
  5905. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  5906. * or just the `postLink` function (all other properties will have the default values).
  5907. *
  5908. * <div class="alert alert-success">
  5909. * **Best Practice:** It's recommended to use the "directive definition object" form.
  5910. * </div>
  5911. *
  5912. * Here's an example directive declared with a Directive Definition Object:
  5913. *
  5914. * ```js
  5915. * var myModule = angular.module(...);
  5916. *
  5917. * myModule.directive('directiveName', function factory(injectables) {
  5918. * var directiveDefinitionObject = {
  5919. * priority: 0,
  5920. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  5921. * // or
  5922. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  5923. * transclude: false,
  5924. * restrict: 'A',
  5925. * templateNamespace: 'html',
  5926. * scope: false,
  5927. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  5928. * controllerAs: 'stringIdentifier',
  5929. * bindToController: false,
  5930. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  5931. * compile: function compile(tElement, tAttrs, transclude) {
  5932. * return {
  5933. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5934. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5935. * }
  5936. * // or
  5937. * // return function postLink( ... ) { ... }
  5938. * },
  5939. * // or
  5940. * // link: {
  5941. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5942. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5943. * // }
  5944. * // or
  5945. * // link: function postLink( ... ) { ... }
  5946. * };
  5947. * return directiveDefinitionObject;
  5948. * });
  5949. * ```
  5950. *
  5951. * <div class="alert alert-warning">
  5952. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  5953. * </div>
  5954. *
  5955. * Therefore the above can be simplified as:
  5956. *
  5957. * ```js
  5958. * var myModule = angular.module(...);
  5959. *
  5960. * myModule.directive('directiveName', function factory(injectables) {
  5961. * var directiveDefinitionObject = {
  5962. * link: function postLink(scope, iElement, iAttrs) { ... }
  5963. * };
  5964. * return directiveDefinitionObject;
  5965. * // or
  5966. * // return function postLink(scope, iElement, iAttrs) { ... }
  5967. * });
  5968. * ```
  5969. *
  5970. *
  5971. *
  5972. * ### Directive Definition Object
  5973. *
  5974. * The directive definition object provides instructions to the {@link ng.$compile
  5975. * compiler}. The attributes are:
  5976. *
  5977. * #### `multiElement`
  5978. * When this property is set to true, the HTML compiler will collect DOM nodes between
  5979. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  5980. * together as the directive elements. It is recommended that this feature be used on directives
  5981. * which are not strictly behavioral (such as {@link ngClick}), and which
  5982. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  5983. *
  5984. * #### `priority`
  5985. * When there are multiple directives defined on a single DOM element, sometimes it
  5986. * is necessary to specify the order in which the directives are applied. The `priority` is used
  5987. * to sort the directives before their `compile` functions get called. Priority is defined as a
  5988. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  5989. * are also run in priority order, but post-link functions are run in reverse order. The order
  5990. * of directives with the same priority is undefined. The default priority is `0`.
  5991. *
  5992. * #### `terminal`
  5993. * If set to true then the current `priority` will be the last set of directives
  5994. * which will execute (any directives at the current priority will still execute
  5995. * as the order of execution on same `priority` is undefined). Note that expressions
  5996. * and other directives used in the directive's template will also be excluded from execution.
  5997. *
  5998. * #### `scope`
  5999. * The scope property can be `true`, an object or a falsy value:
  6000. *
  6001. * * **falsy:** No scope will be created for the directive. The directive will use its parent's scope.
  6002. *
  6003. * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
  6004. * the directive's element. If multiple directives on the same element request a new scope,
  6005. * only one new scope is created. The new scope rule does not apply for the root of the template
  6006. * since the root of the template always gets a new scope.
  6007. *
  6008. * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's element. The
  6009. * 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent
  6010. * scope. This is useful when creating reusable components, which should not accidentally read or modify
  6011. * data in the parent scope.
  6012. *
  6013. * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
  6014. * directive's element. These local properties are useful for aliasing values for templates. The keys in
  6015. * the object hash map to the name of the property on the isolate scope; the values define how the property
  6016. * is bound to the parent scope, via matching attributes on the directive's element:
  6017. *
  6018. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  6019. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  6020. * attribute name is assumed to be the same as the local name. Given `<my-component
  6021. * my-attr="hello {{name}}">` and the isolate scope definition `scope: { localName:'@myAttr' }`,
  6022. * the directive's scope property `localName` will reflect the interpolated value of `hello
  6023. * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's
  6024. * scope. The `name` is read from the parent scope (not the directive's scope).
  6025. *
  6026. * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression
  6027. * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.
  6028. * If no `attr` name is specified then the attribute name is assumed to be the same as the local
  6029. * name. Given `<my-component my-attr="parentModel">` and the isolate scope definition `scope: {
  6030. * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the
  6031. * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in
  6032. * `localModel` and vice versa. Optional attributes should be marked as such with a question mark:
  6033. * `=?` or `=?attr`. If the binding expression is non-assignable, or if the attribute isn't
  6034. * optional and doesn't exist, an exception ({@link error/$compile/nonassign `$compile:nonassign`})
  6035. * will be thrown upon discovering changes to the local value, since it will be impossible to sync
  6036. * them back to the parent scope. By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
  6037. * method is used for tracking changes, and the equality check is based on object identity.
  6038. * However, if an object literal or an array literal is passed as the binding expression, the
  6039. * equality check is done by value (using the {@link angular.equals} function). It's also possible
  6040. * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection
  6041. * `$watchCollection`}: use `=*` or `=*attr` (`=*?` or `=*?attr` if the attribute is optional).
  6042. *
  6043. * * `<` or `<attr` - set up a one-way (one-directional) binding between a local scope property and an
  6044. * expression passed via the attribute `attr`. The expression is evaluated in the context of the
  6045. * parent scope. If no `attr` name is specified then the attribute name is assumed to be the same as the
  6046. * local name. You can also make the binding optional by adding `?`: `<?` or `<?attr`.
  6047. *
  6048. * For example, given `<my-component my-attr="parentModel">` and directive definition of
  6049. * `scope: { localModel:'<myAttr' }`, then the isolated scope property `localModel` will reflect the
  6050. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  6051. * in `localModel`, but changes in `localModel` will not reflect in `parentModel`. There are however
  6052. * two caveats:
  6053. * 1. one-way binding does not copy the value from the parent to the isolate scope, it simply
  6054. * sets the same value. That means if your bound value is an object, changes to its properties
  6055. * in the isolated scope will be reflected in the parent scope (because both reference the same object).
  6056. * 2. one-way binding watches changes to the **identity** of the parent value. That means the
  6057. * {@link ng.$rootScope.Scope#$watch `$watch`} on the parent value only fires if the reference
  6058. * to the value has changed. In most cases, this should not be of concern, but can be important
  6059. * to know if you one-way bind to an object, and then replace that object in the isolated scope.
  6060. * If you now change a property of the object in your parent scope, the change will not be
  6061. * propagated to the isolated scope, because the identity of the object on the parent scope
  6062. * has not changed. Instead you must assign a new object.
  6063. *
  6064. * One-way binding is useful if you do not plan to propagate changes to your isolated scope bindings
  6065. * back to the parent. However, it does not make this completely impossible.
  6066. *
  6067. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. If
  6068. * no `attr` name is specified then the attribute name is assumed to be the same as the local name.
  6069. * Given `<my-component my-attr="count = count + value">` and the isolate scope definition `scope: {
  6070. * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for
  6071. * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope
  6072. * via an expression to the parent scope. This can be done by passing a map of local variable names
  6073. * and values into the expression wrapper fn. For example, if the expression is `increment(amount)`
  6074. * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.
  6075. *
  6076. * In general it's possible to apply more than one directive to one element, but there might be limitations
  6077. * depending on the type of scope required by the directives. The following points will help explain these limitations.
  6078. * For simplicity only two directives are taken into account, but it is also applicable for several directives:
  6079. *
  6080. * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
  6081. * * **child scope** + **no scope** => Both directives will share one single child scope
  6082. * * **child scope** + **child scope** => Both directives will share one single child scope
  6083. * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
  6084. * its parent's scope
  6085. * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
  6086. * be applied to the same element.
  6087. * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
  6088. * cannot be applied to the same element.
  6089. *
  6090. *
  6091. * #### `bindToController`
  6092. * This property is used to bind scope properties directly to the controller. It can be either
  6093. * `true` or an object hash with the same format as the `scope` property. Additionally, a controller
  6094. * alias must be set, either by using `controllerAs: 'myAlias'` or by specifying the alias in the controller
  6095. * definition: `controller: 'myCtrl as myAlias'`.
  6096. *
  6097. * When an isolate scope is used for a directive (see above), `bindToController: true` will
  6098. * allow a component to have its properties bound to the controller, rather than to scope.
  6099. *
  6100. * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller
  6101. * properties. You can access these bindings once they have been initialized by providing a controller method called
  6102. * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings
  6103. * initialized.
  6104. *
  6105. * <div class="alert alert-warning">
  6106. * **Deprecation warning:** although bindings for non-ES6 class controllers are currently
  6107. * bound to `this` before the controller constructor is called, this use is now deprecated. Please place initialization
  6108. * code that relies upon bindings inside a `$onInit` method on the controller, instead.
  6109. * </div>
  6110. *
  6111. * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.
  6112. * This will set up the scope bindings to the controller directly. Note that `scope` can still be used
  6113. * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate
  6114. * scope (useful for component directives).
  6115. *
  6116. * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.
  6117. *
  6118. *
  6119. * #### `controller`
  6120. * Controller constructor function. The controller is instantiated before the
  6121. * pre-linking phase and can be accessed by other directives (see
  6122. * `require` attribute). This allows the directives to communicate with each other and augment
  6123. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  6124. *
  6125. * * `$scope` - Current scope associated with the element
  6126. * * `$element` - Current element
  6127. * * `$attrs` - Current attributes object for the element
  6128. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  6129. * `function([scope], cloneLinkingFn, futureParentElement, slotName)`:
  6130. * * `scope`: (optional) override the scope.
  6131. * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.
  6132. * * `futureParentElement` (optional):
  6133. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  6134. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  6135. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  6136. * and when the `cloneLinkinFn` is passed,
  6137. * as those elements need to created and cloned in a special way when they are defined outside their
  6138. * usual containers (e.g. like `<svg>`).
  6139. * * See also the `directive.templateNamespace` property.
  6140. * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`)
  6141. * then the default translusion is provided.
  6142. * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns
  6143. * `true` if the specified slot contains content (i.e. one or more DOM nodes).
  6144. *
  6145. * The controller can provide the following methods that act as life-cycle hooks:
  6146. * * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and
  6147. * had their bindings initialized (and before the pre &amp; post linking functions for the directives on
  6148. * this element). This is a good place to put initialization code for your controller.
  6149. * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The
  6150. * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an
  6151. * object of the form `{ currentValue: ..., previousValue: ... }`. Use this hook to trigger updates within a component
  6152. * such as cloning the bound value to prevent accidental mutation of the outer value.
  6153. * * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing
  6154. * external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in
  6155. * the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent
  6156. * components will have their `$onDestroy()` hook called before child components.
  6157. * * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link
  6158. * function this hook can be used to set up DOM event handlers and do direct DOM manipulation.
  6159. * Note that child elements that contain `templateUrl` directives will not have been compiled and linked since
  6160. * they are waiting for their template to load asynchronously and their own compilation and linking has been
  6161. * suspended until that occurs.
  6162. *
  6163. *
  6164. * #### `require`
  6165. * Require another directive and inject its controller as the fourth argument to the linking function. The
  6166. * `require` property can be a string, an array or an object:
  6167. * * a **string** containing the name of the directive to pass to the linking function
  6168. * * an **array** containing the names of directives to pass to the linking function. The argument passed to the
  6169. * linking function will be an array of controllers in the same order as the names in the `require` property
  6170. * * an **object** whose property values are the names of the directives to pass to the linking function. The argument
  6171. * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding
  6172. * controllers.
  6173. *
  6174. * If the `require` property is an object and `bindToController` is truthy, then the required controllers are
  6175. * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers
  6176. * have been constructed but before `$onInit` is called.
  6177. * See the {@link $compileProvider#component} helper for an example of how this can be used.
  6178. *
  6179. * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is
  6180. * raised (unless no link function is specified and the required controllers are not being bound to the directive
  6181. * controller, in which case error checking is skipped). The name can be prefixed with:
  6182. *
  6183. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  6184. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  6185. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  6186. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  6187. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  6188. * `null` to the `link` fn if not found.
  6189. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  6190. * `null` to the `link` fn if not found.
  6191. *
  6192. *
  6193. * #### `controllerAs`
  6194. * Identifier name for a reference to the controller in the directive's scope.
  6195. * This allows the controller to be referenced from the directive template. This is especially
  6196. * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
  6197. * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
  6198. * `controllerAs` reference might overwrite a property that already exists on the parent scope.
  6199. *
  6200. *
  6201. * #### `restrict`
  6202. * String of subset of `EACM` which restricts the directive to a specific directive
  6203. * declaration style. If omitted, the defaults (elements and attributes) are used.
  6204. *
  6205. * * `E` - Element name (default): `<my-directive></my-directive>`
  6206. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  6207. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  6208. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  6209. *
  6210. *
  6211. * #### `templateNamespace`
  6212. * String representing the document type used by the markup in the template.
  6213. * AngularJS needs this information as those elements need to be created and cloned
  6214. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  6215. *
  6216. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  6217. * top-level elements such as `<svg>` or `<math>`.
  6218. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  6219. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  6220. *
  6221. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  6222. *
  6223. * #### `template`
  6224. * HTML markup that may:
  6225. * * Replace the contents of the directive's element (default).
  6226. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  6227. * * Wrap the contents of the directive's element (if `transclude` is true).
  6228. *
  6229. * Value may be:
  6230. *
  6231. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  6232. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  6233. * function api below) and returns a string value.
  6234. *
  6235. *
  6236. * #### `templateUrl`
  6237. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  6238. *
  6239. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  6240. * for later when the template has been resolved. In the meantime it will continue to compile and link
  6241. * sibling and parent elements as though this element had not contained any directives.
  6242. *
  6243. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  6244. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  6245. * case when only one deeply nested directive has `templateUrl`.
  6246. *
  6247. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  6248. *
  6249. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  6250. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  6251. * a string value representing the url. In either case, the template URL is passed through {@link
  6252. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  6253. *
  6254. *
  6255. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  6256. * specify what the template should replace. Defaults to `false`.
  6257. *
  6258. * * `true` - the template will replace the directive's element.
  6259. * * `false` - the template will replace the contents of the directive's element.
  6260. *
  6261. * The replacement process migrates all of the attributes / classes from the old element to the new
  6262. * one. See the {@link guide/directive#template-expanding-directive
  6263. * Directives Guide} for an example.
  6264. *
  6265. * There are very few scenarios where element replacement is required for the application function,
  6266. * the main one being reusable custom components that are used within SVG contexts
  6267. * (because SVG doesn't work with custom elements in the DOM tree).
  6268. *
  6269. * #### `transclude`
  6270. * Extract the contents of the element where the directive appears and make it available to the directive.
  6271. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  6272. * {@link $compile#transclusion Transclusion} section below.
  6273. *
  6274. *
  6275. * #### `compile`
  6276. *
  6277. * ```js
  6278. * function compile(tElement, tAttrs, transclude) { ... }
  6279. * ```
  6280. *
  6281. * The compile function deals with transforming the template DOM. Since most directives do not do
  6282. * template transformation, it is not used often. The compile function takes the following arguments:
  6283. *
  6284. * * `tElement` - template element - The element where the directive has been declared. It is
  6285. * safe to do template transformation on the element and child elements only.
  6286. *
  6287. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  6288. * between all directive compile functions.
  6289. *
  6290. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  6291. *
  6292. * <div class="alert alert-warning">
  6293. * **Note:** The template instance and the link instance may be different objects if the template has
  6294. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  6295. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  6296. * should be done in a linking function rather than in a compile function.
  6297. * </div>
  6298. * <div class="alert alert-warning">
  6299. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  6300. * own templates or compile functions. Compiling these directives results in an infinite loop and
  6301. * stack overflow errors.
  6302. *
  6303. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  6304. * a directive's template instead of relying on automatic template compilation via `template` or
  6305. * `templateUrl` declaration or manual compilation inside the compile function.
  6306. * </div>
  6307. *
  6308. * <div class="alert alert-danger">
  6309. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  6310. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  6311. * to the link function instead.
  6312. * </div>
  6313. * A compile function can have a return value which can be either a function or an object.
  6314. *
  6315. * * returning a (post-link) function - is equivalent to registering the linking function via the
  6316. * `link` property of the config object when the compile function is empty.
  6317. *
  6318. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  6319. * control when a linking function should be called during the linking phase. See info about
  6320. * pre-linking and post-linking functions below.
  6321. *
  6322. *
  6323. * #### `link`
  6324. * This property is used only if the `compile` property is not defined.
  6325. *
  6326. * ```js
  6327. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  6328. * ```
  6329. *
  6330. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  6331. * executed after the template has been cloned. This is where most of the directive logic will be
  6332. * put.
  6333. *
  6334. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  6335. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  6336. *
  6337. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  6338. * manipulate the children of the element only in `postLink` function since the children have
  6339. * already been linked.
  6340. *
  6341. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  6342. * between all directive linking functions.
  6343. *
  6344. * * `controller` - the directive's required controller instance(s) - Instances are shared
  6345. * among all directives, which allows the directives to use the controllers as a communication
  6346. * channel. The exact value depends on the directive's `require` property:
  6347. * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
  6348. * * `string`: the controller instance
  6349. * * `array`: array of controller instances
  6350. *
  6351. * If a required controller cannot be found, and it is optional, the instance is `null`,
  6352. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  6353. *
  6354. * Note that you can also require the directive's own controller - it will be made available like
  6355. * any other controller.
  6356. *
  6357. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  6358. * This is the same as the `$transclude`
  6359. * parameter of directive controllers, see there for details.
  6360. * `function([scope], cloneLinkingFn, futureParentElement)`.
  6361. *
  6362. * #### Pre-linking function
  6363. *
  6364. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  6365. * compiler linking function will fail to locate the correct elements for linking.
  6366. *
  6367. * #### Post-linking function
  6368. *
  6369. * Executed after the child elements are linked.
  6370. *
  6371. * Note that child elements that contain `templateUrl` directives will not have been compiled
  6372. * and linked since they are waiting for their template to load asynchronously and their own
  6373. * compilation and linking has been suspended until that occurs.
  6374. *
  6375. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  6376. * for their async templates to be resolved.
  6377. *
  6378. *
  6379. * ### Transclusion
  6380. *
  6381. * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
  6382. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  6383. * scope from where they were taken.
  6384. *
  6385. * Transclusion is used (often with {@link ngTransclude}) to insert the
  6386. * original contents of a directive's element into a specified place in the template of the directive.
  6387. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  6388. * content has access to the properties on the scope from which it was taken, even if the directive
  6389. * has isolated scope.
  6390. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  6391. *
  6392. * This makes it possible for the widget to have private state for its template, while the transcluded
  6393. * content has access to its originating scope.
  6394. *
  6395. * <div class="alert alert-warning">
  6396. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  6397. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  6398. * Testing Transclusion Directives}.
  6399. * </div>
  6400. *
  6401. * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the
  6402. * directive's element, the entire element or multiple parts of the element contents:
  6403. *
  6404. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  6405. * * `'element'` - transclude the whole of the directive's element including any directives on this
  6406. * element that defined at a lower priority than this directive. When used, the `template`
  6407. * property is ignored.
  6408. * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template.
  6409. *
  6410. * **Mult-slot transclusion** is declared by providing an object for the `transclude` property.
  6411. *
  6412. * This object is a map where the keys are the name of the slot to fill and the value is an element selector
  6413. * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`)
  6414. * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc).
  6415. *
  6416. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  6417. *
  6418. * If the element selector is prefixed with a `?` then that slot is optional.
  6419. *
  6420. * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `<my-custom-element>` elements to
  6421. * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive.
  6422. *
  6423. * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements
  6424. * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call
  6425. * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and
  6426. * injectable into the directive's controller.
  6427. *
  6428. *
  6429. * #### Transclusion Functions
  6430. *
  6431. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  6432. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  6433. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  6434. *
  6435. * <div class="alert alert-info">
  6436. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  6437. * ngTransclude will deal with it for us.
  6438. * </div>
  6439. *
  6440. * If you want to manually control the insertion and removal of the transcluded content in your directive
  6441. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  6442. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  6443. *
  6444. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  6445. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  6446. * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
  6447. *
  6448. * <div class="alert alert-info">
  6449. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function
  6450. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  6451. * </div>
  6452. *
  6453. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  6454. * attach function**:
  6455. *
  6456. * ```js
  6457. * var transcludedContent, transclusionScope;
  6458. *
  6459. * $transclude(function(clone, scope) {
  6460. * element.append(clone);
  6461. * transcludedContent = clone;
  6462. * transclusionScope = scope;
  6463. * });
  6464. * ```
  6465. *
  6466. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  6467. * associated transclusion scope:
  6468. *
  6469. * ```js
  6470. * transcludedContent.remove();
  6471. * transclusionScope.$destroy();
  6472. * ```
  6473. *
  6474. * <div class="alert alert-info">
  6475. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  6476. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  6477. * then you are also responsible for calling `$destroy` on the transclusion scope.
  6478. * </div>
  6479. *
  6480. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  6481. * automatically destroy their transcluded clones as necessary so you do not need to worry about this if
  6482. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  6483. *
  6484. *
  6485. * #### Transclusion Scopes
  6486. *
  6487. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  6488. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  6489. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  6490. * was taken.
  6491. *
  6492. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  6493. * like this:
  6494. *
  6495. * ```html
  6496. * <div ng-app>
  6497. * <div isolate>
  6498. * <div transclusion>
  6499. * </div>
  6500. * </div>
  6501. * </div>
  6502. * ```
  6503. *
  6504. * The `$parent` scope hierarchy will look like this:
  6505. *
  6506. ```
  6507. - $rootScope
  6508. - isolate
  6509. - transclusion
  6510. ```
  6511. *
  6512. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  6513. *
  6514. ```
  6515. - $rootScope
  6516. - transclusion
  6517. - isolate
  6518. ```
  6519. *
  6520. *
  6521. * ### Attributes
  6522. *
  6523. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  6524. * `link()` or `compile()` functions. It has a variety of uses.
  6525. *
  6526. * * *Accessing normalized attribute names:* Directives like 'ngBind' can be expressed in many ways:
  6527. * 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. The attributes object allows for normalized access
  6528. * to the attributes.
  6529. *
  6530. * * *Directive inter-communication:* All directives share the same instance of the attributes
  6531. * object which allows the directives to use the attributes object as inter directive
  6532. * communication.
  6533. *
  6534. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  6535. * allowing other directives to read the interpolated value.
  6536. *
  6537. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  6538. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  6539. * the only way to easily get the actual value because during the linking phase the interpolation
  6540. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  6541. *
  6542. * ```js
  6543. * function linkingFn(scope, elm, attrs, ctrl) {
  6544. * // get the attribute value
  6545. * console.log(attrs.ngModel);
  6546. *
  6547. * // change the attribute
  6548. * attrs.$set('ngModel', 'new value');
  6549. *
  6550. * // observe changes to interpolated attribute
  6551. * attrs.$observe('ngModel', function(value) {
  6552. * console.log('ngModel has changed value to ' + value);
  6553. * });
  6554. * }
  6555. * ```
  6556. *
  6557. * ## Example
  6558. *
  6559. * <div class="alert alert-warning">
  6560. * **Note**: Typically directives are registered with `module.directive`. The example below is
  6561. * to illustrate how `$compile` works.
  6562. * </div>
  6563. *
  6564. <example module="compileExample">
  6565. <file name="index.html">
  6566. <script>
  6567. angular.module('compileExample', [], function($compileProvider) {
  6568. // configure new 'compile' directive by passing a directive
  6569. // factory function. The factory function injects the '$compile'
  6570. $compileProvider.directive('compile', function($compile) {
  6571. // directive factory creates a link function
  6572. return function(scope, element, attrs) {
  6573. scope.$watch(
  6574. function(scope) {
  6575. // watch the 'compile' expression for changes
  6576. return scope.$eval(attrs.compile);
  6577. },
  6578. function(value) {
  6579. // when the 'compile' expression changes
  6580. // assign it into the current DOM
  6581. element.html(value);
  6582. // compile the new DOM and link it to the current
  6583. // scope.
  6584. // NOTE: we only compile .childNodes so that
  6585. // we don't get into infinite loop compiling ourselves
  6586. $compile(element.contents())(scope);
  6587. }
  6588. );
  6589. };
  6590. });
  6591. })
  6592. .controller('GreeterController', ['$scope', function($scope) {
  6593. $scope.name = 'Angular';
  6594. $scope.html = 'Hello {{name}}';
  6595. }]);
  6596. </script>
  6597. <div ng-controller="GreeterController">
  6598. <input ng-model="name"> <br/>
  6599. <textarea ng-model="html"></textarea> <br/>
  6600. <div compile="html"></div>
  6601. </div>
  6602. </file>
  6603. <file name="protractor.js" type="protractor">
  6604. it('should auto compile', function() {
  6605. var textarea = $('textarea');
  6606. var output = $('div[compile]');
  6607. // The initial state reads 'Hello Angular'.
  6608. expect(output.getText()).toBe('Hello Angular');
  6609. textarea.clear();
  6610. textarea.sendKeys('{{name}}!');
  6611. expect(output.getText()).toBe('Angular!');
  6612. });
  6613. </file>
  6614. </example>
  6615. *
  6616. *
  6617. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  6618. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  6619. *
  6620. * <div class="alert alert-danger">
  6621. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  6622. * e.g. will not use the right outer scope. Please pass the transclude function as a
  6623. * `parentBoundTranscludeFn` to the link function instead.
  6624. * </div>
  6625. *
  6626. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  6627. * root element(s), not their children)
  6628. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  6629. * (a DOM element/tree) to a scope. Where:
  6630. *
  6631. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  6632. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  6633. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  6634. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  6635. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  6636. *
  6637. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  6638. * * `scope` - is the current scope with which the linking function is working with.
  6639. *
  6640. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  6641. * keys may be used to control linking behavior:
  6642. *
  6643. * * `parentBoundTranscludeFn` - the transclude function made available to
  6644. * directives; if given, it will be passed through to the link functions of
  6645. * directives found in `element` during compilation.
  6646. * * `transcludeControllers` - an object hash with keys that map controller names
  6647. * to a hash with the key `instance`, which maps to the controller instance;
  6648. * if given, it will make the controllers available to directives on the compileNode:
  6649. * ```
  6650. * {
  6651. * parent: {
  6652. * instance: parentControllerInstance
  6653. * }
  6654. * }
  6655. * ```
  6656. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  6657. * the cloned elements; only needed for transcludes that are allowed to contain non html
  6658. * elements (e.g. SVG elements). See also the directive.controller property.
  6659. *
  6660. * Calling the linking function returns the element of the template. It is either the original
  6661. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  6662. *
  6663. * After linking the view is not updated until after a call to $digest which typically is done by
  6664. * Angular automatically.
  6665. *
  6666. * If you need access to the bound view, there are two ways to do it:
  6667. *
  6668. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  6669. * before you send them to the compiler and keep this reference around.
  6670. * ```js
  6671. * var element = $compile('<p>{{total}}</p>')(scope);
  6672. * ```
  6673. *
  6674. * - if on the other hand, you need the element to be cloned, the view reference from the original
  6675. * example would not point to the clone, but rather to the original template that was cloned. In
  6676. * this case, you can access the clone via the cloneAttachFn:
  6677. * ```js
  6678. * var templateElement = angular.element('<p>{{total}}</p>'),
  6679. * scope = ....;
  6680. *
  6681. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  6682. * //attach the clone to DOM document at the right place
  6683. * });
  6684. *
  6685. * //now we have reference to the cloned DOM via `clonedElement`
  6686. * ```
  6687. *
  6688. *
  6689. * For information on how the compiler works, see the
  6690. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  6691. */
  6692. var $compileMinErr = minErr('$compile');
  6693. /**
  6694. * @ngdoc provider
  6695. * @name $compileProvider
  6696. *
  6697. * @description
  6698. */
  6699. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  6700. function $CompileProvider($provide, $$sanitizeUriProvider) {
  6701. var hasDirectives = {},
  6702. Suffix = 'Directive',
  6703. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
  6704. CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
  6705. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  6706. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  6707. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  6708. // The assumption is that future DOM event attribute names will begin with
  6709. // 'on' and be composed of only English letters.
  6710. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  6711. var bindingCache = createMap();
  6712. function parseIsolateBindings(scope, directiveName, isController) {
  6713. var LOCAL_REGEXP = /^\s*([@&<]|=(\*?))(\??)\s*(\w*)\s*$/;
  6714. var bindings = {};
  6715. forEach(scope, function(definition, scopeName) {
  6716. if (definition in bindingCache) {
  6717. bindings[scopeName] = bindingCache[definition];
  6718. return;
  6719. }
  6720. var match = definition.match(LOCAL_REGEXP);
  6721. if (!match) {
  6722. throw $compileMinErr('iscp',
  6723. "Invalid {3} for directive '{0}'." +
  6724. " Definition: {... {1}: '{2}' ...}",
  6725. directiveName, scopeName, definition,
  6726. (isController ? "controller bindings definition" :
  6727. "isolate scope definition"));
  6728. }
  6729. bindings[scopeName] = {
  6730. mode: match[1][0],
  6731. collection: match[2] === '*',
  6732. optional: match[3] === '?',
  6733. attrName: match[4] || scopeName
  6734. };
  6735. if (match[4]) {
  6736. bindingCache[definition] = bindings[scopeName];
  6737. }
  6738. });
  6739. return bindings;
  6740. }
  6741. function parseDirectiveBindings(directive, directiveName) {
  6742. var bindings = {
  6743. isolateScope: null,
  6744. bindToController: null
  6745. };
  6746. if (isObject(directive.scope)) {
  6747. if (directive.bindToController === true) {
  6748. bindings.bindToController = parseIsolateBindings(directive.scope,
  6749. directiveName, true);
  6750. bindings.isolateScope = {};
  6751. } else {
  6752. bindings.isolateScope = parseIsolateBindings(directive.scope,
  6753. directiveName, false);
  6754. }
  6755. }
  6756. if (isObject(directive.bindToController)) {
  6757. bindings.bindToController =
  6758. parseIsolateBindings(directive.bindToController, directiveName, true);
  6759. }
  6760. if (isObject(bindings.bindToController)) {
  6761. var controller = directive.controller;
  6762. var controllerAs = directive.controllerAs;
  6763. if (!controller) {
  6764. // There is no controller, there may or may not be a controllerAs property
  6765. throw $compileMinErr('noctrl',
  6766. "Cannot bind to controller without directive '{0}'s controller.",
  6767. directiveName);
  6768. } else if (!identifierForController(controller, controllerAs)) {
  6769. // There is a controller, but no identifier or controllerAs property
  6770. throw $compileMinErr('noident',
  6771. "Cannot bind to controller without identifier for directive '{0}'.",
  6772. directiveName);
  6773. }
  6774. }
  6775. return bindings;
  6776. }
  6777. function assertValidDirectiveName(name) {
  6778. var letter = name.charAt(0);
  6779. if (!letter || letter !== lowercase(letter)) {
  6780. throw $compileMinErr('baddir', "Directive/Component name '{0}' is invalid. The first character must be a lowercase letter", name);
  6781. }
  6782. if (name !== name.trim()) {
  6783. throw $compileMinErr('baddir',
  6784. "Directive/Component name '{0}' is invalid. The name should not contain leading or trailing whitespaces",
  6785. name);
  6786. }
  6787. }
  6788. /**
  6789. * @ngdoc method
  6790. * @name $compileProvider#directive
  6791. * @kind function
  6792. *
  6793. * @description
  6794. * Register a new directive with the compiler.
  6795. *
  6796. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  6797. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  6798. * names and the values are the factories.
  6799. * @param {Function|Array} directiveFactory An injectable directive factory function. See the
  6800. * {@link guide/directive directive guide} and the {@link $compile compile API} for more info.
  6801. * @returns {ng.$compileProvider} Self for chaining.
  6802. */
  6803. this.directive = function registerDirective(name, directiveFactory) {
  6804. assertNotHasOwnProperty(name, 'directive');
  6805. if (isString(name)) {
  6806. assertValidDirectiveName(name);
  6807. assertArg(directiveFactory, 'directiveFactory');
  6808. if (!hasDirectives.hasOwnProperty(name)) {
  6809. hasDirectives[name] = [];
  6810. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  6811. function($injector, $exceptionHandler) {
  6812. var directives = [];
  6813. forEach(hasDirectives[name], function(directiveFactory, index) {
  6814. try {
  6815. var directive = $injector.invoke(directiveFactory);
  6816. if (isFunction(directive)) {
  6817. directive = { compile: valueFn(directive) };
  6818. } else if (!directive.compile && directive.link) {
  6819. directive.compile = valueFn(directive.link);
  6820. }
  6821. directive.priority = directive.priority || 0;
  6822. directive.index = index;
  6823. directive.name = directive.name || name;
  6824. directive.require = directive.require || (directive.controller && directive.name);
  6825. directive.restrict = directive.restrict || 'EA';
  6826. directive.$$moduleName = directiveFactory.$$moduleName;
  6827. directives.push(directive);
  6828. } catch (e) {
  6829. $exceptionHandler(e);
  6830. }
  6831. });
  6832. return directives;
  6833. }]);
  6834. }
  6835. hasDirectives[name].push(directiveFactory);
  6836. } else {
  6837. forEach(name, reverseParams(registerDirective));
  6838. }
  6839. return this;
  6840. };
  6841. /**
  6842. * @ngdoc method
  6843. * @name $compileProvider#component
  6844. * @module ng
  6845. * @param {string} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`)
  6846. * @param {Object} options Component definition object (a simplified
  6847. * {@link ng.$compile#directive-definition-object directive definition object}),
  6848. * with the following properties (all optional):
  6849. *
  6850. * - `controller` – `{(string|function()=}` – controller constructor function that should be
  6851. * associated with newly created scope or the name of a {@link ng.$compile#-controller-
  6852. * registered controller} if passed as a string. An empty `noop` function by default.
  6853. * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope.
  6854. * If present, the controller will be published to scope under the `controllerAs` name.
  6855. * If not present, this will default to be `$ctrl`.
  6856. * - `template` – `{string=|function()=}` – html template as a string or a function that
  6857. * returns an html template as a string which should be used as the contents of this component.
  6858. * Empty string by default.
  6859. *
  6860. * If `template` is a function, then it is {@link auto.$injector#invoke injected} with
  6861. * the following locals:
  6862. *
  6863. * - `$element` - Current element
  6864. * - `$attrs` - Current attributes object for the element
  6865. *
  6866. * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
  6867. * template that should be used as the contents of this component.
  6868. *
  6869. * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
  6870. * the following locals:
  6871. *
  6872. * - `$element` - Current element
  6873. * - `$attrs` - Current attributes object for the element
  6874. *
  6875. * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties.
  6876. * Component properties are always bound to the component controller and not to the scope.
  6877. * See {@link ng.$compile#-bindtocontroller- `bindToController`}.
  6878. * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled.
  6879. * Disabled by default.
  6880. * - `$...` – additional properties to attach to the directive factory function and the controller
  6881. * constructor function. (This is used by the component router to annotate)
  6882. *
  6883. * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls.
  6884. * @description
  6885. * Register a **component definition** with the compiler. This is a shorthand for registering a special
  6886. * type of directive, which represents a self-contained UI component in your application. Such components
  6887. * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`).
  6888. *
  6889. * Component definitions are very simple and do not require as much configuration as defining general
  6890. * directives. Component definitions usually consist only of a template and a controller backing it.
  6891. *
  6892. * In order to make the definition easier, components enforce best practices like use of `controllerAs`,
  6893. * `bindToController`. They always have **isolate scope** and are restricted to elements.
  6894. *
  6895. * Here are a few examples of how you would usually define components:
  6896. *
  6897. * ```js
  6898. * var myMod = angular.module(...);
  6899. * myMod.component('myComp', {
  6900. * template: '<div>My name is {{$ctrl.name}}</div>',
  6901. * controller: function() {
  6902. * this.name = 'shahar';
  6903. * }
  6904. * });
  6905. *
  6906. * myMod.component('myComp', {
  6907. * template: '<div>My name is {{$ctrl.name}}</div>',
  6908. * bindings: {name: '@'}
  6909. * });
  6910. *
  6911. * myMod.component('myComp', {
  6912. * templateUrl: 'views/my-comp.html',
  6913. * controller: 'MyCtrl',
  6914. * controllerAs: 'ctrl',
  6915. * bindings: {name: '@'}
  6916. * });
  6917. *
  6918. * ```
  6919. * For more examples, and an in-depth guide, see the {@link guide/component component guide}.
  6920. *
  6921. * <br />
  6922. * See also {@link ng.$compileProvider#directive $compileProvider.directive()}.
  6923. */
  6924. this.component = function registerComponent(name, options) {
  6925. var controller = options.controller || noop;
  6926. function factory($injector) {
  6927. function makeInjectable(fn) {
  6928. if (isFunction(fn) || isArray(fn)) {
  6929. return function(tElement, tAttrs) {
  6930. return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
  6931. };
  6932. } else {
  6933. return fn;
  6934. }
  6935. }
  6936. var template = (!options.template && !options.templateUrl ? '' : options.template);
  6937. return {
  6938. controller: controller,
  6939. controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',
  6940. template: makeInjectable(template),
  6941. templateUrl: makeInjectable(options.templateUrl),
  6942. transclude: options.transclude,
  6943. scope: {},
  6944. bindToController: options.bindings || {},
  6945. restrict: 'E',
  6946. require: options.require
  6947. };
  6948. }
  6949. // Copy any annotation properties (starting with $) over to the factory function
  6950. // These could be used by libraries such as the new component router
  6951. forEach(options, function(val, key) {
  6952. if (key.charAt(0) === '$') {
  6953. factory[key] = val;
  6954. controller[key] = val;
  6955. }
  6956. });
  6957. factory.$inject = ['$injector'];
  6958. return this.directive(name, factory);
  6959. };
  6960. /**
  6961. * @ngdoc method
  6962. * @name $compileProvider#aHrefSanitizationWhitelist
  6963. * @kind function
  6964. *
  6965. * @description
  6966. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  6967. * urls during a[href] sanitization.
  6968. *
  6969. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  6970. *
  6971. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  6972. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  6973. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  6974. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  6975. *
  6976. * @param {RegExp=} regexp New regexp to whitelist urls with.
  6977. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  6978. * chaining otherwise.
  6979. */
  6980. this.aHrefSanitizationWhitelist = function(regexp) {
  6981. if (isDefined(regexp)) {
  6982. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  6983. return this;
  6984. } else {
  6985. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  6986. }
  6987. };
  6988. /**
  6989. * @ngdoc method
  6990. * @name $compileProvider#imgSrcSanitizationWhitelist
  6991. * @kind function
  6992. *
  6993. * @description
  6994. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  6995. * urls during img[src] sanitization.
  6996. *
  6997. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  6998. *
  6999. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  7000. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  7001. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  7002. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  7003. *
  7004. * @param {RegExp=} regexp New regexp to whitelist urls with.
  7005. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  7006. * chaining otherwise.
  7007. */
  7008. this.imgSrcSanitizationWhitelist = function(regexp) {
  7009. if (isDefined(regexp)) {
  7010. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  7011. return this;
  7012. } else {
  7013. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  7014. }
  7015. };
  7016. /**
  7017. * @ngdoc method
  7018. * @name $compileProvider#debugInfoEnabled
  7019. *
  7020. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  7021. * current debugInfoEnabled state
  7022. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  7023. *
  7024. * @kind function
  7025. *
  7026. * @description
  7027. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  7028. * binding information and a reference to the current scope on to DOM elements.
  7029. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  7030. * * `ng-binding` CSS class
  7031. * * `$binding` data property containing an array of the binding expressions
  7032. *
  7033. * You may want to disable this in production for a significant performance boost. See
  7034. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  7035. *
  7036. * The default value is true.
  7037. */
  7038. var debugInfoEnabled = true;
  7039. this.debugInfoEnabled = function(enabled) {
  7040. if (isDefined(enabled)) {
  7041. debugInfoEnabled = enabled;
  7042. return this;
  7043. }
  7044. return debugInfoEnabled;
  7045. };
  7046. var TTL = 10;
  7047. /**
  7048. * @ngdoc method
  7049. * @name $compileProvider#onChangesTtl
  7050. * @description
  7051. *
  7052. * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and
  7053. * assuming that the model is unstable.
  7054. *
  7055. * The current default is 10 iterations.
  7056. *
  7057. * In complex applications it's possible that dependencies between `$onChanges` hooks and bindings will result
  7058. * in several iterations of calls to these hooks. However if an application needs more than the default 10
  7059. * iterations to stabilize then you should investigate what is causing the model to continuously change during
  7060. * the `$onChanges` hook execution.
  7061. *
  7062. * Increasing the TTL could have performance implications, so you should not change it without proper justification.
  7063. *
  7064. * @param {number} limit The number of `$onChanges` hook iterations.
  7065. * @returns {number|object} the current limit (or `this` if called as a setter for chaining)
  7066. */
  7067. this.onChangesTtl = function(value) {
  7068. if (arguments.length) {
  7069. TTL = value;
  7070. return this;
  7071. }
  7072. return TTL;
  7073. };
  7074. this.$get = [
  7075. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  7076. '$controller', '$rootScope', '$sce', '$animate', '$$sanitizeUri',
  7077. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  7078. $controller, $rootScope, $sce, $animate, $$sanitizeUri) {
  7079. var SIMPLE_ATTR_NAME = /^\w/;
  7080. var specialAttrHolder = document.createElement('div');
  7081. var onChangesTtl = TTL;
  7082. // The onChanges hooks should all be run together in a single digest
  7083. // When changes occur, the call to trigger their hooks will be added to this queue
  7084. var onChangesQueue;
  7085. // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest
  7086. function flushOnChangesQueue() {
  7087. try {
  7088. if (!(--onChangesTtl)) {
  7089. // We have hit the TTL limit so reset everything
  7090. onChangesQueue = undefined;
  7091. throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\n', TTL);
  7092. }
  7093. // We must run this hook in an apply since the $$postDigest runs outside apply
  7094. $rootScope.$apply(function() {
  7095. for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) {
  7096. onChangesQueue[i]();
  7097. }
  7098. // Reset the queue to trigger a new schedule next time there is a change
  7099. onChangesQueue = undefined;
  7100. });
  7101. } finally {
  7102. onChangesTtl++;
  7103. }
  7104. }
  7105. function Attributes(element, attributesToCopy) {
  7106. if (attributesToCopy) {
  7107. var keys = Object.keys(attributesToCopy);
  7108. var i, l, key;
  7109. for (i = 0, l = keys.length; i < l; i++) {
  7110. key = keys[i];
  7111. this[key] = attributesToCopy[key];
  7112. }
  7113. } else {
  7114. this.$attr = {};
  7115. }
  7116. this.$$element = element;
  7117. }
  7118. Attributes.prototype = {
  7119. /**
  7120. * @ngdoc method
  7121. * @name $compile.directive.Attributes#$normalize
  7122. * @kind function
  7123. *
  7124. * @description
  7125. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  7126. * `data-`) to its normalized, camelCase form.
  7127. *
  7128. * Also there is special case for Moz prefix starting with upper case letter.
  7129. *
  7130. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  7131. *
  7132. * @param {string} name Name to normalize
  7133. */
  7134. $normalize: directiveNormalize,
  7135. /**
  7136. * @ngdoc method
  7137. * @name $compile.directive.Attributes#$addClass
  7138. * @kind function
  7139. *
  7140. * @description
  7141. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  7142. * are enabled then an animation will be triggered for the class addition.
  7143. *
  7144. * @param {string} classVal The className value that will be added to the element
  7145. */
  7146. $addClass: function(classVal) {
  7147. if (classVal && classVal.length > 0) {
  7148. $animate.addClass(this.$$element, classVal);
  7149. }
  7150. },
  7151. /**
  7152. * @ngdoc method
  7153. * @name $compile.directive.Attributes#$removeClass
  7154. * @kind function
  7155. *
  7156. * @description
  7157. * Removes the CSS class value specified by the classVal parameter from the element. If
  7158. * animations are enabled then an animation will be triggered for the class removal.
  7159. *
  7160. * @param {string} classVal The className value that will be removed from the element
  7161. */
  7162. $removeClass: function(classVal) {
  7163. if (classVal && classVal.length > 0) {
  7164. $animate.removeClass(this.$$element, classVal);
  7165. }
  7166. },
  7167. /**
  7168. * @ngdoc method
  7169. * @name $compile.directive.Attributes#$updateClass
  7170. * @kind function
  7171. *
  7172. * @description
  7173. * Adds and removes the appropriate CSS class values to the element based on the difference
  7174. * between the new and old CSS class values (specified as newClasses and oldClasses).
  7175. *
  7176. * @param {string} newClasses The current CSS className value
  7177. * @param {string} oldClasses The former CSS className value
  7178. */
  7179. $updateClass: function(newClasses, oldClasses) {
  7180. var toAdd = tokenDifference(newClasses, oldClasses);
  7181. if (toAdd && toAdd.length) {
  7182. $animate.addClass(this.$$element, toAdd);
  7183. }
  7184. var toRemove = tokenDifference(oldClasses, newClasses);
  7185. if (toRemove && toRemove.length) {
  7186. $animate.removeClass(this.$$element, toRemove);
  7187. }
  7188. },
  7189. /**
  7190. * Set a normalized attribute on the element in a way such that all directives
  7191. * can share the attribute. This function properly handles boolean attributes.
  7192. * @param {string} key Normalized key. (ie ngAttribute)
  7193. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  7194. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  7195. * Defaults to true.
  7196. * @param {string=} attrName Optional none normalized name. Defaults to key.
  7197. */
  7198. $set: function(key, value, writeAttr, attrName) {
  7199. // TODO: decide whether or not to throw an error if "class"
  7200. //is set through this function since it may cause $updateClass to
  7201. //become unstable.
  7202. var node = this.$$element[0],
  7203. booleanKey = getBooleanAttrName(node, key),
  7204. aliasedKey = getAliasedAttrName(key),
  7205. observer = key,
  7206. nodeName;
  7207. if (booleanKey) {
  7208. this.$$element.prop(key, value);
  7209. attrName = booleanKey;
  7210. } else if (aliasedKey) {
  7211. this[aliasedKey] = value;
  7212. observer = aliasedKey;
  7213. }
  7214. this[key] = value;
  7215. // translate normalized key to actual key
  7216. if (attrName) {
  7217. this.$attr[key] = attrName;
  7218. } else {
  7219. attrName = this.$attr[key];
  7220. if (!attrName) {
  7221. this.$attr[key] = attrName = snake_case(key, '-');
  7222. }
  7223. }
  7224. nodeName = nodeName_(this.$$element);
  7225. if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) ||
  7226. (nodeName === 'img' && key === 'src')) {
  7227. // sanitize a[href] and img[src] values
  7228. this[key] = value = $$sanitizeUri(value, key === 'src');
  7229. } else if (nodeName === 'img' && key === 'srcset') {
  7230. // sanitize img[srcset] values
  7231. var result = "";
  7232. // first check if there are spaces because it's not the same pattern
  7233. var trimmedSrcset = trim(value);
  7234. // ( 999x ,| 999w ,| ,|, )
  7235. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  7236. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  7237. // split srcset into tuple of uri and descriptor except for the last item
  7238. var rawUris = trimmedSrcset.split(pattern);
  7239. // for each tuples
  7240. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  7241. for (var i = 0; i < nbrUrisWith2parts; i++) {
  7242. var innerIdx = i * 2;
  7243. // sanitize the uri
  7244. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  7245. // add the descriptor
  7246. result += (" " + trim(rawUris[innerIdx + 1]));
  7247. }
  7248. // split the last item into uri and descriptor
  7249. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  7250. // sanitize the last uri
  7251. result += $$sanitizeUri(trim(lastTuple[0]), true);
  7252. // and add the last descriptor if any
  7253. if (lastTuple.length === 2) {
  7254. result += (" " + trim(lastTuple[1]));
  7255. }
  7256. this[key] = value = result;
  7257. }
  7258. if (writeAttr !== false) {
  7259. if (value === null || isUndefined(value)) {
  7260. this.$$element.removeAttr(attrName);
  7261. } else {
  7262. if (SIMPLE_ATTR_NAME.test(attrName)) {
  7263. this.$$element.attr(attrName, value);
  7264. } else {
  7265. setSpecialAttr(this.$$element[0], attrName, value);
  7266. }
  7267. }
  7268. }
  7269. // fire observers
  7270. var $$observers = this.$$observers;
  7271. $$observers && forEach($$observers[observer], function(fn) {
  7272. try {
  7273. fn(value);
  7274. } catch (e) {
  7275. $exceptionHandler(e);
  7276. }
  7277. });
  7278. },
  7279. /**
  7280. * @ngdoc method
  7281. * @name $compile.directive.Attributes#$observe
  7282. * @kind function
  7283. *
  7284. * @description
  7285. * Observes an interpolated attribute.
  7286. *
  7287. * The observer function will be invoked once during the next `$digest` following
  7288. * compilation. The observer is then invoked whenever the interpolated value
  7289. * changes.
  7290. *
  7291. * @param {string} key Normalized key. (ie ngAttribute) .
  7292. * @param {function(interpolatedValue)} fn Function that will be called whenever
  7293. the interpolated value of the attribute changes.
  7294. * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation
  7295. * guide} for more info.
  7296. * @returns {function()} Returns a deregistration function for this observer.
  7297. */
  7298. $observe: function(key, fn) {
  7299. var attrs = this,
  7300. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  7301. listeners = ($$observers[key] || ($$observers[key] = []));
  7302. listeners.push(fn);
  7303. $rootScope.$evalAsync(function() {
  7304. if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
  7305. // no one registered attribute interpolation function, so lets call it manually
  7306. fn(attrs[key]);
  7307. }
  7308. });
  7309. return function() {
  7310. arrayRemove(listeners, fn);
  7311. };
  7312. }
  7313. };
  7314. function setSpecialAttr(element, attrName, value) {
  7315. // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute`
  7316. // so we have to jump through some hoops to get such an attribute
  7317. // https://github.com/angular/angular.js/pull/13318
  7318. specialAttrHolder.innerHTML = "<span " + attrName + ">";
  7319. var attributes = specialAttrHolder.firstChild.attributes;
  7320. var attribute = attributes[0];
  7321. // We have to remove the attribute from its container element before we can add it to the destination element
  7322. attributes.removeNamedItem(attribute.name);
  7323. attribute.value = value;
  7324. element.attributes.setNamedItem(attribute);
  7325. }
  7326. function safeAddClass($element, className) {
  7327. try {
  7328. $element.addClass(className);
  7329. } catch (e) {
  7330. // ignore, since it means that we are trying to set class on
  7331. // SVG element, where class name is read-only.
  7332. }
  7333. }
  7334. var startSymbol = $interpolate.startSymbol(),
  7335. endSymbol = $interpolate.endSymbol(),
  7336. denormalizeTemplate = (startSymbol == '{{' && endSymbol == '}}')
  7337. ? identity
  7338. : function denormalizeTemplate(template) {
  7339. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  7340. },
  7341. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  7342. var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
  7343. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  7344. var bindings = $element.data('$binding') || [];
  7345. if (isArray(binding)) {
  7346. bindings = bindings.concat(binding);
  7347. } else {
  7348. bindings.push(binding);
  7349. }
  7350. $element.data('$binding', bindings);
  7351. } : noop;
  7352. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  7353. safeAddClass($element, 'ng-binding');
  7354. } : noop;
  7355. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  7356. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  7357. $element.data(dataName, scope);
  7358. } : noop;
  7359. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  7360. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  7361. } : noop;
  7362. compile.$$createComment = function(directiveName, comment) {
  7363. var content = '';
  7364. if (debugInfoEnabled) {
  7365. content = ' ' + (directiveName || '') + ': ' + (comment || '') + ' ';
  7366. }
  7367. return document.createComment(content);
  7368. };
  7369. return compile;
  7370. //================================
  7371. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  7372. previousCompileContext) {
  7373. if (!($compileNodes instanceof jqLite)) {
  7374. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  7375. // modify it.
  7376. $compileNodes = jqLite($compileNodes);
  7377. }
  7378. var NOT_EMPTY = /\S+/;
  7379. // We can not compile top level text elements since text nodes can be merged and we will
  7380. // not be able to attach scope data to them, so we will wrap them in <span>
  7381. for (var i = 0, len = $compileNodes.length; i < len; i++) {
  7382. var domNode = $compileNodes[i];
  7383. if (domNode.nodeType === NODE_TYPE_TEXT && domNode.nodeValue.match(NOT_EMPTY) /* non-empty */) {
  7384. jqLiteWrapNode(domNode, $compileNodes[i] = document.createElement('span'));
  7385. }
  7386. }
  7387. var compositeLinkFn =
  7388. compileNodes($compileNodes, transcludeFn, $compileNodes,
  7389. maxPriority, ignoreDirective, previousCompileContext);
  7390. compile.$$addScopeClass($compileNodes);
  7391. var namespace = null;
  7392. return function publicLinkFn(scope, cloneConnectFn, options) {
  7393. assertArg(scope, 'scope');
  7394. if (previousCompileContext && previousCompileContext.needsNewScope) {
  7395. // A parent directive did a replace and a directive on this element asked
  7396. // for transclusion, which caused us to lose a layer of element on which
  7397. // we could hold the new transclusion scope, so we will create it manually
  7398. // here.
  7399. scope = scope.$parent.$new();
  7400. }
  7401. options = options || {};
  7402. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  7403. transcludeControllers = options.transcludeControllers,
  7404. futureParentElement = options.futureParentElement;
  7405. // When `parentBoundTranscludeFn` is passed, it is a
  7406. // `controllersBoundTransclude` function (it was previously passed
  7407. // as `transclude` to directive.link) so we must unwrap it to get
  7408. // its `boundTranscludeFn`
  7409. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  7410. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  7411. }
  7412. if (!namespace) {
  7413. namespace = detectNamespaceForChildElements(futureParentElement);
  7414. }
  7415. var $linkNode;
  7416. if (namespace !== 'html') {
  7417. // When using a directive with replace:true and templateUrl the $compileNodes
  7418. // (or a child element inside of them)
  7419. // might change, so we need to recreate the namespace adapted compileNodes
  7420. // for call to the link function.
  7421. // Note: This will already clone the nodes...
  7422. $linkNode = jqLite(
  7423. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  7424. );
  7425. } else if (cloneConnectFn) {
  7426. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  7427. // and sometimes changes the structure of the DOM.
  7428. $linkNode = JQLitePrototype.clone.call($compileNodes);
  7429. } else {
  7430. $linkNode = $compileNodes;
  7431. }
  7432. if (transcludeControllers) {
  7433. for (var controllerName in transcludeControllers) {
  7434. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  7435. }
  7436. }
  7437. compile.$$addScopeInfo($linkNode, scope);
  7438. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  7439. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  7440. return $linkNode;
  7441. };
  7442. }
  7443. function detectNamespaceForChildElements(parentElement) {
  7444. // TODO: Make this detect MathML as well...
  7445. var node = parentElement && parentElement[0];
  7446. if (!node) {
  7447. return 'html';
  7448. } else {
  7449. return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html';
  7450. }
  7451. }
  7452. /**
  7453. * Compile function matches each node in nodeList against the directives. Once all directives
  7454. * for a particular node are collected their compile functions are executed. The compile
  7455. * functions return values - the linking functions - are combined into a composite linking
  7456. * function, which is the a linking function for the node.
  7457. *
  7458. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  7459. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  7460. * scope argument is auto-generated to the new child of the transcluded parent scope.
  7461. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  7462. * the rootElement must be set the jqLite collection of the compile root. This is
  7463. * needed so that the jqLite collection items can be replaced with widgets.
  7464. * @param {number=} maxPriority Max directive priority.
  7465. * @returns {Function} A composite linking function of all of the matched directives or null.
  7466. */
  7467. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  7468. previousCompileContext) {
  7469. var linkFns = [],
  7470. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  7471. for (var i = 0; i < nodeList.length; i++) {
  7472. attrs = new Attributes();
  7473. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  7474. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  7475. ignoreDirective);
  7476. nodeLinkFn = (directives.length)
  7477. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  7478. null, [], [], previousCompileContext)
  7479. : null;
  7480. if (nodeLinkFn && nodeLinkFn.scope) {
  7481. compile.$$addScopeClass(attrs.$$element);
  7482. }
  7483. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  7484. !(childNodes = nodeList[i].childNodes) ||
  7485. !childNodes.length)
  7486. ? null
  7487. : compileNodes(childNodes,
  7488. nodeLinkFn ? (
  7489. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  7490. && nodeLinkFn.transclude) : transcludeFn);
  7491. if (nodeLinkFn || childLinkFn) {
  7492. linkFns.push(i, nodeLinkFn, childLinkFn);
  7493. linkFnFound = true;
  7494. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  7495. }
  7496. //use the previous context only for the first element in the virtual group
  7497. previousCompileContext = null;
  7498. }
  7499. // return a linking function if we have found anything, null otherwise
  7500. return linkFnFound ? compositeLinkFn : null;
  7501. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  7502. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  7503. var stableNodeList;
  7504. if (nodeLinkFnFound) {
  7505. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  7506. // offsets don't get screwed up
  7507. var nodeListLength = nodeList.length;
  7508. stableNodeList = new Array(nodeListLength);
  7509. // create a sparse array by only copying the elements which have a linkFn
  7510. for (i = 0; i < linkFns.length; i+=3) {
  7511. idx = linkFns[i];
  7512. stableNodeList[idx] = nodeList[idx];
  7513. }
  7514. } else {
  7515. stableNodeList = nodeList;
  7516. }
  7517. for (i = 0, ii = linkFns.length; i < ii;) {
  7518. node = stableNodeList[linkFns[i++]];
  7519. nodeLinkFn = linkFns[i++];
  7520. childLinkFn = linkFns[i++];
  7521. if (nodeLinkFn) {
  7522. if (nodeLinkFn.scope) {
  7523. childScope = scope.$new();
  7524. compile.$$addScopeInfo(jqLite(node), childScope);
  7525. } else {
  7526. childScope = scope;
  7527. }
  7528. if (nodeLinkFn.transcludeOnThisElement) {
  7529. childBoundTranscludeFn = createBoundTranscludeFn(
  7530. scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  7531. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  7532. childBoundTranscludeFn = parentBoundTranscludeFn;
  7533. } else if (!parentBoundTranscludeFn && transcludeFn) {
  7534. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  7535. } else {
  7536. childBoundTranscludeFn = null;
  7537. }
  7538. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  7539. } else if (childLinkFn) {
  7540. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  7541. }
  7542. }
  7543. }
  7544. }
  7545. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  7546. function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  7547. if (!transcludedScope) {
  7548. transcludedScope = scope.$new(false, containingScope);
  7549. transcludedScope.$$transcluded = true;
  7550. }
  7551. return transcludeFn(transcludedScope, cloneFn, {
  7552. parentBoundTranscludeFn: previousBoundTranscludeFn,
  7553. transcludeControllers: controllers,
  7554. futureParentElement: futureParentElement
  7555. });
  7556. }
  7557. // We need to attach the transclusion slots onto the `boundTranscludeFn`
  7558. // so that they are available inside the `controllersBoundTransclude` function
  7559. var boundSlots = boundTranscludeFn.$$slots = createMap();
  7560. for (var slotName in transcludeFn.$$slots) {
  7561. if (transcludeFn.$$slots[slotName]) {
  7562. boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);
  7563. } else {
  7564. boundSlots[slotName] = null;
  7565. }
  7566. }
  7567. return boundTranscludeFn;
  7568. }
  7569. /**
  7570. * Looks for directives on the given node and adds them to the directive collection which is
  7571. * sorted.
  7572. *
  7573. * @param node Node to search.
  7574. * @param directives An array to which the directives are added to. This array is sorted before
  7575. * the function returns.
  7576. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  7577. * @param {number=} maxPriority Max directive priority.
  7578. */
  7579. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  7580. var nodeType = node.nodeType,
  7581. attrsMap = attrs.$attr,
  7582. match,
  7583. className;
  7584. switch (nodeType) {
  7585. case NODE_TYPE_ELEMENT: /* Element */
  7586. // use the node name: <directive>
  7587. addDirective(directives,
  7588. directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
  7589. // iterate over the attributes
  7590. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  7591. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  7592. var attrStartName = false;
  7593. var attrEndName = false;
  7594. attr = nAttrs[j];
  7595. name = attr.name;
  7596. value = trim(attr.value);
  7597. // support ngAttr attribute binding
  7598. ngAttrName = directiveNormalize(name);
  7599. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  7600. name = name.replace(PREFIX_REGEXP, '')
  7601. .substr(8).replace(/_(.)/g, function(match, letter) {
  7602. return letter.toUpperCase();
  7603. });
  7604. }
  7605. var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);
  7606. if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {
  7607. attrStartName = name;
  7608. attrEndName = name.substr(0, name.length - 5) + 'end';
  7609. name = name.substr(0, name.length - 6);
  7610. }
  7611. nName = directiveNormalize(name.toLowerCase());
  7612. attrsMap[nName] = name;
  7613. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  7614. attrs[nName] = value;
  7615. if (getBooleanAttrName(node, nName)) {
  7616. attrs[nName] = true; // presence means true
  7617. }
  7618. }
  7619. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  7620. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  7621. attrEndName);
  7622. }
  7623. // use class as directive
  7624. className = node.className;
  7625. if (isObject(className)) {
  7626. // Maybe SVGAnimatedString
  7627. className = className.animVal;
  7628. }
  7629. if (isString(className) && className !== '') {
  7630. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  7631. nName = directiveNormalize(match[2]);
  7632. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  7633. attrs[nName] = trim(match[3]);
  7634. }
  7635. className = className.substr(match.index + match[0].length);
  7636. }
  7637. }
  7638. break;
  7639. case NODE_TYPE_TEXT: /* Text Node */
  7640. if (msie === 11) {
  7641. // Workaround for #11781
  7642. while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {
  7643. node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
  7644. node.parentNode.removeChild(node.nextSibling);
  7645. }
  7646. }
  7647. addTextInterpolateDirective(directives, node.nodeValue);
  7648. break;
  7649. case NODE_TYPE_COMMENT: /* Comment */
  7650. try {
  7651. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  7652. if (match) {
  7653. nName = directiveNormalize(match[1]);
  7654. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  7655. attrs[nName] = trim(match[2]);
  7656. }
  7657. }
  7658. } catch (e) {
  7659. // turns out that under some circumstances IE9 throws errors when one attempts to read
  7660. // comment's node value.
  7661. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  7662. }
  7663. break;
  7664. }
  7665. directives.sort(byPriority);
  7666. return directives;
  7667. }
  7668. /**
  7669. * Given a node with an directive-start it collects all of the siblings until it finds
  7670. * directive-end.
  7671. * @param node
  7672. * @param attrStart
  7673. * @param attrEnd
  7674. * @returns {*}
  7675. */
  7676. function groupScan(node, attrStart, attrEnd) {
  7677. var nodes = [];
  7678. var depth = 0;
  7679. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  7680. do {
  7681. if (!node) {
  7682. throw $compileMinErr('uterdir',
  7683. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  7684. attrStart, attrEnd);
  7685. }
  7686. if (node.nodeType == NODE_TYPE_ELEMENT) {
  7687. if (node.hasAttribute(attrStart)) depth++;
  7688. if (node.hasAttribute(attrEnd)) depth--;
  7689. }
  7690. nodes.push(node);
  7691. node = node.nextSibling;
  7692. } while (depth > 0);
  7693. } else {
  7694. nodes.push(node);
  7695. }
  7696. return jqLite(nodes);
  7697. }
  7698. /**
  7699. * Wrapper for linking function which converts normal linking function into a grouped
  7700. * linking function.
  7701. * @param linkFn
  7702. * @param attrStart
  7703. * @param attrEnd
  7704. * @returns {Function}
  7705. */
  7706. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  7707. return function groupedElementsLink(scope, element, attrs, controllers, transcludeFn) {
  7708. element = groupScan(element[0], attrStart, attrEnd);
  7709. return linkFn(scope, element, attrs, controllers, transcludeFn);
  7710. };
  7711. }
  7712. /**
  7713. * A function generator that is used to support both eager and lazy compilation
  7714. * linking function.
  7715. * @param eager
  7716. * @param $compileNodes
  7717. * @param transcludeFn
  7718. * @param maxPriority
  7719. * @param ignoreDirective
  7720. * @param previousCompileContext
  7721. * @returns {Function}
  7722. */
  7723. function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
  7724. var compiled;
  7725. if (eager) {
  7726. return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  7727. }
  7728. return function lazyCompilation() {
  7729. if (!compiled) {
  7730. compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  7731. // Null out all of these references in order to make them eligible for garbage collection
  7732. // since this is a potentially long lived closure
  7733. $compileNodes = transcludeFn = previousCompileContext = null;
  7734. }
  7735. return compiled.apply(this, arguments);
  7736. };
  7737. }
  7738. /**
  7739. * Once the directives have been collected, their compile functions are executed. This method
  7740. * is responsible for inlining directive templates as well as terminating the application
  7741. * of the directives if the terminal directive has been reached.
  7742. *
  7743. * @param {Array} directives Array of collected directives to execute their compile function.
  7744. * this needs to be pre-sorted by priority order.
  7745. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  7746. * @param {Object} templateAttrs The shared attribute function
  7747. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  7748. * scope argument is auto-generated to the new
  7749. * child of the transcluded parent scope.
  7750. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  7751. * argument has the root jqLite array so that we can replace nodes
  7752. * on it.
  7753. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  7754. * compiling the transclusion.
  7755. * @param {Array.<Function>} preLinkFns
  7756. * @param {Array.<Function>} postLinkFns
  7757. * @param {Object} previousCompileContext Context used for previous compilation of the current
  7758. * node
  7759. * @returns {Function} linkFn
  7760. */
  7761. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  7762. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  7763. previousCompileContext) {
  7764. previousCompileContext = previousCompileContext || {};
  7765. var terminalPriority = -Number.MAX_VALUE,
  7766. newScopeDirective = previousCompileContext.newScopeDirective,
  7767. controllerDirectives = previousCompileContext.controllerDirectives,
  7768. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  7769. templateDirective = previousCompileContext.templateDirective,
  7770. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  7771. hasTranscludeDirective = false,
  7772. hasTemplate = false,
  7773. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  7774. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  7775. directive,
  7776. directiveName,
  7777. $template,
  7778. replaceDirective = originalReplaceDirective,
  7779. childTranscludeFn = transcludeFn,
  7780. linkFn,
  7781. didScanForMultipleTransclusion = false,
  7782. mightHaveMultipleTransclusionError = false,
  7783. directiveValue;
  7784. // executes all directives on the current element
  7785. for (var i = 0, ii = directives.length; i < ii; i++) {
  7786. directive = directives[i];
  7787. var attrStart = directive.$$start;
  7788. var attrEnd = directive.$$end;
  7789. // collect multiblock sections
  7790. if (attrStart) {
  7791. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  7792. }
  7793. $template = undefined;
  7794. if (terminalPriority > directive.priority) {
  7795. break; // prevent further processing of directives
  7796. }
  7797. if (directiveValue = directive.scope) {
  7798. // skip the check for directives with async templates, we'll check the derived sync
  7799. // directive when the template arrives
  7800. if (!directive.templateUrl) {
  7801. if (isObject(directiveValue)) {
  7802. // This directive is trying to add an isolated scope.
  7803. // Check that there is no scope of any kind already
  7804. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  7805. directive, $compileNode);
  7806. newIsolateScopeDirective = directive;
  7807. } else {
  7808. // This directive is trying to add a child scope.
  7809. // Check that there is no isolated scope already
  7810. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  7811. $compileNode);
  7812. }
  7813. }
  7814. newScopeDirective = newScopeDirective || directive;
  7815. }
  7816. directiveName = directive.name;
  7817. // If we encounter a condition that can result in transclusion on the directive,
  7818. // then scan ahead in the remaining directives for others that may cause a multiple
  7819. // transclusion error to be thrown during the compilation process. If a matching directive
  7820. // is found, then we know that when we encounter a transcluded directive, we need to eagerly
  7821. // compile the `transclude` function rather than doing it lazily in order to throw
  7822. // exceptions at the correct time
  7823. if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))
  7824. || (directive.transclude && !directive.$$tlb))) {
  7825. var candidateDirective;
  7826. for (var scanningIndex = i + 1; candidateDirective = directives[scanningIndex++];) {
  7827. if ((candidateDirective.transclude && !candidateDirective.$$tlb)
  7828. || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {
  7829. mightHaveMultipleTransclusionError = true;
  7830. break;
  7831. }
  7832. }
  7833. didScanForMultipleTransclusion = true;
  7834. }
  7835. if (!directive.templateUrl && directive.controller) {
  7836. directiveValue = directive.controller;
  7837. controllerDirectives = controllerDirectives || createMap();
  7838. assertNoDuplicate("'" + directiveName + "' controller",
  7839. controllerDirectives[directiveName], directive, $compileNode);
  7840. controllerDirectives[directiveName] = directive;
  7841. }
  7842. if (directiveValue = directive.transclude) {
  7843. hasTranscludeDirective = true;
  7844. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  7845. // This option should only be used by directives that know how to safely handle element transclusion,
  7846. // where the transcluded nodes are added or replaced after linking.
  7847. if (!directive.$$tlb) {
  7848. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  7849. nonTlbTranscludeDirective = directive;
  7850. }
  7851. if (directiveValue == 'element') {
  7852. hasElementTranscludeDirective = true;
  7853. terminalPriority = directive.priority;
  7854. $template = $compileNode;
  7855. $compileNode = templateAttrs.$$element =
  7856. jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName]));
  7857. compileNode = $compileNode[0];
  7858. replaceWith(jqCollection, sliceArgs($template), compileNode);
  7859. // Support: Chrome < 50
  7860. // https://github.com/angular/angular.js/issues/14041
  7861. // In the versions of V8 prior to Chrome 50, the document fragment that is created
  7862. // in the `replaceWith` function is improperly garbage collected despite still
  7863. // being referenced by the `parentNode` property of all of the child nodes. By adding
  7864. // a reference to the fragment via a different property, we can avoid that incorrect
  7865. // behavior.
  7866. // TODO: remove this line after Chrome 50 has been released
  7867. $template[0].$$parentNode = $template[0].parentNode;
  7868. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
  7869. replaceDirective && replaceDirective.name, {
  7870. // Don't pass in:
  7871. // - controllerDirectives - otherwise we'll create duplicates controllers
  7872. // - newIsolateScopeDirective or templateDirective - combining templates with
  7873. // element transclusion doesn't make sense.
  7874. //
  7875. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  7876. // on the same element more than once.
  7877. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  7878. });
  7879. } else {
  7880. var slots = createMap();
  7881. $template = jqLite(jqLiteClone(compileNode)).contents();
  7882. if (isObject(directiveValue)) {
  7883. // We have transclusion slots,
  7884. // collect them up, compile them and store their transclusion functions
  7885. $template = [];
  7886. var slotMap = createMap();
  7887. var filledSlots = createMap();
  7888. // Parse the element selectors
  7889. forEach(directiveValue, function(elementSelector, slotName) {
  7890. // If an element selector starts with a ? then it is optional
  7891. var optional = (elementSelector.charAt(0) === '?');
  7892. elementSelector = optional ? elementSelector.substring(1) : elementSelector;
  7893. slotMap[elementSelector] = slotName;
  7894. // We explicitly assign `null` since this implies that a slot was defined but not filled.
  7895. // Later when calling boundTransclusion functions with a slot name we only error if the
  7896. // slot is `undefined`
  7897. slots[slotName] = null;
  7898. // filledSlots contains `true` for all slots that are either optional or have been
  7899. // filled. This is used to check that we have not missed any required slots
  7900. filledSlots[slotName] = optional;
  7901. });
  7902. // Add the matching elements into their slot
  7903. forEach($compileNode.contents(), function(node) {
  7904. var slotName = slotMap[directiveNormalize(nodeName_(node))];
  7905. if (slotName) {
  7906. filledSlots[slotName] = true;
  7907. slots[slotName] = slots[slotName] || [];
  7908. slots[slotName].push(node);
  7909. } else {
  7910. $template.push(node);
  7911. }
  7912. });
  7913. // Check for required slots that were not filled
  7914. forEach(filledSlots, function(filled, slotName) {
  7915. if (!filled) {
  7916. throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
  7917. }
  7918. });
  7919. for (var slotName in slots) {
  7920. if (slots[slotName]) {
  7921. // Only define a transclusion function if the slot was filled
  7922. slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn);
  7923. }
  7924. }
  7925. }
  7926. $compileNode.empty(); // clear contents
  7927. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
  7928. undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
  7929. childTranscludeFn.$$slots = slots;
  7930. }
  7931. }
  7932. if (directive.template) {
  7933. hasTemplate = true;
  7934. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  7935. templateDirective = directive;
  7936. directiveValue = (isFunction(directive.template))
  7937. ? directive.template($compileNode, templateAttrs)
  7938. : directive.template;
  7939. directiveValue = denormalizeTemplate(directiveValue);
  7940. if (directive.replace) {
  7941. replaceDirective = directive;
  7942. if (jqLiteIsTextNode(directiveValue)) {
  7943. $template = [];
  7944. } else {
  7945. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  7946. }
  7947. compileNode = $template[0];
  7948. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7949. throw $compileMinErr('tplrt',
  7950. "Template for directive '{0}' must have exactly one root element. {1}",
  7951. directiveName, '');
  7952. }
  7953. replaceWith(jqCollection, $compileNode, compileNode);
  7954. var newTemplateAttrs = {$attr: {}};
  7955. // combine directives from the original node and from the template:
  7956. // - take the array of directives for this element
  7957. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  7958. // - collect directives from the template and sort them by priority
  7959. // - combine directives as: processed + template + unprocessed
  7960. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  7961. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  7962. if (newIsolateScopeDirective || newScopeDirective) {
  7963. // The original directive caused the current element to be replaced but this element
  7964. // also needs to have a new scope, so we need to tell the template directives
  7965. // that they would need to get their scope from further up, if they require transclusion
  7966. markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
  7967. }
  7968. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  7969. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  7970. ii = directives.length;
  7971. } else {
  7972. $compileNode.html(directiveValue);
  7973. }
  7974. }
  7975. if (directive.templateUrl) {
  7976. hasTemplate = true;
  7977. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  7978. templateDirective = directive;
  7979. if (directive.replace) {
  7980. replaceDirective = directive;
  7981. }
  7982. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  7983. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  7984. controllerDirectives: controllerDirectives,
  7985. newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
  7986. newIsolateScopeDirective: newIsolateScopeDirective,
  7987. templateDirective: templateDirective,
  7988. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  7989. });
  7990. ii = directives.length;
  7991. } else if (directive.compile) {
  7992. try {
  7993. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  7994. if (isFunction(linkFn)) {
  7995. addLinkFns(null, linkFn, attrStart, attrEnd);
  7996. } else if (linkFn) {
  7997. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  7998. }
  7999. } catch (e) {
  8000. $exceptionHandler(e, startingTag($compileNode));
  8001. }
  8002. }
  8003. if (directive.terminal) {
  8004. nodeLinkFn.terminal = true;
  8005. terminalPriority = Math.max(terminalPriority, directive.priority);
  8006. }
  8007. }
  8008. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  8009. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  8010. nodeLinkFn.templateOnThisElement = hasTemplate;
  8011. nodeLinkFn.transclude = childTranscludeFn;
  8012. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  8013. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  8014. return nodeLinkFn;
  8015. ////////////////////
  8016. function addLinkFns(pre, post, attrStart, attrEnd) {
  8017. if (pre) {
  8018. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  8019. pre.require = directive.require;
  8020. pre.directiveName = directiveName;
  8021. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  8022. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  8023. }
  8024. preLinkFns.push(pre);
  8025. }
  8026. if (post) {
  8027. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  8028. post.require = directive.require;
  8029. post.directiveName = directiveName;
  8030. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  8031. post = cloneAndAnnotateFn(post, {isolateScope: true});
  8032. }
  8033. postLinkFns.push(post);
  8034. }
  8035. }
  8036. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  8037. var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
  8038. attrs, removeScopeBindingWatches, removeControllerBindingWatches;
  8039. if (compileNode === linkNode) {
  8040. attrs = templateAttrs;
  8041. $element = templateAttrs.$$element;
  8042. } else {
  8043. $element = jqLite(linkNode);
  8044. attrs = new Attributes($element, templateAttrs);
  8045. }
  8046. controllerScope = scope;
  8047. if (newIsolateScopeDirective) {
  8048. isolateScope = scope.$new(true);
  8049. } else if (newScopeDirective) {
  8050. controllerScope = scope.$parent;
  8051. }
  8052. if (boundTranscludeFn) {
  8053. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  8054. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  8055. transcludeFn = controllersBoundTransclude;
  8056. transcludeFn.$$boundTransclude = boundTranscludeFn;
  8057. // expose the slots on the `$transclude` function
  8058. transcludeFn.isSlotFilled = function(slotName) {
  8059. return !!boundTranscludeFn.$$slots[slotName];
  8060. };
  8061. }
  8062. if (controllerDirectives) {
  8063. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective);
  8064. }
  8065. if (newIsolateScopeDirective) {
  8066. // Initialize isolate scope bindings for new isolate scope directive.
  8067. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  8068. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  8069. compile.$$addScopeClass($element, true);
  8070. isolateScope.$$isolateBindings =
  8071. newIsolateScopeDirective.$$isolateBindings;
  8072. removeScopeBindingWatches = initializeDirectiveBindings(scope, attrs, isolateScope,
  8073. isolateScope.$$isolateBindings,
  8074. newIsolateScopeDirective);
  8075. if (removeScopeBindingWatches) {
  8076. isolateScope.$on('$destroy', removeScopeBindingWatches);
  8077. }
  8078. }
  8079. // Initialize bindToController bindings
  8080. for (var name in elementControllers) {
  8081. var controllerDirective = controllerDirectives[name];
  8082. var controller = elementControllers[name];
  8083. var bindings = controllerDirective.$$bindings.bindToController;
  8084. if (controller.identifier && bindings) {
  8085. removeControllerBindingWatches =
  8086. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8087. }
  8088. var controllerResult = controller();
  8089. if (controllerResult !== controller.instance) {
  8090. // If the controller constructor has a return value, overwrite the instance
  8091. // from setupControllers
  8092. controller.instance = controllerResult;
  8093. $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
  8094. removeControllerBindingWatches && removeControllerBindingWatches();
  8095. removeControllerBindingWatches =
  8096. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8097. }
  8098. }
  8099. // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy
  8100. forEach(controllerDirectives, function(controllerDirective, name) {
  8101. var require = controllerDirective.require;
  8102. if (controllerDirective.bindToController && !isArray(require) && isObject(require)) {
  8103. extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers));
  8104. }
  8105. });
  8106. // Handle the init and destroy lifecycle hooks on all controllers that have them
  8107. forEach(elementControllers, function(controller) {
  8108. var controllerInstance = controller.instance;
  8109. if (isFunction(controllerInstance.$onInit)) {
  8110. controllerInstance.$onInit();
  8111. }
  8112. if (isFunction(controllerInstance.$onDestroy)) {
  8113. controllerScope.$on('$destroy', function callOnDestroyHook() {
  8114. controllerInstance.$onDestroy();
  8115. });
  8116. }
  8117. });
  8118. // PRELINKING
  8119. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  8120. linkFn = preLinkFns[i];
  8121. invokeLinkFn(linkFn,
  8122. linkFn.isolateScope ? isolateScope : scope,
  8123. $element,
  8124. attrs,
  8125. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  8126. transcludeFn
  8127. );
  8128. }
  8129. // RECURSION
  8130. // We only pass the isolate scope, if the isolate directive has a template,
  8131. // otherwise the child elements do not belong to the isolate directive.
  8132. var scopeToChild = scope;
  8133. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  8134. scopeToChild = isolateScope;
  8135. }
  8136. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  8137. // POSTLINKING
  8138. for (i = postLinkFns.length - 1; i >= 0; i--) {
  8139. linkFn = postLinkFns[i];
  8140. invokeLinkFn(linkFn,
  8141. linkFn.isolateScope ? isolateScope : scope,
  8142. $element,
  8143. attrs,
  8144. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  8145. transcludeFn
  8146. );
  8147. }
  8148. // Trigger $postLink lifecycle hooks
  8149. forEach(elementControllers, function(controller) {
  8150. var controllerInstance = controller.instance;
  8151. if (isFunction(controllerInstance.$postLink)) {
  8152. controllerInstance.$postLink();
  8153. }
  8154. });
  8155. // This is the function that is injected as `$transclude`.
  8156. // Note: all arguments are optional!
  8157. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
  8158. var transcludeControllers;
  8159. // No scope passed in:
  8160. if (!isScope(scope)) {
  8161. slotName = futureParentElement;
  8162. futureParentElement = cloneAttachFn;
  8163. cloneAttachFn = scope;
  8164. scope = undefined;
  8165. }
  8166. if (hasElementTranscludeDirective) {
  8167. transcludeControllers = elementControllers;
  8168. }
  8169. if (!futureParentElement) {
  8170. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  8171. }
  8172. if (slotName) {
  8173. // slotTranscludeFn can be one of three things:
  8174. // * a transclude function - a filled slot
  8175. // * `null` - an optional slot that was not filled
  8176. // * `undefined` - a slot that was not declared (i.e. invalid)
  8177. var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];
  8178. if (slotTranscludeFn) {
  8179. return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  8180. } else if (isUndefined(slotTranscludeFn)) {
  8181. throw $compileMinErr('noslot',
  8182. 'No parent directive that requires a transclusion with slot name "{0}". ' +
  8183. 'Element: {1}',
  8184. slotName, startingTag($element));
  8185. }
  8186. } else {
  8187. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  8188. }
  8189. }
  8190. }
  8191. }
  8192. function getControllers(directiveName, require, $element, elementControllers) {
  8193. var value;
  8194. if (isString(require)) {
  8195. var match = require.match(REQUIRE_PREFIX_REGEXP);
  8196. var name = require.substring(match[0].length);
  8197. var inheritType = match[1] || match[3];
  8198. var optional = match[2] === '?';
  8199. //If only parents then start at the parent element
  8200. if (inheritType === '^^') {
  8201. $element = $element.parent();
  8202. //Otherwise attempt getting the controller from elementControllers in case
  8203. //the element is transcluded (and has no data) and to avoid .data if possible
  8204. } else {
  8205. value = elementControllers && elementControllers[name];
  8206. value = value && value.instance;
  8207. }
  8208. if (!value) {
  8209. var dataName = '$' + name + 'Controller';
  8210. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  8211. }
  8212. if (!value && !optional) {
  8213. throw $compileMinErr('ctreq',
  8214. "Controller '{0}', required by directive '{1}', can't be found!",
  8215. name, directiveName);
  8216. }
  8217. } else if (isArray(require)) {
  8218. value = [];
  8219. for (var i = 0, ii = require.length; i < ii; i++) {
  8220. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  8221. }
  8222. } else if (isObject(require)) {
  8223. value = {};
  8224. forEach(require, function(controller, property) {
  8225. value[property] = getControllers(directiveName, controller, $element, elementControllers);
  8226. });
  8227. }
  8228. return value || null;
  8229. }
  8230. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective) {
  8231. var elementControllers = createMap();
  8232. for (var controllerKey in controllerDirectives) {
  8233. var directive = controllerDirectives[controllerKey];
  8234. var locals = {
  8235. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  8236. $element: $element,
  8237. $attrs: attrs,
  8238. $transclude: transcludeFn
  8239. };
  8240. var controller = directive.controller;
  8241. if (controller == '@') {
  8242. controller = attrs[directive.name];
  8243. }
  8244. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  8245. // For directives with element transclusion the element is a comment.
  8246. // In this case .data will not attach any data.
  8247. // Instead, we save the controllers for the element in a local hash and attach to .data
  8248. // later, once we have the actual element.
  8249. elementControllers[directive.name] = controllerInstance;
  8250. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  8251. }
  8252. return elementControllers;
  8253. }
  8254. // Depending upon the context in which a directive finds itself it might need to have a new isolated
  8255. // or child scope created. For instance:
  8256. // * if the directive has been pulled into a template because another directive with a higher priority
  8257. // asked for element transclusion
  8258. // * if the directive itself asks for transclusion but it is at the root of a template and the original
  8259. // element was replaced. See https://github.com/angular/angular.js/issues/12936
  8260. function markDirectiveScope(directives, isolateScope, newScope) {
  8261. for (var j = 0, jj = directives.length; j < jj; j++) {
  8262. directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
  8263. }
  8264. }
  8265. /**
  8266. * looks up the directive and decorates it with exception handling and proper parameters. We
  8267. * call this the boundDirective.
  8268. *
  8269. * @param {string} name name of the directive to look up.
  8270. * @param {string} location The directive must be found in specific format.
  8271. * String containing any of theses characters:
  8272. *
  8273. * * `E`: element name
  8274. * * `A': attribute
  8275. * * `C`: class
  8276. * * `M`: comment
  8277. * @returns {boolean} true if directive was added.
  8278. */
  8279. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  8280. endAttrName) {
  8281. if (name === ignoreDirective) return null;
  8282. var match = null;
  8283. if (hasDirectives.hasOwnProperty(name)) {
  8284. for (var directive, directives = $injector.get(name + Suffix),
  8285. i = 0, ii = directives.length; i < ii; i++) {
  8286. try {
  8287. directive = directives[i];
  8288. if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
  8289. directive.restrict.indexOf(location) != -1) {
  8290. if (startAttrName) {
  8291. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  8292. }
  8293. if (!directive.$$bindings) {
  8294. var bindings = directive.$$bindings =
  8295. parseDirectiveBindings(directive, directive.name);
  8296. if (isObject(bindings.isolateScope)) {
  8297. directive.$$isolateBindings = bindings.isolateScope;
  8298. }
  8299. }
  8300. tDirectives.push(directive);
  8301. match = directive;
  8302. }
  8303. } catch (e) { $exceptionHandler(e); }
  8304. }
  8305. }
  8306. return match;
  8307. }
  8308. /**
  8309. * looks up the directive and returns true if it is a multi-element directive,
  8310. * and therefore requires DOM nodes between -start and -end markers to be grouped
  8311. * together.
  8312. *
  8313. * @param {string} name name of the directive to look up.
  8314. * @returns true if directive was registered as multi-element.
  8315. */
  8316. function directiveIsMultiElement(name) {
  8317. if (hasDirectives.hasOwnProperty(name)) {
  8318. for (var directive, directives = $injector.get(name + Suffix),
  8319. i = 0, ii = directives.length; i < ii; i++) {
  8320. directive = directives[i];
  8321. if (directive.multiElement) {
  8322. return true;
  8323. }
  8324. }
  8325. }
  8326. return false;
  8327. }
  8328. /**
  8329. * When the element is replaced with HTML template then the new attributes
  8330. * on the template need to be merged with the existing attributes in the DOM.
  8331. * The desired effect is to have both of the attributes present.
  8332. *
  8333. * @param {object} dst destination attributes (original DOM)
  8334. * @param {object} src source attributes (from the directive template)
  8335. */
  8336. function mergeTemplateAttributes(dst, src) {
  8337. var srcAttr = src.$attr,
  8338. dstAttr = dst.$attr,
  8339. $element = dst.$$element;
  8340. // reapply the old attributes to the new element
  8341. forEach(dst, function(value, key) {
  8342. if (key.charAt(0) != '$') {
  8343. if (src[key] && src[key] !== value) {
  8344. value += (key === 'style' ? ';' : ' ') + src[key];
  8345. }
  8346. dst.$set(key, value, true, srcAttr[key]);
  8347. }
  8348. });
  8349. // copy the new attributes on the old attrs object
  8350. forEach(src, function(value, key) {
  8351. if (key == 'class') {
  8352. safeAddClass($element, value);
  8353. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  8354. } else if (key == 'style') {
  8355. $element.attr('style', $element.attr('style') + ';' + value);
  8356. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  8357. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  8358. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  8359. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  8360. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  8361. dst[key] = value;
  8362. dstAttr[key] = srcAttr[key];
  8363. }
  8364. });
  8365. }
  8366. function compileTemplateUrl(directives, $compileNode, tAttrs,
  8367. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  8368. var linkQueue = [],
  8369. afterTemplateNodeLinkFn,
  8370. afterTemplateChildLinkFn,
  8371. beforeTemplateCompileNode = $compileNode[0],
  8372. origAsyncDirective = directives.shift(),
  8373. derivedSyncDirective = inherit(origAsyncDirective, {
  8374. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  8375. }),
  8376. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  8377. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  8378. : origAsyncDirective.templateUrl,
  8379. templateNamespace = origAsyncDirective.templateNamespace;
  8380. $compileNode.empty();
  8381. $templateRequest(templateUrl)
  8382. .then(function(content) {
  8383. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  8384. content = denormalizeTemplate(content);
  8385. if (origAsyncDirective.replace) {
  8386. if (jqLiteIsTextNode(content)) {
  8387. $template = [];
  8388. } else {
  8389. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  8390. }
  8391. compileNode = $template[0];
  8392. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  8393. throw $compileMinErr('tplrt',
  8394. "Template for directive '{0}' must have exactly one root element. {1}",
  8395. origAsyncDirective.name, templateUrl);
  8396. }
  8397. tempTemplateAttrs = {$attr: {}};
  8398. replaceWith($rootElement, $compileNode, compileNode);
  8399. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  8400. if (isObject(origAsyncDirective.scope)) {
  8401. // the original directive that caused the template to be loaded async required
  8402. // an isolate scope
  8403. markDirectiveScope(templateDirectives, true);
  8404. }
  8405. directives = templateDirectives.concat(directives);
  8406. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  8407. } else {
  8408. compileNode = beforeTemplateCompileNode;
  8409. $compileNode.html(content);
  8410. }
  8411. directives.unshift(derivedSyncDirective);
  8412. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  8413. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  8414. previousCompileContext);
  8415. forEach($rootElement, function(node, i) {
  8416. if (node == compileNode) {
  8417. $rootElement[i] = $compileNode[0];
  8418. }
  8419. });
  8420. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  8421. while (linkQueue.length) {
  8422. var scope = linkQueue.shift(),
  8423. beforeTemplateLinkNode = linkQueue.shift(),
  8424. linkRootElement = linkQueue.shift(),
  8425. boundTranscludeFn = linkQueue.shift(),
  8426. linkNode = $compileNode[0];
  8427. if (scope.$$destroyed) continue;
  8428. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  8429. var oldClasses = beforeTemplateLinkNode.className;
  8430. if (!(previousCompileContext.hasElementTranscludeDirective &&
  8431. origAsyncDirective.replace)) {
  8432. // it was cloned therefore we have to clone as well.
  8433. linkNode = jqLiteClone(compileNode);
  8434. }
  8435. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  8436. // Copy in CSS classes from original node
  8437. safeAddClass(jqLite(linkNode), oldClasses);
  8438. }
  8439. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  8440. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  8441. } else {
  8442. childBoundTranscludeFn = boundTranscludeFn;
  8443. }
  8444. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  8445. childBoundTranscludeFn);
  8446. }
  8447. linkQueue = null;
  8448. });
  8449. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  8450. var childBoundTranscludeFn = boundTranscludeFn;
  8451. if (scope.$$destroyed) return;
  8452. if (linkQueue) {
  8453. linkQueue.push(scope,
  8454. node,
  8455. rootElement,
  8456. childBoundTranscludeFn);
  8457. } else {
  8458. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  8459. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  8460. }
  8461. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  8462. }
  8463. };
  8464. }
  8465. /**
  8466. * Sorting function for bound directives.
  8467. */
  8468. function byPriority(a, b) {
  8469. var diff = b.priority - a.priority;
  8470. if (diff !== 0) return diff;
  8471. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  8472. return a.index - b.index;
  8473. }
  8474. function assertNoDuplicate(what, previousDirective, directive, element) {
  8475. function wrapModuleNameIfDefined(moduleName) {
  8476. return moduleName ?
  8477. (' (module: ' + moduleName + ')') :
  8478. '';
  8479. }
  8480. if (previousDirective) {
  8481. throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
  8482. previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
  8483. directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
  8484. }
  8485. }
  8486. function addTextInterpolateDirective(directives, text) {
  8487. var interpolateFn = $interpolate(text, true);
  8488. if (interpolateFn) {
  8489. directives.push({
  8490. priority: 0,
  8491. compile: function textInterpolateCompileFn(templateNode) {
  8492. var templateNodeParent = templateNode.parent(),
  8493. hasCompileParent = !!templateNodeParent.length;
  8494. // When transcluding a template that has bindings in the root
  8495. // we don't have a parent and thus need to add the class during linking fn.
  8496. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  8497. return function textInterpolateLinkFn(scope, node) {
  8498. var parent = node.parent();
  8499. if (!hasCompileParent) compile.$$addBindingClass(parent);
  8500. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  8501. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  8502. node[0].nodeValue = value;
  8503. });
  8504. };
  8505. }
  8506. });
  8507. }
  8508. }
  8509. function wrapTemplate(type, template) {
  8510. type = lowercase(type || 'html');
  8511. switch (type) {
  8512. case 'svg':
  8513. case 'math':
  8514. var wrapper = document.createElement('div');
  8515. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  8516. return wrapper.childNodes[0].childNodes;
  8517. default:
  8518. return template;
  8519. }
  8520. }
  8521. function getTrustedContext(node, attrNormalizedName) {
  8522. if (attrNormalizedName == "srcdoc") {
  8523. return $sce.HTML;
  8524. }
  8525. var tag = nodeName_(node);
  8526. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  8527. if (attrNormalizedName == "xlinkHref" ||
  8528. (tag == "form" && attrNormalizedName == "action") ||
  8529. (tag != "img" && (attrNormalizedName == "src" ||
  8530. attrNormalizedName == "ngSrc"))) {
  8531. return $sce.RESOURCE_URL;
  8532. }
  8533. }
  8534. function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  8535. var trustedContext = getTrustedContext(node, name);
  8536. allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
  8537. var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
  8538. // no interpolation found -> ignore
  8539. if (!interpolateFn) return;
  8540. if (name === "multiple" && nodeName_(node) === "select") {
  8541. throw $compileMinErr("selmulti",
  8542. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  8543. startingTag(node));
  8544. }
  8545. directives.push({
  8546. priority: 100,
  8547. compile: function() {
  8548. return {
  8549. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  8550. var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
  8551. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  8552. throw $compileMinErr('nodomevents',
  8553. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  8554. "ng- versions (such as ng-click instead of onclick) instead.");
  8555. }
  8556. // If the attribute has changed since last $interpolate()ed
  8557. var newValue = attr[name];
  8558. if (newValue !== value) {
  8559. // we need to interpolate again since the attribute value has been updated
  8560. // (e.g. by another directive's compile function)
  8561. // ensure unset/empty values make interpolateFn falsy
  8562. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  8563. value = newValue;
  8564. }
  8565. // if attribute was updated so that there is no interpolation going on we don't want to
  8566. // register any observers
  8567. if (!interpolateFn) return;
  8568. // initialize attr object so that it's ready in case we need the value for isolate
  8569. // scope initialization, otherwise the value would not be available from isolate
  8570. // directive's linking fn during linking phase
  8571. attr[name] = interpolateFn(scope);
  8572. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  8573. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  8574. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  8575. //special case for class attribute addition + removal
  8576. //so that class changes can tap into the animation
  8577. //hooks provided by the $animate service. Be sure to
  8578. //skip animations when the first digest occurs (when
  8579. //both the new and the old values are the same) since
  8580. //the CSS classes are the non-interpolated values
  8581. if (name === 'class' && newValue != oldValue) {
  8582. attr.$updateClass(newValue, oldValue);
  8583. } else {
  8584. attr.$set(name, newValue);
  8585. }
  8586. });
  8587. }
  8588. };
  8589. }
  8590. });
  8591. }
  8592. /**
  8593. * This is a special jqLite.replaceWith, which can replace items which
  8594. * have no parents, provided that the containing jqLite collection is provided.
  8595. *
  8596. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  8597. * in the root of the tree.
  8598. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  8599. * the shell, but replace its DOM node reference.
  8600. * @param {Node} newNode The new DOM node.
  8601. */
  8602. function replaceWith($rootElement, elementsToRemove, newNode) {
  8603. var firstElementToRemove = elementsToRemove[0],
  8604. removeCount = elementsToRemove.length,
  8605. parent = firstElementToRemove.parentNode,
  8606. i, ii;
  8607. if ($rootElement) {
  8608. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  8609. if ($rootElement[i] == firstElementToRemove) {
  8610. $rootElement[i++] = newNode;
  8611. for (var j = i, j2 = j + removeCount - 1,
  8612. jj = $rootElement.length;
  8613. j < jj; j++, j2++) {
  8614. if (j2 < jj) {
  8615. $rootElement[j] = $rootElement[j2];
  8616. } else {
  8617. delete $rootElement[j];
  8618. }
  8619. }
  8620. $rootElement.length -= removeCount - 1;
  8621. // If the replaced element is also the jQuery .context then replace it
  8622. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  8623. // http://api.jquery.com/context/
  8624. if ($rootElement.context === firstElementToRemove) {
  8625. $rootElement.context = newNode;
  8626. }
  8627. break;
  8628. }
  8629. }
  8630. }
  8631. if (parent) {
  8632. parent.replaceChild(newNode, firstElementToRemove);
  8633. }
  8634. // Append all the `elementsToRemove` to a fragment. This will...
  8635. // - remove them from the DOM
  8636. // - allow them to still be traversed with .nextSibling
  8637. // - allow a single fragment.qSA to fetch all elements being removed
  8638. var fragment = document.createDocumentFragment();
  8639. for (i = 0; i < removeCount; i++) {
  8640. fragment.appendChild(elementsToRemove[i]);
  8641. }
  8642. if (jqLite.hasData(firstElementToRemove)) {
  8643. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  8644. // data here because there's no public interface in jQuery to do that and copying over
  8645. // event listeners (which is the main use of private data) wouldn't work anyway.
  8646. jqLite.data(newNode, jqLite.data(firstElementToRemove));
  8647. // Remove $destroy event listeners from `firstElementToRemove`
  8648. jqLite(firstElementToRemove).off('$destroy');
  8649. }
  8650. // Cleanup any data/listeners on the elements and children.
  8651. // This includes invoking the $destroy event on any elements with listeners.
  8652. jqLite.cleanData(fragment.querySelectorAll('*'));
  8653. // Update the jqLite collection to only contain the `newNode`
  8654. for (i = 1; i < removeCount; i++) {
  8655. delete elementsToRemove[i];
  8656. }
  8657. elementsToRemove[0] = newNode;
  8658. elementsToRemove.length = 1;
  8659. }
  8660. function cloneAndAnnotateFn(fn, annotation) {
  8661. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  8662. }
  8663. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  8664. try {
  8665. linkFn(scope, $element, attrs, controllers, transcludeFn);
  8666. } catch (e) {
  8667. $exceptionHandler(e, startingTag($element));
  8668. }
  8669. }
  8670. // Set up $watches for isolate scope and controller bindings. This process
  8671. // only occurs for isolate scopes and new scopes with controllerAs.
  8672. function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
  8673. var removeWatchCollection = [];
  8674. var changes;
  8675. forEach(bindings, function initializeBinding(definition, scopeName) {
  8676. var attrName = definition.attrName,
  8677. optional = definition.optional,
  8678. mode = definition.mode, // @, =, or &
  8679. lastValue,
  8680. parentGet, parentSet, compare, removeWatch;
  8681. switch (mode) {
  8682. case '@':
  8683. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  8684. destination[scopeName] = attrs[attrName] = void 0;
  8685. }
  8686. attrs.$observe(attrName, function(value) {
  8687. if (isString(value)) {
  8688. var oldValue = destination[scopeName];
  8689. recordChanges(scopeName, value, oldValue);
  8690. destination[scopeName] = value;
  8691. }
  8692. });
  8693. attrs.$$observers[attrName].$$scope = scope;
  8694. lastValue = attrs[attrName];
  8695. if (isString(lastValue)) {
  8696. // If the attribute has been provided then we trigger an interpolation to ensure
  8697. // the value is there for use in the link fn
  8698. destination[scopeName] = $interpolate(lastValue)(scope);
  8699. } else if (isBoolean(lastValue)) {
  8700. // If the attributes is one of the BOOLEAN_ATTR then Angular will have converted
  8701. // the value to boolean rather than a string, so we special case this situation
  8702. destination[scopeName] = lastValue;
  8703. }
  8704. break;
  8705. case '=':
  8706. if (!hasOwnProperty.call(attrs, attrName)) {
  8707. if (optional) break;
  8708. attrs[attrName] = void 0;
  8709. }
  8710. if (optional && !attrs[attrName]) break;
  8711. parentGet = $parse(attrs[attrName]);
  8712. if (parentGet.literal) {
  8713. compare = equals;
  8714. } else {
  8715. compare = function simpleCompare(a, b) { return a === b || (a !== a && b !== b); };
  8716. }
  8717. parentSet = parentGet.assign || function() {
  8718. // reset the change, or we will throw this exception on every $digest
  8719. lastValue = destination[scopeName] = parentGet(scope);
  8720. throw $compileMinErr('nonassign',
  8721. "Expression '{0}' in attribute '{1}' used with directive '{2}' is non-assignable!",
  8722. attrs[attrName], attrName, directive.name);
  8723. };
  8724. lastValue = destination[scopeName] = parentGet(scope);
  8725. var parentValueWatch = function parentValueWatch(parentValue) {
  8726. if (!compare(parentValue, destination[scopeName])) {
  8727. // we are out of sync and need to copy
  8728. if (!compare(parentValue, lastValue)) {
  8729. // parent changed and it has precedence
  8730. destination[scopeName] = parentValue;
  8731. } else {
  8732. // if the parent can be assigned then do so
  8733. parentSet(scope, parentValue = destination[scopeName]);
  8734. }
  8735. }
  8736. return lastValue = parentValue;
  8737. };
  8738. parentValueWatch.$stateful = true;
  8739. if (definition.collection) {
  8740. removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  8741. } else {
  8742. removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  8743. }
  8744. removeWatchCollection.push(removeWatch);
  8745. break;
  8746. case '<':
  8747. if (!hasOwnProperty.call(attrs, attrName)) {
  8748. if (optional) break;
  8749. attrs[attrName] = void 0;
  8750. }
  8751. if (optional && !attrs[attrName]) break;
  8752. parentGet = $parse(attrs[attrName]);
  8753. destination[scopeName] = parentGet(scope);
  8754. removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newParentValue) {
  8755. var oldValue = destination[scopeName];
  8756. recordChanges(scopeName, newParentValue, oldValue);
  8757. destination[scopeName] = newParentValue;
  8758. }, parentGet.literal);
  8759. removeWatchCollection.push(removeWatch);
  8760. break;
  8761. case '&':
  8762. // Don't assign Object.prototype method to scope
  8763. parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
  8764. // Don't assign noop to destination if expression is not valid
  8765. if (parentGet === noop && optional) break;
  8766. destination[scopeName] = function(locals) {
  8767. return parentGet(scope, locals);
  8768. };
  8769. break;
  8770. }
  8771. });
  8772. function recordChanges(key, currentValue, previousValue) {
  8773. if (isFunction(destination.$onChanges) && currentValue !== previousValue) {
  8774. // If we have not already scheduled the top level onChangesQueue handler then do so now
  8775. if (!onChangesQueue) {
  8776. scope.$$postDigest(flushOnChangesQueue);
  8777. onChangesQueue = [];
  8778. }
  8779. // If we have not already queued a trigger of onChanges for this controller then do so now
  8780. if (!changes) {
  8781. changes = {};
  8782. onChangesQueue.push(triggerOnChangesHook);
  8783. }
  8784. // If the has been a change on this property already then we need to reuse the previous value
  8785. if (changes[key]) {
  8786. previousValue = changes[key].previousValue;
  8787. }
  8788. // Store this change
  8789. changes[key] = {previousValue: previousValue, currentValue: currentValue};
  8790. }
  8791. }
  8792. function triggerOnChangesHook() {
  8793. destination.$onChanges(changes);
  8794. // Now clear the changes so that we schedule onChanges when more changes arrive
  8795. changes = undefined;
  8796. }
  8797. return removeWatchCollection.length && function removeWatches() {
  8798. for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
  8799. removeWatchCollection[i]();
  8800. }
  8801. };
  8802. }
  8803. }];
  8804. }
  8805. var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
  8806. /**
  8807. * Converts all accepted directives format into proper directive name.
  8808. * @param name Name to normalize
  8809. */
  8810. function directiveNormalize(name) {
  8811. return camelCase(name.replace(PREFIX_REGEXP, ''));
  8812. }
  8813. /**
  8814. * @ngdoc type
  8815. * @name $compile.directive.Attributes
  8816. *
  8817. * @description
  8818. * A shared object between directive compile / linking functions which contains normalized DOM
  8819. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  8820. * needed since all of these are treated as equivalent in Angular:
  8821. *
  8822. * ```
  8823. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  8824. * ```
  8825. */
  8826. /**
  8827. * @ngdoc property
  8828. * @name $compile.directive.Attributes#$attr
  8829. *
  8830. * @description
  8831. * A map of DOM element attribute names to the normalized name. This is
  8832. * needed to do reverse lookup from normalized name back to actual name.
  8833. */
  8834. /**
  8835. * @ngdoc method
  8836. * @name $compile.directive.Attributes#$set
  8837. * @kind function
  8838. *
  8839. * @description
  8840. * Set DOM element attribute value.
  8841. *
  8842. *
  8843. * @param {string} name Normalized element attribute name of the property to modify. The name is
  8844. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  8845. * property to the original name.
  8846. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  8847. */
  8848. /**
  8849. * Closure compiler type information
  8850. */
  8851. function nodesetLinkingFn(
  8852. /* angular.Scope */ scope,
  8853. /* NodeList */ nodeList,
  8854. /* Element */ rootElement,
  8855. /* function(Function) */ boundTranscludeFn
  8856. ) {}
  8857. function directiveLinkingFn(
  8858. /* nodesetLinkingFn */ nodesetLinkingFn,
  8859. /* angular.Scope */ scope,
  8860. /* Node */ node,
  8861. /* Element */ rootElement,
  8862. /* function(Function) */ boundTranscludeFn
  8863. ) {}
  8864. function tokenDifference(str1, str2) {
  8865. var values = '',
  8866. tokens1 = str1.split(/\s+/),
  8867. tokens2 = str2.split(/\s+/);
  8868. outer:
  8869. for (var i = 0; i < tokens1.length; i++) {
  8870. var token = tokens1[i];
  8871. for (var j = 0; j < tokens2.length; j++) {
  8872. if (token == tokens2[j]) continue outer;
  8873. }
  8874. values += (values.length > 0 ? ' ' : '') + token;
  8875. }
  8876. return values;
  8877. }
  8878. function removeComments(jqNodes) {
  8879. jqNodes = jqLite(jqNodes);
  8880. var i = jqNodes.length;
  8881. if (i <= 1) {
  8882. return jqNodes;
  8883. }
  8884. while (i--) {
  8885. var node = jqNodes[i];
  8886. if (node.nodeType === NODE_TYPE_COMMENT) {
  8887. splice.call(jqNodes, i, 1);
  8888. }
  8889. }
  8890. return jqNodes;
  8891. }
  8892. var $controllerMinErr = minErr('$controller');
  8893. var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/;
  8894. function identifierForController(controller, ident) {
  8895. if (ident && isString(ident)) return ident;
  8896. if (isString(controller)) {
  8897. var match = CNTRL_REG.exec(controller);
  8898. if (match) return match[3];
  8899. }
  8900. }
  8901. /**
  8902. * @ngdoc provider
  8903. * @name $controllerProvider
  8904. * @description
  8905. * The {@link ng.$controller $controller service} is used by Angular to create new
  8906. * controllers.
  8907. *
  8908. * This provider allows controller registration via the
  8909. * {@link ng.$controllerProvider#register register} method.
  8910. */
  8911. function $ControllerProvider() {
  8912. var controllers = {},
  8913. globals = false;
  8914. /**
  8915. * @ngdoc method
  8916. * @name $controllerProvider#has
  8917. * @param {string} name Controller name to check.
  8918. */
  8919. this.has = function(name) {
  8920. return controllers.hasOwnProperty(name);
  8921. };
  8922. /**
  8923. * @ngdoc method
  8924. * @name $controllerProvider#register
  8925. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  8926. * the names and the values are the constructors.
  8927. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  8928. * annotations in the array notation).
  8929. */
  8930. this.register = function(name, constructor) {
  8931. assertNotHasOwnProperty(name, 'controller');
  8932. if (isObject(name)) {
  8933. extend(controllers, name);
  8934. } else {
  8935. controllers[name] = constructor;
  8936. }
  8937. };
  8938. /**
  8939. * @ngdoc method
  8940. * @name $controllerProvider#allowGlobals
  8941. * @description If called, allows `$controller` to find controller constructors on `window`
  8942. */
  8943. this.allowGlobals = function() {
  8944. globals = true;
  8945. };
  8946. this.$get = ['$injector', '$window', function($injector, $window) {
  8947. /**
  8948. * @ngdoc service
  8949. * @name $controller
  8950. * @requires $injector
  8951. *
  8952. * @param {Function|string} constructor If called with a function then it's considered to be the
  8953. * controller constructor function. Otherwise it's considered to be a string which is used
  8954. * to retrieve the controller constructor using the following steps:
  8955. *
  8956. * * check if a controller with given name is registered via `$controllerProvider`
  8957. * * check if evaluating the string on the current scope returns a constructor
  8958. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  8959. * `window` object (not recommended)
  8960. *
  8961. * The string can use the `controller as property` syntax, where the controller instance is published
  8962. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  8963. * to work correctly.
  8964. *
  8965. * @param {Object} locals Injection locals for Controller.
  8966. * @return {Object} Instance of given controller.
  8967. *
  8968. * @description
  8969. * `$controller` service is responsible for instantiating controllers.
  8970. *
  8971. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  8972. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  8973. */
  8974. return function $controller(expression, locals, later, ident) {
  8975. // PRIVATE API:
  8976. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  8977. // If true, $controller will allocate the object with the correct
  8978. // prototype chain, but will not invoke the controller until a returned
  8979. // callback is invoked.
  8980. // param `ident` --- An optional label which overrides the label parsed from the controller
  8981. // expression, if any.
  8982. var instance, match, constructor, identifier;
  8983. later = later === true;
  8984. if (ident && isString(ident)) {
  8985. identifier = ident;
  8986. }
  8987. if (isString(expression)) {
  8988. match = expression.match(CNTRL_REG);
  8989. if (!match) {
  8990. throw $controllerMinErr('ctrlfmt',
  8991. "Badly formed controller string '{0}'. " +
  8992. "Must match `__name__ as __id__` or `__name__`.", expression);
  8993. }
  8994. constructor = match[1],
  8995. identifier = identifier || match[3];
  8996. expression = controllers.hasOwnProperty(constructor)
  8997. ? controllers[constructor]
  8998. : getter(locals.$scope, constructor, true) ||
  8999. (globals ? getter($window, constructor, true) : undefined);
  9000. assertArgFn(expression, constructor, true);
  9001. }
  9002. if (later) {
  9003. // Instantiate controller later:
  9004. // This machinery is used to create an instance of the object before calling the
  9005. // controller's constructor itself.
  9006. //
  9007. // This allows properties to be added to the controller before the constructor is
  9008. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  9009. //
  9010. // This feature is not intended for use by applications, and is thus not documented
  9011. // publicly.
  9012. // Object creation: http://jsperf.com/create-constructor/2
  9013. var controllerPrototype = (isArray(expression) ?
  9014. expression[expression.length - 1] : expression).prototype;
  9015. instance = Object.create(controllerPrototype || null);
  9016. if (identifier) {
  9017. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9018. }
  9019. var instantiate;
  9020. return instantiate = extend(function $controllerInit() {
  9021. var result = $injector.invoke(expression, instance, locals, constructor);
  9022. if (result !== instance && (isObject(result) || isFunction(result))) {
  9023. instance = result;
  9024. if (identifier) {
  9025. // If result changed, re-assign controllerAs value to scope.
  9026. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9027. }
  9028. }
  9029. return instance;
  9030. }, {
  9031. instance: instance,
  9032. identifier: identifier
  9033. });
  9034. }
  9035. instance = $injector.instantiate(expression, locals, constructor);
  9036. if (identifier) {
  9037. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9038. }
  9039. return instance;
  9040. };
  9041. function addIdentifier(locals, identifier, instance, name) {
  9042. if (!(locals && isObject(locals.$scope))) {
  9043. throw minErr('$controller')('noscp',
  9044. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  9045. name, identifier);
  9046. }
  9047. locals.$scope[identifier] = instance;
  9048. }
  9049. }];
  9050. }
  9051. /**
  9052. * @ngdoc service
  9053. * @name $document
  9054. * @requires $window
  9055. *
  9056. * @description
  9057. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  9058. *
  9059. * @example
  9060. <example module="documentExample">
  9061. <file name="index.html">
  9062. <div ng-controller="ExampleController">
  9063. <p>$document title: <b ng-bind="title"></b></p>
  9064. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  9065. </div>
  9066. </file>
  9067. <file name="script.js">
  9068. angular.module('documentExample', [])
  9069. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  9070. $scope.title = $document[0].title;
  9071. $scope.windowTitle = angular.element(window.document)[0].title;
  9072. }]);
  9073. </file>
  9074. </example>
  9075. */
  9076. function $DocumentProvider() {
  9077. this.$get = ['$window', function(window) {
  9078. return jqLite(window.document);
  9079. }];
  9080. }
  9081. /**
  9082. * @ngdoc service
  9083. * @name $exceptionHandler
  9084. * @requires ng.$log
  9085. *
  9086. * @description
  9087. * Any uncaught exception in angular expressions is delegated to this service.
  9088. * The default implementation simply delegates to `$log.error` which logs it into
  9089. * the browser console.
  9090. *
  9091. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  9092. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  9093. *
  9094. * ## Example:
  9095. *
  9096. * ```js
  9097. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
  9098. * return function(exception, cause) {
  9099. * exception.message += ' (caused by "' + cause + '")';
  9100. * throw exception;
  9101. * };
  9102. * });
  9103. * ```
  9104. *
  9105. * This example will override the normal action of `$exceptionHandler`, to make angular
  9106. * exceptions fail hard when they happen, instead of just logging to the console.
  9107. *
  9108. * <hr />
  9109. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  9110. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  9111. * (unless executed during a digest).
  9112. *
  9113. * If you wish, you can manually delegate exceptions, e.g.
  9114. * `try { ... } catch(e) { $exceptionHandler(e); }`
  9115. *
  9116. * @param {Error} exception Exception associated with the error.
  9117. * @param {string=} cause optional information about the context in which
  9118. * the error was thrown.
  9119. *
  9120. */
  9121. function $ExceptionHandlerProvider() {
  9122. this.$get = ['$log', function($log) {
  9123. return function(exception, cause) {
  9124. $log.error.apply($log, arguments);
  9125. };
  9126. }];
  9127. }
  9128. var $$ForceReflowProvider = function() {
  9129. this.$get = ['$document', function($document) {
  9130. return function(domNode) {
  9131. //the line below will force the browser to perform a repaint so
  9132. //that all the animated elements within the animation frame will
  9133. //be properly updated and drawn on screen. This is required to
  9134. //ensure that the preparation animation is properly flushed so that
  9135. //the active state picks up from there. DO NOT REMOVE THIS LINE.
  9136. //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
  9137. //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
  9138. //WILL TAKE YEARS AWAY FROM YOUR LIFE.
  9139. if (domNode) {
  9140. if (!domNode.nodeType && domNode instanceof jqLite) {
  9141. domNode = domNode[0];
  9142. }
  9143. } else {
  9144. domNode = $document[0].body;
  9145. }
  9146. return domNode.offsetWidth + 1;
  9147. };
  9148. }];
  9149. };
  9150. var APPLICATION_JSON = 'application/json';
  9151. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  9152. var JSON_START = /^\[|^\{(?!\{)/;
  9153. var JSON_ENDS = {
  9154. '[': /]$/,
  9155. '{': /}$/
  9156. };
  9157. var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
  9158. var $httpMinErr = minErr('$http');
  9159. var $httpMinErrLegacyFn = function(method) {
  9160. return function() {
  9161. throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method);
  9162. };
  9163. };
  9164. function serializeValue(v) {
  9165. if (isObject(v)) {
  9166. return isDate(v) ? v.toISOString() : toJson(v);
  9167. }
  9168. return v;
  9169. }
  9170. function $HttpParamSerializerProvider() {
  9171. /**
  9172. * @ngdoc service
  9173. * @name $httpParamSerializer
  9174. * @description
  9175. *
  9176. * Default {@link $http `$http`} params serializer that converts objects to strings
  9177. * according to the following rules:
  9178. *
  9179. * * `{'foo': 'bar'}` results in `foo=bar`
  9180. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  9181. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  9182. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
  9183. *
  9184. * Note that serializer will sort the request parameters alphabetically.
  9185. * */
  9186. this.$get = function() {
  9187. return function ngParamSerializer(params) {
  9188. if (!params) return '';
  9189. var parts = [];
  9190. forEachSorted(params, function(value, key) {
  9191. if (value === null || isUndefined(value)) return;
  9192. if (isArray(value)) {
  9193. forEach(value, function(v) {
  9194. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  9195. });
  9196. } else {
  9197. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  9198. }
  9199. });
  9200. return parts.join('&');
  9201. };
  9202. };
  9203. }
  9204. function $HttpParamSerializerJQLikeProvider() {
  9205. /**
  9206. * @ngdoc service
  9207. * @name $httpParamSerializerJQLike
  9208. * @description
  9209. *
  9210. * Alternative {@link $http `$http`} params serializer that follows
  9211. * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  9212. * The serializer will also sort the params alphabetically.
  9213. *
  9214. * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
  9215. *
  9216. * ```js
  9217. * $http({
  9218. * url: myUrl,
  9219. * method: 'GET',
  9220. * params: myParams,
  9221. * paramSerializer: '$httpParamSerializerJQLike'
  9222. * });
  9223. * ```
  9224. *
  9225. * It is also possible to set it as the default `paramSerializer` in the
  9226. * {@link $httpProvider#defaults `$httpProvider`}.
  9227. *
  9228. * Additionally, you can inject the serializer and use it explicitly, for example to serialize
  9229. * form data for submission:
  9230. *
  9231. * ```js
  9232. * .controller(function($http, $httpParamSerializerJQLike) {
  9233. * //...
  9234. *
  9235. * $http({
  9236. * url: myUrl,
  9237. * method: 'POST',
  9238. * data: $httpParamSerializerJQLike(myData),
  9239. * headers: {
  9240. * 'Content-Type': 'application/x-www-form-urlencoded'
  9241. * }
  9242. * });
  9243. *
  9244. * });
  9245. * ```
  9246. *
  9247. * */
  9248. this.$get = function() {
  9249. return function jQueryLikeParamSerializer(params) {
  9250. if (!params) return '';
  9251. var parts = [];
  9252. serialize(params, '', true);
  9253. return parts.join('&');
  9254. function serialize(toSerialize, prefix, topLevel) {
  9255. if (toSerialize === null || isUndefined(toSerialize)) return;
  9256. if (isArray(toSerialize)) {
  9257. forEach(toSerialize, function(value, index) {
  9258. serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
  9259. });
  9260. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  9261. forEachSorted(toSerialize, function(value, key) {
  9262. serialize(value, prefix +
  9263. (topLevel ? '' : '[') +
  9264. key +
  9265. (topLevel ? '' : ']'));
  9266. });
  9267. } else {
  9268. parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
  9269. }
  9270. }
  9271. };
  9272. };
  9273. }
  9274. function defaultHttpResponseTransform(data, headers) {
  9275. if (isString(data)) {
  9276. // Strip json vulnerability protection prefix and trim whitespace
  9277. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  9278. if (tempData) {
  9279. var contentType = headers('Content-Type');
  9280. if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
  9281. data = fromJson(tempData);
  9282. }
  9283. }
  9284. }
  9285. return data;
  9286. }
  9287. function isJsonLike(str) {
  9288. var jsonStart = str.match(JSON_START);
  9289. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  9290. }
  9291. /**
  9292. * Parse headers into key value object
  9293. *
  9294. * @param {string} headers Raw headers as a string
  9295. * @returns {Object} Parsed headers as key value object
  9296. */
  9297. function parseHeaders(headers) {
  9298. var parsed = createMap(), i;
  9299. function fillInParsed(key, val) {
  9300. if (key) {
  9301. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  9302. }
  9303. }
  9304. if (isString(headers)) {
  9305. forEach(headers.split('\n'), function(line) {
  9306. i = line.indexOf(':');
  9307. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  9308. });
  9309. } else if (isObject(headers)) {
  9310. forEach(headers, function(headerVal, headerKey) {
  9311. fillInParsed(lowercase(headerKey), trim(headerVal));
  9312. });
  9313. }
  9314. return parsed;
  9315. }
  9316. /**
  9317. * Returns a function that provides access to parsed headers.
  9318. *
  9319. * Headers are lazy parsed when first requested.
  9320. * @see parseHeaders
  9321. *
  9322. * @param {(string|Object)} headers Headers to provide access to.
  9323. * @returns {function(string=)} Returns a getter function which if called with:
  9324. *
  9325. * - if called with single an argument returns a single header value or null
  9326. * - if called with no arguments returns an object containing all headers.
  9327. */
  9328. function headersGetter(headers) {
  9329. var headersObj;
  9330. return function(name) {
  9331. if (!headersObj) headersObj = parseHeaders(headers);
  9332. if (name) {
  9333. var value = headersObj[lowercase(name)];
  9334. if (value === void 0) {
  9335. value = null;
  9336. }
  9337. return value;
  9338. }
  9339. return headersObj;
  9340. };
  9341. }
  9342. /**
  9343. * Chain all given functions
  9344. *
  9345. * This function is used for both request and response transforming
  9346. *
  9347. * @param {*} data Data to transform.
  9348. * @param {function(string=)} headers HTTP headers getter fn.
  9349. * @param {number} status HTTP status code of the response.
  9350. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  9351. * @returns {*} Transformed data.
  9352. */
  9353. function transformData(data, headers, status, fns) {
  9354. if (isFunction(fns)) {
  9355. return fns(data, headers, status);
  9356. }
  9357. forEach(fns, function(fn) {
  9358. data = fn(data, headers, status);
  9359. });
  9360. return data;
  9361. }
  9362. function isSuccess(status) {
  9363. return 200 <= status && status < 300;
  9364. }
  9365. /**
  9366. * @ngdoc provider
  9367. * @name $httpProvider
  9368. * @description
  9369. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  9370. * */
  9371. function $HttpProvider() {
  9372. /**
  9373. * @ngdoc property
  9374. * @name $httpProvider#defaults
  9375. * @description
  9376. *
  9377. * Object containing default values for all {@link ng.$http $http} requests.
  9378. *
  9379. * - **`defaults.cache`** - {boolean|Object} - A boolean value or object created with
  9380. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of HTTP responses
  9381. * by default. See {@link $http#caching $http Caching} for more information.
  9382. *
  9383. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  9384. * Defaults value is `'XSRF-TOKEN'`.
  9385. *
  9386. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  9387. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  9388. *
  9389. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  9390. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  9391. * setting default headers.
  9392. * - **`defaults.headers.common`**
  9393. * - **`defaults.headers.post`**
  9394. * - **`defaults.headers.put`**
  9395. * - **`defaults.headers.patch`**
  9396. *
  9397. *
  9398. * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
  9399. * used to the prepare string representation of request parameters (specified as an object).
  9400. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  9401. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  9402. *
  9403. **/
  9404. var defaults = this.defaults = {
  9405. // transform incoming response data
  9406. transformResponse: [defaultHttpResponseTransform],
  9407. // transform outgoing request data
  9408. transformRequest: [function(d) {
  9409. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  9410. }],
  9411. // default headers
  9412. headers: {
  9413. common: {
  9414. 'Accept': 'application/json, text/plain, */*'
  9415. },
  9416. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  9417. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  9418. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  9419. },
  9420. xsrfCookieName: 'XSRF-TOKEN',
  9421. xsrfHeaderName: 'X-XSRF-TOKEN',
  9422. paramSerializer: '$httpParamSerializer'
  9423. };
  9424. var useApplyAsync = false;
  9425. /**
  9426. * @ngdoc method
  9427. * @name $httpProvider#useApplyAsync
  9428. * @description
  9429. *
  9430. * Configure $http service to combine processing of multiple http responses received at around
  9431. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  9432. * significant performance improvement for bigger applications that make many HTTP requests
  9433. * concurrently (common during application bootstrap).
  9434. *
  9435. * Defaults to false. If no value is specified, returns the current configured value.
  9436. *
  9437. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  9438. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  9439. * to load and share the same digest cycle.
  9440. *
  9441. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  9442. * otherwise, returns the current configured value.
  9443. **/
  9444. this.useApplyAsync = function(value) {
  9445. if (isDefined(value)) {
  9446. useApplyAsync = !!value;
  9447. return this;
  9448. }
  9449. return useApplyAsync;
  9450. };
  9451. var useLegacyPromise = true;
  9452. /**
  9453. * @ngdoc method
  9454. * @name $httpProvider#useLegacyPromiseExtensions
  9455. * @description
  9456. *
  9457. * Configure `$http` service to return promises without the shorthand methods `success` and `error`.
  9458. * This should be used to make sure that applications work without these methods.
  9459. *
  9460. * Defaults to true. If no value is specified, returns the current configured value.
  9461. *
  9462. * @param {boolean=} value If true, `$http` will return a promise with the deprecated legacy `success` and `error` methods.
  9463. *
  9464. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  9465. * otherwise, returns the current configured value.
  9466. **/
  9467. this.useLegacyPromiseExtensions = function(value) {
  9468. if (isDefined(value)) {
  9469. useLegacyPromise = !!value;
  9470. return this;
  9471. }
  9472. return useLegacyPromise;
  9473. };
  9474. /**
  9475. * @ngdoc property
  9476. * @name $httpProvider#interceptors
  9477. * @description
  9478. *
  9479. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  9480. * pre-processing of request or postprocessing of responses.
  9481. *
  9482. * These service factories are ordered by request, i.e. they are applied in the same order as the
  9483. * array, on request, but reverse order, on response.
  9484. *
  9485. * {@link ng.$http#interceptors Interceptors detailed info}
  9486. **/
  9487. var interceptorFactories = this.interceptors = [];
  9488. this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
  9489. function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
  9490. var defaultCache = $cacheFactory('$http');
  9491. /**
  9492. * Make sure that default param serializer is exposed as a function
  9493. */
  9494. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  9495. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  9496. /**
  9497. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  9498. * The reversal is needed so that we can build up the interception chain around the
  9499. * server request.
  9500. */
  9501. var reversedInterceptors = [];
  9502. forEach(interceptorFactories, function(interceptorFactory) {
  9503. reversedInterceptors.unshift(isString(interceptorFactory)
  9504. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  9505. });
  9506. /**
  9507. * @ngdoc service
  9508. * @kind function
  9509. * @name $http
  9510. * @requires ng.$httpBackend
  9511. * @requires $cacheFactory
  9512. * @requires $rootScope
  9513. * @requires $q
  9514. * @requires $injector
  9515. *
  9516. * @description
  9517. * The `$http` service is a core Angular service that facilitates communication with the remote
  9518. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  9519. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  9520. *
  9521. * For unit testing applications that use `$http` service, see
  9522. * {@link ngMock.$httpBackend $httpBackend mock}.
  9523. *
  9524. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  9525. * $resource} service.
  9526. *
  9527. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  9528. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  9529. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  9530. *
  9531. *
  9532. * ## General usage
  9533. * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
  9534. * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
  9535. *
  9536. * ```js
  9537. * // Simple GET request example:
  9538. * $http({
  9539. * method: 'GET',
  9540. * url: '/someUrl'
  9541. * }).then(function successCallback(response) {
  9542. * // this callback will be called asynchronously
  9543. * // when the response is available
  9544. * }, function errorCallback(response) {
  9545. * // called asynchronously if an error occurs
  9546. * // or server returns response with an error status.
  9547. * });
  9548. * ```
  9549. *
  9550. * The response object has these properties:
  9551. *
  9552. * - **data** – `{string|Object}` – The response body transformed with the transform
  9553. * functions.
  9554. * - **status** – `{number}` – HTTP status code of the response.
  9555. * - **headers** – `{function([headerName])}` – Header getter function.
  9556. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  9557. * - **statusText** – `{string}` – HTTP status text of the response.
  9558. *
  9559. * A response status code between 200 and 299 is considered a success status and
  9560. * will result in the success callback being called. Note that if the response is a redirect,
  9561. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  9562. * called for such responses.
  9563. *
  9564. *
  9565. * ## Shortcut methods
  9566. *
  9567. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  9568. * request data must be passed in for POST/PUT requests. An optional config can be passed as the
  9569. * last argument.
  9570. *
  9571. * ```js
  9572. * $http.get('/someUrl', config).then(successCallback, errorCallback);
  9573. * $http.post('/someUrl', data, config).then(successCallback, errorCallback);
  9574. * ```
  9575. *
  9576. * Complete list of shortcut methods:
  9577. *
  9578. * - {@link ng.$http#get $http.get}
  9579. * - {@link ng.$http#head $http.head}
  9580. * - {@link ng.$http#post $http.post}
  9581. * - {@link ng.$http#put $http.put}
  9582. * - {@link ng.$http#delete $http.delete}
  9583. * - {@link ng.$http#jsonp $http.jsonp}
  9584. * - {@link ng.$http#patch $http.patch}
  9585. *
  9586. *
  9587. * ## Writing Unit Tests that use $http
  9588. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  9589. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  9590. * request using trained responses.
  9591. *
  9592. * ```
  9593. * $httpBackend.expectGET(...);
  9594. * $http.get(...);
  9595. * $httpBackend.flush();
  9596. * ```
  9597. *
  9598. * ## Deprecation Notice
  9599. * <div class="alert alert-danger">
  9600. * The `$http` legacy promise methods `success` and `error` have been deprecated.
  9601. * Use the standard `then` method instead.
  9602. * If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to
  9603. * `false` then these methods will throw {@link $http:legacy `$http/legacy`} error.
  9604. * </div>
  9605. *
  9606. * ## Setting HTTP Headers
  9607. *
  9608. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  9609. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  9610. * object, which currently contains this default configuration:
  9611. *
  9612. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  9613. * - `Accept: application/json, text/plain, * / *`
  9614. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  9615. * - `Content-Type: application/json`
  9616. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  9617. * - `Content-Type: application/json`
  9618. *
  9619. * To add or overwrite these defaults, simply add or remove a property from these configuration
  9620. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  9621. * with the lowercased HTTP method name as the key, e.g.
  9622. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  9623. *
  9624. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  9625. * fashion. For example:
  9626. *
  9627. * ```
  9628. * module.run(function($http) {
  9629. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
  9630. * });
  9631. * ```
  9632. *
  9633. * In addition, you can supply a `headers` property in the config object passed when
  9634. * calling `$http(config)`, which overrides the defaults without changing them globally.
  9635. *
  9636. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  9637. * Use the `headers` property, setting the desired header to `undefined`. For example:
  9638. *
  9639. * ```js
  9640. * var req = {
  9641. * method: 'POST',
  9642. * url: 'http://example.com',
  9643. * headers: {
  9644. * 'Content-Type': undefined
  9645. * },
  9646. * data: { test: 'test' }
  9647. * }
  9648. *
  9649. * $http(req).then(function(){...}, function(){...});
  9650. * ```
  9651. *
  9652. * ## Transforming Requests and Responses
  9653. *
  9654. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  9655. * and `transformResponse`. These properties can be a single function that returns
  9656. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  9657. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  9658. *
  9659. * <div class="alert alert-warning">
  9660. * **Note:** Angular does not make a copy of the `data` parameter before it is passed into the `transformRequest` pipeline.
  9661. * That means changes to the properties of `data` are not local to the transform function (since Javascript passes objects by reference).
  9662. * For example, when calling `$http.get(url, $scope.myObject)`, modifications to the object's properties in a transformRequest
  9663. * function will be reflected on the scope and in any templates where the object is data-bound.
  9664. * To prevent his, transform functions should have no side-effects.
  9665. * If you need to modify properties, it is recommended to make a copy of the data, or create new object to return.
  9666. * </div>
  9667. *
  9668. * ### Default Transformations
  9669. *
  9670. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  9671. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  9672. * then these will be applied.
  9673. *
  9674. * You can augment or replace the default transformations by modifying these properties by adding to or
  9675. * replacing the array.
  9676. *
  9677. * Angular provides the following default transformations:
  9678. *
  9679. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  9680. *
  9681. * - If the `data` property of the request configuration object contains an object, serialize it
  9682. * into JSON format.
  9683. *
  9684. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  9685. *
  9686. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  9687. * - If JSON response is detected, deserialize it using a JSON parser.
  9688. *
  9689. *
  9690. * ### Overriding the Default Transformations Per Request
  9691. *
  9692. * If you wish override the request/response transformations only for a single request then provide
  9693. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  9694. * into `$http`.
  9695. *
  9696. * Note that if you provide these properties on the config object the default transformations will be
  9697. * overwritten. If you wish to augment the default transformations then you must include them in your
  9698. * local transformation array.
  9699. *
  9700. * The following code demonstrates adding a new response transformation to be run after the default response
  9701. * transformations have been run.
  9702. *
  9703. * ```js
  9704. * function appendTransform(defaults, transform) {
  9705. *
  9706. * // We can't guarantee that the default transformation is an array
  9707. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  9708. *
  9709. * // Append the new transformation to the defaults
  9710. * return defaults.concat(transform);
  9711. * }
  9712. *
  9713. * $http({
  9714. * url: '...',
  9715. * method: 'GET',
  9716. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  9717. * return doTransform(value);
  9718. * })
  9719. * });
  9720. * ```
  9721. *
  9722. *
  9723. * ## Caching
  9724. *
  9725. * {@link ng.$http `$http`} responses are not cached by default. To enable caching, you must
  9726. * set the config.cache value or the default cache value to TRUE or to a cache object (created
  9727. * with {@link ng.$cacheFactory `$cacheFactory`}). If defined, the value of config.cache takes
  9728. * precedence over the default cache value.
  9729. *
  9730. * In order to:
  9731. * * cache all responses - set the default cache value to TRUE or to a cache object
  9732. * * cache a specific response - set config.cache value to TRUE or to a cache object
  9733. *
  9734. * If caching is enabled, but neither the default cache nor config.cache are set to a cache object,
  9735. * then the default `$cacheFactory($http)` object is used.
  9736. *
  9737. * The default cache value can be set by updating the
  9738. * {@link ng.$http#defaults `$http.defaults.cache`} property or the
  9739. * {@link $httpProvider#defaults `$httpProvider.defaults.cache`} property.
  9740. *
  9741. * When caching is enabled, {@link ng.$http `$http`} stores the response from the server using
  9742. * the relevant cache object. The next time the same request is made, the response is returned
  9743. * from the cache without sending a request to the server.
  9744. *
  9745. * Take note that:
  9746. *
  9747. * * Only GET and JSONP requests are cached.
  9748. * * The cache key is the request URL including search parameters; headers are not considered.
  9749. * * Cached responses are returned asynchronously, in the same way as responses from the server.
  9750. * * If multiple identical requests are made using the same cache, which is not yet populated,
  9751. * one request will be made to the server and remaining requests will return the same response.
  9752. * * A cache-control header on the response does not affect if or how responses are cached.
  9753. *
  9754. *
  9755. * ## Interceptors
  9756. *
  9757. * Before you start creating interceptors, be sure to understand the
  9758. * {@link ng.$q $q and deferred/promise APIs}.
  9759. *
  9760. * For purposes of global error handling, authentication, or any kind of synchronous or
  9761. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  9762. * able to intercept requests before they are handed to the server and
  9763. * responses before they are handed over to the application code that
  9764. * initiated these requests. The interceptors leverage the {@link ng.$q
  9765. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  9766. *
  9767. * The interceptors are service factories that are registered with the `$httpProvider` by
  9768. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  9769. * injected with dependencies (if specified) and returns the interceptor.
  9770. *
  9771. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  9772. *
  9773. * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
  9774. * modify the `config` object or create a new one. The function needs to return the `config`
  9775. * object directly, or a promise containing the `config` or a new `config` object.
  9776. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  9777. * resolved with a rejection.
  9778. * * `response`: interceptors get called with http `response` object. The function is free to
  9779. * modify the `response` object or create a new one. The function needs to return the `response`
  9780. * object directly, or as a promise containing the `response` or a new `response` object.
  9781. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  9782. * resolved with a rejection.
  9783. *
  9784. *
  9785. * ```js
  9786. * // register the interceptor as a service
  9787. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  9788. * return {
  9789. * // optional method
  9790. * 'request': function(config) {
  9791. * // do something on success
  9792. * return config;
  9793. * },
  9794. *
  9795. * // optional method
  9796. * 'requestError': function(rejection) {
  9797. * // do something on error
  9798. * if (canRecover(rejection)) {
  9799. * return responseOrNewPromise
  9800. * }
  9801. * return $q.reject(rejection);
  9802. * },
  9803. *
  9804. *
  9805. *
  9806. * // optional method
  9807. * 'response': function(response) {
  9808. * // do something on success
  9809. * return response;
  9810. * },
  9811. *
  9812. * // optional method
  9813. * 'responseError': function(rejection) {
  9814. * // do something on error
  9815. * if (canRecover(rejection)) {
  9816. * return responseOrNewPromise
  9817. * }
  9818. * return $q.reject(rejection);
  9819. * }
  9820. * };
  9821. * });
  9822. *
  9823. * $httpProvider.interceptors.push('myHttpInterceptor');
  9824. *
  9825. *
  9826. * // alternatively, register the interceptor via an anonymous factory
  9827. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  9828. * return {
  9829. * 'request': function(config) {
  9830. * // same as above
  9831. * },
  9832. *
  9833. * 'response': function(response) {
  9834. * // same as above
  9835. * }
  9836. * };
  9837. * });
  9838. * ```
  9839. *
  9840. * ## Security Considerations
  9841. *
  9842. * When designing web applications, consider security threats from:
  9843. *
  9844. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  9845. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  9846. *
  9847. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  9848. * pre-configured with strategies that address these issues, but for this to work backend server
  9849. * cooperation is required.
  9850. *
  9851. * ### JSON Vulnerability Protection
  9852. *
  9853. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  9854. * allows third party website to turn your JSON resource URL into
  9855. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  9856. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  9857. * Angular will automatically strip the prefix before processing it as JSON.
  9858. *
  9859. * For example if your server needs to return:
  9860. * ```js
  9861. * ['one','two']
  9862. * ```
  9863. *
  9864. * which is vulnerable to attack, your server can return:
  9865. * ```js
  9866. * )]}',
  9867. * ['one','two']
  9868. * ```
  9869. *
  9870. * Angular will strip the prefix, before processing the JSON.
  9871. *
  9872. *
  9873. * ### Cross Site Request Forgery (XSRF) Protection
  9874. *
  9875. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by
  9876. * which the attacker can trick an authenticated user into unknowingly executing actions on your
  9877. * website. Angular provides a mechanism to counter XSRF. When performing XHR requests, the
  9878. * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP
  9879. * header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the
  9880. * cookie, your server can be assured that the XHR came from JavaScript running on your domain.
  9881. * The header will not be set for cross-domain requests.
  9882. *
  9883. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  9884. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  9885. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  9886. * that only JavaScript running on your domain could have sent the request. The token must be
  9887. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  9888. * making up its own tokens). We recommend that the token is a digest of your site's
  9889. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  9890. * for added security.
  9891. *
  9892. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  9893. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  9894. * or the per-request config object.
  9895. *
  9896. * In order to prevent collisions in environments where multiple Angular apps share the
  9897. * same domain or subdomain, we recommend that each application uses unique cookie name.
  9898. *
  9899. * @param {object} config Object describing the request to be made and how it should be
  9900. * processed. The object has following properties:
  9901. *
  9902. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  9903. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  9904. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
  9905. * with the `paramSerializer` and appended as GET parameters.
  9906. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  9907. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  9908. * HTTP headers to send to the server. If the return value of a function is null, the
  9909. * header will not be sent. Functions accept a config object as an argument.
  9910. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  9911. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  9912. * - **transformRequest** –
  9913. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  9914. * transform function or an array of such functions. The transform function takes the http
  9915. * request body and headers and returns its transformed (typically serialized) version.
  9916. * See {@link ng.$http#overriding-the-default-transformations-per-request
  9917. * Overriding the Default Transformations}
  9918. * - **transformResponse** –
  9919. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  9920. * transform function or an array of such functions. The transform function takes the http
  9921. * response body, headers and status and returns its transformed (typically deserialized) version.
  9922. * See {@link ng.$http#overriding-the-default-transformations-per-request
  9923. * Overriding the Default Transformations}
  9924. * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
  9925. * prepare the string representation of request parameters (specified as an object).
  9926. * If specified as string, it is interpreted as function registered with the
  9927. * {@link $injector $injector}, which means you can create your own serializer
  9928. * by registering it as a {@link auto.$provide#service service}.
  9929. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
  9930. * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
  9931. * - **cache** – `{boolean|Object}` – A boolean value or object created with
  9932. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response.
  9933. * See {@link $http#caching $http Caching} for more information.
  9934. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  9935. * that should abort the request when resolved.
  9936. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  9937. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  9938. * for more information.
  9939. * - **responseType** - `{string}` - see
  9940. * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
  9941. *
  9942. * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
  9943. * when the request succeeds or fails.
  9944. *
  9945. *
  9946. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  9947. * requests. This is primarily meant to be used for debugging purposes.
  9948. *
  9949. *
  9950. * @example
  9951. <example module="httpExample">
  9952. <file name="index.html">
  9953. <div ng-controller="FetchController">
  9954. <select ng-model="method" aria-label="Request method">
  9955. <option>GET</option>
  9956. <option>JSONP</option>
  9957. </select>
  9958. <input type="text" ng-model="url" size="80" aria-label="URL" />
  9959. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  9960. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  9961. <button id="samplejsonpbtn"
  9962. ng-click="updateModel('JSONP',
  9963. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  9964. Sample JSONP
  9965. </button>
  9966. <button id="invalidjsonpbtn"
  9967. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  9968. Invalid JSONP
  9969. </button>
  9970. <pre>http status code: {{status}}</pre>
  9971. <pre>http response data: {{data}}</pre>
  9972. </div>
  9973. </file>
  9974. <file name="script.js">
  9975. angular.module('httpExample', [])
  9976. .controller('FetchController', ['$scope', '$http', '$templateCache',
  9977. function($scope, $http, $templateCache) {
  9978. $scope.method = 'GET';
  9979. $scope.url = 'http-hello.html';
  9980. $scope.fetch = function() {
  9981. $scope.code = null;
  9982. $scope.response = null;
  9983. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  9984. then(function(response) {
  9985. $scope.status = response.status;
  9986. $scope.data = response.data;
  9987. }, function(response) {
  9988. $scope.data = response.data || "Request failed";
  9989. $scope.status = response.status;
  9990. });
  9991. };
  9992. $scope.updateModel = function(method, url) {
  9993. $scope.method = method;
  9994. $scope.url = url;
  9995. };
  9996. }]);
  9997. </file>
  9998. <file name="http-hello.html">
  9999. Hello, $http!
  10000. </file>
  10001. <file name="protractor.js" type="protractor">
  10002. var status = element(by.binding('status'));
  10003. var data = element(by.binding('data'));
  10004. var fetchBtn = element(by.id('fetchbtn'));
  10005. var sampleGetBtn = element(by.id('samplegetbtn'));
  10006. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  10007. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  10008. it('should make an xhr GET request', function() {
  10009. sampleGetBtn.click();
  10010. fetchBtn.click();
  10011. expect(status.getText()).toMatch('200');
  10012. expect(data.getText()).toMatch(/Hello, \$http!/);
  10013. });
  10014. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  10015. // it('should make a JSONP request to angularjs.org', function() {
  10016. // sampleJsonpBtn.click();
  10017. // fetchBtn.click();
  10018. // expect(status.getText()).toMatch('200');
  10019. // expect(data.getText()).toMatch(/Super Hero!/);
  10020. // });
  10021. it('should make JSONP request to invalid URL and invoke the error handler',
  10022. function() {
  10023. invalidJsonpBtn.click();
  10024. fetchBtn.click();
  10025. expect(status.getText()).toMatch('0');
  10026. expect(data.getText()).toMatch('Request failed');
  10027. });
  10028. </file>
  10029. </example>
  10030. */
  10031. function $http(requestConfig) {
  10032. if (!isObject(requestConfig)) {
  10033. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  10034. }
  10035. if (!isString(requestConfig.url)) {
  10036. throw minErr('$http')('badreq', 'Http request configuration url must be a string. Received: {0}', requestConfig.url);
  10037. }
  10038. var config = extend({
  10039. method: 'get',
  10040. transformRequest: defaults.transformRequest,
  10041. transformResponse: defaults.transformResponse,
  10042. paramSerializer: defaults.paramSerializer
  10043. }, requestConfig);
  10044. config.headers = mergeHeaders(requestConfig);
  10045. config.method = uppercase(config.method);
  10046. config.paramSerializer = isString(config.paramSerializer) ?
  10047. $injector.get(config.paramSerializer) : config.paramSerializer;
  10048. var serverRequest = function(config) {
  10049. var headers = config.headers;
  10050. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  10051. // strip content-type if data is undefined
  10052. if (isUndefined(reqData)) {
  10053. forEach(headers, function(value, header) {
  10054. if (lowercase(header) === 'content-type') {
  10055. delete headers[header];
  10056. }
  10057. });
  10058. }
  10059. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  10060. config.withCredentials = defaults.withCredentials;
  10061. }
  10062. // send request
  10063. return sendReq(config, reqData).then(transformResponse, transformResponse);
  10064. };
  10065. var chain = [serverRequest, undefined];
  10066. var promise = $q.when(config);
  10067. // apply interceptors
  10068. forEach(reversedInterceptors, function(interceptor) {
  10069. if (interceptor.request || interceptor.requestError) {
  10070. chain.unshift(interceptor.request, interceptor.requestError);
  10071. }
  10072. if (interceptor.response || interceptor.responseError) {
  10073. chain.push(interceptor.response, interceptor.responseError);
  10074. }
  10075. });
  10076. while (chain.length) {
  10077. var thenFn = chain.shift();
  10078. var rejectFn = chain.shift();
  10079. promise = promise.then(thenFn, rejectFn);
  10080. }
  10081. if (useLegacyPromise) {
  10082. promise.success = function(fn) {
  10083. assertArgFn(fn, 'fn');
  10084. promise.then(function(response) {
  10085. fn(response.data, response.status, response.headers, config);
  10086. });
  10087. return promise;
  10088. };
  10089. promise.error = function(fn) {
  10090. assertArgFn(fn, 'fn');
  10091. promise.then(null, function(response) {
  10092. fn(response.data, response.status, response.headers, config);
  10093. });
  10094. return promise;
  10095. };
  10096. } else {
  10097. promise.success = $httpMinErrLegacyFn('success');
  10098. promise.error = $httpMinErrLegacyFn('error');
  10099. }
  10100. return promise;
  10101. function transformResponse(response) {
  10102. // make a copy since the response must be cacheable
  10103. var resp = extend({}, response);
  10104. resp.data = transformData(response.data, response.headers, response.status,
  10105. config.transformResponse);
  10106. return (isSuccess(response.status))
  10107. ? resp
  10108. : $q.reject(resp);
  10109. }
  10110. function executeHeaderFns(headers, config) {
  10111. var headerContent, processedHeaders = {};
  10112. forEach(headers, function(headerFn, header) {
  10113. if (isFunction(headerFn)) {
  10114. headerContent = headerFn(config);
  10115. if (headerContent != null) {
  10116. processedHeaders[header] = headerContent;
  10117. }
  10118. } else {
  10119. processedHeaders[header] = headerFn;
  10120. }
  10121. });
  10122. return processedHeaders;
  10123. }
  10124. function mergeHeaders(config) {
  10125. var defHeaders = defaults.headers,
  10126. reqHeaders = extend({}, config.headers),
  10127. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  10128. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  10129. // using for-in instead of forEach to avoid unnecessary iteration after header has been found
  10130. defaultHeadersIteration:
  10131. for (defHeaderName in defHeaders) {
  10132. lowercaseDefHeaderName = lowercase(defHeaderName);
  10133. for (reqHeaderName in reqHeaders) {
  10134. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  10135. continue defaultHeadersIteration;
  10136. }
  10137. }
  10138. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  10139. }
  10140. // execute if header value is a function for merged headers
  10141. return executeHeaderFns(reqHeaders, shallowCopy(config));
  10142. }
  10143. }
  10144. $http.pendingRequests = [];
  10145. /**
  10146. * @ngdoc method
  10147. * @name $http#get
  10148. *
  10149. * @description
  10150. * Shortcut method to perform `GET` request.
  10151. *
  10152. * @param {string} url Relative or absolute URL specifying the destination of the request
  10153. * @param {Object=} config Optional configuration object
  10154. * @returns {HttpPromise} Future object
  10155. */
  10156. /**
  10157. * @ngdoc method
  10158. * @name $http#delete
  10159. *
  10160. * @description
  10161. * Shortcut method to perform `DELETE` request.
  10162. *
  10163. * @param {string} url Relative or absolute URL specifying the destination of the request
  10164. * @param {Object=} config Optional configuration object
  10165. * @returns {HttpPromise} Future object
  10166. */
  10167. /**
  10168. * @ngdoc method
  10169. * @name $http#head
  10170. *
  10171. * @description
  10172. * Shortcut method to perform `HEAD` request.
  10173. *
  10174. * @param {string} url Relative or absolute URL specifying the destination of the request
  10175. * @param {Object=} config Optional configuration object
  10176. * @returns {HttpPromise} Future object
  10177. */
  10178. /**
  10179. * @ngdoc method
  10180. * @name $http#jsonp
  10181. *
  10182. * @description
  10183. * Shortcut method to perform `JSONP` request.
  10184. *
  10185. * @param {string} url Relative or absolute URL specifying the destination of the request.
  10186. * The name of the callback should be the string `JSON_CALLBACK`.
  10187. * @param {Object=} config Optional configuration object
  10188. * @returns {HttpPromise} Future object
  10189. */
  10190. createShortMethods('get', 'delete', 'head', 'jsonp');
  10191. /**
  10192. * @ngdoc method
  10193. * @name $http#post
  10194. *
  10195. * @description
  10196. * Shortcut method to perform `POST` request.
  10197. *
  10198. * @param {string} url Relative or absolute URL specifying the destination of the request
  10199. * @param {*} data Request content
  10200. * @param {Object=} config Optional configuration object
  10201. * @returns {HttpPromise} Future object
  10202. */
  10203. /**
  10204. * @ngdoc method
  10205. * @name $http#put
  10206. *
  10207. * @description
  10208. * Shortcut method to perform `PUT` request.
  10209. *
  10210. * @param {string} url Relative or absolute URL specifying the destination of the request
  10211. * @param {*} data Request content
  10212. * @param {Object=} config Optional configuration object
  10213. * @returns {HttpPromise} Future object
  10214. */
  10215. /**
  10216. * @ngdoc method
  10217. * @name $http#patch
  10218. *
  10219. * @description
  10220. * Shortcut method to perform `PATCH` request.
  10221. *
  10222. * @param {string} url Relative or absolute URL specifying the destination of the request
  10223. * @param {*} data Request content
  10224. * @param {Object=} config Optional configuration object
  10225. * @returns {HttpPromise} Future object
  10226. */
  10227. createShortMethodsWithData('post', 'put', 'patch');
  10228. /**
  10229. * @ngdoc property
  10230. * @name $http#defaults
  10231. *
  10232. * @description
  10233. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  10234. * default headers, withCredentials as well as request and response transformations.
  10235. *
  10236. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  10237. */
  10238. $http.defaults = defaults;
  10239. return $http;
  10240. function createShortMethods(names) {
  10241. forEach(arguments, function(name) {
  10242. $http[name] = function(url, config) {
  10243. return $http(extend({}, config || {}, {
  10244. method: name,
  10245. url: url
  10246. }));
  10247. };
  10248. });
  10249. }
  10250. function createShortMethodsWithData(name) {
  10251. forEach(arguments, function(name) {
  10252. $http[name] = function(url, data, config) {
  10253. return $http(extend({}, config || {}, {
  10254. method: name,
  10255. url: url,
  10256. data: data
  10257. }));
  10258. };
  10259. });
  10260. }
  10261. /**
  10262. * Makes the request.
  10263. *
  10264. * !!! ACCESSES CLOSURE VARS:
  10265. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  10266. */
  10267. function sendReq(config, reqData) {
  10268. var deferred = $q.defer(),
  10269. promise = deferred.promise,
  10270. cache,
  10271. cachedResp,
  10272. reqHeaders = config.headers,
  10273. url = buildUrl(config.url, config.paramSerializer(config.params));
  10274. $http.pendingRequests.push(config);
  10275. promise.then(removePendingReq, removePendingReq);
  10276. if ((config.cache || defaults.cache) && config.cache !== false &&
  10277. (config.method === 'GET' || config.method === 'JSONP')) {
  10278. cache = isObject(config.cache) ? config.cache
  10279. : isObject(defaults.cache) ? defaults.cache
  10280. : defaultCache;
  10281. }
  10282. if (cache) {
  10283. cachedResp = cache.get(url);
  10284. if (isDefined(cachedResp)) {
  10285. if (isPromiseLike(cachedResp)) {
  10286. // cached request has already been sent, but there is no response yet
  10287. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  10288. } else {
  10289. // serving from cache
  10290. if (isArray(cachedResp)) {
  10291. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  10292. } else {
  10293. resolvePromise(cachedResp, 200, {}, 'OK');
  10294. }
  10295. }
  10296. } else {
  10297. // put the promise for the non-transformed response into cache as a placeholder
  10298. cache.put(url, promise);
  10299. }
  10300. }
  10301. // if we won't have the response in cache, set the xsrf headers and
  10302. // send the request to the backend
  10303. if (isUndefined(cachedResp)) {
  10304. var xsrfValue = urlIsSameOrigin(config.url)
  10305. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  10306. : undefined;
  10307. if (xsrfValue) {
  10308. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  10309. }
  10310. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  10311. config.withCredentials, config.responseType);
  10312. }
  10313. return promise;
  10314. /**
  10315. * Callback registered to $httpBackend():
  10316. * - caches the response if desired
  10317. * - resolves the raw $http promise
  10318. * - calls $apply
  10319. */
  10320. function done(status, response, headersString, statusText) {
  10321. if (cache) {
  10322. if (isSuccess(status)) {
  10323. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  10324. } else {
  10325. // remove promise from the cache
  10326. cache.remove(url);
  10327. }
  10328. }
  10329. function resolveHttpPromise() {
  10330. resolvePromise(response, status, headersString, statusText);
  10331. }
  10332. if (useApplyAsync) {
  10333. $rootScope.$applyAsync(resolveHttpPromise);
  10334. } else {
  10335. resolveHttpPromise();
  10336. if (!$rootScope.$$phase) $rootScope.$apply();
  10337. }
  10338. }
  10339. /**
  10340. * Resolves the raw $http promise.
  10341. */
  10342. function resolvePromise(response, status, headers, statusText) {
  10343. //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
  10344. status = status >= -1 ? status : 0;
  10345. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  10346. data: response,
  10347. status: status,
  10348. headers: headersGetter(headers),
  10349. config: config,
  10350. statusText: statusText
  10351. });
  10352. }
  10353. function resolvePromiseWithResult(result) {
  10354. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
  10355. }
  10356. function removePendingReq() {
  10357. var idx = $http.pendingRequests.indexOf(config);
  10358. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  10359. }
  10360. }
  10361. function buildUrl(url, serializedParams) {
  10362. if (serializedParams.length > 0) {
  10363. url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
  10364. }
  10365. return url;
  10366. }
  10367. }];
  10368. }
  10369. /**
  10370. * @ngdoc service
  10371. * @name $xhrFactory
  10372. *
  10373. * @description
  10374. * Factory function used to create XMLHttpRequest objects.
  10375. *
  10376. * Replace or decorate this service to create your own custom XMLHttpRequest objects.
  10377. *
  10378. * ```
  10379. * angular.module('myApp', [])
  10380. * .factory('$xhrFactory', function() {
  10381. * return function createXhr(method, url) {
  10382. * return new window.XMLHttpRequest({mozSystem: true});
  10383. * };
  10384. * });
  10385. * ```
  10386. *
  10387. * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
  10388. * @param {string} url URL of the request.
  10389. */
  10390. function $xhrFactoryProvider() {
  10391. this.$get = function() {
  10392. return function createXhr() {
  10393. return new window.XMLHttpRequest();
  10394. };
  10395. };
  10396. }
  10397. /**
  10398. * @ngdoc service
  10399. * @name $httpBackend
  10400. * @requires $window
  10401. * @requires $document
  10402. * @requires $xhrFactory
  10403. *
  10404. * @description
  10405. * HTTP backend used by the {@link ng.$http service} that delegates to
  10406. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  10407. *
  10408. * You should never need to use this service directly, instead use the higher-level abstractions:
  10409. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  10410. *
  10411. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  10412. * $httpBackend} which can be trained with responses.
  10413. */
  10414. function $HttpBackendProvider() {
  10415. this.$get = ['$browser', '$window', '$document', '$xhrFactory', function($browser, $window, $document, $xhrFactory) {
  10416. return createHttpBackend($browser, $xhrFactory, $browser.defer, $window.angular.callbacks, $document[0]);
  10417. }];
  10418. }
  10419. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  10420. // TODO(vojta): fix the signature
  10421. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  10422. $browser.$$incOutstandingRequestCount();
  10423. url = url || $browser.url();
  10424. if (lowercase(method) == 'jsonp') {
  10425. var callbackId = '_' + (callbacks.counter++).toString(36);
  10426. callbacks[callbackId] = function(data) {
  10427. callbacks[callbackId].data = data;
  10428. callbacks[callbackId].called = true;
  10429. };
  10430. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  10431. callbackId, function(status, text) {
  10432. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  10433. callbacks[callbackId] = noop;
  10434. });
  10435. } else {
  10436. var xhr = createXhr(method, url);
  10437. xhr.open(method, url, true);
  10438. forEach(headers, function(value, key) {
  10439. if (isDefined(value)) {
  10440. xhr.setRequestHeader(key, value);
  10441. }
  10442. });
  10443. xhr.onload = function requestLoaded() {
  10444. var statusText = xhr.statusText || '';
  10445. // responseText is the old-school way of retrieving response (supported by IE9)
  10446. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  10447. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  10448. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  10449. var status = xhr.status === 1223 ? 204 : xhr.status;
  10450. // fix status code when it is 0 (0 status is undocumented).
  10451. // Occurs when accessing file resources or on Android 4.1 stock browser
  10452. // while retrieving files from application cache.
  10453. if (status === 0) {
  10454. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  10455. }
  10456. completeRequest(callback,
  10457. status,
  10458. response,
  10459. xhr.getAllResponseHeaders(),
  10460. statusText);
  10461. };
  10462. var requestError = function() {
  10463. // The response is always empty
  10464. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  10465. completeRequest(callback, -1, null, null, '');
  10466. };
  10467. xhr.onerror = requestError;
  10468. xhr.onabort = requestError;
  10469. if (withCredentials) {
  10470. xhr.withCredentials = true;
  10471. }
  10472. if (responseType) {
  10473. try {
  10474. xhr.responseType = responseType;
  10475. } catch (e) {
  10476. // WebKit added support for the json responseType value on 09/03/2013
  10477. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  10478. // known to throw when setting the value "json" as the response type. Other older
  10479. // browsers implementing the responseType
  10480. //
  10481. // The json response type can be ignored if not supported, because JSON payloads are
  10482. // parsed on the client-side regardless.
  10483. if (responseType !== 'json') {
  10484. throw e;
  10485. }
  10486. }
  10487. }
  10488. xhr.send(isUndefined(post) ? null : post);
  10489. }
  10490. if (timeout > 0) {
  10491. var timeoutId = $browserDefer(timeoutRequest, timeout);
  10492. } else if (isPromiseLike(timeout)) {
  10493. timeout.then(timeoutRequest);
  10494. }
  10495. function timeoutRequest() {
  10496. jsonpDone && jsonpDone();
  10497. xhr && xhr.abort();
  10498. }
  10499. function completeRequest(callback, status, response, headersString, statusText) {
  10500. // cancel timeout and subsequent timeout promise resolution
  10501. if (isDefined(timeoutId)) {
  10502. $browserDefer.cancel(timeoutId);
  10503. }
  10504. jsonpDone = xhr = null;
  10505. callback(status, response, headersString, statusText);
  10506. $browser.$$completeOutstandingRequest(noop);
  10507. }
  10508. };
  10509. function jsonpReq(url, callbackId, done) {
  10510. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  10511. // - fetches local scripts via XHR and evals them
  10512. // - adds and immediately removes script elements from the document
  10513. var script = rawDocument.createElement('script'), callback = null;
  10514. script.type = "text/javascript";
  10515. script.src = url;
  10516. script.async = true;
  10517. callback = function(event) {
  10518. removeEventListenerFn(script, "load", callback);
  10519. removeEventListenerFn(script, "error", callback);
  10520. rawDocument.body.removeChild(script);
  10521. script = null;
  10522. var status = -1;
  10523. var text = "unknown";
  10524. if (event) {
  10525. if (event.type === "load" && !callbacks[callbackId].called) {
  10526. event = { type: "error" };
  10527. }
  10528. text = event.type;
  10529. status = event.type === "error" ? 404 : 200;
  10530. }
  10531. if (done) {
  10532. done(status, text);
  10533. }
  10534. };
  10535. addEventListenerFn(script, "load", callback);
  10536. addEventListenerFn(script, "error", callback);
  10537. rawDocument.body.appendChild(script);
  10538. return callback;
  10539. }
  10540. }
  10541. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  10542. $interpolateMinErr.throwNoconcat = function(text) {
  10543. throw $interpolateMinErr('noconcat',
  10544. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  10545. "interpolations that concatenate multiple expressions when a trusted value is " +
  10546. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  10547. };
  10548. $interpolateMinErr.interr = function(text, err) {
  10549. return $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
  10550. };
  10551. /**
  10552. * @ngdoc provider
  10553. * @name $interpolateProvider
  10554. *
  10555. * @description
  10556. *
  10557. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  10558. *
  10559. * <div class="alert alert-danger">
  10560. * This feature is sometimes used to mix different markup languages, e.g. to wrap an Angular
  10561. * template within a Python Jinja template (or any other template language). Mixing templating
  10562. * languages is **very dangerous**. The embedding template language will not safely escape Angular
  10563. * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)
  10564. * security bugs!
  10565. * </div>
  10566. *
  10567. * @example
  10568. <example name="custom-interpolation-markup" module="customInterpolationApp">
  10569. <file name="index.html">
  10570. <script>
  10571. var customInterpolationApp = angular.module('customInterpolationApp', []);
  10572. customInterpolationApp.config(function($interpolateProvider) {
  10573. $interpolateProvider.startSymbol('//');
  10574. $interpolateProvider.endSymbol('//');
  10575. });
  10576. customInterpolationApp.controller('DemoController', function() {
  10577. this.label = "This binding is brought you by // interpolation symbols.";
  10578. });
  10579. </script>
  10580. <div ng-controller="DemoController as demo">
  10581. //demo.label//
  10582. </div>
  10583. </file>
  10584. <file name="protractor.js" type="protractor">
  10585. it('should interpolate binding with custom symbols', function() {
  10586. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  10587. });
  10588. </file>
  10589. </example>
  10590. */
  10591. function $InterpolateProvider() {
  10592. var startSymbol = '{{';
  10593. var endSymbol = '}}';
  10594. /**
  10595. * @ngdoc method
  10596. * @name $interpolateProvider#startSymbol
  10597. * @description
  10598. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  10599. *
  10600. * @param {string=} value new value to set the starting symbol to.
  10601. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  10602. */
  10603. this.startSymbol = function(value) {
  10604. if (value) {
  10605. startSymbol = value;
  10606. return this;
  10607. } else {
  10608. return startSymbol;
  10609. }
  10610. };
  10611. /**
  10612. * @ngdoc method
  10613. * @name $interpolateProvider#endSymbol
  10614. * @description
  10615. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  10616. *
  10617. * @param {string=} value new value to set the ending symbol to.
  10618. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  10619. */
  10620. this.endSymbol = function(value) {
  10621. if (value) {
  10622. endSymbol = value;
  10623. return this;
  10624. } else {
  10625. return endSymbol;
  10626. }
  10627. };
  10628. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  10629. var startSymbolLength = startSymbol.length,
  10630. endSymbolLength = endSymbol.length,
  10631. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  10632. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  10633. function escape(ch) {
  10634. return '\\\\\\' + ch;
  10635. }
  10636. function unescapeText(text) {
  10637. return text.replace(escapedStartRegexp, startSymbol).
  10638. replace(escapedEndRegexp, endSymbol);
  10639. }
  10640. function stringify(value) {
  10641. if (value == null) { // null || undefined
  10642. return '';
  10643. }
  10644. switch (typeof value) {
  10645. case 'string':
  10646. break;
  10647. case 'number':
  10648. value = '' + value;
  10649. break;
  10650. default:
  10651. value = toJson(value);
  10652. }
  10653. return value;
  10654. }
  10655. //TODO: this is the same as the constantWatchDelegate in parse.js
  10656. function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {
  10657. var unwatch;
  10658. return unwatch = scope.$watch(function constantInterpolateWatch(scope) {
  10659. unwatch();
  10660. return constantInterp(scope);
  10661. }, listener, objectEquality);
  10662. }
  10663. /**
  10664. * @ngdoc service
  10665. * @name $interpolate
  10666. * @kind function
  10667. *
  10668. * @requires $parse
  10669. * @requires $sce
  10670. *
  10671. * @description
  10672. *
  10673. * Compiles a string with markup into an interpolation function. This service is used by the
  10674. * HTML {@link ng.$compile $compile} service for data binding. See
  10675. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  10676. * interpolation markup.
  10677. *
  10678. *
  10679. * ```js
  10680. * var $interpolate = ...; // injected
  10681. * var exp = $interpolate('Hello {{name | uppercase}}!');
  10682. * expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
  10683. * ```
  10684. *
  10685. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  10686. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  10687. * evaluate to a value other than `undefined`.
  10688. *
  10689. * ```js
  10690. * var $interpolate = ...; // injected
  10691. * var context = {greeting: 'Hello', name: undefined };
  10692. *
  10693. * // default "forgiving" mode
  10694. * var exp = $interpolate('{{greeting}} {{name}}!');
  10695. * expect(exp(context)).toEqual('Hello !');
  10696. *
  10697. * // "allOrNothing" mode
  10698. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  10699. * expect(exp(context)).toBeUndefined();
  10700. * context.name = 'Angular';
  10701. * expect(exp(context)).toEqual('Hello Angular!');
  10702. * ```
  10703. *
  10704. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  10705. *
  10706. * ####Escaped Interpolation
  10707. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  10708. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  10709. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  10710. * or binding.
  10711. *
  10712. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  10713. * degree, while also enabling code examples to work without relying on the
  10714. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  10715. *
  10716. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  10717. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  10718. * interpolation start/end markers with their escaped counterparts.**
  10719. *
  10720. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  10721. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  10722. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  10723. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  10724. * this is typically useful only when user-data is used in rendering a template from the server, or
  10725. * when otherwise untrusted data is used by a directive.
  10726. *
  10727. * <example>
  10728. * <file name="index.html">
  10729. * <div ng-init="username='A user'">
  10730. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  10731. * </p>
  10732. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  10733. * application, but fails to accomplish their task, because the server has correctly
  10734. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  10735. * characters.</p>
  10736. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  10737. * from the database by an administrator.</p>
  10738. * </div>
  10739. * </file>
  10740. * </example>
  10741. *
  10742. * @param {string} text The text with markup to interpolate.
  10743. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  10744. * embedded expression in order to return an interpolation function. Strings with no
  10745. * embedded expression will return null for the interpolation function.
  10746. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  10747. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  10748. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  10749. * provides Strict Contextual Escaping for details.
  10750. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  10751. * unless all embedded expressions evaluate to a value other than `undefined`.
  10752. * @returns {function(context)} an interpolation function which is used to compute the
  10753. * interpolated string. The function has these parameters:
  10754. *
  10755. * - `context`: evaluation context for all expressions embedded in the interpolated text
  10756. */
  10757. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  10758. // Provide a quick exit and simplified result function for text with no interpolation
  10759. if (!text.length || text.indexOf(startSymbol) === -1) {
  10760. var constantInterp;
  10761. if (!mustHaveExpression) {
  10762. var unescapedText = unescapeText(text);
  10763. constantInterp = valueFn(unescapedText);
  10764. constantInterp.exp = text;
  10765. constantInterp.expressions = [];
  10766. constantInterp.$$watchDelegate = constantWatchDelegate;
  10767. }
  10768. return constantInterp;
  10769. }
  10770. allOrNothing = !!allOrNothing;
  10771. var startIndex,
  10772. endIndex,
  10773. index = 0,
  10774. expressions = [],
  10775. parseFns = [],
  10776. textLength = text.length,
  10777. exp,
  10778. concat = [],
  10779. expressionPositions = [];
  10780. while (index < textLength) {
  10781. if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  10782. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
  10783. if (index !== startIndex) {
  10784. concat.push(unescapeText(text.substring(index, startIndex)));
  10785. }
  10786. exp = text.substring(startIndex + startSymbolLength, endIndex);
  10787. expressions.push(exp);
  10788. parseFns.push($parse(exp, parseStringifyInterceptor));
  10789. index = endIndex + endSymbolLength;
  10790. expressionPositions.push(concat.length);
  10791. concat.push('');
  10792. } else {
  10793. // we did not find an interpolation, so we have to add the remainder to the separators array
  10794. if (index !== textLength) {
  10795. concat.push(unescapeText(text.substring(index)));
  10796. }
  10797. break;
  10798. }
  10799. }
  10800. // Concatenating expressions makes it hard to reason about whether some combination of
  10801. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  10802. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  10803. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  10804. // make it obvious that you bound the value to some user controlled value. This helps reduce
  10805. // the load when auditing for XSS issues.
  10806. if (trustedContext && concat.length > 1) {
  10807. $interpolateMinErr.throwNoconcat(text);
  10808. }
  10809. if (!mustHaveExpression || expressions.length) {
  10810. var compute = function(values) {
  10811. for (var i = 0, ii = expressions.length; i < ii; i++) {
  10812. if (allOrNothing && isUndefined(values[i])) return;
  10813. concat[expressionPositions[i]] = values[i];
  10814. }
  10815. return concat.join('');
  10816. };
  10817. var getValue = function(value) {
  10818. return trustedContext ?
  10819. $sce.getTrusted(trustedContext, value) :
  10820. $sce.valueOf(value);
  10821. };
  10822. return extend(function interpolationFn(context) {
  10823. var i = 0;
  10824. var ii = expressions.length;
  10825. var values = new Array(ii);
  10826. try {
  10827. for (; i < ii; i++) {
  10828. values[i] = parseFns[i](context);
  10829. }
  10830. return compute(values);
  10831. } catch (err) {
  10832. $exceptionHandler($interpolateMinErr.interr(text, err));
  10833. }
  10834. }, {
  10835. // all of these properties are undocumented for now
  10836. exp: text, //just for compatibility with regular watchers created via $watch
  10837. expressions: expressions,
  10838. $$watchDelegate: function(scope, listener) {
  10839. var lastValue;
  10840. return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
  10841. var currValue = compute(values);
  10842. if (isFunction(listener)) {
  10843. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  10844. }
  10845. lastValue = currValue;
  10846. });
  10847. }
  10848. });
  10849. }
  10850. function parseStringifyInterceptor(value) {
  10851. try {
  10852. value = getValue(value);
  10853. return allOrNothing && !isDefined(value) ? value : stringify(value);
  10854. } catch (err) {
  10855. $exceptionHandler($interpolateMinErr.interr(text, err));
  10856. }
  10857. }
  10858. }
  10859. /**
  10860. * @ngdoc method
  10861. * @name $interpolate#startSymbol
  10862. * @description
  10863. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  10864. *
  10865. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  10866. * the symbol.
  10867. *
  10868. * @returns {string} start symbol.
  10869. */
  10870. $interpolate.startSymbol = function() {
  10871. return startSymbol;
  10872. };
  10873. /**
  10874. * @ngdoc method
  10875. * @name $interpolate#endSymbol
  10876. * @description
  10877. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  10878. *
  10879. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  10880. * the symbol.
  10881. *
  10882. * @returns {string} end symbol.
  10883. */
  10884. $interpolate.endSymbol = function() {
  10885. return endSymbol;
  10886. };
  10887. return $interpolate;
  10888. }];
  10889. }
  10890. function $IntervalProvider() {
  10891. this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',
  10892. function($rootScope, $window, $q, $$q, $browser) {
  10893. var intervals = {};
  10894. /**
  10895. * @ngdoc service
  10896. * @name $interval
  10897. *
  10898. * @description
  10899. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  10900. * milliseconds.
  10901. *
  10902. * The return value of registering an interval function is a promise. This promise will be
  10903. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  10904. * run indefinitely if `count` is not defined. The value of the notification will be the
  10905. * number of iterations that have run.
  10906. * To cancel an interval, call `$interval.cancel(promise)`.
  10907. *
  10908. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  10909. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  10910. * time.
  10911. *
  10912. * <div class="alert alert-warning">
  10913. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  10914. * with them. In particular they are not automatically destroyed when a controller's scope or a
  10915. * directive's element are destroyed.
  10916. * You should take this into consideration and make sure to always cancel the interval at the
  10917. * appropriate moment. See the example below for more details on how and when to do this.
  10918. * </div>
  10919. *
  10920. * @param {function()} fn A function that should be called repeatedly.
  10921. * @param {number} delay Number of milliseconds between each function call.
  10922. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  10923. * indefinitely.
  10924. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  10925. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  10926. * @param {...*=} Pass additional parameters to the executed function.
  10927. * @returns {promise} A promise which will be notified on each iteration.
  10928. *
  10929. * @example
  10930. * <example module="intervalExample">
  10931. * <file name="index.html">
  10932. * <script>
  10933. * angular.module('intervalExample', [])
  10934. * .controller('ExampleController', ['$scope', '$interval',
  10935. * function($scope, $interval) {
  10936. * $scope.format = 'M/d/yy h:mm:ss a';
  10937. * $scope.blood_1 = 100;
  10938. * $scope.blood_2 = 120;
  10939. *
  10940. * var stop;
  10941. * $scope.fight = function() {
  10942. * // Don't start a new fight if we are already fighting
  10943. * if ( angular.isDefined(stop) ) return;
  10944. *
  10945. * stop = $interval(function() {
  10946. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  10947. * $scope.blood_1 = $scope.blood_1 - 3;
  10948. * $scope.blood_2 = $scope.blood_2 - 4;
  10949. * } else {
  10950. * $scope.stopFight();
  10951. * }
  10952. * }, 100);
  10953. * };
  10954. *
  10955. * $scope.stopFight = function() {
  10956. * if (angular.isDefined(stop)) {
  10957. * $interval.cancel(stop);
  10958. * stop = undefined;
  10959. * }
  10960. * };
  10961. *
  10962. * $scope.resetFight = function() {
  10963. * $scope.blood_1 = 100;
  10964. * $scope.blood_2 = 120;
  10965. * };
  10966. *
  10967. * $scope.$on('$destroy', function() {
  10968. * // Make sure that the interval is destroyed too
  10969. * $scope.stopFight();
  10970. * });
  10971. * }])
  10972. * // Register the 'myCurrentTime' directive factory method.
  10973. * // We inject $interval and dateFilter service since the factory method is DI.
  10974. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  10975. * function($interval, dateFilter) {
  10976. * // return the directive link function. (compile function not needed)
  10977. * return function(scope, element, attrs) {
  10978. * var format, // date format
  10979. * stopTime; // so that we can cancel the time updates
  10980. *
  10981. * // used to update the UI
  10982. * function updateTime() {
  10983. * element.text(dateFilter(new Date(), format));
  10984. * }
  10985. *
  10986. * // watch the expression, and update the UI on change.
  10987. * scope.$watch(attrs.myCurrentTime, function(value) {
  10988. * format = value;
  10989. * updateTime();
  10990. * });
  10991. *
  10992. * stopTime = $interval(updateTime, 1000);
  10993. *
  10994. * // listen on DOM destroy (removal) event, and cancel the next UI update
  10995. * // to prevent updating time after the DOM element was removed.
  10996. * element.on('$destroy', function() {
  10997. * $interval.cancel(stopTime);
  10998. * });
  10999. * }
  11000. * }]);
  11001. * </script>
  11002. *
  11003. * <div>
  11004. * <div ng-controller="ExampleController">
  11005. * <label>Date format: <input ng-model="format"></label> <hr/>
  11006. * Current time is: <span my-current-time="format"></span>
  11007. * <hr/>
  11008. * Blood 1 : <font color='red'>{{blood_1}}</font>
  11009. * Blood 2 : <font color='red'>{{blood_2}}</font>
  11010. * <button type="button" data-ng-click="fight()">Fight</button>
  11011. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  11012. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  11013. * </div>
  11014. * </div>
  11015. *
  11016. * </file>
  11017. * </example>
  11018. */
  11019. function interval(fn, delay, count, invokeApply) {
  11020. var hasParams = arguments.length > 4,
  11021. args = hasParams ? sliceArgs(arguments, 4) : [],
  11022. setInterval = $window.setInterval,
  11023. clearInterval = $window.clearInterval,
  11024. iteration = 0,
  11025. skipApply = (isDefined(invokeApply) && !invokeApply),
  11026. deferred = (skipApply ? $$q : $q).defer(),
  11027. promise = deferred.promise;
  11028. count = isDefined(count) ? count : 0;
  11029. promise.$$intervalId = setInterval(function tick() {
  11030. if (skipApply) {
  11031. $browser.defer(callback);
  11032. } else {
  11033. $rootScope.$evalAsync(callback);
  11034. }
  11035. deferred.notify(iteration++);
  11036. if (count > 0 && iteration >= count) {
  11037. deferred.resolve(iteration);
  11038. clearInterval(promise.$$intervalId);
  11039. delete intervals[promise.$$intervalId];
  11040. }
  11041. if (!skipApply) $rootScope.$apply();
  11042. }, delay);
  11043. intervals[promise.$$intervalId] = deferred;
  11044. return promise;
  11045. function callback() {
  11046. if (!hasParams) {
  11047. fn(iteration);
  11048. } else {
  11049. fn.apply(null, args);
  11050. }
  11051. }
  11052. }
  11053. /**
  11054. * @ngdoc method
  11055. * @name $interval#cancel
  11056. *
  11057. * @description
  11058. * Cancels a task associated with the `promise`.
  11059. *
  11060. * @param {Promise=} promise returned by the `$interval` function.
  11061. * @returns {boolean} Returns `true` if the task was successfully canceled.
  11062. */
  11063. interval.cancel = function(promise) {
  11064. if (promise && promise.$$intervalId in intervals) {
  11065. intervals[promise.$$intervalId].reject('canceled');
  11066. $window.clearInterval(promise.$$intervalId);
  11067. delete intervals[promise.$$intervalId];
  11068. return true;
  11069. }
  11070. return false;
  11071. };
  11072. return interval;
  11073. }];
  11074. }
  11075. /**
  11076. * @ngdoc service
  11077. * @name $locale
  11078. *
  11079. * @description
  11080. * $locale service provides localization rules for various Angular components. As of right now the
  11081. * only public api is:
  11082. *
  11083. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  11084. */
  11085. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  11086. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  11087. var $locationMinErr = minErr('$location');
  11088. /**
  11089. * Encode path using encodeUriSegment, ignoring forward slashes
  11090. *
  11091. * @param {string} path Path to encode
  11092. * @returns {string}
  11093. */
  11094. function encodePath(path) {
  11095. var segments = path.split('/'),
  11096. i = segments.length;
  11097. while (i--) {
  11098. segments[i] = encodeUriSegment(segments[i]);
  11099. }
  11100. return segments.join('/');
  11101. }
  11102. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  11103. var parsedUrl = urlResolve(absoluteUrl);
  11104. locationObj.$$protocol = parsedUrl.protocol;
  11105. locationObj.$$host = parsedUrl.hostname;
  11106. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  11107. }
  11108. function parseAppUrl(relativeUrl, locationObj) {
  11109. var prefixed = (relativeUrl.charAt(0) !== '/');
  11110. if (prefixed) {
  11111. relativeUrl = '/' + relativeUrl;
  11112. }
  11113. var match = urlResolve(relativeUrl);
  11114. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  11115. match.pathname.substring(1) : match.pathname);
  11116. locationObj.$$search = parseKeyValue(match.search);
  11117. locationObj.$$hash = decodeURIComponent(match.hash);
  11118. // make sure path starts with '/';
  11119. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  11120. locationObj.$$path = '/' + locationObj.$$path;
  11121. }
  11122. }
  11123. /**
  11124. *
  11125. * @param {string} begin
  11126. * @param {string} whole
  11127. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  11128. * expected string.
  11129. */
  11130. function beginsWith(begin, whole) {
  11131. if (whole.indexOf(begin) === 0) {
  11132. return whole.substr(begin.length);
  11133. }
  11134. }
  11135. function stripHash(url) {
  11136. var index = url.indexOf('#');
  11137. return index == -1 ? url : url.substr(0, index);
  11138. }
  11139. function trimEmptyHash(url) {
  11140. return url.replace(/(#.+)|#$/, '$1');
  11141. }
  11142. function stripFile(url) {
  11143. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  11144. }
  11145. /* return the server only (scheme://host:port) */
  11146. function serverBase(url) {
  11147. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  11148. }
  11149. /**
  11150. * LocationHtml5Url represents an url
  11151. * This object is exposed as $location service when HTML5 mode is enabled and supported
  11152. *
  11153. * @constructor
  11154. * @param {string} appBase application base URL
  11155. * @param {string} appBaseNoFile application base URL stripped of any filename
  11156. * @param {string} basePrefix url path prefix
  11157. */
  11158. function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
  11159. this.$$html5 = true;
  11160. basePrefix = basePrefix || '';
  11161. parseAbsoluteUrl(appBase, this);
  11162. /**
  11163. * Parse given html5 (regular) url string into properties
  11164. * @param {string} url HTML5 url
  11165. * @private
  11166. */
  11167. this.$$parse = function(url) {
  11168. var pathUrl = beginsWith(appBaseNoFile, url);
  11169. if (!isString(pathUrl)) {
  11170. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  11171. appBaseNoFile);
  11172. }
  11173. parseAppUrl(pathUrl, this);
  11174. if (!this.$$path) {
  11175. this.$$path = '/';
  11176. }
  11177. this.$$compose();
  11178. };
  11179. /**
  11180. * Compose url and update `absUrl` property
  11181. * @private
  11182. */
  11183. this.$$compose = function() {
  11184. var search = toKeyValue(this.$$search),
  11185. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  11186. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  11187. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  11188. };
  11189. this.$$parseLinkUrl = function(url, relHref) {
  11190. if (relHref && relHref[0] === '#') {
  11191. // special case for links to hash fragments:
  11192. // keep the old url and only replace the hash fragment
  11193. this.hash(relHref.slice(1));
  11194. return true;
  11195. }
  11196. var appUrl, prevAppUrl;
  11197. var rewrittenUrl;
  11198. if (isDefined(appUrl = beginsWith(appBase, url))) {
  11199. prevAppUrl = appUrl;
  11200. if (isDefined(appUrl = beginsWith(basePrefix, appUrl))) {
  11201. rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  11202. } else {
  11203. rewrittenUrl = appBase + prevAppUrl;
  11204. }
  11205. } else if (isDefined(appUrl = beginsWith(appBaseNoFile, url))) {
  11206. rewrittenUrl = appBaseNoFile + appUrl;
  11207. } else if (appBaseNoFile == url + '/') {
  11208. rewrittenUrl = appBaseNoFile;
  11209. }
  11210. if (rewrittenUrl) {
  11211. this.$$parse(rewrittenUrl);
  11212. }
  11213. return !!rewrittenUrl;
  11214. };
  11215. }
  11216. /**
  11217. * LocationHashbangUrl represents url
  11218. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  11219. * It also serves as the base class for html5 mode fallback on legacy browsers.
  11220. *
  11221. * @constructor
  11222. * @param {string} appBase application base URL
  11223. * @param {string} appBaseNoFile application base URL stripped of any filename
  11224. * @param {string} hashPrefix hashbang prefix
  11225. */
  11226. function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
  11227. parseAbsoluteUrl(appBase, this);
  11228. /**
  11229. * Parse given hashbang url into properties
  11230. * @param {string} url Hashbang url
  11231. * @private
  11232. */
  11233. this.$$parse = function(url) {
  11234. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  11235. var withoutHashUrl;
  11236. if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
  11237. // The rest of the url starts with a hash so we have
  11238. // got either a hashbang path or a plain hash fragment
  11239. withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
  11240. if (isUndefined(withoutHashUrl)) {
  11241. // There was no hashbang prefix so we just have a hash fragment
  11242. withoutHashUrl = withoutBaseUrl;
  11243. }
  11244. } else {
  11245. // There was no hashbang path nor hash fragment:
  11246. // If we are in HTML5 mode we use what is left as the path;
  11247. // Otherwise we ignore what is left
  11248. if (this.$$html5) {
  11249. withoutHashUrl = withoutBaseUrl;
  11250. } else {
  11251. withoutHashUrl = '';
  11252. if (isUndefined(withoutBaseUrl)) {
  11253. appBase = url;
  11254. this.replace();
  11255. }
  11256. }
  11257. }
  11258. parseAppUrl(withoutHashUrl, this);
  11259. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  11260. this.$$compose();
  11261. /*
  11262. * In Windows, on an anchor node on documents loaded from
  11263. * the filesystem, the browser will return a pathname
  11264. * prefixed with the drive name ('/C:/path') when a
  11265. * pathname without a drive is set:
  11266. * * a.setAttribute('href', '/foo')
  11267. * * a.pathname === '/C:/foo' //true
  11268. *
  11269. * Inside of Angular, we're always using pathnames that
  11270. * do not include drive names for routing.
  11271. */
  11272. function removeWindowsDriveName(path, url, base) {
  11273. /*
  11274. Matches paths for file protocol on windows,
  11275. such as /C:/foo/bar, and captures only /foo/bar.
  11276. */
  11277. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  11278. var firstPathSegmentMatch;
  11279. //Get the relative path from the input URL.
  11280. if (url.indexOf(base) === 0) {
  11281. url = url.replace(base, '');
  11282. }
  11283. // The input URL intentionally contains a first path segment that ends with a colon.
  11284. if (windowsFilePathExp.exec(url)) {
  11285. return path;
  11286. }
  11287. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  11288. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  11289. }
  11290. };
  11291. /**
  11292. * Compose hashbang url and update `absUrl` property
  11293. * @private
  11294. */
  11295. this.$$compose = function() {
  11296. var search = toKeyValue(this.$$search),
  11297. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  11298. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  11299. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  11300. };
  11301. this.$$parseLinkUrl = function(url, relHref) {
  11302. if (stripHash(appBase) == stripHash(url)) {
  11303. this.$$parse(url);
  11304. return true;
  11305. }
  11306. return false;
  11307. };
  11308. }
  11309. /**
  11310. * LocationHashbangUrl represents url
  11311. * This object is exposed as $location service when html5 history api is enabled but the browser
  11312. * does not support it.
  11313. *
  11314. * @constructor
  11315. * @param {string} appBase application base URL
  11316. * @param {string} appBaseNoFile application base URL stripped of any filename
  11317. * @param {string} hashPrefix hashbang prefix
  11318. */
  11319. function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
  11320. this.$$html5 = true;
  11321. LocationHashbangUrl.apply(this, arguments);
  11322. this.$$parseLinkUrl = function(url, relHref) {
  11323. if (relHref && relHref[0] === '#') {
  11324. // special case for links to hash fragments:
  11325. // keep the old url and only replace the hash fragment
  11326. this.hash(relHref.slice(1));
  11327. return true;
  11328. }
  11329. var rewrittenUrl;
  11330. var appUrl;
  11331. if (appBase == stripHash(url)) {
  11332. rewrittenUrl = url;
  11333. } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
  11334. rewrittenUrl = appBase + hashPrefix + appUrl;
  11335. } else if (appBaseNoFile === url + '/') {
  11336. rewrittenUrl = appBaseNoFile;
  11337. }
  11338. if (rewrittenUrl) {
  11339. this.$$parse(rewrittenUrl);
  11340. }
  11341. return !!rewrittenUrl;
  11342. };
  11343. this.$$compose = function() {
  11344. var search = toKeyValue(this.$$search),
  11345. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  11346. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  11347. // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
  11348. this.$$absUrl = appBase + hashPrefix + this.$$url;
  11349. };
  11350. }
  11351. var locationPrototype = {
  11352. /**
  11353. * Are we in html5 mode?
  11354. * @private
  11355. */
  11356. $$html5: false,
  11357. /**
  11358. * Has any change been replacing?
  11359. * @private
  11360. */
  11361. $$replace: false,
  11362. /**
  11363. * @ngdoc method
  11364. * @name $location#absUrl
  11365. *
  11366. * @description
  11367. * This method is getter only.
  11368. *
  11369. * Return full url representation with all segments encoded according to rules specified in
  11370. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  11371. *
  11372. *
  11373. * ```js
  11374. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11375. * var absUrl = $location.absUrl();
  11376. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  11377. * ```
  11378. *
  11379. * @return {string} full url
  11380. */
  11381. absUrl: locationGetter('$$absUrl'),
  11382. /**
  11383. * @ngdoc method
  11384. * @name $location#url
  11385. *
  11386. * @description
  11387. * This method is getter / setter.
  11388. *
  11389. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  11390. *
  11391. * Change path, search and hash, when called with parameter and return `$location`.
  11392. *
  11393. *
  11394. * ```js
  11395. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11396. * var url = $location.url();
  11397. * // => "/some/path?foo=bar&baz=xoxo"
  11398. * ```
  11399. *
  11400. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  11401. * @return {string} url
  11402. */
  11403. url: function(url) {
  11404. if (isUndefined(url)) {
  11405. return this.$$url;
  11406. }
  11407. var match = PATH_MATCH.exec(url);
  11408. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  11409. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  11410. this.hash(match[5] || '');
  11411. return this;
  11412. },
  11413. /**
  11414. * @ngdoc method
  11415. * @name $location#protocol
  11416. *
  11417. * @description
  11418. * This method is getter only.
  11419. *
  11420. * Return protocol of current url.
  11421. *
  11422. *
  11423. * ```js
  11424. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11425. * var protocol = $location.protocol();
  11426. * // => "http"
  11427. * ```
  11428. *
  11429. * @return {string} protocol of current url
  11430. */
  11431. protocol: locationGetter('$$protocol'),
  11432. /**
  11433. * @ngdoc method
  11434. * @name $location#host
  11435. *
  11436. * @description
  11437. * This method is getter only.
  11438. *
  11439. * Return host of current url.
  11440. *
  11441. * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  11442. *
  11443. *
  11444. * ```js
  11445. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11446. * var host = $location.host();
  11447. * // => "example.com"
  11448. *
  11449. * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  11450. * host = $location.host();
  11451. * // => "example.com"
  11452. * host = location.host;
  11453. * // => "example.com:8080"
  11454. * ```
  11455. *
  11456. * @return {string} host of current url.
  11457. */
  11458. host: locationGetter('$$host'),
  11459. /**
  11460. * @ngdoc method
  11461. * @name $location#port
  11462. *
  11463. * @description
  11464. * This method is getter only.
  11465. *
  11466. * Return port of current url.
  11467. *
  11468. *
  11469. * ```js
  11470. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11471. * var port = $location.port();
  11472. * // => 80
  11473. * ```
  11474. *
  11475. * @return {Number} port
  11476. */
  11477. port: locationGetter('$$port'),
  11478. /**
  11479. * @ngdoc method
  11480. * @name $location#path
  11481. *
  11482. * @description
  11483. * This method is getter / setter.
  11484. *
  11485. * Return path of current url when called without any parameter.
  11486. *
  11487. * Change path when called with parameter and return `$location`.
  11488. *
  11489. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  11490. * if it is missing.
  11491. *
  11492. *
  11493. * ```js
  11494. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11495. * var path = $location.path();
  11496. * // => "/some/path"
  11497. * ```
  11498. *
  11499. * @param {(string|number)=} path New path
  11500. * @return {string} path
  11501. */
  11502. path: locationGetterSetter('$$path', function(path) {
  11503. path = path !== null ? path.toString() : '';
  11504. return path.charAt(0) == '/' ? path : '/' + path;
  11505. }),
  11506. /**
  11507. * @ngdoc method
  11508. * @name $location#search
  11509. *
  11510. * @description
  11511. * This method is getter / setter.
  11512. *
  11513. * Return search part (as object) of current url when called without any parameter.
  11514. *
  11515. * Change search part when called with parameter and return `$location`.
  11516. *
  11517. *
  11518. * ```js
  11519. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11520. * var searchObject = $location.search();
  11521. * // => {foo: 'bar', baz: 'xoxo'}
  11522. *
  11523. * // set foo to 'yipee'
  11524. * $location.search('foo', 'yipee');
  11525. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  11526. * ```
  11527. *
  11528. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  11529. * hash object.
  11530. *
  11531. * When called with a single argument the method acts as a setter, setting the `search` component
  11532. * of `$location` to the specified value.
  11533. *
  11534. * If the argument is a hash object containing an array of values, these values will be encoded
  11535. * as duplicate search parameters in the url.
  11536. *
  11537. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  11538. * will override only a single search property.
  11539. *
  11540. * If `paramValue` is an array, it will override the property of the `search` component of
  11541. * `$location` specified via the first argument.
  11542. *
  11543. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  11544. *
  11545. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  11546. * value nor trailing equal sign.
  11547. *
  11548. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  11549. * one or more arguments returns `$location` object itself.
  11550. */
  11551. search: function(search, paramValue) {
  11552. switch (arguments.length) {
  11553. case 0:
  11554. return this.$$search;
  11555. case 1:
  11556. if (isString(search) || isNumber(search)) {
  11557. search = search.toString();
  11558. this.$$search = parseKeyValue(search);
  11559. } else if (isObject(search)) {
  11560. search = copy(search, {});
  11561. // remove object undefined or null properties
  11562. forEach(search, function(value, key) {
  11563. if (value == null) delete search[key];
  11564. });
  11565. this.$$search = search;
  11566. } else {
  11567. throw $locationMinErr('isrcharg',
  11568. 'The first argument of the `$location#search()` call must be a string or an object.');
  11569. }
  11570. break;
  11571. default:
  11572. if (isUndefined(paramValue) || paramValue === null) {
  11573. delete this.$$search[search];
  11574. } else {
  11575. this.$$search[search] = paramValue;
  11576. }
  11577. }
  11578. this.$$compose();
  11579. return this;
  11580. },
  11581. /**
  11582. * @ngdoc method
  11583. * @name $location#hash
  11584. *
  11585. * @description
  11586. * This method is getter / setter.
  11587. *
  11588. * Returns the hash fragment when called without any parameters.
  11589. *
  11590. * Changes the hash fragment when called with a parameter and returns `$location`.
  11591. *
  11592. *
  11593. * ```js
  11594. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  11595. * var hash = $location.hash();
  11596. * // => "hashValue"
  11597. * ```
  11598. *
  11599. * @param {(string|number)=} hash New hash fragment
  11600. * @return {string} hash
  11601. */
  11602. hash: locationGetterSetter('$$hash', function(hash) {
  11603. return hash !== null ? hash.toString() : '';
  11604. }),
  11605. /**
  11606. * @ngdoc method
  11607. * @name $location#replace
  11608. *
  11609. * @description
  11610. * If called, all changes to $location during the current `$digest` will replace the current history
  11611. * record, instead of adding a new one.
  11612. */
  11613. replace: function() {
  11614. this.$$replace = true;
  11615. return this;
  11616. }
  11617. };
  11618. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  11619. Location.prototype = Object.create(locationPrototype);
  11620. /**
  11621. * @ngdoc method
  11622. * @name $location#state
  11623. *
  11624. * @description
  11625. * This method is getter / setter.
  11626. *
  11627. * Return the history state object when called without any parameter.
  11628. *
  11629. * Change the history state object when called with one parameter and return `$location`.
  11630. * The state object is later passed to `pushState` or `replaceState`.
  11631. *
  11632. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  11633. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  11634. * older browsers (like IE9 or Android < 4.0), don't use this method.
  11635. *
  11636. * @param {object=} state State object for pushState or replaceState
  11637. * @return {object} state
  11638. */
  11639. Location.prototype.state = function(state) {
  11640. if (!arguments.length) {
  11641. return this.$$state;
  11642. }
  11643. if (Location !== LocationHtml5Url || !this.$$html5) {
  11644. throw $locationMinErr('nostate', 'History API state support is available only ' +
  11645. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  11646. }
  11647. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  11648. // but we're changing the $$state reference to $browser.state() during the $digest
  11649. // so the modification window is narrow.
  11650. this.$$state = isUndefined(state) ? null : state;
  11651. return this;
  11652. };
  11653. });
  11654. function locationGetter(property) {
  11655. return function() {
  11656. return this[property];
  11657. };
  11658. }
  11659. function locationGetterSetter(property, preprocess) {
  11660. return function(value) {
  11661. if (isUndefined(value)) {
  11662. return this[property];
  11663. }
  11664. this[property] = preprocess(value);
  11665. this.$$compose();
  11666. return this;
  11667. };
  11668. }
  11669. /**
  11670. * @ngdoc service
  11671. * @name $location
  11672. *
  11673. * @requires $rootElement
  11674. *
  11675. * @description
  11676. * The $location service parses the URL in the browser address bar (based on the
  11677. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  11678. * available to your application. Changes to the URL in the address bar are reflected into
  11679. * $location service and changes to $location are reflected into the browser address bar.
  11680. *
  11681. * **The $location service:**
  11682. *
  11683. * - Exposes the current URL in the browser address bar, so you can
  11684. * - Watch and observe the URL.
  11685. * - Change the URL.
  11686. * - Synchronizes the URL with the browser when the user
  11687. * - Changes the address bar.
  11688. * - Clicks the back or forward button (or clicks a History link).
  11689. * - Clicks on a link.
  11690. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  11691. *
  11692. * For more information see {@link guide/$location Developer Guide: Using $location}
  11693. */
  11694. /**
  11695. * @ngdoc provider
  11696. * @name $locationProvider
  11697. * @description
  11698. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  11699. */
  11700. function $LocationProvider() {
  11701. var hashPrefix = '',
  11702. html5Mode = {
  11703. enabled: false,
  11704. requireBase: true,
  11705. rewriteLinks: true
  11706. };
  11707. /**
  11708. * @ngdoc method
  11709. * @name $locationProvider#hashPrefix
  11710. * @description
  11711. * @param {string=} prefix Prefix for hash part (containing path and search)
  11712. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  11713. */
  11714. this.hashPrefix = function(prefix) {
  11715. if (isDefined(prefix)) {
  11716. hashPrefix = prefix;
  11717. return this;
  11718. } else {
  11719. return hashPrefix;
  11720. }
  11721. };
  11722. /**
  11723. * @ngdoc method
  11724. * @name $locationProvider#html5Mode
  11725. * @description
  11726. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  11727. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  11728. * properties:
  11729. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  11730. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  11731. * support `pushState`.
  11732. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  11733. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  11734. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  11735. * See the {@link guide/$location $location guide for more information}
  11736. * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
  11737. * enables/disables url rewriting for relative links.
  11738. *
  11739. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  11740. */
  11741. this.html5Mode = function(mode) {
  11742. if (isBoolean(mode)) {
  11743. html5Mode.enabled = mode;
  11744. return this;
  11745. } else if (isObject(mode)) {
  11746. if (isBoolean(mode.enabled)) {
  11747. html5Mode.enabled = mode.enabled;
  11748. }
  11749. if (isBoolean(mode.requireBase)) {
  11750. html5Mode.requireBase = mode.requireBase;
  11751. }
  11752. if (isBoolean(mode.rewriteLinks)) {
  11753. html5Mode.rewriteLinks = mode.rewriteLinks;
  11754. }
  11755. return this;
  11756. } else {
  11757. return html5Mode;
  11758. }
  11759. };
  11760. /**
  11761. * @ngdoc event
  11762. * @name $location#$locationChangeStart
  11763. * @eventType broadcast on root scope
  11764. * @description
  11765. * Broadcasted before a URL will change.
  11766. *
  11767. * This change can be prevented by calling
  11768. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  11769. * details about event object. Upon successful change
  11770. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  11771. *
  11772. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  11773. * the browser supports the HTML5 History API.
  11774. *
  11775. * @param {Object} angularEvent Synthetic event object.
  11776. * @param {string} newUrl New URL
  11777. * @param {string=} oldUrl URL that was before it was changed.
  11778. * @param {string=} newState New history state object
  11779. * @param {string=} oldState History state object that was before it was changed.
  11780. */
  11781. /**
  11782. * @ngdoc event
  11783. * @name $location#$locationChangeSuccess
  11784. * @eventType broadcast on root scope
  11785. * @description
  11786. * Broadcasted after a URL was changed.
  11787. *
  11788. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  11789. * the browser supports the HTML5 History API.
  11790. *
  11791. * @param {Object} angularEvent Synthetic event object.
  11792. * @param {string} newUrl New URL
  11793. * @param {string=} oldUrl URL that was before it was changed.
  11794. * @param {string=} newState New history state object
  11795. * @param {string=} oldState History state object that was before it was changed.
  11796. */
  11797. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  11798. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  11799. var $location,
  11800. LocationMode,
  11801. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  11802. initialUrl = $browser.url(),
  11803. appBase;
  11804. if (html5Mode.enabled) {
  11805. if (!baseHref && html5Mode.requireBase) {
  11806. throw $locationMinErr('nobase',
  11807. "$location in HTML5 mode requires a <base> tag to be present!");
  11808. }
  11809. appBase = serverBase(initialUrl) + (baseHref || '/');
  11810. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  11811. } else {
  11812. appBase = stripHash(initialUrl);
  11813. LocationMode = LocationHashbangUrl;
  11814. }
  11815. var appBaseNoFile = stripFile(appBase);
  11816. $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
  11817. $location.$$parseLinkUrl(initialUrl, initialUrl);
  11818. $location.$$state = $browser.state();
  11819. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  11820. function setBrowserUrlWithFallback(url, replace, state) {
  11821. var oldUrl = $location.url();
  11822. var oldState = $location.$$state;
  11823. try {
  11824. $browser.url(url, replace, state);
  11825. // Make sure $location.state() returns referentially identical (not just deeply equal)
  11826. // state object; this makes possible quick checking if the state changed in the digest
  11827. // loop. Checking deep equality would be too expensive.
  11828. $location.$$state = $browser.state();
  11829. } catch (e) {
  11830. // Restore old values if pushState fails
  11831. $location.url(oldUrl);
  11832. $location.$$state = oldState;
  11833. throw e;
  11834. }
  11835. }
  11836. $rootElement.on('click', function(event) {
  11837. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  11838. // currently we open nice url link and redirect then
  11839. if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
  11840. var elm = jqLite(event.target);
  11841. // traverse the DOM up to find first A tag
  11842. while (nodeName_(elm[0]) !== 'a') {
  11843. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  11844. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  11845. }
  11846. var absHref = elm.prop('href');
  11847. // get the actual href attribute - see
  11848. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  11849. var relHref = elm.attr('href') || elm.attr('xlink:href');
  11850. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  11851. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  11852. // an animation.
  11853. absHref = urlResolve(absHref.animVal).href;
  11854. }
  11855. // Ignore when url is started with javascript: or mailto:
  11856. if (IGNORE_URI_REGEXP.test(absHref)) return;
  11857. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  11858. if ($location.$$parseLinkUrl(absHref, relHref)) {
  11859. // We do a preventDefault for all urls that are part of the angular application,
  11860. // in html5mode and also without, so that we are able to abort navigation without
  11861. // getting double entries in the location history.
  11862. event.preventDefault();
  11863. // update location manually
  11864. if ($location.absUrl() != $browser.url()) {
  11865. $rootScope.$apply();
  11866. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  11867. $window.angular['ff-684208-preventDefault'] = true;
  11868. }
  11869. }
  11870. }
  11871. });
  11872. // rewrite hashbang url <> html5 url
  11873. if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
  11874. $browser.url($location.absUrl(), true);
  11875. }
  11876. var initializing = true;
  11877. // update $location when $browser url changes
  11878. $browser.onUrlChange(function(newUrl, newState) {
  11879. if (isUndefined(beginsWith(appBaseNoFile, newUrl))) {
  11880. // If we are navigating outside of the app then force a reload
  11881. $window.location.href = newUrl;
  11882. return;
  11883. }
  11884. $rootScope.$evalAsync(function() {
  11885. var oldUrl = $location.absUrl();
  11886. var oldState = $location.$$state;
  11887. var defaultPrevented;
  11888. newUrl = trimEmptyHash(newUrl);
  11889. $location.$$parse(newUrl);
  11890. $location.$$state = newState;
  11891. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  11892. newState, oldState).defaultPrevented;
  11893. // if the location was changed by a `$locationChangeStart` handler then stop
  11894. // processing this location change
  11895. if ($location.absUrl() !== newUrl) return;
  11896. if (defaultPrevented) {
  11897. $location.$$parse(oldUrl);
  11898. $location.$$state = oldState;
  11899. setBrowserUrlWithFallback(oldUrl, false, oldState);
  11900. } else {
  11901. initializing = false;
  11902. afterLocationChange(oldUrl, oldState);
  11903. }
  11904. });
  11905. if (!$rootScope.$$phase) $rootScope.$digest();
  11906. });
  11907. // update browser
  11908. $rootScope.$watch(function $locationWatch() {
  11909. var oldUrl = trimEmptyHash($browser.url());
  11910. var newUrl = trimEmptyHash($location.absUrl());
  11911. var oldState = $browser.state();
  11912. var currentReplace = $location.$$replace;
  11913. var urlOrStateChanged = oldUrl !== newUrl ||
  11914. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  11915. if (initializing || urlOrStateChanged) {
  11916. initializing = false;
  11917. $rootScope.$evalAsync(function() {
  11918. var newUrl = $location.absUrl();
  11919. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  11920. $location.$$state, oldState).defaultPrevented;
  11921. // if the location was changed by a `$locationChangeStart` handler then stop
  11922. // processing this location change
  11923. if ($location.absUrl() !== newUrl) return;
  11924. if (defaultPrevented) {
  11925. $location.$$parse(oldUrl);
  11926. $location.$$state = oldState;
  11927. } else {
  11928. if (urlOrStateChanged) {
  11929. setBrowserUrlWithFallback(newUrl, currentReplace,
  11930. oldState === $location.$$state ? null : $location.$$state);
  11931. }
  11932. afterLocationChange(oldUrl, oldState);
  11933. }
  11934. });
  11935. }
  11936. $location.$$replace = false;
  11937. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  11938. // there is a change
  11939. });
  11940. return $location;
  11941. function afterLocationChange(oldUrl, oldState) {
  11942. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  11943. $location.$$state, oldState);
  11944. }
  11945. }];
  11946. }
  11947. /**
  11948. * @ngdoc service
  11949. * @name $log
  11950. * @requires $window
  11951. *
  11952. * @description
  11953. * Simple service for logging. Default implementation safely writes the message
  11954. * into the browser's console (if present).
  11955. *
  11956. * The main purpose of this service is to simplify debugging and troubleshooting.
  11957. *
  11958. * The default is to log `debug` messages. You can use
  11959. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  11960. *
  11961. * @example
  11962. <example module="logExample">
  11963. <file name="script.js">
  11964. angular.module('logExample', [])
  11965. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  11966. $scope.$log = $log;
  11967. $scope.message = 'Hello World!';
  11968. }]);
  11969. </file>
  11970. <file name="index.html">
  11971. <div ng-controller="LogController">
  11972. <p>Reload this page with open console, enter text and hit the log button...</p>
  11973. <label>Message:
  11974. <input type="text" ng-model="message" /></label>
  11975. <button ng-click="$log.log(message)">log</button>
  11976. <button ng-click="$log.warn(message)">warn</button>
  11977. <button ng-click="$log.info(message)">info</button>
  11978. <button ng-click="$log.error(message)">error</button>
  11979. <button ng-click="$log.debug(message)">debug</button>
  11980. </div>
  11981. </file>
  11982. </example>
  11983. */
  11984. /**
  11985. * @ngdoc provider
  11986. * @name $logProvider
  11987. * @description
  11988. * Use the `$logProvider` to configure how the application logs messages
  11989. */
  11990. function $LogProvider() {
  11991. var debug = true,
  11992. self = this;
  11993. /**
  11994. * @ngdoc method
  11995. * @name $logProvider#debugEnabled
  11996. * @description
  11997. * @param {boolean=} flag enable or disable debug level messages
  11998. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  11999. */
  12000. this.debugEnabled = function(flag) {
  12001. if (isDefined(flag)) {
  12002. debug = flag;
  12003. return this;
  12004. } else {
  12005. return debug;
  12006. }
  12007. };
  12008. this.$get = ['$window', function($window) {
  12009. return {
  12010. /**
  12011. * @ngdoc method
  12012. * @name $log#log
  12013. *
  12014. * @description
  12015. * Write a log message
  12016. */
  12017. log: consoleLog('log'),
  12018. /**
  12019. * @ngdoc method
  12020. * @name $log#info
  12021. *
  12022. * @description
  12023. * Write an information message
  12024. */
  12025. info: consoleLog('info'),
  12026. /**
  12027. * @ngdoc method
  12028. * @name $log#warn
  12029. *
  12030. * @description
  12031. * Write a warning message
  12032. */
  12033. warn: consoleLog('warn'),
  12034. /**
  12035. * @ngdoc method
  12036. * @name $log#error
  12037. *
  12038. * @description
  12039. * Write an error message
  12040. */
  12041. error: consoleLog('error'),
  12042. /**
  12043. * @ngdoc method
  12044. * @name $log#debug
  12045. *
  12046. * @description
  12047. * Write a debug message
  12048. */
  12049. debug: (function() {
  12050. var fn = consoleLog('debug');
  12051. return function() {
  12052. if (debug) {
  12053. fn.apply(self, arguments);
  12054. }
  12055. };
  12056. }())
  12057. };
  12058. function formatError(arg) {
  12059. if (arg instanceof Error) {
  12060. if (arg.stack) {
  12061. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  12062. ? 'Error: ' + arg.message + '\n' + arg.stack
  12063. : arg.stack;
  12064. } else if (arg.sourceURL) {
  12065. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  12066. }
  12067. }
  12068. return arg;
  12069. }
  12070. function consoleLog(type) {
  12071. var console = $window.console || {},
  12072. logFn = console[type] || console.log || noop,
  12073. hasApply = false;
  12074. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  12075. // The reason behind this is that console.log has type "object" in IE8...
  12076. try {
  12077. hasApply = !!logFn.apply;
  12078. } catch (e) {}
  12079. if (hasApply) {
  12080. return function() {
  12081. var args = [];
  12082. forEach(arguments, function(arg) {
  12083. args.push(formatError(arg));
  12084. });
  12085. return logFn.apply(console, args);
  12086. };
  12087. }
  12088. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  12089. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  12090. return function(arg1, arg2) {
  12091. logFn(arg1, arg2 == null ? '' : arg2);
  12092. };
  12093. }
  12094. }];
  12095. }
  12096. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  12097. * Any commits to this file should be reviewed with security in mind. *
  12098. * Changes to this file can potentially create security vulnerabilities. *
  12099. * An approval from 2 Core members with history of modifying *
  12100. * this file is required. *
  12101. * *
  12102. * Does the change somehow allow for arbitrary javascript to be executed? *
  12103. * Or allows for someone to change the prototype of built-in objects? *
  12104. * Or gives undesired access to variables likes document or window? *
  12105. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  12106. var $parseMinErr = minErr('$parse');
  12107. // Sandboxing Angular Expressions
  12108. // ------------------------------
  12109. // Angular expressions are generally considered safe because these expressions only have direct
  12110. // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
  12111. // obtaining a reference to native JS functions such as the Function constructor.
  12112. //
  12113. // As an example, consider the following Angular expression:
  12114. //
  12115. // {}.toString.constructor('alert("evil JS code")')
  12116. //
  12117. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  12118. // against the expression language, but not to prevent exploits that were enabled by exposing
  12119. // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
  12120. // practice and therefore we are not even trying to protect against interaction with an object
  12121. // explicitly exposed in this way.
  12122. //
  12123. // In general, it is not possible to access a Window object from an angular expression unless a
  12124. // window or some DOM object that has a reference to window is published onto a Scope.
  12125. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  12126. // native objects.
  12127. //
  12128. // See https://docs.angularjs.org/guide/security
  12129. function ensureSafeMemberName(name, fullExpression) {
  12130. if (name === "__defineGetter__" || name === "__defineSetter__"
  12131. || name === "__lookupGetter__" || name === "__lookupSetter__"
  12132. || name === "__proto__") {
  12133. throw $parseMinErr('isecfld',
  12134. 'Attempting to access a disallowed field in Angular expressions! '
  12135. + 'Expression: {0}', fullExpression);
  12136. }
  12137. return name;
  12138. }
  12139. function getStringValue(name) {
  12140. // Property names must be strings. This means that non-string objects cannot be used
  12141. // as keys in an object. Any non-string object, including a number, is typecasted
  12142. // into a string via the toString method.
  12143. // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names
  12144. //
  12145. // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it
  12146. // to a string. It's not always possible. If `name` is an object and its `toString` method is
  12147. // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:
  12148. //
  12149. // TypeError: Cannot convert object to primitive value
  12150. //
  12151. // For performance reasons, we don't catch this error here and allow it to propagate up the call
  12152. // stack. Note that you'll get the same error in JavaScript if you try to access a property using
  12153. // such a 'broken' object as a key.
  12154. return name + '';
  12155. }
  12156. function ensureSafeObject(obj, fullExpression) {
  12157. // nifty check if obj is Function that is fast and works across iframes and other contexts
  12158. if (obj) {
  12159. if (obj.constructor === obj) {
  12160. throw $parseMinErr('isecfn',
  12161. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  12162. fullExpression);
  12163. } else if (// isWindow(obj)
  12164. obj.window === obj) {
  12165. throw $parseMinErr('isecwindow',
  12166. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  12167. fullExpression);
  12168. } else if (// isElement(obj)
  12169. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  12170. throw $parseMinErr('isecdom',
  12171. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  12172. fullExpression);
  12173. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  12174. obj === Object) {
  12175. throw $parseMinErr('isecobj',
  12176. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  12177. fullExpression);
  12178. }
  12179. }
  12180. return obj;
  12181. }
  12182. var CALL = Function.prototype.call;
  12183. var APPLY = Function.prototype.apply;
  12184. var BIND = Function.prototype.bind;
  12185. function ensureSafeFunction(obj, fullExpression) {
  12186. if (obj) {
  12187. if (obj.constructor === obj) {
  12188. throw $parseMinErr('isecfn',
  12189. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  12190. fullExpression);
  12191. } else if (obj === CALL || obj === APPLY || obj === BIND) {
  12192. throw $parseMinErr('isecff',
  12193. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  12194. fullExpression);
  12195. }
  12196. }
  12197. }
  12198. function ensureSafeAssignContext(obj, fullExpression) {
  12199. if (obj) {
  12200. if (obj === (0).constructor || obj === (false).constructor || obj === ''.constructor ||
  12201. obj === {}.constructor || obj === [].constructor || obj === Function.constructor) {
  12202. throw $parseMinErr('isecaf',
  12203. 'Assigning to a constructor is disallowed! Expression: {0}', fullExpression);
  12204. }
  12205. }
  12206. }
  12207. var OPERATORS = createMap();
  12208. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  12209. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  12210. /////////////////////////////////////////
  12211. /**
  12212. * @constructor
  12213. */
  12214. var Lexer = function(options) {
  12215. this.options = options;
  12216. };
  12217. Lexer.prototype = {
  12218. constructor: Lexer,
  12219. lex: function(text) {
  12220. this.text = text;
  12221. this.index = 0;
  12222. this.tokens = [];
  12223. while (this.index < this.text.length) {
  12224. var ch = this.text.charAt(this.index);
  12225. if (ch === '"' || ch === "'") {
  12226. this.readString(ch);
  12227. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  12228. this.readNumber();
  12229. } else if (this.isIdent(ch)) {
  12230. this.readIdent();
  12231. } else if (this.is(ch, '(){}[].,;:?')) {
  12232. this.tokens.push({index: this.index, text: ch});
  12233. this.index++;
  12234. } else if (this.isWhitespace(ch)) {
  12235. this.index++;
  12236. } else {
  12237. var ch2 = ch + this.peek();
  12238. var ch3 = ch2 + this.peek(2);
  12239. var op1 = OPERATORS[ch];
  12240. var op2 = OPERATORS[ch2];
  12241. var op3 = OPERATORS[ch3];
  12242. if (op1 || op2 || op3) {
  12243. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  12244. this.tokens.push({index: this.index, text: token, operator: true});
  12245. this.index += token.length;
  12246. } else {
  12247. this.throwError('Unexpected next character ', this.index, this.index + 1);
  12248. }
  12249. }
  12250. }
  12251. return this.tokens;
  12252. },
  12253. is: function(ch, chars) {
  12254. return chars.indexOf(ch) !== -1;
  12255. },
  12256. peek: function(i) {
  12257. var num = i || 1;
  12258. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  12259. },
  12260. isNumber: function(ch) {
  12261. return ('0' <= ch && ch <= '9') && typeof ch === "string";
  12262. },
  12263. isWhitespace: function(ch) {
  12264. // IE treats non-breaking space as \u00A0
  12265. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  12266. ch === '\n' || ch === '\v' || ch === '\u00A0');
  12267. },
  12268. isIdent: function(ch) {
  12269. return ('a' <= ch && ch <= 'z' ||
  12270. 'A' <= ch && ch <= 'Z' ||
  12271. '_' === ch || ch === '$');
  12272. },
  12273. isExpOperator: function(ch) {
  12274. return (ch === '-' || ch === '+' || this.isNumber(ch));
  12275. },
  12276. throwError: function(error, start, end) {
  12277. end = end || this.index;
  12278. var colStr = (isDefined(start)
  12279. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  12280. : ' ' + end);
  12281. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  12282. error, colStr, this.text);
  12283. },
  12284. readNumber: function() {
  12285. var number = '';
  12286. var start = this.index;
  12287. while (this.index < this.text.length) {
  12288. var ch = lowercase(this.text.charAt(this.index));
  12289. if (ch == '.' || this.isNumber(ch)) {
  12290. number += ch;
  12291. } else {
  12292. var peekCh = this.peek();
  12293. if (ch == 'e' && this.isExpOperator(peekCh)) {
  12294. number += ch;
  12295. } else if (this.isExpOperator(ch) &&
  12296. peekCh && this.isNumber(peekCh) &&
  12297. number.charAt(number.length - 1) == 'e') {
  12298. number += ch;
  12299. } else if (this.isExpOperator(ch) &&
  12300. (!peekCh || !this.isNumber(peekCh)) &&
  12301. number.charAt(number.length - 1) == 'e') {
  12302. this.throwError('Invalid exponent');
  12303. } else {
  12304. break;
  12305. }
  12306. }
  12307. this.index++;
  12308. }
  12309. this.tokens.push({
  12310. index: start,
  12311. text: number,
  12312. constant: true,
  12313. value: Number(number)
  12314. });
  12315. },
  12316. readIdent: function() {
  12317. var start = this.index;
  12318. while (this.index < this.text.length) {
  12319. var ch = this.text.charAt(this.index);
  12320. if (!(this.isIdent(ch) || this.isNumber(ch))) {
  12321. break;
  12322. }
  12323. this.index++;
  12324. }
  12325. this.tokens.push({
  12326. index: start,
  12327. text: this.text.slice(start, this.index),
  12328. identifier: true
  12329. });
  12330. },
  12331. readString: function(quote) {
  12332. var start = this.index;
  12333. this.index++;
  12334. var string = '';
  12335. var rawString = quote;
  12336. var escape = false;
  12337. while (this.index < this.text.length) {
  12338. var ch = this.text.charAt(this.index);
  12339. rawString += ch;
  12340. if (escape) {
  12341. if (ch === 'u') {
  12342. var hex = this.text.substring(this.index + 1, this.index + 5);
  12343. if (!hex.match(/[\da-f]{4}/i)) {
  12344. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  12345. }
  12346. this.index += 4;
  12347. string += String.fromCharCode(parseInt(hex, 16));
  12348. } else {
  12349. var rep = ESCAPE[ch];
  12350. string = string + (rep || ch);
  12351. }
  12352. escape = false;
  12353. } else if (ch === '\\') {
  12354. escape = true;
  12355. } else if (ch === quote) {
  12356. this.index++;
  12357. this.tokens.push({
  12358. index: start,
  12359. text: rawString,
  12360. constant: true,
  12361. value: string
  12362. });
  12363. return;
  12364. } else {
  12365. string += ch;
  12366. }
  12367. this.index++;
  12368. }
  12369. this.throwError('Unterminated quote', start);
  12370. }
  12371. };
  12372. var AST = function(lexer, options) {
  12373. this.lexer = lexer;
  12374. this.options = options;
  12375. };
  12376. AST.Program = 'Program';
  12377. AST.ExpressionStatement = 'ExpressionStatement';
  12378. AST.AssignmentExpression = 'AssignmentExpression';
  12379. AST.ConditionalExpression = 'ConditionalExpression';
  12380. AST.LogicalExpression = 'LogicalExpression';
  12381. AST.BinaryExpression = 'BinaryExpression';
  12382. AST.UnaryExpression = 'UnaryExpression';
  12383. AST.CallExpression = 'CallExpression';
  12384. AST.MemberExpression = 'MemberExpression';
  12385. AST.Identifier = 'Identifier';
  12386. AST.Literal = 'Literal';
  12387. AST.ArrayExpression = 'ArrayExpression';
  12388. AST.Property = 'Property';
  12389. AST.ObjectExpression = 'ObjectExpression';
  12390. AST.ThisExpression = 'ThisExpression';
  12391. AST.LocalsExpression = 'LocalsExpression';
  12392. // Internal use only
  12393. AST.NGValueParameter = 'NGValueParameter';
  12394. AST.prototype = {
  12395. ast: function(text) {
  12396. this.text = text;
  12397. this.tokens = this.lexer.lex(text);
  12398. var value = this.program();
  12399. if (this.tokens.length !== 0) {
  12400. this.throwError('is an unexpected token', this.tokens[0]);
  12401. }
  12402. return value;
  12403. },
  12404. program: function() {
  12405. var body = [];
  12406. while (true) {
  12407. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  12408. body.push(this.expressionStatement());
  12409. if (!this.expect(';')) {
  12410. return { type: AST.Program, body: body};
  12411. }
  12412. }
  12413. },
  12414. expressionStatement: function() {
  12415. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  12416. },
  12417. filterChain: function() {
  12418. var left = this.expression();
  12419. var token;
  12420. while ((token = this.expect('|'))) {
  12421. left = this.filter(left);
  12422. }
  12423. return left;
  12424. },
  12425. expression: function() {
  12426. return this.assignment();
  12427. },
  12428. assignment: function() {
  12429. var result = this.ternary();
  12430. if (this.expect('=')) {
  12431. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  12432. }
  12433. return result;
  12434. },
  12435. ternary: function() {
  12436. var test = this.logicalOR();
  12437. var alternate;
  12438. var consequent;
  12439. if (this.expect('?')) {
  12440. alternate = this.expression();
  12441. if (this.consume(':')) {
  12442. consequent = this.expression();
  12443. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  12444. }
  12445. }
  12446. return test;
  12447. },
  12448. logicalOR: function() {
  12449. var left = this.logicalAND();
  12450. while (this.expect('||')) {
  12451. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  12452. }
  12453. return left;
  12454. },
  12455. logicalAND: function() {
  12456. var left = this.equality();
  12457. while (this.expect('&&')) {
  12458. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  12459. }
  12460. return left;
  12461. },
  12462. equality: function() {
  12463. var left = this.relational();
  12464. var token;
  12465. while ((token = this.expect('==','!=','===','!=='))) {
  12466. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  12467. }
  12468. return left;
  12469. },
  12470. relational: function() {
  12471. var left = this.additive();
  12472. var token;
  12473. while ((token = this.expect('<', '>', '<=', '>='))) {
  12474. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  12475. }
  12476. return left;
  12477. },
  12478. additive: function() {
  12479. var left = this.multiplicative();
  12480. var token;
  12481. while ((token = this.expect('+','-'))) {
  12482. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  12483. }
  12484. return left;
  12485. },
  12486. multiplicative: function() {
  12487. var left = this.unary();
  12488. var token;
  12489. while ((token = this.expect('*','/','%'))) {
  12490. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  12491. }
  12492. return left;
  12493. },
  12494. unary: function() {
  12495. var token;
  12496. if ((token = this.expect('+', '-', '!'))) {
  12497. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  12498. } else {
  12499. return this.primary();
  12500. }
  12501. },
  12502. primary: function() {
  12503. var primary;
  12504. if (this.expect('(')) {
  12505. primary = this.filterChain();
  12506. this.consume(')');
  12507. } else if (this.expect('[')) {
  12508. primary = this.arrayDeclaration();
  12509. } else if (this.expect('{')) {
  12510. primary = this.object();
  12511. } else if (this.selfReferential.hasOwnProperty(this.peek().text)) {
  12512. primary = copy(this.selfReferential[this.consume().text]);
  12513. } else if (this.options.literals.hasOwnProperty(this.peek().text)) {
  12514. primary = { type: AST.Literal, value: this.options.literals[this.consume().text]};
  12515. } else if (this.peek().identifier) {
  12516. primary = this.identifier();
  12517. } else if (this.peek().constant) {
  12518. primary = this.constant();
  12519. } else {
  12520. this.throwError('not a primary expression', this.peek());
  12521. }
  12522. var next;
  12523. while ((next = this.expect('(', '[', '.'))) {
  12524. if (next.text === '(') {
  12525. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  12526. this.consume(')');
  12527. } else if (next.text === '[') {
  12528. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  12529. this.consume(']');
  12530. } else if (next.text === '.') {
  12531. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  12532. } else {
  12533. this.throwError('IMPOSSIBLE');
  12534. }
  12535. }
  12536. return primary;
  12537. },
  12538. filter: function(baseExpression) {
  12539. var args = [baseExpression];
  12540. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  12541. while (this.expect(':')) {
  12542. args.push(this.expression());
  12543. }
  12544. return result;
  12545. },
  12546. parseArguments: function() {
  12547. var args = [];
  12548. if (this.peekToken().text !== ')') {
  12549. do {
  12550. args.push(this.expression());
  12551. } while (this.expect(','));
  12552. }
  12553. return args;
  12554. },
  12555. identifier: function() {
  12556. var token = this.consume();
  12557. if (!token.identifier) {
  12558. this.throwError('is not a valid identifier', token);
  12559. }
  12560. return { type: AST.Identifier, name: token.text };
  12561. },
  12562. constant: function() {
  12563. // TODO check that it is a constant
  12564. return { type: AST.Literal, value: this.consume().value };
  12565. },
  12566. arrayDeclaration: function() {
  12567. var elements = [];
  12568. if (this.peekToken().text !== ']') {
  12569. do {
  12570. if (this.peek(']')) {
  12571. // Support trailing commas per ES5.1.
  12572. break;
  12573. }
  12574. elements.push(this.expression());
  12575. } while (this.expect(','));
  12576. }
  12577. this.consume(']');
  12578. return { type: AST.ArrayExpression, elements: elements };
  12579. },
  12580. object: function() {
  12581. var properties = [], property;
  12582. if (this.peekToken().text !== '}') {
  12583. do {
  12584. if (this.peek('}')) {
  12585. // Support trailing commas per ES5.1.
  12586. break;
  12587. }
  12588. property = {type: AST.Property, kind: 'init'};
  12589. if (this.peek().constant) {
  12590. property.key = this.constant();
  12591. } else if (this.peek().identifier) {
  12592. property.key = this.identifier();
  12593. } else {
  12594. this.throwError("invalid key", this.peek());
  12595. }
  12596. this.consume(':');
  12597. property.value = this.expression();
  12598. properties.push(property);
  12599. } while (this.expect(','));
  12600. }
  12601. this.consume('}');
  12602. return {type: AST.ObjectExpression, properties: properties };
  12603. },
  12604. throwError: function(msg, token) {
  12605. throw $parseMinErr('syntax',
  12606. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  12607. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  12608. },
  12609. consume: function(e1) {
  12610. if (this.tokens.length === 0) {
  12611. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  12612. }
  12613. var token = this.expect(e1);
  12614. if (!token) {
  12615. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  12616. }
  12617. return token;
  12618. },
  12619. peekToken: function() {
  12620. if (this.tokens.length === 0) {
  12621. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  12622. }
  12623. return this.tokens[0];
  12624. },
  12625. peek: function(e1, e2, e3, e4) {
  12626. return this.peekAhead(0, e1, e2, e3, e4);
  12627. },
  12628. peekAhead: function(i, e1, e2, e3, e4) {
  12629. if (this.tokens.length > i) {
  12630. var token = this.tokens[i];
  12631. var t = token.text;
  12632. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  12633. (!e1 && !e2 && !e3 && !e4)) {
  12634. return token;
  12635. }
  12636. }
  12637. return false;
  12638. },
  12639. expect: function(e1, e2, e3, e4) {
  12640. var token = this.peek(e1, e2, e3, e4);
  12641. if (token) {
  12642. this.tokens.shift();
  12643. return token;
  12644. }
  12645. return false;
  12646. },
  12647. selfReferential: {
  12648. 'this': {type: AST.ThisExpression },
  12649. '$locals': {type: AST.LocalsExpression }
  12650. }
  12651. };
  12652. function ifDefined(v, d) {
  12653. return typeof v !== 'undefined' ? v : d;
  12654. }
  12655. function plusFn(l, r) {
  12656. if (typeof l === 'undefined') return r;
  12657. if (typeof r === 'undefined') return l;
  12658. return l + r;
  12659. }
  12660. function isStateless($filter, filterName) {
  12661. var fn = $filter(filterName);
  12662. return !fn.$stateful;
  12663. }
  12664. function findConstantAndWatchExpressions(ast, $filter) {
  12665. var allConstants;
  12666. var argsToWatch;
  12667. switch (ast.type) {
  12668. case AST.Program:
  12669. allConstants = true;
  12670. forEach(ast.body, function(expr) {
  12671. findConstantAndWatchExpressions(expr.expression, $filter);
  12672. allConstants = allConstants && expr.expression.constant;
  12673. });
  12674. ast.constant = allConstants;
  12675. break;
  12676. case AST.Literal:
  12677. ast.constant = true;
  12678. ast.toWatch = [];
  12679. break;
  12680. case AST.UnaryExpression:
  12681. findConstantAndWatchExpressions(ast.argument, $filter);
  12682. ast.constant = ast.argument.constant;
  12683. ast.toWatch = ast.argument.toWatch;
  12684. break;
  12685. case AST.BinaryExpression:
  12686. findConstantAndWatchExpressions(ast.left, $filter);
  12687. findConstantAndWatchExpressions(ast.right, $filter);
  12688. ast.constant = ast.left.constant && ast.right.constant;
  12689. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  12690. break;
  12691. case AST.LogicalExpression:
  12692. findConstantAndWatchExpressions(ast.left, $filter);
  12693. findConstantAndWatchExpressions(ast.right, $filter);
  12694. ast.constant = ast.left.constant && ast.right.constant;
  12695. ast.toWatch = ast.constant ? [] : [ast];
  12696. break;
  12697. case AST.ConditionalExpression:
  12698. findConstantAndWatchExpressions(ast.test, $filter);
  12699. findConstantAndWatchExpressions(ast.alternate, $filter);
  12700. findConstantAndWatchExpressions(ast.consequent, $filter);
  12701. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  12702. ast.toWatch = ast.constant ? [] : [ast];
  12703. break;
  12704. case AST.Identifier:
  12705. ast.constant = false;
  12706. ast.toWatch = [ast];
  12707. break;
  12708. case AST.MemberExpression:
  12709. findConstantAndWatchExpressions(ast.object, $filter);
  12710. if (ast.computed) {
  12711. findConstantAndWatchExpressions(ast.property, $filter);
  12712. }
  12713. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  12714. ast.toWatch = [ast];
  12715. break;
  12716. case AST.CallExpression:
  12717. allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
  12718. argsToWatch = [];
  12719. forEach(ast.arguments, function(expr) {
  12720. findConstantAndWatchExpressions(expr, $filter);
  12721. allConstants = allConstants && expr.constant;
  12722. if (!expr.constant) {
  12723. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  12724. }
  12725. });
  12726. ast.constant = allConstants;
  12727. ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
  12728. break;
  12729. case AST.AssignmentExpression:
  12730. findConstantAndWatchExpressions(ast.left, $filter);
  12731. findConstantAndWatchExpressions(ast.right, $filter);
  12732. ast.constant = ast.left.constant && ast.right.constant;
  12733. ast.toWatch = [ast];
  12734. break;
  12735. case AST.ArrayExpression:
  12736. allConstants = true;
  12737. argsToWatch = [];
  12738. forEach(ast.elements, function(expr) {
  12739. findConstantAndWatchExpressions(expr, $filter);
  12740. allConstants = allConstants && expr.constant;
  12741. if (!expr.constant) {
  12742. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  12743. }
  12744. });
  12745. ast.constant = allConstants;
  12746. ast.toWatch = argsToWatch;
  12747. break;
  12748. case AST.ObjectExpression:
  12749. allConstants = true;
  12750. argsToWatch = [];
  12751. forEach(ast.properties, function(property) {
  12752. findConstantAndWatchExpressions(property.value, $filter);
  12753. allConstants = allConstants && property.value.constant;
  12754. if (!property.value.constant) {
  12755. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  12756. }
  12757. });
  12758. ast.constant = allConstants;
  12759. ast.toWatch = argsToWatch;
  12760. break;
  12761. case AST.ThisExpression:
  12762. ast.constant = false;
  12763. ast.toWatch = [];
  12764. break;
  12765. case AST.LocalsExpression:
  12766. ast.constant = false;
  12767. ast.toWatch = [];
  12768. break;
  12769. }
  12770. }
  12771. function getInputs(body) {
  12772. if (body.length != 1) return;
  12773. var lastExpression = body[0].expression;
  12774. var candidate = lastExpression.toWatch;
  12775. if (candidate.length !== 1) return candidate;
  12776. return candidate[0] !== lastExpression ? candidate : undefined;
  12777. }
  12778. function isAssignable(ast) {
  12779. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  12780. }
  12781. function assignableAST(ast) {
  12782. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  12783. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  12784. }
  12785. }
  12786. function isLiteral(ast) {
  12787. return ast.body.length === 0 ||
  12788. ast.body.length === 1 && (
  12789. ast.body[0].expression.type === AST.Literal ||
  12790. ast.body[0].expression.type === AST.ArrayExpression ||
  12791. ast.body[0].expression.type === AST.ObjectExpression);
  12792. }
  12793. function isConstant(ast) {
  12794. return ast.constant;
  12795. }
  12796. function ASTCompiler(astBuilder, $filter) {
  12797. this.astBuilder = astBuilder;
  12798. this.$filter = $filter;
  12799. }
  12800. ASTCompiler.prototype = {
  12801. compile: function(expression, expensiveChecks) {
  12802. var self = this;
  12803. var ast = this.astBuilder.ast(expression);
  12804. this.state = {
  12805. nextId: 0,
  12806. filters: {},
  12807. expensiveChecks: expensiveChecks,
  12808. fn: {vars: [], body: [], own: {}},
  12809. assign: {vars: [], body: [], own: {}},
  12810. inputs: []
  12811. };
  12812. findConstantAndWatchExpressions(ast, self.$filter);
  12813. var extra = '';
  12814. var assignable;
  12815. this.stage = 'assign';
  12816. if ((assignable = assignableAST(ast))) {
  12817. this.state.computing = 'assign';
  12818. var result = this.nextId();
  12819. this.recurse(assignable, result);
  12820. this.return_(result);
  12821. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  12822. }
  12823. var toWatch = getInputs(ast.body);
  12824. self.stage = 'inputs';
  12825. forEach(toWatch, function(watch, key) {
  12826. var fnKey = 'fn' + key;
  12827. self.state[fnKey] = {vars: [], body: [], own: {}};
  12828. self.state.computing = fnKey;
  12829. var intoId = self.nextId();
  12830. self.recurse(watch, intoId);
  12831. self.return_(intoId);
  12832. self.state.inputs.push(fnKey);
  12833. watch.watchId = key;
  12834. });
  12835. this.state.computing = 'fn';
  12836. this.stage = 'main';
  12837. this.recurse(ast);
  12838. var fnString =
  12839. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  12840. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  12841. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  12842. this.filterPrefix() +
  12843. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  12844. extra +
  12845. this.watchFns() +
  12846. 'return fn;';
  12847. /* jshint -W054 */
  12848. var fn = (new Function('$filter',
  12849. 'ensureSafeMemberName',
  12850. 'ensureSafeObject',
  12851. 'ensureSafeFunction',
  12852. 'getStringValue',
  12853. 'ensureSafeAssignContext',
  12854. 'ifDefined',
  12855. 'plus',
  12856. 'text',
  12857. fnString))(
  12858. this.$filter,
  12859. ensureSafeMemberName,
  12860. ensureSafeObject,
  12861. ensureSafeFunction,
  12862. getStringValue,
  12863. ensureSafeAssignContext,
  12864. ifDefined,
  12865. plusFn,
  12866. expression);
  12867. /* jshint +W054 */
  12868. this.state = this.stage = undefined;
  12869. fn.literal = isLiteral(ast);
  12870. fn.constant = isConstant(ast);
  12871. return fn;
  12872. },
  12873. USE: 'use',
  12874. STRICT: 'strict',
  12875. watchFns: function() {
  12876. var result = [];
  12877. var fns = this.state.inputs;
  12878. var self = this;
  12879. forEach(fns, function(name) {
  12880. result.push('var ' + name + '=' + self.generateFunction(name, 's'));
  12881. });
  12882. if (fns.length) {
  12883. result.push('fn.inputs=[' + fns.join(',') + '];');
  12884. }
  12885. return result.join('');
  12886. },
  12887. generateFunction: function(name, params) {
  12888. return 'function(' + params + '){' +
  12889. this.varsPrefix(name) +
  12890. this.body(name) +
  12891. '};';
  12892. },
  12893. filterPrefix: function() {
  12894. var parts = [];
  12895. var self = this;
  12896. forEach(this.state.filters, function(id, filter) {
  12897. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  12898. });
  12899. if (parts.length) return 'var ' + parts.join(',') + ';';
  12900. return '';
  12901. },
  12902. varsPrefix: function(section) {
  12903. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  12904. },
  12905. body: function(section) {
  12906. return this.state[section].body.join('');
  12907. },
  12908. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  12909. var left, right, self = this, args, expression;
  12910. recursionFn = recursionFn || noop;
  12911. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  12912. intoId = intoId || this.nextId();
  12913. this.if_('i',
  12914. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  12915. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  12916. );
  12917. return;
  12918. }
  12919. switch (ast.type) {
  12920. case AST.Program:
  12921. forEach(ast.body, function(expression, pos) {
  12922. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  12923. if (pos !== ast.body.length - 1) {
  12924. self.current().body.push(right, ';');
  12925. } else {
  12926. self.return_(right);
  12927. }
  12928. });
  12929. break;
  12930. case AST.Literal:
  12931. expression = this.escape(ast.value);
  12932. this.assign(intoId, expression);
  12933. recursionFn(expression);
  12934. break;
  12935. case AST.UnaryExpression:
  12936. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  12937. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  12938. this.assign(intoId, expression);
  12939. recursionFn(expression);
  12940. break;
  12941. case AST.BinaryExpression:
  12942. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  12943. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  12944. if (ast.operator === '+') {
  12945. expression = this.plus(left, right);
  12946. } else if (ast.operator === '-') {
  12947. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  12948. } else {
  12949. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  12950. }
  12951. this.assign(intoId, expression);
  12952. recursionFn(expression);
  12953. break;
  12954. case AST.LogicalExpression:
  12955. intoId = intoId || this.nextId();
  12956. self.recurse(ast.left, intoId);
  12957. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  12958. recursionFn(intoId);
  12959. break;
  12960. case AST.ConditionalExpression:
  12961. intoId = intoId || this.nextId();
  12962. self.recurse(ast.test, intoId);
  12963. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  12964. recursionFn(intoId);
  12965. break;
  12966. case AST.Identifier:
  12967. intoId = intoId || this.nextId();
  12968. if (nameId) {
  12969. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  12970. nameId.computed = false;
  12971. nameId.name = ast.name;
  12972. }
  12973. ensureSafeMemberName(ast.name);
  12974. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  12975. function() {
  12976. self.if_(self.stage === 'inputs' || 's', function() {
  12977. if (create && create !== 1) {
  12978. self.if_(
  12979. self.not(self.nonComputedMember('s', ast.name)),
  12980. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  12981. }
  12982. self.assign(intoId, self.nonComputedMember('s', ast.name));
  12983. });
  12984. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  12985. );
  12986. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
  12987. self.addEnsureSafeObject(intoId);
  12988. }
  12989. recursionFn(intoId);
  12990. break;
  12991. case AST.MemberExpression:
  12992. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  12993. intoId = intoId || this.nextId();
  12994. self.recurse(ast.object, left, undefined, function() {
  12995. self.if_(self.notNull(left), function() {
  12996. if (create && create !== 1) {
  12997. self.addEnsureSafeAssignContext(left);
  12998. }
  12999. if (ast.computed) {
  13000. right = self.nextId();
  13001. self.recurse(ast.property, right);
  13002. self.getStringValue(right);
  13003. self.addEnsureSafeMemberName(right);
  13004. if (create && create !== 1) {
  13005. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  13006. }
  13007. expression = self.ensureSafeObject(self.computedMember(left, right));
  13008. self.assign(intoId, expression);
  13009. if (nameId) {
  13010. nameId.computed = true;
  13011. nameId.name = right;
  13012. }
  13013. } else {
  13014. ensureSafeMemberName(ast.property.name);
  13015. if (create && create !== 1) {
  13016. self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  13017. }
  13018. expression = self.nonComputedMember(left, ast.property.name);
  13019. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
  13020. expression = self.ensureSafeObject(expression);
  13021. }
  13022. self.assign(intoId, expression);
  13023. if (nameId) {
  13024. nameId.computed = false;
  13025. nameId.name = ast.property.name;
  13026. }
  13027. }
  13028. }, function() {
  13029. self.assign(intoId, 'undefined');
  13030. });
  13031. recursionFn(intoId);
  13032. }, !!create);
  13033. break;
  13034. case AST.CallExpression:
  13035. intoId = intoId || this.nextId();
  13036. if (ast.filter) {
  13037. right = self.filter(ast.callee.name);
  13038. args = [];
  13039. forEach(ast.arguments, function(expr) {
  13040. var argument = self.nextId();
  13041. self.recurse(expr, argument);
  13042. args.push(argument);
  13043. });
  13044. expression = right + '(' + args.join(',') + ')';
  13045. self.assign(intoId, expression);
  13046. recursionFn(intoId);
  13047. } else {
  13048. right = self.nextId();
  13049. left = {};
  13050. args = [];
  13051. self.recurse(ast.callee, right, left, function() {
  13052. self.if_(self.notNull(right), function() {
  13053. self.addEnsureSafeFunction(right);
  13054. forEach(ast.arguments, function(expr) {
  13055. self.recurse(expr, self.nextId(), undefined, function(argument) {
  13056. args.push(self.ensureSafeObject(argument));
  13057. });
  13058. });
  13059. if (left.name) {
  13060. if (!self.state.expensiveChecks) {
  13061. self.addEnsureSafeObject(left.context);
  13062. }
  13063. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  13064. } else {
  13065. expression = right + '(' + args.join(',') + ')';
  13066. }
  13067. expression = self.ensureSafeObject(expression);
  13068. self.assign(intoId, expression);
  13069. }, function() {
  13070. self.assign(intoId, 'undefined');
  13071. });
  13072. recursionFn(intoId);
  13073. });
  13074. }
  13075. break;
  13076. case AST.AssignmentExpression:
  13077. right = this.nextId();
  13078. left = {};
  13079. if (!isAssignable(ast.left)) {
  13080. throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
  13081. }
  13082. this.recurse(ast.left, undefined, left, function() {
  13083. self.if_(self.notNull(left.context), function() {
  13084. self.recurse(ast.right, right);
  13085. self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
  13086. self.addEnsureSafeAssignContext(left.context);
  13087. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  13088. self.assign(intoId, expression);
  13089. recursionFn(intoId || expression);
  13090. });
  13091. }, 1);
  13092. break;
  13093. case AST.ArrayExpression:
  13094. args = [];
  13095. forEach(ast.elements, function(expr) {
  13096. self.recurse(expr, self.nextId(), undefined, function(argument) {
  13097. args.push(argument);
  13098. });
  13099. });
  13100. expression = '[' + args.join(',') + ']';
  13101. this.assign(intoId, expression);
  13102. recursionFn(expression);
  13103. break;
  13104. case AST.ObjectExpression:
  13105. args = [];
  13106. forEach(ast.properties, function(property) {
  13107. self.recurse(property.value, self.nextId(), undefined, function(expr) {
  13108. args.push(self.escape(
  13109. property.key.type === AST.Identifier ? property.key.name :
  13110. ('' + property.key.value)) +
  13111. ':' + expr);
  13112. });
  13113. });
  13114. expression = '{' + args.join(',') + '}';
  13115. this.assign(intoId, expression);
  13116. recursionFn(expression);
  13117. break;
  13118. case AST.ThisExpression:
  13119. this.assign(intoId, 's');
  13120. recursionFn('s');
  13121. break;
  13122. case AST.LocalsExpression:
  13123. this.assign(intoId, 'l');
  13124. recursionFn('l');
  13125. break;
  13126. case AST.NGValueParameter:
  13127. this.assign(intoId, 'v');
  13128. recursionFn('v');
  13129. break;
  13130. }
  13131. },
  13132. getHasOwnProperty: function(element, property) {
  13133. var key = element + '.' + property;
  13134. var own = this.current().own;
  13135. if (!own.hasOwnProperty(key)) {
  13136. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  13137. }
  13138. return own[key];
  13139. },
  13140. assign: function(id, value) {
  13141. if (!id) return;
  13142. this.current().body.push(id, '=', value, ';');
  13143. return id;
  13144. },
  13145. filter: function(filterName) {
  13146. if (!this.state.filters.hasOwnProperty(filterName)) {
  13147. this.state.filters[filterName] = this.nextId(true);
  13148. }
  13149. return this.state.filters[filterName];
  13150. },
  13151. ifDefined: function(id, defaultValue) {
  13152. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  13153. },
  13154. plus: function(left, right) {
  13155. return 'plus(' + left + ',' + right + ')';
  13156. },
  13157. return_: function(id) {
  13158. this.current().body.push('return ', id, ';');
  13159. },
  13160. if_: function(test, alternate, consequent) {
  13161. if (test === true) {
  13162. alternate();
  13163. } else {
  13164. var body = this.current().body;
  13165. body.push('if(', test, '){');
  13166. alternate();
  13167. body.push('}');
  13168. if (consequent) {
  13169. body.push('else{');
  13170. consequent();
  13171. body.push('}');
  13172. }
  13173. }
  13174. },
  13175. not: function(expression) {
  13176. return '!(' + expression + ')';
  13177. },
  13178. notNull: function(expression) {
  13179. return expression + '!=null';
  13180. },
  13181. nonComputedMember: function(left, right) {
  13182. return left + '.' + right;
  13183. },
  13184. computedMember: function(left, right) {
  13185. return left + '[' + right + ']';
  13186. },
  13187. member: function(left, right, computed) {
  13188. if (computed) return this.computedMember(left, right);
  13189. return this.nonComputedMember(left, right);
  13190. },
  13191. addEnsureSafeObject: function(item) {
  13192. this.current().body.push(this.ensureSafeObject(item), ';');
  13193. },
  13194. addEnsureSafeMemberName: function(item) {
  13195. this.current().body.push(this.ensureSafeMemberName(item), ';');
  13196. },
  13197. addEnsureSafeFunction: function(item) {
  13198. this.current().body.push(this.ensureSafeFunction(item), ';');
  13199. },
  13200. addEnsureSafeAssignContext: function(item) {
  13201. this.current().body.push(this.ensureSafeAssignContext(item), ';');
  13202. },
  13203. ensureSafeObject: function(item) {
  13204. return 'ensureSafeObject(' + item + ',text)';
  13205. },
  13206. ensureSafeMemberName: function(item) {
  13207. return 'ensureSafeMemberName(' + item + ',text)';
  13208. },
  13209. ensureSafeFunction: function(item) {
  13210. return 'ensureSafeFunction(' + item + ',text)';
  13211. },
  13212. getStringValue: function(item) {
  13213. this.assign(item, 'getStringValue(' + item + ')');
  13214. },
  13215. ensureSafeAssignContext: function(item) {
  13216. return 'ensureSafeAssignContext(' + item + ',text)';
  13217. },
  13218. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  13219. var self = this;
  13220. return function() {
  13221. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  13222. };
  13223. },
  13224. lazyAssign: function(id, value) {
  13225. var self = this;
  13226. return function() {
  13227. self.assign(id, value);
  13228. };
  13229. },
  13230. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  13231. stringEscapeFn: function(c) {
  13232. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  13233. },
  13234. escape: function(value) {
  13235. if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
  13236. if (isNumber(value)) return value.toString();
  13237. if (value === true) return 'true';
  13238. if (value === false) return 'false';
  13239. if (value === null) return 'null';
  13240. if (typeof value === 'undefined') return 'undefined';
  13241. throw $parseMinErr('esc', 'IMPOSSIBLE');
  13242. },
  13243. nextId: function(skip, init) {
  13244. var id = 'v' + (this.state.nextId++);
  13245. if (!skip) {
  13246. this.current().vars.push(id + (init ? '=' + init : ''));
  13247. }
  13248. return id;
  13249. },
  13250. current: function() {
  13251. return this.state[this.state.computing];
  13252. }
  13253. };
  13254. function ASTInterpreter(astBuilder, $filter) {
  13255. this.astBuilder = astBuilder;
  13256. this.$filter = $filter;
  13257. }
  13258. ASTInterpreter.prototype = {
  13259. compile: function(expression, expensiveChecks) {
  13260. var self = this;
  13261. var ast = this.astBuilder.ast(expression);
  13262. this.expression = expression;
  13263. this.expensiveChecks = expensiveChecks;
  13264. findConstantAndWatchExpressions(ast, self.$filter);
  13265. var assignable;
  13266. var assign;
  13267. if ((assignable = assignableAST(ast))) {
  13268. assign = this.recurse(assignable);
  13269. }
  13270. var toWatch = getInputs(ast.body);
  13271. var inputs;
  13272. if (toWatch) {
  13273. inputs = [];
  13274. forEach(toWatch, function(watch, key) {
  13275. var input = self.recurse(watch);
  13276. watch.input = input;
  13277. inputs.push(input);
  13278. watch.watchId = key;
  13279. });
  13280. }
  13281. var expressions = [];
  13282. forEach(ast.body, function(expression) {
  13283. expressions.push(self.recurse(expression.expression));
  13284. });
  13285. var fn = ast.body.length === 0 ? noop :
  13286. ast.body.length === 1 ? expressions[0] :
  13287. function(scope, locals) {
  13288. var lastValue;
  13289. forEach(expressions, function(exp) {
  13290. lastValue = exp(scope, locals);
  13291. });
  13292. return lastValue;
  13293. };
  13294. if (assign) {
  13295. fn.assign = function(scope, value, locals) {
  13296. return assign(scope, locals, value);
  13297. };
  13298. }
  13299. if (inputs) {
  13300. fn.inputs = inputs;
  13301. }
  13302. fn.literal = isLiteral(ast);
  13303. fn.constant = isConstant(ast);
  13304. return fn;
  13305. },
  13306. recurse: function(ast, context, create) {
  13307. var left, right, self = this, args, expression;
  13308. if (ast.input) {
  13309. return this.inputs(ast.input, ast.watchId);
  13310. }
  13311. switch (ast.type) {
  13312. case AST.Literal:
  13313. return this.value(ast.value, context);
  13314. case AST.UnaryExpression:
  13315. right = this.recurse(ast.argument);
  13316. return this['unary' + ast.operator](right, context);
  13317. case AST.BinaryExpression:
  13318. left = this.recurse(ast.left);
  13319. right = this.recurse(ast.right);
  13320. return this['binary' + ast.operator](left, right, context);
  13321. case AST.LogicalExpression:
  13322. left = this.recurse(ast.left);
  13323. right = this.recurse(ast.right);
  13324. return this['binary' + ast.operator](left, right, context);
  13325. case AST.ConditionalExpression:
  13326. return this['ternary?:'](
  13327. this.recurse(ast.test),
  13328. this.recurse(ast.alternate),
  13329. this.recurse(ast.consequent),
  13330. context
  13331. );
  13332. case AST.Identifier:
  13333. ensureSafeMemberName(ast.name, self.expression);
  13334. return self.identifier(ast.name,
  13335. self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
  13336. context, create, self.expression);
  13337. case AST.MemberExpression:
  13338. left = this.recurse(ast.object, false, !!create);
  13339. if (!ast.computed) {
  13340. ensureSafeMemberName(ast.property.name, self.expression);
  13341. right = ast.property.name;
  13342. }
  13343. if (ast.computed) right = this.recurse(ast.property);
  13344. return ast.computed ?
  13345. this.computedMember(left, right, context, create, self.expression) :
  13346. this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
  13347. case AST.CallExpression:
  13348. args = [];
  13349. forEach(ast.arguments, function(expr) {
  13350. args.push(self.recurse(expr));
  13351. });
  13352. if (ast.filter) right = this.$filter(ast.callee.name);
  13353. if (!ast.filter) right = this.recurse(ast.callee, true);
  13354. return ast.filter ?
  13355. function(scope, locals, assign, inputs) {
  13356. var values = [];
  13357. for (var i = 0; i < args.length; ++i) {
  13358. values.push(args[i](scope, locals, assign, inputs));
  13359. }
  13360. var value = right.apply(undefined, values, inputs);
  13361. return context ? {context: undefined, name: undefined, value: value} : value;
  13362. } :
  13363. function(scope, locals, assign, inputs) {
  13364. var rhs = right(scope, locals, assign, inputs);
  13365. var value;
  13366. if (rhs.value != null) {
  13367. ensureSafeObject(rhs.context, self.expression);
  13368. ensureSafeFunction(rhs.value, self.expression);
  13369. var values = [];
  13370. for (var i = 0; i < args.length; ++i) {
  13371. values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
  13372. }
  13373. value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
  13374. }
  13375. return context ? {value: value} : value;
  13376. };
  13377. case AST.AssignmentExpression:
  13378. left = this.recurse(ast.left, true, 1);
  13379. right = this.recurse(ast.right);
  13380. return function(scope, locals, assign, inputs) {
  13381. var lhs = left(scope, locals, assign, inputs);
  13382. var rhs = right(scope, locals, assign, inputs);
  13383. ensureSafeObject(lhs.value, self.expression);
  13384. ensureSafeAssignContext(lhs.context);
  13385. lhs.context[lhs.name] = rhs;
  13386. return context ? {value: rhs} : rhs;
  13387. };
  13388. case AST.ArrayExpression:
  13389. args = [];
  13390. forEach(ast.elements, function(expr) {
  13391. args.push(self.recurse(expr));
  13392. });
  13393. return function(scope, locals, assign, inputs) {
  13394. var value = [];
  13395. for (var i = 0; i < args.length; ++i) {
  13396. value.push(args[i](scope, locals, assign, inputs));
  13397. }
  13398. return context ? {value: value} : value;
  13399. };
  13400. case AST.ObjectExpression:
  13401. args = [];
  13402. forEach(ast.properties, function(property) {
  13403. args.push({key: property.key.type === AST.Identifier ?
  13404. property.key.name :
  13405. ('' + property.key.value),
  13406. value: self.recurse(property.value)
  13407. });
  13408. });
  13409. return function(scope, locals, assign, inputs) {
  13410. var value = {};
  13411. for (var i = 0; i < args.length; ++i) {
  13412. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  13413. }
  13414. return context ? {value: value} : value;
  13415. };
  13416. case AST.ThisExpression:
  13417. return function(scope) {
  13418. return context ? {value: scope} : scope;
  13419. };
  13420. case AST.LocalsExpression:
  13421. return function(scope, locals) {
  13422. return context ? {value: locals} : locals;
  13423. };
  13424. case AST.NGValueParameter:
  13425. return function(scope, locals, assign) {
  13426. return context ? {value: assign} : assign;
  13427. };
  13428. }
  13429. },
  13430. 'unary+': function(argument, context) {
  13431. return function(scope, locals, assign, inputs) {
  13432. var arg = argument(scope, locals, assign, inputs);
  13433. if (isDefined(arg)) {
  13434. arg = +arg;
  13435. } else {
  13436. arg = 0;
  13437. }
  13438. return context ? {value: arg} : arg;
  13439. };
  13440. },
  13441. 'unary-': function(argument, context) {
  13442. return function(scope, locals, assign, inputs) {
  13443. var arg = argument(scope, locals, assign, inputs);
  13444. if (isDefined(arg)) {
  13445. arg = -arg;
  13446. } else {
  13447. arg = 0;
  13448. }
  13449. return context ? {value: arg} : arg;
  13450. };
  13451. },
  13452. 'unary!': function(argument, context) {
  13453. return function(scope, locals, assign, inputs) {
  13454. var arg = !argument(scope, locals, assign, inputs);
  13455. return context ? {value: arg} : arg;
  13456. };
  13457. },
  13458. 'binary+': function(left, right, context) {
  13459. return function(scope, locals, assign, inputs) {
  13460. var lhs = left(scope, locals, assign, inputs);
  13461. var rhs = right(scope, locals, assign, inputs);
  13462. var arg = plusFn(lhs, rhs);
  13463. return context ? {value: arg} : arg;
  13464. };
  13465. },
  13466. 'binary-': function(left, right, context) {
  13467. return function(scope, locals, assign, inputs) {
  13468. var lhs = left(scope, locals, assign, inputs);
  13469. var rhs = right(scope, locals, assign, inputs);
  13470. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  13471. return context ? {value: arg} : arg;
  13472. };
  13473. },
  13474. 'binary*': function(left, right, context) {
  13475. return function(scope, locals, assign, inputs) {
  13476. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  13477. return context ? {value: arg} : arg;
  13478. };
  13479. },
  13480. 'binary/': function(left, right, context) {
  13481. return function(scope, locals, assign, inputs) {
  13482. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  13483. return context ? {value: arg} : arg;
  13484. };
  13485. },
  13486. 'binary%': function(left, right, context) {
  13487. return function(scope, locals, assign, inputs) {
  13488. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  13489. return context ? {value: arg} : arg;
  13490. };
  13491. },
  13492. 'binary===': function(left, right, context) {
  13493. return function(scope, locals, assign, inputs) {
  13494. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  13495. return context ? {value: arg} : arg;
  13496. };
  13497. },
  13498. 'binary!==': function(left, right, context) {
  13499. return function(scope, locals, assign, inputs) {
  13500. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  13501. return context ? {value: arg} : arg;
  13502. };
  13503. },
  13504. 'binary==': function(left, right, context) {
  13505. return function(scope, locals, assign, inputs) {
  13506. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  13507. return context ? {value: arg} : arg;
  13508. };
  13509. },
  13510. 'binary!=': function(left, right, context) {
  13511. return function(scope, locals, assign, inputs) {
  13512. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  13513. return context ? {value: arg} : arg;
  13514. };
  13515. },
  13516. 'binary<': function(left, right, context) {
  13517. return function(scope, locals, assign, inputs) {
  13518. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  13519. return context ? {value: arg} : arg;
  13520. };
  13521. },
  13522. 'binary>': function(left, right, context) {
  13523. return function(scope, locals, assign, inputs) {
  13524. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  13525. return context ? {value: arg} : arg;
  13526. };
  13527. },
  13528. 'binary<=': function(left, right, context) {
  13529. return function(scope, locals, assign, inputs) {
  13530. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  13531. return context ? {value: arg} : arg;
  13532. };
  13533. },
  13534. 'binary>=': function(left, right, context) {
  13535. return function(scope, locals, assign, inputs) {
  13536. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  13537. return context ? {value: arg} : arg;
  13538. };
  13539. },
  13540. 'binary&&': function(left, right, context) {
  13541. return function(scope, locals, assign, inputs) {
  13542. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  13543. return context ? {value: arg} : arg;
  13544. };
  13545. },
  13546. 'binary||': function(left, right, context) {
  13547. return function(scope, locals, assign, inputs) {
  13548. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  13549. return context ? {value: arg} : arg;
  13550. };
  13551. },
  13552. 'ternary?:': function(test, alternate, consequent, context) {
  13553. return function(scope, locals, assign, inputs) {
  13554. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  13555. return context ? {value: arg} : arg;
  13556. };
  13557. },
  13558. value: function(value, context) {
  13559. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  13560. },
  13561. identifier: function(name, expensiveChecks, context, create, expression) {
  13562. return function(scope, locals, assign, inputs) {
  13563. var base = locals && (name in locals) ? locals : scope;
  13564. if (create && create !== 1 && base && !(base[name])) {
  13565. base[name] = {};
  13566. }
  13567. var value = base ? base[name] : undefined;
  13568. if (expensiveChecks) {
  13569. ensureSafeObject(value, expression);
  13570. }
  13571. if (context) {
  13572. return {context: base, name: name, value: value};
  13573. } else {
  13574. return value;
  13575. }
  13576. };
  13577. },
  13578. computedMember: function(left, right, context, create, expression) {
  13579. return function(scope, locals, assign, inputs) {
  13580. var lhs = left(scope, locals, assign, inputs);
  13581. var rhs;
  13582. var value;
  13583. if (lhs != null) {
  13584. rhs = right(scope, locals, assign, inputs);
  13585. rhs = getStringValue(rhs);
  13586. ensureSafeMemberName(rhs, expression);
  13587. if (create && create !== 1) {
  13588. ensureSafeAssignContext(lhs);
  13589. if (lhs && !(lhs[rhs])) {
  13590. lhs[rhs] = {};
  13591. }
  13592. }
  13593. value = lhs[rhs];
  13594. ensureSafeObject(value, expression);
  13595. }
  13596. if (context) {
  13597. return {context: lhs, name: rhs, value: value};
  13598. } else {
  13599. return value;
  13600. }
  13601. };
  13602. },
  13603. nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
  13604. return function(scope, locals, assign, inputs) {
  13605. var lhs = left(scope, locals, assign, inputs);
  13606. if (create && create !== 1) {
  13607. ensureSafeAssignContext(lhs);
  13608. if (lhs && !(lhs[right])) {
  13609. lhs[right] = {};
  13610. }
  13611. }
  13612. var value = lhs != null ? lhs[right] : undefined;
  13613. if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
  13614. ensureSafeObject(value, expression);
  13615. }
  13616. if (context) {
  13617. return {context: lhs, name: right, value: value};
  13618. } else {
  13619. return value;
  13620. }
  13621. };
  13622. },
  13623. inputs: function(input, watchId) {
  13624. return function(scope, value, locals, inputs) {
  13625. if (inputs) return inputs[watchId];
  13626. return input(scope, value, locals);
  13627. };
  13628. }
  13629. };
  13630. /**
  13631. * @constructor
  13632. */
  13633. var Parser = function(lexer, $filter, options) {
  13634. this.lexer = lexer;
  13635. this.$filter = $filter;
  13636. this.options = options;
  13637. this.ast = new AST(lexer, options);
  13638. this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
  13639. new ASTCompiler(this.ast, $filter);
  13640. };
  13641. Parser.prototype = {
  13642. constructor: Parser,
  13643. parse: function(text) {
  13644. return this.astCompiler.compile(text, this.options.expensiveChecks);
  13645. }
  13646. };
  13647. function isPossiblyDangerousMemberName(name) {
  13648. return name == 'constructor';
  13649. }
  13650. var objectValueOf = Object.prototype.valueOf;
  13651. function getValueOf(value) {
  13652. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  13653. }
  13654. ///////////////////////////////////
  13655. /**
  13656. * @ngdoc service
  13657. * @name $parse
  13658. * @kind function
  13659. *
  13660. * @description
  13661. *
  13662. * Converts Angular {@link guide/expression expression} into a function.
  13663. *
  13664. * ```js
  13665. * var getter = $parse('user.name');
  13666. * var setter = getter.assign;
  13667. * var context = {user:{name:'angular'}};
  13668. * var locals = {user:{name:'local'}};
  13669. *
  13670. * expect(getter(context)).toEqual('angular');
  13671. * setter(context, 'newValue');
  13672. * expect(context.user.name).toEqual('newValue');
  13673. * expect(getter(context, locals)).toEqual('local');
  13674. * ```
  13675. *
  13676. *
  13677. * @param {string} expression String expression to compile.
  13678. * @returns {function(context, locals)} a function which represents the compiled expression:
  13679. *
  13680. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  13681. * are evaluated against (typically a scope object).
  13682. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  13683. * `context`.
  13684. *
  13685. * The returned function also has the following properties:
  13686. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  13687. * literal.
  13688. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  13689. * constant literals.
  13690. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  13691. * set to a function to change its value on the given context.
  13692. *
  13693. */
  13694. /**
  13695. * @ngdoc provider
  13696. * @name $parseProvider
  13697. *
  13698. * @description
  13699. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  13700. * service.
  13701. */
  13702. function $ParseProvider() {
  13703. var cacheDefault = createMap();
  13704. var cacheExpensive = createMap();
  13705. var literals = {
  13706. 'true': true,
  13707. 'false': false,
  13708. 'null': null,
  13709. 'undefined': undefined
  13710. };
  13711. /**
  13712. * @ngdoc method
  13713. * @name $parseProvider#addLiteral
  13714. * @description
  13715. *
  13716. * Configure $parse service to add literal values that will be present as literal at expressions.
  13717. *
  13718. * @param {string} literalName Token for the literal value. The literal name value must be a valid literal name.
  13719. * @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`.
  13720. *
  13721. **/
  13722. this.addLiteral = function(literalName, literalValue) {
  13723. literals[literalName] = literalValue;
  13724. };
  13725. this.$get = ['$filter', function($filter) {
  13726. var noUnsafeEval = csp().noUnsafeEval;
  13727. var $parseOptions = {
  13728. csp: noUnsafeEval,
  13729. expensiveChecks: false,
  13730. literals: copy(literals)
  13731. },
  13732. $parseOptionsExpensive = {
  13733. csp: noUnsafeEval,
  13734. expensiveChecks: true,
  13735. literals: copy(literals)
  13736. };
  13737. var runningChecksEnabled = false;
  13738. $parse.$$runningExpensiveChecks = function() {
  13739. return runningChecksEnabled;
  13740. };
  13741. return $parse;
  13742. function $parse(exp, interceptorFn, expensiveChecks) {
  13743. var parsedExpression, oneTime, cacheKey;
  13744. expensiveChecks = expensiveChecks || runningChecksEnabled;
  13745. switch (typeof exp) {
  13746. case 'string':
  13747. exp = exp.trim();
  13748. cacheKey = exp;
  13749. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  13750. parsedExpression = cache[cacheKey];
  13751. if (!parsedExpression) {
  13752. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  13753. oneTime = true;
  13754. exp = exp.substring(2);
  13755. }
  13756. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  13757. var lexer = new Lexer(parseOptions);
  13758. var parser = new Parser(lexer, $filter, parseOptions);
  13759. parsedExpression = parser.parse(exp);
  13760. if (parsedExpression.constant) {
  13761. parsedExpression.$$watchDelegate = constantWatchDelegate;
  13762. } else if (oneTime) {
  13763. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  13764. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  13765. } else if (parsedExpression.inputs) {
  13766. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  13767. }
  13768. if (expensiveChecks) {
  13769. parsedExpression = expensiveChecksInterceptor(parsedExpression);
  13770. }
  13771. cache[cacheKey] = parsedExpression;
  13772. }
  13773. return addInterceptor(parsedExpression, interceptorFn);
  13774. case 'function':
  13775. return addInterceptor(exp, interceptorFn);
  13776. default:
  13777. return addInterceptor(noop, interceptorFn);
  13778. }
  13779. }
  13780. function expensiveChecksInterceptor(fn) {
  13781. if (!fn) return fn;
  13782. expensiveCheckFn.$$watchDelegate = fn.$$watchDelegate;
  13783. expensiveCheckFn.assign = expensiveChecksInterceptor(fn.assign);
  13784. expensiveCheckFn.constant = fn.constant;
  13785. expensiveCheckFn.literal = fn.literal;
  13786. for (var i = 0; fn.inputs && i < fn.inputs.length; ++i) {
  13787. fn.inputs[i] = expensiveChecksInterceptor(fn.inputs[i]);
  13788. }
  13789. expensiveCheckFn.inputs = fn.inputs;
  13790. return expensiveCheckFn;
  13791. function expensiveCheckFn(scope, locals, assign, inputs) {
  13792. var expensiveCheckOldValue = runningChecksEnabled;
  13793. runningChecksEnabled = true;
  13794. try {
  13795. return fn(scope, locals, assign, inputs);
  13796. } finally {
  13797. runningChecksEnabled = expensiveCheckOldValue;
  13798. }
  13799. }
  13800. }
  13801. function expressionInputDirtyCheck(newValue, oldValueOfValue) {
  13802. if (newValue == null || oldValueOfValue == null) { // null/undefined
  13803. return newValue === oldValueOfValue;
  13804. }
  13805. if (typeof newValue === 'object') {
  13806. // attempt to convert the value to a primitive type
  13807. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  13808. // be cheaply dirty-checked
  13809. newValue = getValueOf(newValue);
  13810. if (typeof newValue === 'object') {
  13811. // objects/arrays are not supported - deep-watching them would be too expensive
  13812. return false;
  13813. }
  13814. // fall-through to the primitive equality check
  13815. }
  13816. //Primitive or NaN
  13817. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  13818. }
  13819. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  13820. var inputExpressions = parsedExpression.inputs;
  13821. var lastResult;
  13822. if (inputExpressions.length === 1) {
  13823. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  13824. inputExpressions = inputExpressions[0];
  13825. return scope.$watch(function expressionInputWatch(scope) {
  13826. var newInputValue = inputExpressions(scope);
  13827. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
  13828. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  13829. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  13830. }
  13831. return lastResult;
  13832. }, listener, objectEquality, prettyPrintExpression);
  13833. }
  13834. var oldInputValueOfValues = [];
  13835. var oldInputValues = [];
  13836. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  13837. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  13838. oldInputValues[i] = null;
  13839. }
  13840. return scope.$watch(function expressionInputsWatch(scope) {
  13841. var changed = false;
  13842. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  13843. var newInputValue = inputExpressions[i](scope);
  13844. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
  13845. oldInputValues[i] = newInputValue;
  13846. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  13847. }
  13848. }
  13849. if (changed) {
  13850. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  13851. }
  13852. return lastResult;
  13853. }, listener, objectEquality, prettyPrintExpression);
  13854. }
  13855. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  13856. var unwatch, lastValue;
  13857. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  13858. return parsedExpression(scope);
  13859. }, function oneTimeListener(value, old, scope) {
  13860. lastValue = value;
  13861. if (isFunction(listener)) {
  13862. listener.apply(this, arguments);
  13863. }
  13864. if (isDefined(value)) {
  13865. scope.$$postDigest(function() {
  13866. if (isDefined(lastValue)) {
  13867. unwatch();
  13868. }
  13869. });
  13870. }
  13871. }, objectEquality);
  13872. }
  13873. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  13874. var unwatch, lastValue;
  13875. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  13876. return parsedExpression(scope);
  13877. }, function oneTimeListener(value, old, scope) {
  13878. lastValue = value;
  13879. if (isFunction(listener)) {
  13880. listener.call(this, value, old, scope);
  13881. }
  13882. if (isAllDefined(value)) {
  13883. scope.$$postDigest(function() {
  13884. if (isAllDefined(lastValue)) unwatch();
  13885. });
  13886. }
  13887. }, objectEquality);
  13888. function isAllDefined(value) {
  13889. var allDefined = true;
  13890. forEach(value, function(val) {
  13891. if (!isDefined(val)) allDefined = false;
  13892. });
  13893. return allDefined;
  13894. }
  13895. }
  13896. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  13897. var unwatch;
  13898. return unwatch = scope.$watch(function constantWatch(scope) {
  13899. unwatch();
  13900. return parsedExpression(scope);
  13901. }, listener, objectEquality);
  13902. }
  13903. function addInterceptor(parsedExpression, interceptorFn) {
  13904. if (!interceptorFn) return parsedExpression;
  13905. var watchDelegate = parsedExpression.$$watchDelegate;
  13906. var useInputs = false;
  13907. var regularWatch =
  13908. watchDelegate !== oneTimeLiteralWatchDelegate &&
  13909. watchDelegate !== oneTimeWatchDelegate;
  13910. var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
  13911. var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
  13912. return interceptorFn(value, scope, locals);
  13913. } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
  13914. var value = parsedExpression(scope, locals, assign, inputs);
  13915. var result = interceptorFn(value, scope, locals);
  13916. // we only return the interceptor's result if the
  13917. // initial value is defined (for bind-once)
  13918. return isDefined(value) ? result : value;
  13919. };
  13920. // Propagate $$watchDelegates other then inputsWatchDelegate
  13921. if (parsedExpression.$$watchDelegate &&
  13922. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  13923. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  13924. } else if (!interceptorFn.$stateful) {
  13925. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  13926. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  13927. fn.$$watchDelegate = inputsWatchDelegate;
  13928. useInputs = !parsedExpression.inputs;
  13929. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  13930. }
  13931. return fn;
  13932. }
  13933. }];
  13934. }
  13935. /**
  13936. * @ngdoc service
  13937. * @name $q
  13938. * @requires $rootScope
  13939. *
  13940. * @description
  13941. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  13942. * when they are done processing.
  13943. *
  13944. * This is an implementation of promises/deferred objects inspired by
  13945. * [Kris Kowal's Q](https://github.com/kriskowal/q).
  13946. *
  13947. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  13948. * implementations, and the other which resembles ES6 (ES2015) promises to some degree.
  13949. *
  13950. * # $q constructor
  13951. *
  13952. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  13953. * function as the first argument. This is similar to the native Promise implementation from ES6,
  13954. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  13955. *
  13956. * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are
  13957. * available yet.
  13958. *
  13959. * It can be used like so:
  13960. *
  13961. * ```js
  13962. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  13963. * // are available in the current lexical scope (they could have been injected or passed in).
  13964. *
  13965. * function asyncGreet(name) {
  13966. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  13967. * return $q(function(resolve, reject) {
  13968. * setTimeout(function() {
  13969. * if (okToGreet(name)) {
  13970. * resolve('Hello, ' + name + '!');
  13971. * } else {
  13972. * reject('Greeting ' + name + ' is not allowed.');
  13973. * }
  13974. * }, 1000);
  13975. * });
  13976. * }
  13977. *
  13978. * var promise = asyncGreet('Robin Hood');
  13979. * promise.then(function(greeting) {
  13980. * alert('Success: ' + greeting);
  13981. * }, function(reason) {
  13982. * alert('Failed: ' + reason);
  13983. * });
  13984. * ```
  13985. *
  13986. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  13987. *
  13988. * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.
  13989. *
  13990. * However, the more traditional CommonJS-style usage is still available, and documented below.
  13991. *
  13992. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  13993. * interface for interacting with an object that represents the result of an action that is
  13994. * performed asynchronously, and may or may not be finished at any given point in time.
  13995. *
  13996. * From the perspective of dealing with error handling, deferred and promise APIs are to
  13997. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  13998. *
  13999. * ```js
  14000. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  14001. * // are available in the current lexical scope (they could have been injected or passed in).
  14002. *
  14003. * function asyncGreet(name) {
  14004. * var deferred = $q.defer();
  14005. *
  14006. * setTimeout(function() {
  14007. * deferred.notify('About to greet ' + name + '.');
  14008. *
  14009. * if (okToGreet(name)) {
  14010. * deferred.resolve('Hello, ' + name + '!');
  14011. * } else {
  14012. * deferred.reject('Greeting ' + name + ' is not allowed.');
  14013. * }
  14014. * }, 1000);
  14015. *
  14016. * return deferred.promise;
  14017. * }
  14018. *
  14019. * var promise = asyncGreet('Robin Hood');
  14020. * promise.then(function(greeting) {
  14021. * alert('Success: ' + greeting);
  14022. * }, function(reason) {
  14023. * alert('Failed: ' + reason);
  14024. * }, function(update) {
  14025. * alert('Got notification: ' + update);
  14026. * });
  14027. * ```
  14028. *
  14029. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  14030. * comes in the way of guarantees that promise and deferred APIs make, see
  14031. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  14032. *
  14033. * Additionally the promise api allows for composition that is very hard to do with the
  14034. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  14035. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  14036. * section on serial or parallel joining of promises.
  14037. *
  14038. * # The Deferred API
  14039. *
  14040. * A new instance of deferred is constructed by calling `$q.defer()`.
  14041. *
  14042. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  14043. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  14044. * of the task.
  14045. *
  14046. * **Methods**
  14047. *
  14048. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  14049. * constructed via `$q.reject`, the promise will be rejected instead.
  14050. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  14051. * resolving it with a rejection constructed via `$q.reject`.
  14052. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  14053. * multiple times before the promise is either resolved or rejected.
  14054. *
  14055. * **Properties**
  14056. *
  14057. * - promise – `{Promise}` – promise object associated with this deferred.
  14058. *
  14059. *
  14060. * # The Promise API
  14061. *
  14062. * A new promise instance is created when a deferred instance is created and can be retrieved by
  14063. * calling `deferred.promise`.
  14064. *
  14065. * The purpose of the promise object is to allow for interested parties to get access to the result
  14066. * of the deferred task when it completes.
  14067. *
  14068. * **Methods**
  14069. *
  14070. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  14071. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  14072. * as soon as the result is available. The callbacks are called with a single argument: the result
  14073. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  14074. * provide a progress indication, before the promise is resolved or rejected.
  14075. *
  14076. * This method *returns a new promise* which is resolved or rejected via the return value of the
  14077. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  14078. * with the value which is resolved in that promise using
  14079. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  14080. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  14081. * resolved or rejected from the notifyCallback method.
  14082. *
  14083. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  14084. *
  14085. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  14086. * but to do so without modifying the final value. This is useful to release resources or do some
  14087. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  14088. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  14089. * more information.
  14090. *
  14091. * # Chaining promises
  14092. *
  14093. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  14094. * possible to create a chain of promises:
  14095. *
  14096. * ```js
  14097. * promiseB = promiseA.then(function(result) {
  14098. * return result + 1;
  14099. * });
  14100. *
  14101. * // promiseB will be resolved immediately after promiseA is resolved and its value
  14102. * // will be the result of promiseA incremented by 1
  14103. * ```
  14104. *
  14105. * It is possible to create chains of any length and since a promise can be resolved with another
  14106. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  14107. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  14108. * $http's response interceptors.
  14109. *
  14110. *
  14111. * # Differences between Kris Kowal's Q and $q
  14112. *
  14113. * There are two main differences:
  14114. *
  14115. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  14116. * mechanism in angular, which means faster propagation of resolution or rejection into your
  14117. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  14118. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  14119. * all the important functionality needed for common async tasks.
  14120. *
  14121. * # Testing
  14122. *
  14123. * ```js
  14124. * it('should simulate promise', inject(function($q, $rootScope) {
  14125. * var deferred = $q.defer();
  14126. * var promise = deferred.promise;
  14127. * var resolvedValue;
  14128. *
  14129. * promise.then(function(value) { resolvedValue = value; });
  14130. * expect(resolvedValue).toBeUndefined();
  14131. *
  14132. * // Simulate resolving of promise
  14133. * deferred.resolve(123);
  14134. * // Note that the 'then' function does not get called synchronously.
  14135. * // This is because we want the promise API to always be async, whether or not
  14136. * // it got called synchronously or asynchronously.
  14137. * expect(resolvedValue).toBeUndefined();
  14138. *
  14139. * // Propagate promise resolution to 'then' functions using $apply().
  14140. * $rootScope.$apply();
  14141. * expect(resolvedValue).toEqual(123);
  14142. * }));
  14143. * ```
  14144. *
  14145. * @param {function(function, function)} resolver Function which is responsible for resolving or
  14146. * rejecting the newly created promise. The first parameter is a function which resolves the
  14147. * promise, the second parameter is a function which rejects the promise.
  14148. *
  14149. * @returns {Promise} The newly created promise.
  14150. */
  14151. function $QProvider() {
  14152. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  14153. return qFactory(function(callback) {
  14154. $rootScope.$evalAsync(callback);
  14155. }, $exceptionHandler);
  14156. }];
  14157. }
  14158. function $$QProvider() {
  14159. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  14160. return qFactory(function(callback) {
  14161. $browser.defer(callback);
  14162. }, $exceptionHandler);
  14163. }];
  14164. }
  14165. /**
  14166. * Constructs a promise manager.
  14167. *
  14168. * @param {function(function)} nextTick Function for executing functions in the next turn.
  14169. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  14170. * debugging purposes.
  14171. * @returns {object} Promise manager.
  14172. */
  14173. function qFactory(nextTick, exceptionHandler) {
  14174. var $qMinErr = minErr('$q', TypeError);
  14175. /**
  14176. * @ngdoc method
  14177. * @name ng.$q#defer
  14178. * @kind function
  14179. *
  14180. * @description
  14181. * Creates a `Deferred` object which represents a task which will finish in the future.
  14182. *
  14183. * @returns {Deferred} Returns a new instance of deferred.
  14184. */
  14185. var defer = function() {
  14186. var d = new Deferred();
  14187. //Necessary to support unbound execution :/
  14188. d.resolve = simpleBind(d, d.resolve);
  14189. d.reject = simpleBind(d, d.reject);
  14190. d.notify = simpleBind(d, d.notify);
  14191. return d;
  14192. };
  14193. function Promise() {
  14194. this.$$state = { status: 0 };
  14195. }
  14196. extend(Promise.prototype, {
  14197. then: function(onFulfilled, onRejected, progressBack) {
  14198. if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
  14199. return this;
  14200. }
  14201. var result = new Deferred();
  14202. this.$$state.pending = this.$$state.pending || [];
  14203. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  14204. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  14205. return result.promise;
  14206. },
  14207. "catch": function(callback) {
  14208. return this.then(null, callback);
  14209. },
  14210. "finally": function(callback, progressBack) {
  14211. return this.then(function(value) {
  14212. return handleCallback(value, true, callback);
  14213. }, function(error) {
  14214. return handleCallback(error, false, callback);
  14215. }, progressBack);
  14216. }
  14217. });
  14218. //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
  14219. function simpleBind(context, fn) {
  14220. return function(value) {
  14221. fn.call(context, value);
  14222. };
  14223. }
  14224. function processQueue(state) {
  14225. var fn, deferred, pending;
  14226. pending = state.pending;
  14227. state.processScheduled = false;
  14228. state.pending = undefined;
  14229. for (var i = 0, ii = pending.length; i < ii; ++i) {
  14230. deferred = pending[i][0];
  14231. fn = pending[i][state.status];
  14232. try {
  14233. if (isFunction(fn)) {
  14234. deferred.resolve(fn(state.value));
  14235. } else if (state.status === 1) {
  14236. deferred.resolve(state.value);
  14237. } else {
  14238. deferred.reject(state.value);
  14239. }
  14240. } catch (e) {
  14241. deferred.reject(e);
  14242. exceptionHandler(e);
  14243. }
  14244. }
  14245. }
  14246. function scheduleProcessQueue(state) {
  14247. if (state.processScheduled || !state.pending) return;
  14248. state.processScheduled = true;
  14249. nextTick(function() { processQueue(state); });
  14250. }
  14251. function Deferred() {
  14252. this.promise = new Promise();
  14253. }
  14254. extend(Deferred.prototype, {
  14255. resolve: function(val) {
  14256. if (this.promise.$$state.status) return;
  14257. if (val === this.promise) {
  14258. this.$$reject($qMinErr(
  14259. 'qcycle',
  14260. "Expected promise to be resolved with value other than itself '{0}'",
  14261. val));
  14262. } else {
  14263. this.$$resolve(val);
  14264. }
  14265. },
  14266. $$resolve: function(val) {
  14267. var then;
  14268. var that = this;
  14269. var done = false;
  14270. try {
  14271. if ((isObject(val) || isFunction(val))) then = val && val.then;
  14272. if (isFunction(then)) {
  14273. this.promise.$$state.status = -1;
  14274. then.call(val, resolvePromise, rejectPromise, simpleBind(this, this.notify));
  14275. } else {
  14276. this.promise.$$state.value = val;
  14277. this.promise.$$state.status = 1;
  14278. scheduleProcessQueue(this.promise.$$state);
  14279. }
  14280. } catch (e) {
  14281. rejectPromise(e);
  14282. exceptionHandler(e);
  14283. }
  14284. function resolvePromise(val) {
  14285. if (done) return;
  14286. done = true;
  14287. that.$$resolve(val);
  14288. }
  14289. function rejectPromise(val) {
  14290. if (done) return;
  14291. done = true;
  14292. that.$$reject(val);
  14293. }
  14294. },
  14295. reject: function(reason) {
  14296. if (this.promise.$$state.status) return;
  14297. this.$$reject(reason);
  14298. },
  14299. $$reject: function(reason) {
  14300. this.promise.$$state.value = reason;
  14301. this.promise.$$state.status = 2;
  14302. scheduleProcessQueue(this.promise.$$state);
  14303. },
  14304. notify: function(progress) {
  14305. var callbacks = this.promise.$$state.pending;
  14306. if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
  14307. nextTick(function() {
  14308. var callback, result;
  14309. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  14310. result = callbacks[i][0];
  14311. callback = callbacks[i][3];
  14312. try {
  14313. result.notify(isFunction(callback) ? callback(progress) : progress);
  14314. } catch (e) {
  14315. exceptionHandler(e);
  14316. }
  14317. }
  14318. });
  14319. }
  14320. }
  14321. });
  14322. /**
  14323. * @ngdoc method
  14324. * @name $q#reject
  14325. * @kind function
  14326. *
  14327. * @description
  14328. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  14329. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  14330. * a promise chain, you don't need to worry about it.
  14331. *
  14332. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  14333. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  14334. * a promise error callback and you want to forward the error to the promise derived from the
  14335. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  14336. * `reject`.
  14337. *
  14338. * ```js
  14339. * promiseB = promiseA.then(function(result) {
  14340. * // success: do something and resolve promiseB
  14341. * // with the old or a new result
  14342. * return result;
  14343. * }, function(reason) {
  14344. * // error: handle the error if possible and
  14345. * // resolve promiseB with newPromiseOrValue,
  14346. * // otherwise forward the rejection to promiseB
  14347. * if (canHandle(reason)) {
  14348. * // handle the error and recover
  14349. * return newPromiseOrValue;
  14350. * }
  14351. * return $q.reject(reason);
  14352. * });
  14353. * ```
  14354. *
  14355. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  14356. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  14357. */
  14358. var reject = function(reason) {
  14359. var result = new Deferred();
  14360. result.reject(reason);
  14361. return result.promise;
  14362. };
  14363. var makePromise = function makePromise(value, resolved) {
  14364. var result = new Deferred();
  14365. if (resolved) {
  14366. result.resolve(value);
  14367. } else {
  14368. result.reject(value);
  14369. }
  14370. return result.promise;
  14371. };
  14372. var handleCallback = function handleCallback(value, isResolved, callback) {
  14373. var callbackOutput = null;
  14374. try {
  14375. if (isFunction(callback)) callbackOutput = callback();
  14376. } catch (e) {
  14377. return makePromise(e, false);
  14378. }
  14379. if (isPromiseLike(callbackOutput)) {
  14380. return callbackOutput.then(function() {
  14381. return makePromise(value, isResolved);
  14382. }, function(error) {
  14383. return makePromise(error, false);
  14384. });
  14385. } else {
  14386. return makePromise(value, isResolved);
  14387. }
  14388. };
  14389. /**
  14390. * @ngdoc method
  14391. * @name $q#when
  14392. * @kind function
  14393. *
  14394. * @description
  14395. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  14396. * This is useful when you are dealing with an object that might or might not be a promise, or if
  14397. * the promise comes from a source that can't be trusted.
  14398. *
  14399. * @param {*} value Value or a promise
  14400. * @param {Function=} successCallback
  14401. * @param {Function=} errorCallback
  14402. * @param {Function=} progressCallback
  14403. * @returns {Promise} Returns a promise of the passed value or promise
  14404. */
  14405. var when = function(value, callback, errback, progressBack) {
  14406. var result = new Deferred();
  14407. result.resolve(value);
  14408. return result.promise.then(callback, errback, progressBack);
  14409. };
  14410. /**
  14411. * @ngdoc method
  14412. * @name $q#resolve
  14413. * @kind function
  14414. *
  14415. * @description
  14416. * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
  14417. *
  14418. * @param {*} value Value or a promise
  14419. * @param {Function=} successCallback
  14420. * @param {Function=} errorCallback
  14421. * @param {Function=} progressCallback
  14422. * @returns {Promise} Returns a promise of the passed value or promise
  14423. */
  14424. var resolve = when;
  14425. /**
  14426. * @ngdoc method
  14427. * @name $q#all
  14428. * @kind function
  14429. *
  14430. * @description
  14431. * Combines multiple promises into a single promise that is resolved when all of the input
  14432. * promises are resolved.
  14433. *
  14434. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  14435. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  14436. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  14437. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  14438. * with the same rejection value.
  14439. */
  14440. function all(promises) {
  14441. var deferred = new Deferred(),
  14442. counter = 0,
  14443. results = isArray(promises) ? [] : {};
  14444. forEach(promises, function(promise, key) {
  14445. counter++;
  14446. when(promise).then(function(value) {
  14447. if (results.hasOwnProperty(key)) return;
  14448. results[key] = value;
  14449. if (!(--counter)) deferred.resolve(results);
  14450. }, function(reason) {
  14451. if (results.hasOwnProperty(key)) return;
  14452. deferred.reject(reason);
  14453. });
  14454. });
  14455. if (counter === 0) {
  14456. deferred.resolve(results);
  14457. }
  14458. return deferred.promise;
  14459. }
  14460. var $Q = function Q(resolver) {
  14461. if (!isFunction(resolver)) {
  14462. throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
  14463. }
  14464. var deferred = new Deferred();
  14465. function resolveFn(value) {
  14466. deferred.resolve(value);
  14467. }
  14468. function rejectFn(reason) {
  14469. deferred.reject(reason);
  14470. }
  14471. resolver(resolveFn, rejectFn);
  14472. return deferred.promise;
  14473. };
  14474. // Let's make the instanceof operator work for promises, so that
  14475. // `new $q(fn) instanceof $q` would evaluate to true.
  14476. $Q.prototype = Promise.prototype;
  14477. $Q.defer = defer;
  14478. $Q.reject = reject;
  14479. $Q.when = when;
  14480. $Q.resolve = resolve;
  14481. $Q.all = all;
  14482. return $Q;
  14483. }
  14484. function $$RAFProvider() { //rAF
  14485. this.$get = ['$window', '$timeout', function($window, $timeout) {
  14486. var requestAnimationFrame = $window.requestAnimationFrame ||
  14487. $window.webkitRequestAnimationFrame;
  14488. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  14489. $window.webkitCancelAnimationFrame ||
  14490. $window.webkitCancelRequestAnimationFrame;
  14491. var rafSupported = !!requestAnimationFrame;
  14492. var raf = rafSupported
  14493. ? function(fn) {
  14494. var id = requestAnimationFrame(fn);
  14495. return function() {
  14496. cancelAnimationFrame(id);
  14497. };
  14498. }
  14499. : function(fn) {
  14500. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  14501. return function() {
  14502. $timeout.cancel(timer);
  14503. };
  14504. };
  14505. raf.supported = rafSupported;
  14506. return raf;
  14507. }];
  14508. }
  14509. /**
  14510. * DESIGN NOTES
  14511. *
  14512. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  14513. *
  14514. * The typical use of scope is to watch the expressions, which most of the time return the same
  14515. * value as last time so we optimize the operation.
  14516. *
  14517. * Closures construction is expensive in terms of speed as well as memory:
  14518. * - No closures, instead use prototypical inheritance for API
  14519. * - Internal state needs to be stored on scope directly, which means that private state is
  14520. * exposed as $$____ properties
  14521. *
  14522. * Loop operations are optimized by using while(count--) { ... }
  14523. * - This means that in order to keep the same order of execution as addition we have to add
  14524. * items to the array at the beginning (unshift) instead of at the end (push)
  14525. *
  14526. * Child scopes are created and removed often
  14527. * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
  14528. *
  14529. * There are fewer watches than observers. This is why you don't want the observer to be implemented
  14530. * in the same way as watch. Watch requires return of the initialization function which is expensive
  14531. * to construct.
  14532. */
  14533. /**
  14534. * @ngdoc provider
  14535. * @name $rootScopeProvider
  14536. * @description
  14537. *
  14538. * Provider for the $rootScope service.
  14539. */
  14540. /**
  14541. * @ngdoc method
  14542. * @name $rootScopeProvider#digestTtl
  14543. * @description
  14544. *
  14545. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  14546. * assuming that the model is unstable.
  14547. *
  14548. * The current default is 10 iterations.
  14549. *
  14550. * In complex applications it's possible that the dependencies between `$watch`s will result in
  14551. * several digest iterations. However if an application needs more than the default 10 digest
  14552. * iterations for its model to stabilize then you should investigate what is causing the model to
  14553. * continuously change during the digest.
  14554. *
  14555. * Increasing the TTL could have performance implications, so you should not change it without
  14556. * proper justification.
  14557. *
  14558. * @param {number} limit The number of digest iterations.
  14559. */
  14560. /**
  14561. * @ngdoc service
  14562. * @name $rootScope
  14563. * @description
  14564. *
  14565. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  14566. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  14567. * between the model and the view, via a mechanism for watching the model for changes.
  14568. * They also provide event emission/broadcast and subscription facility. See the
  14569. * {@link guide/scope developer guide on scopes}.
  14570. */
  14571. function $RootScopeProvider() {
  14572. var TTL = 10;
  14573. var $rootScopeMinErr = minErr('$rootScope');
  14574. var lastDirtyWatch = null;
  14575. var applyAsyncId = null;
  14576. this.digestTtl = function(value) {
  14577. if (arguments.length) {
  14578. TTL = value;
  14579. }
  14580. return TTL;
  14581. };
  14582. function createChildScopeClass(parent) {
  14583. function ChildScope() {
  14584. this.$$watchers = this.$$nextSibling =
  14585. this.$$childHead = this.$$childTail = null;
  14586. this.$$listeners = {};
  14587. this.$$listenerCount = {};
  14588. this.$$watchersCount = 0;
  14589. this.$id = nextUid();
  14590. this.$$ChildScope = null;
  14591. }
  14592. ChildScope.prototype = parent;
  14593. return ChildScope;
  14594. }
  14595. this.$get = ['$exceptionHandler', '$parse', '$browser',
  14596. function($exceptionHandler, $parse, $browser) {
  14597. function destroyChildScope($event) {
  14598. $event.currentScope.$$destroyed = true;
  14599. }
  14600. function cleanUpScope($scope) {
  14601. if (msie === 9) {
  14602. // There is a memory leak in IE9 if all child scopes are not disconnected
  14603. // completely when a scope is destroyed. So this code will recurse up through
  14604. // all this scopes children
  14605. //
  14606. // See issue https://github.com/angular/angular.js/issues/10706
  14607. $scope.$$childHead && cleanUpScope($scope.$$childHead);
  14608. $scope.$$nextSibling && cleanUpScope($scope.$$nextSibling);
  14609. }
  14610. // The code below works around IE9 and V8's memory leaks
  14611. //
  14612. // See:
  14613. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  14614. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  14615. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  14616. $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
  14617. $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
  14618. }
  14619. /**
  14620. * @ngdoc type
  14621. * @name $rootScope.Scope
  14622. *
  14623. * @description
  14624. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  14625. * {@link auto.$injector $injector}. Child scopes are created using the
  14626. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  14627. * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
  14628. * an in-depth introduction and usage examples.
  14629. *
  14630. *
  14631. * # Inheritance
  14632. * A scope can inherit from a parent scope, as in this example:
  14633. * ```js
  14634. var parent = $rootScope;
  14635. var child = parent.$new();
  14636. parent.salutation = "Hello";
  14637. expect(child.salutation).toEqual('Hello');
  14638. child.salutation = "Welcome";
  14639. expect(child.salutation).toEqual('Welcome');
  14640. expect(parent.salutation).toEqual('Hello');
  14641. * ```
  14642. *
  14643. * When interacting with `Scope` in tests, additional helper methods are available on the
  14644. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  14645. * details.
  14646. *
  14647. *
  14648. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  14649. * provided for the current scope. Defaults to {@link ng}.
  14650. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  14651. * append/override services provided by `providers`. This is handy
  14652. * when unit-testing and having the need to override a default
  14653. * service.
  14654. * @returns {Object} Newly created scope.
  14655. *
  14656. */
  14657. function Scope() {
  14658. this.$id = nextUid();
  14659. this.$$phase = this.$parent = this.$$watchers =
  14660. this.$$nextSibling = this.$$prevSibling =
  14661. this.$$childHead = this.$$childTail = null;
  14662. this.$root = this;
  14663. this.$$destroyed = false;
  14664. this.$$listeners = {};
  14665. this.$$listenerCount = {};
  14666. this.$$watchersCount = 0;
  14667. this.$$isolateBindings = null;
  14668. }
  14669. /**
  14670. * @ngdoc property
  14671. * @name $rootScope.Scope#$id
  14672. *
  14673. * @description
  14674. * Unique scope ID (monotonically increasing) useful for debugging.
  14675. */
  14676. /**
  14677. * @ngdoc property
  14678. * @name $rootScope.Scope#$parent
  14679. *
  14680. * @description
  14681. * Reference to the parent scope.
  14682. */
  14683. /**
  14684. * @ngdoc property
  14685. * @name $rootScope.Scope#$root
  14686. *
  14687. * @description
  14688. * Reference to the root scope.
  14689. */
  14690. Scope.prototype = {
  14691. constructor: Scope,
  14692. /**
  14693. * @ngdoc method
  14694. * @name $rootScope.Scope#$new
  14695. * @kind function
  14696. *
  14697. * @description
  14698. * Creates a new child {@link ng.$rootScope.Scope scope}.
  14699. *
  14700. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  14701. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  14702. *
  14703. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  14704. * desired for the scope and its child scopes to be permanently detached from the parent and
  14705. * thus stop participating in model change detection and listener notification by invoking.
  14706. *
  14707. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  14708. * parent scope. The scope is isolated, as it can not see parent scope properties.
  14709. * When creating widgets, it is useful for the widget to not accidentally read parent
  14710. * state.
  14711. *
  14712. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  14713. * of the newly created scope. Defaults to `this` scope if not provided.
  14714. * This is used when creating a transclude scope to correctly place it
  14715. * in the scope hierarchy while maintaining the correct prototypical
  14716. * inheritance.
  14717. *
  14718. * @returns {Object} The newly created child scope.
  14719. *
  14720. */
  14721. $new: function(isolate, parent) {
  14722. var child;
  14723. parent = parent || this;
  14724. if (isolate) {
  14725. child = new Scope();
  14726. child.$root = this.$root;
  14727. } else {
  14728. // Only create a child scope class if somebody asks for one,
  14729. // but cache it to allow the VM to optimize lookups.
  14730. if (!this.$$ChildScope) {
  14731. this.$$ChildScope = createChildScopeClass(this);
  14732. }
  14733. child = new this.$$ChildScope();
  14734. }
  14735. child.$parent = parent;
  14736. child.$$prevSibling = parent.$$childTail;
  14737. if (parent.$$childHead) {
  14738. parent.$$childTail.$$nextSibling = child;
  14739. parent.$$childTail = child;
  14740. } else {
  14741. parent.$$childHead = parent.$$childTail = child;
  14742. }
  14743. // When the new scope is not isolated or we inherit from `this`, and
  14744. // the parent scope is destroyed, the property `$$destroyed` is inherited
  14745. // prototypically. In all other cases, this property needs to be set
  14746. // when the parent scope is destroyed.
  14747. // The listener needs to be added after the parent is set
  14748. if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
  14749. return child;
  14750. },
  14751. /**
  14752. * @ngdoc method
  14753. * @name $rootScope.Scope#$watch
  14754. * @kind function
  14755. *
  14756. * @description
  14757. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  14758. *
  14759. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  14760. * $digest()} and should return the value that will be watched. (`watchExpression` should not change
  14761. * its value when executed multiple times with the same input because it may be executed multiple
  14762. * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
  14763. * [idempotent](http://en.wikipedia.org/wiki/Idempotence).
  14764. * - The `listener` is called only when the value from the current `watchExpression` and the
  14765. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  14766. * see below). Inequality is determined according to reference inequality,
  14767. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  14768. * via the `!==` Javascript operator, unless `objectEquality == true`
  14769. * (see next point)
  14770. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  14771. * according to the {@link angular.equals} function. To save the value of the object for
  14772. * later comparison, the {@link angular.copy} function is used. This therefore means that
  14773. * watching complex objects will have adverse memory and performance implications.
  14774. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  14775. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  14776. * iteration limit is 10 to prevent an infinite loop deadlock.
  14777. *
  14778. *
  14779. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  14780. * you can register a `watchExpression` function with no `listener`. (Be prepared for
  14781. * multiple calls to your `watchExpression` because it will execute multiple times in a
  14782. * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
  14783. *
  14784. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  14785. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  14786. * watcher. In rare cases, this is undesirable because the listener is called when the result
  14787. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  14788. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  14789. * listener was called due to initialization.
  14790. *
  14791. *
  14792. *
  14793. * # Example
  14794. * ```js
  14795. // let's assume that scope was dependency injected as the $rootScope
  14796. var scope = $rootScope;
  14797. scope.name = 'misko';
  14798. scope.counter = 0;
  14799. expect(scope.counter).toEqual(0);
  14800. scope.$watch('name', function(newValue, oldValue) {
  14801. scope.counter = scope.counter + 1;
  14802. });
  14803. expect(scope.counter).toEqual(0);
  14804. scope.$digest();
  14805. // the listener is always called during the first $digest loop after it was registered
  14806. expect(scope.counter).toEqual(1);
  14807. scope.$digest();
  14808. // but now it will not be called unless the value changes
  14809. expect(scope.counter).toEqual(1);
  14810. scope.name = 'adam';
  14811. scope.$digest();
  14812. expect(scope.counter).toEqual(2);
  14813. // Using a function as a watchExpression
  14814. var food;
  14815. scope.foodCounter = 0;
  14816. expect(scope.foodCounter).toEqual(0);
  14817. scope.$watch(
  14818. // This function returns the value being watched. It is called for each turn of the $digest loop
  14819. function() { return food; },
  14820. // This is the change listener, called when the value returned from the above function changes
  14821. function(newValue, oldValue) {
  14822. if ( newValue !== oldValue ) {
  14823. // Only increment the counter if the value changed
  14824. scope.foodCounter = scope.foodCounter + 1;
  14825. }
  14826. }
  14827. );
  14828. // No digest has been run so the counter will be zero
  14829. expect(scope.foodCounter).toEqual(0);
  14830. // Run the digest but since food has not changed count will still be zero
  14831. scope.$digest();
  14832. expect(scope.foodCounter).toEqual(0);
  14833. // Update food and run digest. Now the counter will increment
  14834. food = 'cheeseburger';
  14835. scope.$digest();
  14836. expect(scope.foodCounter).toEqual(1);
  14837. * ```
  14838. *
  14839. *
  14840. *
  14841. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  14842. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  14843. * a call to the `listener`.
  14844. *
  14845. * - `string`: Evaluated as {@link guide/expression expression}
  14846. * - `function(scope)`: called with current `scope` as a parameter.
  14847. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  14848. * of `watchExpression` changes.
  14849. *
  14850. * - `newVal` contains the current value of the `watchExpression`
  14851. * - `oldVal` contains the previous value of the `watchExpression`
  14852. * - `scope` refers to the current scope
  14853. * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of
  14854. * comparing for reference equality.
  14855. * @returns {function()} Returns a deregistration function for this listener.
  14856. */
  14857. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  14858. var get = $parse(watchExp);
  14859. if (get.$$watchDelegate) {
  14860. return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
  14861. }
  14862. var scope = this,
  14863. array = scope.$$watchers,
  14864. watcher = {
  14865. fn: listener,
  14866. last: initWatchVal,
  14867. get: get,
  14868. exp: prettyPrintExpression || watchExp,
  14869. eq: !!objectEquality
  14870. };
  14871. lastDirtyWatch = null;
  14872. if (!isFunction(listener)) {
  14873. watcher.fn = noop;
  14874. }
  14875. if (!array) {
  14876. array = scope.$$watchers = [];
  14877. }
  14878. // we use unshift since we use a while loop in $digest for speed.
  14879. // the while loop reads in reverse order.
  14880. array.unshift(watcher);
  14881. incrementWatchersCount(this, 1);
  14882. return function deregisterWatch() {
  14883. if (arrayRemove(array, watcher) >= 0) {
  14884. incrementWatchersCount(scope, -1);
  14885. }
  14886. lastDirtyWatch = null;
  14887. };
  14888. },
  14889. /**
  14890. * @ngdoc method
  14891. * @name $rootScope.Scope#$watchGroup
  14892. * @kind function
  14893. *
  14894. * @description
  14895. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  14896. * If any one expression in the collection changes the `listener` is executed.
  14897. *
  14898. * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
  14899. * call to $digest() to see if any items changes.
  14900. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  14901. *
  14902. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  14903. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  14904. *
  14905. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  14906. * expression in `watchExpressions` changes
  14907. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  14908. * those of `watchExpression`
  14909. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  14910. * those of `watchExpression`
  14911. * The `scope` refers to the current scope.
  14912. * @returns {function()} Returns a de-registration function for all listeners.
  14913. */
  14914. $watchGroup: function(watchExpressions, listener) {
  14915. var oldValues = new Array(watchExpressions.length);
  14916. var newValues = new Array(watchExpressions.length);
  14917. var deregisterFns = [];
  14918. var self = this;
  14919. var changeReactionScheduled = false;
  14920. var firstRun = true;
  14921. if (!watchExpressions.length) {
  14922. // No expressions means we call the listener ASAP
  14923. var shouldCall = true;
  14924. self.$evalAsync(function() {
  14925. if (shouldCall) listener(newValues, newValues, self);
  14926. });
  14927. return function deregisterWatchGroup() {
  14928. shouldCall = false;
  14929. };
  14930. }
  14931. if (watchExpressions.length === 1) {
  14932. // Special case size of one
  14933. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  14934. newValues[0] = value;
  14935. oldValues[0] = oldValue;
  14936. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  14937. });
  14938. }
  14939. forEach(watchExpressions, function(expr, i) {
  14940. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  14941. newValues[i] = value;
  14942. oldValues[i] = oldValue;
  14943. if (!changeReactionScheduled) {
  14944. changeReactionScheduled = true;
  14945. self.$evalAsync(watchGroupAction);
  14946. }
  14947. });
  14948. deregisterFns.push(unwatchFn);
  14949. });
  14950. function watchGroupAction() {
  14951. changeReactionScheduled = false;
  14952. if (firstRun) {
  14953. firstRun = false;
  14954. listener(newValues, newValues, self);
  14955. } else {
  14956. listener(newValues, oldValues, self);
  14957. }
  14958. }
  14959. return function deregisterWatchGroup() {
  14960. while (deregisterFns.length) {
  14961. deregisterFns.shift()();
  14962. }
  14963. };
  14964. },
  14965. /**
  14966. * @ngdoc method
  14967. * @name $rootScope.Scope#$watchCollection
  14968. * @kind function
  14969. *
  14970. * @description
  14971. * Shallow watches the properties of an object and fires whenever any of the properties change
  14972. * (for arrays, this implies watching the array items; for object maps, this implies watching
  14973. * the properties). If a change is detected, the `listener` callback is fired.
  14974. *
  14975. * - The `obj` collection is observed via standard $watch operation and is examined on every
  14976. * call to $digest() to see if any items have been added, removed, or moved.
  14977. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  14978. * adding, removing, and moving items belonging to an object or array.
  14979. *
  14980. *
  14981. * # Example
  14982. * ```js
  14983. $scope.names = ['igor', 'matias', 'misko', 'james'];
  14984. $scope.dataCount = 4;
  14985. $scope.$watchCollection('names', function(newNames, oldNames) {
  14986. $scope.dataCount = newNames.length;
  14987. });
  14988. expect($scope.dataCount).toEqual(4);
  14989. $scope.$digest();
  14990. //still at 4 ... no changes
  14991. expect($scope.dataCount).toEqual(4);
  14992. $scope.names.pop();
  14993. $scope.$digest();
  14994. //now there's been a change
  14995. expect($scope.dataCount).toEqual(3);
  14996. * ```
  14997. *
  14998. *
  14999. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  15000. * expression value should evaluate to an object or an array which is observed on each
  15001. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  15002. * collection will trigger a call to the `listener`.
  15003. *
  15004. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  15005. * when a change is detected.
  15006. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  15007. * - The `oldCollection` object is a copy of the former collection data.
  15008. * Due to performance considerations, the`oldCollection` value is computed only if the
  15009. * `listener` function declares two or more arguments.
  15010. * - The `scope` argument refers to the current scope.
  15011. *
  15012. * @returns {function()} Returns a de-registration function for this listener. When the
  15013. * de-registration function is executed, the internal watch operation is terminated.
  15014. */
  15015. $watchCollection: function(obj, listener) {
  15016. $watchCollectionInterceptor.$stateful = true;
  15017. var self = this;
  15018. // the current value, updated on each dirty-check run
  15019. var newValue;
  15020. // a shallow copy of the newValue from the last dirty-check run,
  15021. // updated to match newValue during dirty-check run
  15022. var oldValue;
  15023. // a shallow copy of the newValue from when the last change happened
  15024. var veryOldValue;
  15025. // only track veryOldValue if the listener is asking for it
  15026. var trackVeryOldValue = (listener.length > 1);
  15027. var changeDetected = 0;
  15028. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  15029. var internalArray = [];
  15030. var internalObject = {};
  15031. var initRun = true;
  15032. var oldLength = 0;
  15033. function $watchCollectionInterceptor(_value) {
  15034. newValue = _value;
  15035. var newLength, key, bothNaN, newItem, oldItem;
  15036. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  15037. if (isUndefined(newValue)) return;
  15038. if (!isObject(newValue)) { // if primitive
  15039. if (oldValue !== newValue) {
  15040. oldValue = newValue;
  15041. changeDetected++;
  15042. }
  15043. } else if (isArrayLike(newValue)) {
  15044. if (oldValue !== internalArray) {
  15045. // we are transitioning from something which was not an array into array.
  15046. oldValue = internalArray;
  15047. oldLength = oldValue.length = 0;
  15048. changeDetected++;
  15049. }
  15050. newLength = newValue.length;
  15051. if (oldLength !== newLength) {
  15052. // if lengths do not match we need to trigger change notification
  15053. changeDetected++;
  15054. oldValue.length = oldLength = newLength;
  15055. }
  15056. // copy the items to oldValue and look for changes.
  15057. for (var i = 0; i < newLength; i++) {
  15058. oldItem = oldValue[i];
  15059. newItem = newValue[i];
  15060. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  15061. if (!bothNaN && (oldItem !== newItem)) {
  15062. changeDetected++;
  15063. oldValue[i] = newItem;
  15064. }
  15065. }
  15066. } else {
  15067. if (oldValue !== internalObject) {
  15068. // we are transitioning from something which was not an object into object.
  15069. oldValue = internalObject = {};
  15070. oldLength = 0;
  15071. changeDetected++;
  15072. }
  15073. // copy the items to oldValue and look for changes.
  15074. newLength = 0;
  15075. for (key in newValue) {
  15076. if (hasOwnProperty.call(newValue, key)) {
  15077. newLength++;
  15078. newItem = newValue[key];
  15079. oldItem = oldValue[key];
  15080. if (key in oldValue) {
  15081. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  15082. if (!bothNaN && (oldItem !== newItem)) {
  15083. changeDetected++;
  15084. oldValue[key] = newItem;
  15085. }
  15086. } else {
  15087. oldLength++;
  15088. oldValue[key] = newItem;
  15089. changeDetected++;
  15090. }
  15091. }
  15092. }
  15093. if (oldLength > newLength) {
  15094. // we used to have more keys, need to find them and destroy them.
  15095. changeDetected++;
  15096. for (key in oldValue) {
  15097. if (!hasOwnProperty.call(newValue, key)) {
  15098. oldLength--;
  15099. delete oldValue[key];
  15100. }
  15101. }
  15102. }
  15103. }
  15104. return changeDetected;
  15105. }
  15106. function $watchCollectionAction() {
  15107. if (initRun) {
  15108. initRun = false;
  15109. listener(newValue, newValue, self);
  15110. } else {
  15111. listener(newValue, veryOldValue, self);
  15112. }
  15113. // make a copy for the next time a collection is changed
  15114. if (trackVeryOldValue) {
  15115. if (!isObject(newValue)) {
  15116. //primitive
  15117. veryOldValue = newValue;
  15118. } else if (isArrayLike(newValue)) {
  15119. veryOldValue = new Array(newValue.length);
  15120. for (var i = 0; i < newValue.length; i++) {
  15121. veryOldValue[i] = newValue[i];
  15122. }
  15123. } else { // if object
  15124. veryOldValue = {};
  15125. for (var key in newValue) {
  15126. if (hasOwnProperty.call(newValue, key)) {
  15127. veryOldValue[key] = newValue[key];
  15128. }
  15129. }
  15130. }
  15131. }
  15132. }
  15133. return this.$watch(changeDetector, $watchCollectionAction);
  15134. },
  15135. /**
  15136. * @ngdoc method
  15137. * @name $rootScope.Scope#$digest
  15138. * @kind function
  15139. *
  15140. * @description
  15141. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  15142. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  15143. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  15144. * until no more listeners are firing. This means that it is possible to get into an infinite
  15145. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  15146. * iterations exceeds 10.
  15147. *
  15148. * Usually, you don't call `$digest()` directly in
  15149. * {@link ng.directive:ngController controllers} or in
  15150. * {@link ng.$compileProvider#directive directives}.
  15151. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  15152. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  15153. *
  15154. * If you want to be notified whenever `$digest()` is called,
  15155. * you can register a `watchExpression` function with
  15156. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  15157. *
  15158. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  15159. *
  15160. * # Example
  15161. * ```js
  15162. var scope = ...;
  15163. scope.name = 'misko';
  15164. scope.counter = 0;
  15165. expect(scope.counter).toEqual(0);
  15166. scope.$watch('name', function(newValue, oldValue) {
  15167. scope.counter = scope.counter + 1;
  15168. });
  15169. expect(scope.counter).toEqual(0);
  15170. scope.$digest();
  15171. // the listener is always called during the first $digest loop after it was registered
  15172. expect(scope.counter).toEqual(1);
  15173. scope.$digest();
  15174. // but now it will not be called unless the value changes
  15175. expect(scope.counter).toEqual(1);
  15176. scope.name = 'adam';
  15177. scope.$digest();
  15178. expect(scope.counter).toEqual(2);
  15179. * ```
  15180. *
  15181. */
  15182. $digest: function() {
  15183. var watch, value, last, fn, get,
  15184. watchers,
  15185. length,
  15186. dirty, ttl = TTL,
  15187. next, current, target = this,
  15188. watchLog = [],
  15189. logIdx, asyncTask;
  15190. beginPhase('$digest');
  15191. // Check for changes to browser url that happened in sync before the call to $digest
  15192. $browser.$$checkUrlChange();
  15193. if (this === $rootScope && applyAsyncId !== null) {
  15194. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  15195. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  15196. $browser.defer.cancel(applyAsyncId);
  15197. flushApplyAsync();
  15198. }
  15199. lastDirtyWatch = null;
  15200. do { // "while dirty" loop
  15201. dirty = false;
  15202. current = target;
  15203. while (asyncQueue.length) {
  15204. try {
  15205. asyncTask = asyncQueue.shift();
  15206. asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
  15207. } catch (e) {
  15208. $exceptionHandler(e);
  15209. }
  15210. lastDirtyWatch = null;
  15211. }
  15212. traverseScopesLoop:
  15213. do { // "traverse the scopes" loop
  15214. if ((watchers = current.$$watchers)) {
  15215. // process our watches
  15216. length = watchers.length;
  15217. while (length--) {
  15218. try {
  15219. watch = watchers[length];
  15220. // Most common watches are on primitives, in which case we can short
  15221. // circuit it with === operator, only when === fails do we use .equals
  15222. if (watch) {
  15223. get = watch.get;
  15224. if ((value = get(current)) !== (last = watch.last) &&
  15225. !(watch.eq
  15226. ? equals(value, last)
  15227. : (typeof value === 'number' && typeof last === 'number'
  15228. && isNaN(value) && isNaN(last)))) {
  15229. dirty = true;
  15230. lastDirtyWatch = watch;
  15231. watch.last = watch.eq ? copy(value, null) : value;
  15232. fn = watch.fn;
  15233. fn(value, ((last === initWatchVal) ? value : last), current);
  15234. if (ttl < 5) {
  15235. logIdx = 4 - ttl;
  15236. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  15237. watchLog[logIdx].push({
  15238. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  15239. newVal: value,
  15240. oldVal: last
  15241. });
  15242. }
  15243. } else if (watch === lastDirtyWatch) {
  15244. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  15245. // have already been tested.
  15246. dirty = false;
  15247. break traverseScopesLoop;
  15248. }
  15249. }
  15250. } catch (e) {
  15251. $exceptionHandler(e);
  15252. }
  15253. }
  15254. }
  15255. // Insanity Warning: scope depth-first traversal
  15256. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  15257. // this piece should be kept in sync with the traversal in $broadcast
  15258. if (!(next = ((current.$$watchersCount && current.$$childHead) ||
  15259. (current !== target && current.$$nextSibling)))) {
  15260. while (current !== target && !(next = current.$$nextSibling)) {
  15261. current = current.$parent;
  15262. }
  15263. }
  15264. } while ((current = next));
  15265. // `break traverseScopesLoop;` takes us to here
  15266. if ((dirty || asyncQueue.length) && !(ttl--)) {
  15267. clearPhase();
  15268. throw $rootScopeMinErr('infdig',
  15269. '{0} $digest() iterations reached. Aborting!\n' +
  15270. 'Watchers fired in the last 5 iterations: {1}',
  15271. TTL, watchLog);
  15272. }
  15273. } while (dirty || asyncQueue.length);
  15274. clearPhase();
  15275. while (postDigestQueue.length) {
  15276. try {
  15277. postDigestQueue.shift()();
  15278. } catch (e) {
  15279. $exceptionHandler(e);
  15280. }
  15281. }
  15282. },
  15283. /**
  15284. * @ngdoc event
  15285. * @name $rootScope.Scope#$destroy
  15286. * @eventType broadcast on scope being destroyed
  15287. *
  15288. * @description
  15289. * Broadcasted when a scope and its children are being destroyed.
  15290. *
  15291. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  15292. * clean up DOM bindings before an element is removed from the DOM.
  15293. */
  15294. /**
  15295. * @ngdoc method
  15296. * @name $rootScope.Scope#$destroy
  15297. * @kind function
  15298. *
  15299. * @description
  15300. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  15301. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  15302. * propagate to the current scope and its children. Removal also implies that the current
  15303. * scope is eligible for garbage collection.
  15304. *
  15305. * The `$destroy()` is usually used by directives such as
  15306. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  15307. * unrolling of the loop.
  15308. *
  15309. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  15310. * Application code can register a `$destroy` event handler that will give it a chance to
  15311. * perform any necessary cleanup.
  15312. *
  15313. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  15314. * clean up DOM bindings before an element is removed from the DOM.
  15315. */
  15316. $destroy: function() {
  15317. // We can't destroy a scope that has been already destroyed.
  15318. if (this.$$destroyed) return;
  15319. var parent = this.$parent;
  15320. this.$broadcast('$destroy');
  15321. this.$$destroyed = true;
  15322. if (this === $rootScope) {
  15323. //Remove handlers attached to window when $rootScope is removed
  15324. $browser.$$applicationDestroyed();
  15325. }
  15326. incrementWatchersCount(this, -this.$$watchersCount);
  15327. for (var eventName in this.$$listenerCount) {
  15328. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  15329. }
  15330. // sever all the references to parent scopes (after this cleanup, the current scope should
  15331. // not be retained by any of our references and should be eligible for garbage collection)
  15332. if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  15333. if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  15334. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  15335. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  15336. // Disable listeners, watchers and apply/digest methods
  15337. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  15338. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  15339. this.$$listeners = {};
  15340. // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
  15341. this.$$nextSibling = null;
  15342. cleanUpScope(this);
  15343. },
  15344. /**
  15345. * @ngdoc method
  15346. * @name $rootScope.Scope#$eval
  15347. * @kind function
  15348. *
  15349. * @description
  15350. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  15351. * the expression are propagated (uncaught). This is useful when evaluating Angular
  15352. * expressions.
  15353. *
  15354. * # Example
  15355. * ```js
  15356. var scope = ng.$rootScope.Scope();
  15357. scope.a = 1;
  15358. scope.b = 2;
  15359. expect(scope.$eval('a+b')).toEqual(3);
  15360. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  15361. * ```
  15362. *
  15363. * @param {(string|function())=} expression An angular expression to be executed.
  15364. *
  15365. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  15366. * - `function(scope)`: execute the function with the current `scope` parameter.
  15367. *
  15368. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  15369. * @returns {*} The result of evaluating the expression.
  15370. */
  15371. $eval: function(expr, locals) {
  15372. return $parse(expr)(this, locals);
  15373. },
  15374. /**
  15375. * @ngdoc method
  15376. * @name $rootScope.Scope#$evalAsync
  15377. * @kind function
  15378. *
  15379. * @description
  15380. * Executes the expression on the current scope at a later point in time.
  15381. *
  15382. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  15383. * that:
  15384. *
  15385. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  15386. * rendering).
  15387. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  15388. * `expression` execution.
  15389. *
  15390. * Any exceptions from the execution of the expression are forwarded to the
  15391. * {@link ng.$exceptionHandler $exceptionHandler} service.
  15392. *
  15393. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  15394. * will be scheduled. However, it is encouraged to always call code that changes the model
  15395. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  15396. *
  15397. * @param {(string|function())=} expression An angular expression to be executed.
  15398. *
  15399. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  15400. * - `function(scope)`: execute the function with the current `scope` parameter.
  15401. *
  15402. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  15403. */
  15404. $evalAsync: function(expr, locals) {
  15405. // if we are outside of an $digest loop and this is the first time we are scheduling async
  15406. // task also schedule async auto-flush
  15407. if (!$rootScope.$$phase && !asyncQueue.length) {
  15408. $browser.defer(function() {
  15409. if (asyncQueue.length) {
  15410. $rootScope.$digest();
  15411. }
  15412. });
  15413. }
  15414. asyncQueue.push({scope: this, expression: $parse(expr), locals: locals});
  15415. },
  15416. $$postDigest: function(fn) {
  15417. postDigestQueue.push(fn);
  15418. },
  15419. /**
  15420. * @ngdoc method
  15421. * @name $rootScope.Scope#$apply
  15422. * @kind function
  15423. *
  15424. * @description
  15425. * `$apply()` is used to execute an expression in angular from outside of the angular
  15426. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  15427. * Because we are calling into the angular framework we need to perform proper scope life
  15428. * cycle of {@link ng.$exceptionHandler exception handling},
  15429. * {@link ng.$rootScope.Scope#$digest executing watches}.
  15430. *
  15431. * ## Life cycle
  15432. *
  15433. * # Pseudo-Code of `$apply()`
  15434. * ```js
  15435. function $apply(expr) {
  15436. try {
  15437. return $eval(expr);
  15438. } catch (e) {
  15439. $exceptionHandler(e);
  15440. } finally {
  15441. $root.$digest();
  15442. }
  15443. }
  15444. * ```
  15445. *
  15446. *
  15447. * Scope's `$apply()` method transitions through the following stages:
  15448. *
  15449. * 1. The {@link guide/expression expression} is executed using the
  15450. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  15451. * 2. Any exceptions from the execution of the expression are forwarded to the
  15452. * {@link ng.$exceptionHandler $exceptionHandler} service.
  15453. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  15454. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  15455. *
  15456. *
  15457. * @param {(string|function())=} exp An angular expression to be executed.
  15458. *
  15459. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  15460. * - `function(scope)`: execute the function with current `scope` parameter.
  15461. *
  15462. * @returns {*} The result of evaluating the expression.
  15463. */
  15464. $apply: function(expr) {
  15465. try {
  15466. beginPhase('$apply');
  15467. try {
  15468. return this.$eval(expr);
  15469. } finally {
  15470. clearPhase();
  15471. }
  15472. } catch (e) {
  15473. $exceptionHandler(e);
  15474. } finally {
  15475. try {
  15476. $rootScope.$digest();
  15477. } catch (e) {
  15478. $exceptionHandler(e);
  15479. throw e;
  15480. }
  15481. }
  15482. },
  15483. /**
  15484. * @ngdoc method
  15485. * @name $rootScope.Scope#$applyAsync
  15486. * @kind function
  15487. *
  15488. * @description
  15489. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  15490. * varies across browsers, but is typically around ~10 milliseconds.
  15491. *
  15492. * This can be used to queue up multiple expressions which need to be evaluated in the same
  15493. * digest.
  15494. *
  15495. * @param {(string|function())=} exp An angular expression to be executed.
  15496. *
  15497. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  15498. * - `function(scope)`: execute the function with current `scope` parameter.
  15499. */
  15500. $applyAsync: function(expr) {
  15501. var scope = this;
  15502. expr && applyAsyncQueue.push($applyAsyncExpression);
  15503. expr = $parse(expr);
  15504. scheduleApplyAsync();
  15505. function $applyAsyncExpression() {
  15506. scope.$eval(expr);
  15507. }
  15508. },
  15509. /**
  15510. * @ngdoc method
  15511. * @name $rootScope.Scope#$on
  15512. * @kind function
  15513. *
  15514. * @description
  15515. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  15516. * discussion of event life cycle.
  15517. *
  15518. * The event listener function format is: `function(event, args...)`. The `event` object
  15519. * passed into the listener has the following attributes:
  15520. *
  15521. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  15522. * `$broadcast`-ed.
  15523. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  15524. * event propagates through the scope hierarchy, this property is set to null.
  15525. * - `name` - `{string}`: name of the event.
  15526. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  15527. * further event propagation (available only for events that were `$emit`-ed).
  15528. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  15529. * to true.
  15530. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  15531. *
  15532. * @param {string} name Event name to listen on.
  15533. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  15534. * @returns {function()} Returns a deregistration function for this listener.
  15535. */
  15536. $on: function(name, listener) {
  15537. var namedListeners = this.$$listeners[name];
  15538. if (!namedListeners) {
  15539. this.$$listeners[name] = namedListeners = [];
  15540. }
  15541. namedListeners.push(listener);
  15542. var current = this;
  15543. do {
  15544. if (!current.$$listenerCount[name]) {
  15545. current.$$listenerCount[name] = 0;
  15546. }
  15547. current.$$listenerCount[name]++;
  15548. } while ((current = current.$parent));
  15549. var self = this;
  15550. return function() {
  15551. var indexOfListener = namedListeners.indexOf(listener);
  15552. if (indexOfListener !== -1) {
  15553. namedListeners[indexOfListener] = null;
  15554. decrementListenerCount(self, 1, name);
  15555. }
  15556. };
  15557. },
  15558. /**
  15559. * @ngdoc method
  15560. * @name $rootScope.Scope#$emit
  15561. * @kind function
  15562. *
  15563. * @description
  15564. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  15565. * registered {@link ng.$rootScope.Scope#$on} listeners.
  15566. *
  15567. * The event life cycle starts at the scope on which `$emit` was called. All
  15568. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  15569. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  15570. * registered listeners along the way. The event will stop propagating if one of the listeners
  15571. * cancels it.
  15572. *
  15573. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  15574. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  15575. *
  15576. * @param {string} name Event name to emit.
  15577. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  15578. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  15579. */
  15580. $emit: function(name, args) {
  15581. var empty = [],
  15582. namedListeners,
  15583. scope = this,
  15584. stopPropagation = false,
  15585. event = {
  15586. name: name,
  15587. targetScope: scope,
  15588. stopPropagation: function() {stopPropagation = true;},
  15589. preventDefault: function() {
  15590. event.defaultPrevented = true;
  15591. },
  15592. defaultPrevented: false
  15593. },
  15594. listenerArgs = concat([event], arguments, 1),
  15595. i, length;
  15596. do {
  15597. namedListeners = scope.$$listeners[name] || empty;
  15598. event.currentScope = scope;
  15599. for (i = 0, length = namedListeners.length; i < length; i++) {
  15600. // if listeners were deregistered, defragment the array
  15601. if (!namedListeners[i]) {
  15602. namedListeners.splice(i, 1);
  15603. i--;
  15604. length--;
  15605. continue;
  15606. }
  15607. try {
  15608. //allow all listeners attached to the current scope to run
  15609. namedListeners[i].apply(null, listenerArgs);
  15610. } catch (e) {
  15611. $exceptionHandler(e);
  15612. }
  15613. }
  15614. //if any listener on the current scope stops propagation, prevent bubbling
  15615. if (stopPropagation) {
  15616. event.currentScope = null;
  15617. return event;
  15618. }
  15619. //traverse upwards
  15620. scope = scope.$parent;
  15621. } while (scope);
  15622. event.currentScope = null;
  15623. return event;
  15624. },
  15625. /**
  15626. * @ngdoc method
  15627. * @name $rootScope.Scope#$broadcast
  15628. * @kind function
  15629. *
  15630. * @description
  15631. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  15632. * registered {@link ng.$rootScope.Scope#$on} listeners.
  15633. *
  15634. * The event life cycle starts at the scope on which `$broadcast` was called. All
  15635. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  15636. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  15637. * scope and calls all registered listeners along the way. The event cannot be canceled.
  15638. *
  15639. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  15640. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  15641. *
  15642. * @param {string} name Event name to broadcast.
  15643. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  15644. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  15645. */
  15646. $broadcast: function(name, args) {
  15647. var target = this,
  15648. current = target,
  15649. next = target,
  15650. event = {
  15651. name: name,
  15652. targetScope: target,
  15653. preventDefault: function() {
  15654. event.defaultPrevented = true;
  15655. },
  15656. defaultPrevented: false
  15657. };
  15658. if (!target.$$listenerCount[name]) return event;
  15659. var listenerArgs = concat([event], arguments, 1),
  15660. listeners, i, length;
  15661. //down while you can, then up and next sibling or up and next sibling until back at root
  15662. while ((current = next)) {
  15663. event.currentScope = current;
  15664. listeners = current.$$listeners[name] || [];
  15665. for (i = 0, length = listeners.length; i < length; i++) {
  15666. // if listeners were deregistered, defragment the array
  15667. if (!listeners[i]) {
  15668. listeners.splice(i, 1);
  15669. i--;
  15670. length--;
  15671. continue;
  15672. }
  15673. try {
  15674. listeners[i].apply(null, listenerArgs);
  15675. } catch (e) {
  15676. $exceptionHandler(e);
  15677. }
  15678. }
  15679. // Insanity Warning: scope depth-first traversal
  15680. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  15681. // this piece should be kept in sync with the traversal in $digest
  15682. // (though it differs due to having the extra check for $$listenerCount)
  15683. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  15684. (current !== target && current.$$nextSibling)))) {
  15685. while (current !== target && !(next = current.$$nextSibling)) {
  15686. current = current.$parent;
  15687. }
  15688. }
  15689. }
  15690. event.currentScope = null;
  15691. return event;
  15692. }
  15693. };
  15694. var $rootScope = new Scope();
  15695. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  15696. var asyncQueue = $rootScope.$$asyncQueue = [];
  15697. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  15698. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  15699. return $rootScope;
  15700. function beginPhase(phase) {
  15701. if ($rootScope.$$phase) {
  15702. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  15703. }
  15704. $rootScope.$$phase = phase;
  15705. }
  15706. function clearPhase() {
  15707. $rootScope.$$phase = null;
  15708. }
  15709. function incrementWatchersCount(current, count) {
  15710. do {
  15711. current.$$watchersCount += count;
  15712. } while ((current = current.$parent));
  15713. }
  15714. function decrementListenerCount(current, count, name) {
  15715. do {
  15716. current.$$listenerCount[name] -= count;
  15717. if (current.$$listenerCount[name] === 0) {
  15718. delete current.$$listenerCount[name];
  15719. }
  15720. } while ((current = current.$parent));
  15721. }
  15722. /**
  15723. * function used as an initial value for watchers.
  15724. * because it's unique we can easily tell it apart from other values
  15725. */
  15726. function initWatchVal() {}
  15727. function flushApplyAsync() {
  15728. while (applyAsyncQueue.length) {
  15729. try {
  15730. applyAsyncQueue.shift()();
  15731. } catch (e) {
  15732. $exceptionHandler(e);
  15733. }
  15734. }
  15735. applyAsyncId = null;
  15736. }
  15737. function scheduleApplyAsync() {
  15738. if (applyAsyncId === null) {
  15739. applyAsyncId = $browser.defer(function() {
  15740. $rootScope.$apply(flushApplyAsync);
  15741. });
  15742. }
  15743. }
  15744. }];
  15745. }
  15746. /**
  15747. * @ngdoc service
  15748. * @name $rootElement
  15749. *
  15750. * @description
  15751. * The root element of Angular application. This is either the element where {@link
  15752. * ng.directive:ngApp ngApp} was declared or the element passed into
  15753. * {@link angular.bootstrap}. The element represents the root element of application. It is also the
  15754. * location where the application's {@link auto.$injector $injector} service gets
  15755. * published, and can be retrieved using `$rootElement.injector()`.
  15756. */
  15757. // the implementation is in angular.bootstrap
  15758. /**
  15759. * @description
  15760. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  15761. */
  15762. function $$SanitizeUriProvider() {
  15763. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  15764. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  15765. /**
  15766. * @description
  15767. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  15768. * urls during a[href] sanitization.
  15769. *
  15770. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  15771. *
  15772. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  15773. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  15774. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  15775. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  15776. *
  15777. * @param {RegExp=} regexp New regexp to whitelist urls with.
  15778. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  15779. * chaining otherwise.
  15780. */
  15781. this.aHrefSanitizationWhitelist = function(regexp) {
  15782. if (isDefined(regexp)) {
  15783. aHrefSanitizationWhitelist = regexp;
  15784. return this;
  15785. }
  15786. return aHrefSanitizationWhitelist;
  15787. };
  15788. /**
  15789. * @description
  15790. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  15791. * urls during img[src] sanitization.
  15792. *
  15793. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  15794. *
  15795. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  15796. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  15797. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  15798. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  15799. *
  15800. * @param {RegExp=} regexp New regexp to whitelist urls with.
  15801. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  15802. * chaining otherwise.
  15803. */
  15804. this.imgSrcSanitizationWhitelist = function(regexp) {
  15805. if (isDefined(regexp)) {
  15806. imgSrcSanitizationWhitelist = regexp;
  15807. return this;
  15808. }
  15809. return imgSrcSanitizationWhitelist;
  15810. };
  15811. this.$get = function() {
  15812. return function sanitizeUri(uri, isImage) {
  15813. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  15814. var normalizedVal;
  15815. normalizedVal = urlResolve(uri).href;
  15816. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  15817. return 'unsafe:' + normalizedVal;
  15818. }
  15819. return uri;
  15820. };
  15821. };
  15822. }
  15823. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  15824. * Any commits to this file should be reviewed with security in mind. *
  15825. * Changes to this file can potentially create security vulnerabilities. *
  15826. * An approval from 2 Core members with history of modifying *
  15827. * this file is required. *
  15828. * *
  15829. * Does the change somehow allow for arbitrary javascript to be executed? *
  15830. * Or allows for someone to change the prototype of built-in objects? *
  15831. * Or gives undesired access to variables likes document or window? *
  15832. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  15833. var $sceMinErr = minErr('$sce');
  15834. var SCE_CONTEXTS = {
  15835. HTML: 'html',
  15836. CSS: 'css',
  15837. URL: 'url',
  15838. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  15839. // url. (e.g. ng-include, script src, templateUrl)
  15840. RESOURCE_URL: 'resourceUrl',
  15841. JS: 'js'
  15842. };
  15843. // Helper functions follow.
  15844. function adjustMatcher(matcher) {
  15845. if (matcher === 'self') {
  15846. return matcher;
  15847. } else if (isString(matcher)) {
  15848. // Strings match exactly except for 2 wildcards - '*' and '**'.
  15849. // '*' matches any character except those from the set ':/.?&'.
  15850. // '**' matches any character (like .* in a RegExp).
  15851. // More than 2 *'s raises an error as it's ill defined.
  15852. if (matcher.indexOf('***') > -1) {
  15853. throw $sceMinErr('iwcard',
  15854. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  15855. }
  15856. matcher = escapeForRegexp(matcher).
  15857. replace('\\*\\*', '.*').
  15858. replace('\\*', '[^:/.?&;]*');
  15859. return new RegExp('^' + matcher + '$');
  15860. } else if (isRegExp(matcher)) {
  15861. // The only other type of matcher allowed is a Regexp.
  15862. // Match entire URL / disallow partial matches.
  15863. // Flags are reset (i.e. no global, ignoreCase or multiline)
  15864. return new RegExp('^' + matcher.source + '$');
  15865. } else {
  15866. throw $sceMinErr('imatcher',
  15867. 'Matchers may only be "self", string patterns or RegExp objects');
  15868. }
  15869. }
  15870. function adjustMatchers(matchers) {
  15871. var adjustedMatchers = [];
  15872. if (isDefined(matchers)) {
  15873. forEach(matchers, function(matcher) {
  15874. adjustedMatchers.push(adjustMatcher(matcher));
  15875. });
  15876. }
  15877. return adjustedMatchers;
  15878. }
  15879. /**
  15880. * @ngdoc service
  15881. * @name $sceDelegate
  15882. * @kind function
  15883. *
  15884. * @description
  15885. *
  15886. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  15887. * Contextual Escaping (SCE)} services to AngularJS.
  15888. *
  15889. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  15890. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  15891. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  15892. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  15893. * work because `$sce` delegates to `$sceDelegate` for these operations.
  15894. *
  15895. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  15896. *
  15897. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  15898. * can override it completely to change the behavior of `$sce`, the common case would
  15899. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  15900. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  15901. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  15902. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  15903. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  15904. */
  15905. /**
  15906. * @ngdoc provider
  15907. * @name $sceDelegateProvider
  15908. * @description
  15909. *
  15910. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  15911. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  15912. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  15913. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  15914. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  15915. *
  15916. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  15917. * Strict Contextual Escaping (SCE)}.
  15918. *
  15919. * **Example**: Consider the following case. <a name="example"></a>
  15920. *
  15921. * - your app is hosted at url `http://myapp.example.com/`
  15922. * - but some of your templates are hosted on other domains you control such as
  15923. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  15924. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  15925. *
  15926. * Here is what a secure configuration for this scenario might look like:
  15927. *
  15928. * ```
  15929. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  15930. * $sceDelegateProvider.resourceUrlWhitelist([
  15931. * // Allow same origin resource loads.
  15932. * 'self',
  15933. * // Allow loading from our assets domain. Notice the difference between * and **.
  15934. * 'http://srv*.assets.example.com/**'
  15935. * ]);
  15936. *
  15937. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  15938. * $sceDelegateProvider.resourceUrlBlacklist([
  15939. * 'http://myapp.example.com/clickThru**'
  15940. * ]);
  15941. * });
  15942. * ```
  15943. */
  15944. function $SceDelegateProvider() {
  15945. this.SCE_CONTEXTS = SCE_CONTEXTS;
  15946. // Resource URLs can also be trusted by policy.
  15947. var resourceUrlWhitelist = ['self'],
  15948. resourceUrlBlacklist = [];
  15949. /**
  15950. * @ngdoc method
  15951. * @name $sceDelegateProvider#resourceUrlWhitelist
  15952. * @kind function
  15953. *
  15954. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  15955. * provided. This must be an array or null. A snapshot of this array is used so further
  15956. * changes to the array are ignored.
  15957. *
  15958. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  15959. * allowed in this array.
  15960. *
  15961. * <div class="alert alert-warning">
  15962. * **Note:** an empty whitelist array will block all URLs!
  15963. * </div>
  15964. *
  15965. * @return {Array} the currently set whitelist array.
  15966. *
  15967. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  15968. * same origin resource requests.
  15969. *
  15970. * @description
  15971. * Sets/Gets the whitelist of trusted resource URLs.
  15972. */
  15973. this.resourceUrlWhitelist = function(value) {
  15974. if (arguments.length) {
  15975. resourceUrlWhitelist = adjustMatchers(value);
  15976. }
  15977. return resourceUrlWhitelist;
  15978. };
  15979. /**
  15980. * @ngdoc method
  15981. * @name $sceDelegateProvider#resourceUrlBlacklist
  15982. * @kind function
  15983. *
  15984. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  15985. * provided. This must be an array or null. A snapshot of this array is used so further
  15986. * changes to the array are ignored.
  15987. *
  15988. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  15989. * allowed in this array.
  15990. *
  15991. * The typical usage for the blacklist is to **block
  15992. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  15993. * these would otherwise be trusted but actually return content from the redirected domain.
  15994. *
  15995. * Finally, **the blacklist overrides the whitelist** and has the final say.
  15996. *
  15997. * @return {Array} the currently set blacklist array.
  15998. *
  15999. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  16000. * is no blacklist.)
  16001. *
  16002. * @description
  16003. * Sets/Gets the blacklist of trusted resource URLs.
  16004. */
  16005. this.resourceUrlBlacklist = function(value) {
  16006. if (arguments.length) {
  16007. resourceUrlBlacklist = adjustMatchers(value);
  16008. }
  16009. return resourceUrlBlacklist;
  16010. };
  16011. this.$get = ['$injector', function($injector) {
  16012. var htmlSanitizer = function htmlSanitizer(html) {
  16013. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  16014. };
  16015. if ($injector.has('$sanitize')) {
  16016. htmlSanitizer = $injector.get('$sanitize');
  16017. }
  16018. function matchUrl(matcher, parsedUrl) {
  16019. if (matcher === 'self') {
  16020. return urlIsSameOrigin(parsedUrl);
  16021. } else {
  16022. // definitely a regex. See adjustMatchers()
  16023. return !!matcher.exec(parsedUrl.href);
  16024. }
  16025. }
  16026. function isResourceUrlAllowedByPolicy(url) {
  16027. var parsedUrl = urlResolve(url.toString());
  16028. var i, n, allowed = false;
  16029. // Ensure that at least one item from the whitelist allows this url.
  16030. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  16031. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  16032. allowed = true;
  16033. break;
  16034. }
  16035. }
  16036. if (allowed) {
  16037. // Ensure that no item from the blacklist blocked this url.
  16038. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  16039. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  16040. allowed = false;
  16041. break;
  16042. }
  16043. }
  16044. }
  16045. return allowed;
  16046. }
  16047. function generateHolderType(Base) {
  16048. var holderType = function TrustedValueHolderType(trustedValue) {
  16049. this.$$unwrapTrustedValue = function() {
  16050. return trustedValue;
  16051. };
  16052. };
  16053. if (Base) {
  16054. holderType.prototype = new Base();
  16055. }
  16056. holderType.prototype.valueOf = function sceValueOf() {
  16057. return this.$$unwrapTrustedValue();
  16058. };
  16059. holderType.prototype.toString = function sceToString() {
  16060. return this.$$unwrapTrustedValue().toString();
  16061. };
  16062. return holderType;
  16063. }
  16064. var trustedValueHolderBase = generateHolderType(),
  16065. byType = {};
  16066. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  16067. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  16068. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  16069. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  16070. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  16071. /**
  16072. * @ngdoc method
  16073. * @name $sceDelegate#trustAs
  16074. *
  16075. * @description
  16076. * Returns an object that is trusted by angular for use in specified strict
  16077. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  16078. * attribute interpolation, any dom event binding attribute interpolation
  16079. * such as for onclick, etc.) that uses the provided value.
  16080. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  16081. *
  16082. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  16083. * resourceUrl, html, js and css.
  16084. * @param {*} value The value that that should be considered trusted/safe.
  16085. * @returns {*} A value that can be used to stand in for the provided `value` in places
  16086. * where Angular expects a $sce.trustAs() return value.
  16087. */
  16088. function trustAs(type, trustedValue) {
  16089. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  16090. if (!Constructor) {
  16091. throw $sceMinErr('icontext',
  16092. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  16093. type, trustedValue);
  16094. }
  16095. if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
  16096. return trustedValue;
  16097. }
  16098. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  16099. // mutable objects, we ensure here that the value passed in is actually a string.
  16100. if (typeof trustedValue !== 'string') {
  16101. throw $sceMinErr('itype',
  16102. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  16103. type);
  16104. }
  16105. return new Constructor(trustedValue);
  16106. }
  16107. /**
  16108. * @ngdoc method
  16109. * @name $sceDelegate#valueOf
  16110. *
  16111. * @description
  16112. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  16113. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  16114. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  16115. *
  16116. * If the passed parameter is not a value that had been returned by {@link
  16117. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  16118. *
  16119. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  16120. * call or anything else.
  16121. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  16122. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  16123. * `value` unchanged.
  16124. */
  16125. function valueOf(maybeTrusted) {
  16126. if (maybeTrusted instanceof trustedValueHolderBase) {
  16127. return maybeTrusted.$$unwrapTrustedValue();
  16128. } else {
  16129. return maybeTrusted;
  16130. }
  16131. }
  16132. /**
  16133. * @ngdoc method
  16134. * @name $sceDelegate#getTrusted
  16135. *
  16136. * @description
  16137. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  16138. * returns the originally supplied value if the queried context type is a supertype of the
  16139. * created type. If this condition isn't satisfied, throws an exception.
  16140. *
  16141. * <div class="alert alert-danger">
  16142. * Disabling auto-escaping is extremely dangerous, it usually creates a Cross Site Scripting
  16143. * (XSS) vulnerability in your application.
  16144. * </div>
  16145. *
  16146. * @param {string} type The kind of context in which this value is to be used.
  16147. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  16148. * `$sceDelegate.trustAs`} call.
  16149. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  16150. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  16151. */
  16152. function getTrusted(type, maybeTrusted) {
  16153. if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
  16154. return maybeTrusted;
  16155. }
  16156. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  16157. if (constructor && maybeTrusted instanceof constructor) {
  16158. return maybeTrusted.$$unwrapTrustedValue();
  16159. }
  16160. // If we get here, then we may only take one of two actions.
  16161. // 1. sanitize the value for the requested type, or
  16162. // 2. throw an exception.
  16163. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  16164. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  16165. return maybeTrusted;
  16166. } else {
  16167. throw $sceMinErr('insecurl',
  16168. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  16169. maybeTrusted.toString());
  16170. }
  16171. } else if (type === SCE_CONTEXTS.HTML) {
  16172. return htmlSanitizer(maybeTrusted);
  16173. }
  16174. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  16175. }
  16176. return { trustAs: trustAs,
  16177. getTrusted: getTrusted,
  16178. valueOf: valueOf };
  16179. }];
  16180. }
  16181. /**
  16182. * @ngdoc provider
  16183. * @name $sceProvider
  16184. * @description
  16185. *
  16186. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  16187. * - enable/disable Strict Contextual Escaping (SCE) in a module
  16188. * - override the default implementation with a custom delegate
  16189. *
  16190. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  16191. */
  16192. /* jshint maxlen: false*/
  16193. /**
  16194. * @ngdoc service
  16195. * @name $sce
  16196. * @kind function
  16197. *
  16198. * @description
  16199. *
  16200. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  16201. *
  16202. * # Strict Contextual Escaping
  16203. *
  16204. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  16205. * contexts to result in a value that is marked as safe to use for that context. One example of
  16206. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  16207. * to these contexts as privileged or SCE contexts.
  16208. *
  16209. * As of version 1.2, Angular ships with SCE enabled by default.
  16210. *
  16211. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  16212. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  16213. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  16214. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  16215. * to the top of your HTML document.
  16216. *
  16217. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  16218. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  16219. *
  16220. * Here's an example of a binding in a privileged context:
  16221. *
  16222. * ```
  16223. * <input ng-model="userHtml" aria-label="User input">
  16224. * <div ng-bind-html="userHtml"></div>
  16225. * ```
  16226. *
  16227. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  16228. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  16229. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  16230. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  16231. * security vulnerabilities.)
  16232. *
  16233. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  16234. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  16235. *
  16236. * How would you ensure that every place that used these types of bindings was bound to a value that
  16237. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  16238. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  16239. * properties/fields and forgot to update the binding to the sanitized value?
  16240. *
  16241. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  16242. * determine that something explicitly says it's safe to use a value for binding in that
  16243. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  16244. * for those values that you can easily tell are safe - because they were received from your server,
  16245. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  16246. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  16247. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  16248. *
  16249. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  16250. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  16251. * obtain values that will be accepted by SCE / privileged contexts.
  16252. *
  16253. *
  16254. * ## How does it work?
  16255. *
  16256. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  16257. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  16258. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  16259. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  16260. *
  16261. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  16262. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  16263. * simplified):
  16264. *
  16265. * ```
  16266. * var ngBindHtmlDirective = ['$sce', function($sce) {
  16267. * return function(scope, element, attr) {
  16268. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  16269. * element.html(value || '');
  16270. * });
  16271. * };
  16272. * }];
  16273. * ```
  16274. *
  16275. * ## Impact on loading templates
  16276. *
  16277. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  16278. * `templateUrl`'s specified by {@link guide/directive directives}.
  16279. *
  16280. * By default, Angular only loads templates from the same domain and protocol as the application
  16281. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  16282. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  16283. * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  16284. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  16285. *
  16286. * *Please note*:
  16287. * The browser's
  16288. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  16289. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  16290. * policy apply in addition to this and may further restrict whether the template is successfully
  16291. * loaded. This means that without the right CORS policy, loading templates from a different domain
  16292. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  16293. * browsers.
  16294. *
  16295. * ## This feels like too much overhead
  16296. *
  16297. * It's important to remember that SCE only applies to interpolation expressions.
  16298. *
  16299. * If your expressions are constant literals, they're automatically trusted and you don't need to
  16300. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  16301. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  16302. *
  16303. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  16304. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  16305. *
  16306. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  16307. * templates in `ng-include` from your application's domain without having to even know about SCE.
  16308. * It blocks loading templates from other domains or loading templates over http from an https
  16309. * served document. You can change these by setting your own custom {@link
  16310. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  16311. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  16312. *
  16313. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  16314. * application that's secure and can be audited to verify that with much more ease than bolting
  16315. * security onto an application later.
  16316. *
  16317. * <a name="contexts"></a>
  16318. * ## What trusted context types are supported?
  16319. *
  16320. * | Context | Notes |
  16321. * |---------------------|----------------|
  16322. * | `$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. |
  16323. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  16324. * | `$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. |
  16325. * | `$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. |
  16326. * | `$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. |
  16327. *
  16328. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  16329. *
  16330. * Each element in these arrays must be one of the following:
  16331. *
  16332. * - **'self'**
  16333. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  16334. * domain** as the application document using the **same protocol**.
  16335. * - **String** (except the special value `'self'`)
  16336. * - The string is matched against the full *normalized / absolute URL* of the resource
  16337. * being tested (substring matches are not good enough.)
  16338. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  16339. * match themselves.
  16340. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  16341. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
  16342. * in a whitelist.
  16343. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  16344. * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
  16345. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  16346. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  16347. * http://foo.example.com/templates/**).
  16348. * - **RegExp** (*see caveat below*)
  16349. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  16350. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  16351. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  16352. * have good test coverage). For instance, the use of `.` in the regex is correct only in a
  16353. * small number of cases. A `.` character in the regex used when matching the scheme or a
  16354. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  16355. * is highly recommended to use the string patterns and only fall back to regular expressions
  16356. * as a last resort.
  16357. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  16358. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  16359. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  16360. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  16361. * - If you are generating your JavaScript from some other templating engine (not
  16362. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  16363. * remember to escape your regular expression (and be aware that you might need more than
  16364. * one level of escaping depending on your templating engine and the way you interpolated
  16365. * the value.) Do make use of your platform's escaping mechanism as it might be good
  16366. * enough before coding your own. E.g. Ruby has
  16367. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  16368. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  16369. * Javascript lacks a similar built in function for escaping. Take a look at Google
  16370. * Closure library's [goog.string.regExpEscape(s)](
  16371. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  16372. *
  16373. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  16374. *
  16375. * ## Show me an example using SCE.
  16376. *
  16377. * <example module="mySceApp" deps="angular-sanitize.js">
  16378. * <file name="index.html">
  16379. * <div ng-controller="AppController as myCtrl">
  16380. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  16381. * <b>User comments</b><br>
  16382. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  16383. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  16384. * exploit.
  16385. * <div class="well">
  16386. * <div ng-repeat="userComment in myCtrl.userComments">
  16387. * <b>{{userComment.name}}</b>:
  16388. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  16389. * <br>
  16390. * </div>
  16391. * </div>
  16392. * </div>
  16393. * </file>
  16394. *
  16395. * <file name="script.js">
  16396. * angular.module('mySceApp', ['ngSanitize'])
  16397. * .controller('AppController', ['$http', '$templateCache', '$sce',
  16398. * function($http, $templateCache, $sce) {
  16399. * var self = this;
  16400. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  16401. * self.userComments = userComments;
  16402. * });
  16403. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  16404. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  16405. * 'sanitization.&quot;">Hover over this text.</span>');
  16406. * }]);
  16407. * </file>
  16408. *
  16409. * <file name="test_data.json">
  16410. * [
  16411. * { "name": "Alice",
  16412. * "htmlComment":
  16413. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  16414. * },
  16415. * { "name": "Bob",
  16416. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  16417. * }
  16418. * ]
  16419. * </file>
  16420. *
  16421. * <file name="protractor.js" type="protractor">
  16422. * describe('SCE doc demo', function() {
  16423. * it('should sanitize untrusted values', function() {
  16424. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  16425. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  16426. * });
  16427. *
  16428. * it('should NOT sanitize explicitly trusted values', function() {
  16429. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  16430. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  16431. * 'sanitization.&quot;">Hover over this text.</span>');
  16432. * });
  16433. * });
  16434. * </file>
  16435. * </example>
  16436. *
  16437. *
  16438. *
  16439. * ## Can I disable SCE completely?
  16440. *
  16441. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  16442. * for little coding overhead. It will be much harder to take an SCE disabled application and
  16443. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  16444. * for cases where you have a lot of existing code that was written before SCE was introduced and
  16445. * you're migrating them a module at a time.
  16446. *
  16447. * That said, here's how you can completely disable SCE:
  16448. *
  16449. * ```
  16450. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  16451. * // Completely disable SCE. For demonstration purposes only!
  16452. * // Do not use in new projects.
  16453. * $sceProvider.enabled(false);
  16454. * });
  16455. * ```
  16456. *
  16457. */
  16458. /* jshint maxlen: 100 */
  16459. function $SceProvider() {
  16460. var enabled = true;
  16461. /**
  16462. * @ngdoc method
  16463. * @name $sceProvider#enabled
  16464. * @kind function
  16465. *
  16466. * @param {boolean=} value If provided, then enables/disables SCE.
  16467. * @return {boolean} true if SCE is enabled, false otherwise.
  16468. *
  16469. * @description
  16470. * Enables/disables SCE and returns the current value.
  16471. */
  16472. this.enabled = function(value) {
  16473. if (arguments.length) {
  16474. enabled = !!value;
  16475. }
  16476. return enabled;
  16477. };
  16478. /* Design notes on the default implementation for SCE.
  16479. *
  16480. * The API contract for the SCE delegate
  16481. * -------------------------------------
  16482. * The SCE delegate object must provide the following 3 methods:
  16483. *
  16484. * - trustAs(contextEnum, value)
  16485. * This method is used to tell the SCE service that the provided value is OK to use in the
  16486. * contexts specified by contextEnum. It must return an object that will be accepted by
  16487. * getTrusted() for a compatible contextEnum and return this value.
  16488. *
  16489. * - valueOf(value)
  16490. * For values that were not produced by trustAs(), return them as is. For values that were
  16491. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  16492. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  16493. * such a value.
  16494. *
  16495. * - getTrusted(contextEnum, value)
  16496. * This function should return the a value that is safe to use in the context specified by
  16497. * contextEnum or throw and exception otherwise.
  16498. *
  16499. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  16500. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  16501. * instance, an implementation could maintain a registry of all trusted objects by context. In
  16502. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  16503. * return the same object passed in if it was found in the registry under a compatible context or
  16504. * throw an exception otherwise. An implementation might only wrap values some of the time based
  16505. * on some criteria. getTrusted() might return a value and not throw an exception for special
  16506. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  16507. *
  16508. *
  16509. * A note on the inheritance model for SCE contexts
  16510. * ------------------------------------------------
  16511. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  16512. * is purely an implementation details.
  16513. *
  16514. * The contract is simply this:
  16515. *
  16516. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  16517. * will also succeed.
  16518. *
  16519. * Inheritance happens to capture this in a natural way. In some future, we
  16520. * may not use inheritance anymore. That is OK because no code outside of
  16521. * sce.js and sceSpecs.js would need to be aware of this detail.
  16522. */
  16523. this.$get = ['$parse', '$sceDelegate', function(
  16524. $parse, $sceDelegate) {
  16525. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  16526. // the "expression(javascript expression)" syntax which is insecure.
  16527. if (enabled && msie < 8) {
  16528. throw $sceMinErr('iequirks',
  16529. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  16530. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  16531. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  16532. }
  16533. var sce = shallowCopy(SCE_CONTEXTS);
  16534. /**
  16535. * @ngdoc method
  16536. * @name $sce#isEnabled
  16537. * @kind function
  16538. *
  16539. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  16540. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  16541. *
  16542. * @description
  16543. * Returns a boolean indicating if SCE is enabled.
  16544. */
  16545. sce.isEnabled = function() {
  16546. return enabled;
  16547. };
  16548. sce.trustAs = $sceDelegate.trustAs;
  16549. sce.getTrusted = $sceDelegate.getTrusted;
  16550. sce.valueOf = $sceDelegate.valueOf;
  16551. if (!enabled) {
  16552. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  16553. sce.valueOf = identity;
  16554. }
  16555. /**
  16556. * @ngdoc method
  16557. * @name $sce#parseAs
  16558. *
  16559. * @description
  16560. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  16561. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  16562. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  16563. * *result*)}
  16564. *
  16565. * @param {string} type The kind of SCE context in which this result will be used.
  16566. * @param {string} expression String expression to compile.
  16567. * @returns {function(context, locals)} a function which represents the compiled expression:
  16568. *
  16569. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  16570. * are evaluated against (typically a scope object).
  16571. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  16572. * `context`.
  16573. */
  16574. sce.parseAs = function sceParseAs(type, expr) {
  16575. var parsed = $parse(expr);
  16576. if (parsed.literal && parsed.constant) {
  16577. return parsed;
  16578. } else {
  16579. return $parse(expr, function(value) {
  16580. return sce.getTrusted(type, value);
  16581. });
  16582. }
  16583. };
  16584. /**
  16585. * @ngdoc method
  16586. * @name $sce#trustAs
  16587. *
  16588. * @description
  16589. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  16590. * returns an object that is trusted by angular for use in specified strict contextual
  16591. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  16592. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  16593. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  16594. * escaping.
  16595. *
  16596. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  16597. * resourceUrl, html, js and css.
  16598. * @param {*} value The value that that should be considered trusted/safe.
  16599. * @returns {*} A value that can be used to stand in for the provided `value` in places
  16600. * where Angular expects a $sce.trustAs() return value.
  16601. */
  16602. /**
  16603. * @ngdoc method
  16604. * @name $sce#trustAsHtml
  16605. *
  16606. * @description
  16607. * Shorthand method. `$sce.trustAsHtml(value)` →
  16608. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  16609. *
  16610. * @param {*} value The value to trustAs.
  16611. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  16612. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  16613. * only accept expressions that are either literal constants or are the
  16614. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  16615. */
  16616. /**
  16617. * @ngdoc method
  16618. * @name $sce#trustAsUrl
  16619. *
  16620. * @description
  16621. * Shorthand method. `$sce.trustAsUrl(value)` →
  16622. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  16623. *
  16624. * @param {*} value The value to trustAs.
  16625. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  16626. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  16627. * only accept expressions that are either literal constants or are the
  16628. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  16629. */
  16630. /**
  16631. * @ngdoc method
  16632. * @name $sce#trustAsResourceUrl
  16633. *
  16634. * @description
  16635. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  16636. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  16637. *
  16638. * @param {*} value The value to trustAs.
  16639. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  16640. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  16641. * only accept expressions that are either literal constants or are the return
  16642. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  16643. */
  16644. /**
  16645. * @ngdoc method
  16646. * @name $sce#trustAsJs
  16647. *
  16648. * @description
  16649. * Shorthand method. `$sce.trustAsJs(value)` →
  16650. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  16651. *
  16652. * @param {*} value The value to trustAs.
  16653. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  16654. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  16655. * only accept expressions that are either literal constants or are the
  16656. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  16657. */
  16658. /**
  16659. * @ngdoc method
  16660. * @name $sce#getTrusted
  16661. *
  16662. * @description
  16663. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  16664. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  16665. * originally supplied value if the queried context type is a supertype of the created type.
  16666. * If this condition isn't satisfied, throws an exception.
  16667. *
  16668. * @param {string} type The kind of context in which this value is to be used.
  16669. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  16670. * call.
  16671. * @returns {*} The value the was originally provided to
  16672. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  16673. * Otherwise, throws an exception.
  16674. */
  16675. /**
  16676. * @ngdoc method
  16677. * @name $sce#getTrustedHtml
  16678. *
  16679. * @description
  16680. * Shorthand method. `$sce.getTrustedHtml(value)` →
  16681. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  16682. *
  16683. * @param {*} value The value to pass to `$sce.getTrusted`.
  16684. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  16685. */
  16686. /**
  16687. * @ngdoc method
  16688. * @name $sce#getTrustedCss
  16689. *
  16690. * @description
  16691. * Shorthand method. `$sce.getTrustedCss(value)` →
  16692. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  16693. *
  16694. * @param {*} value The value to pass to `$sce.getTrusted`.
  16695. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  16696. */
  16697. /**
  16698. * @ngdoc method
  16699. * @name $sce#getTrustedUrl
  16700. *
  16701. * @description
  16702. * Shorthand method. `$sce.getTrustedUrl(value)` →
  16703. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  16704. *
  16705. * @param {*} value The value to pass to `$sce.getTrusted`.
  16706. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  16707. */
  16708. /**
  16709. * @ngdoc method
  16710. * @name $sce#getTrustedResourceUrl
  16711. *
  16712. * @description
  16713. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  16714. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  16715. *
  16716. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  16717. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  16718. */
  16719. /**
  16720. * @ngdoc method
  16721. * @name $sce#getTrustedJs
  16722. *
  16723. * @description
  16724. * Shorthand method. `$sce.getTrustedJs(value)` →
  16725. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  16726. *
  16727. * @param {*} value The value to pass to `$sce.getTrusted`.
  16728. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  16729. */
  16730. /**
  16731. * @ngdoc method
  16732. * @name $sce#parseAsHtml
  16733. *
  16734. * @description
  16735. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  16736. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  16737. *
  16738. * @param {string} expression String expression to compile.
  16739. * @returns {function(context, locals)} a function which represents the compiled expression:
  16740. *
  16741. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  16742. * are evaluated against (typically a scope object).
  16743. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  16744. * `context`.
  16745. */
  16746. /**
  16747. * @ngdoc method
  16748. * @name $sce#parseAsCss
  16749. *
  16750. * @description
  16751. * Shorthand method. `$sce.parseAsCss(value)` →
  16752. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  16753. *
  16754. * @param {string} expression String expression to compile.
  16755. * @returns {function(context, locals)} a function which represents the compiled expression:
  16756. *
  16757. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  16758. * are evaluated against (typically a scope object).
  16759. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  16760. * `context`.
  16761. */
  16762. /**
  16763. * @ngdoc method
  16764. * @name $sce#parseAsUrl
  16765. *
  16766. * @description
  16767. * Shorthand method. `$sce.parseAsUrl(value)` →
  16768. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  16769. *
  16770. * @param {string} expression String expression to compile.
  16771. * @returns {function(context, locals)} a function which represents the compiled expression:
  16772. *
  16773. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  16774. * are evaluated against (typically a scope object).
  16775. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  16776. * `context`.
  16777. */
  16778. /**
  16779. * @ngdoc method
  16780. * @name $sce#parseAsResourceUrl
  16781. *
  16782. * @description
  16783. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  16784. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  16785. *
  16786. * @param {string} expression String expression to compile.
  16787. * @returns {function(context, locals)} a function which represents the compiled expression:
  16788. *
  16789. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  16790. * are evaluated against (typically a scope object).
  16791. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  16792. * `context`.
  16793. */
  16794. /**
  16795. * @ngdoc method
  16796. * @name $sce#parseAsJs
  16797. *
  16798. * @description
  16799. * Shorthand method. `$sce.parseAsJs(value)` →
  16800. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  16801. *
  16802. * @param {string} expression String expression to compile.
  16803. * @returns {function(context, locals)} a function which represents the compiled expression:
  16804. *
  16805. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  16806. * are evaluated against (typically a scope object).
  16807. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  16808. * `context`.
  16809. */
  16810. // Shorthand delegations.
  16811. var parse = sce.parseAs,
  16812. getTrusted = sce.getTrusted,
  16813. trustAs = sce.trustAs;
  16814. forEach(SCE_CONTEXTS, function(enumValue, name) {
  16815. var lName = lowercase(name);
  16816. sce[camelCase("parse_as_" + lName)] = function(expr) {
  16817. return parse(enumValue, expr);
  16818. };
  16819. sce[camelCase("get_trusted_" + lName)] = function(value) {
  16820. return getTrusted(enumValue, value);
  16821. };
  16822. sce[camelCase("trust_as_" + lName)] = function(value) {
  16823. return trustAs(enumValue, value);
  16824. };
  16825. });
  16826. return sce;
  16827. }];
  16828. }
  16829. /**
  16830. * !!! This is an undocumented "private" service !!!
  16831. *
  16832. * @name $sniffer
  16833. * @requires $window
  16834. * @requires $document
  16835. *
  16836. * @property {boolean} history Does the browser support html5 history api ?
  16837. * @property {boolean} transitions Does the browser support CSS transition events ?
  16838. * @property {boolean} animations Does the browser support CSS animation events ?
  16839. *
  16840. * @description
  16841. * This is very simple implementation of testing browser's features.
  16842. */
  16843. function $SnifferProvider() {
  16844. this.$get = ['$window', '$document', function($window, $document) {
  16845. var eventSupport = {},
  16846. // Chrome Packaged Apps are not allowed to access `history.pushState`. They can be detected by
  16847. // the presence of `chrome.app.runtime` (see https://developer.chrome.com/apps/api_index)
  16848. isChromePackagedApp = $window.chrome && $window.chrome.app && $window.chrome.app.runtime,
  16849. hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState,
  16850. android =
  16851. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  16852. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  16853. document = $document[0] || {},
  16854. vendorPrefix,
  16855. vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
  16856. bodyStyle = document.body && document.body.style,
  16857. transitions = false,
  16858. animations = false,
  16859. match;
  16860. if (bodyStyle) {
  16861. for (var prop in bodyStyle) {
  16862. if (match = vendorRegex.exec(prop)) {
  16863. vendorPrefix = match[0];
  16864. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  16865. break;
  16866. }
  16867. }
  16868. if (!vendorPrefix) {
  16869. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  16870. }
  16871. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  16872. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  16873. if (android && (!transitions || !animations)) {
  16874. transitions = isString(bodyStyle.webkitTransition);
  16875. animations = isString(bodyStyle.webkitAnimation);
  16876. }
  16877. }
  16878. return {
  16879. // Android has history.pushState, but it does not update location correctly
  16880. // so let's not use the history API at all.
  16881. // http://code.google.com/p/android/issues/detail?id=17471
  16882. // https://github.com/angular/angular.js/issues/904
  16883. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  16884. // so let's not use the history API also
  16885. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  16886. // jshint -W018
  16887. history: !!(hasHistoryPushState && !(android < 4) && !boxee),
  16888. // jshint +W018
  16889. hasEvent: function(event) {
  16890. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  16891. // it. In particular the event is not fired when backspace or delete key are pressed or
  16892. // when cut operation is performed.
  16893. // IE10+ implements 'input' event but it erroneously fires under various situations,
  16894. // e.g. when placeholder changes, or a form is focused.
  16895. if (event === 'input' && msie <= 11) return false;
  16896. if (isUndefined(eventSupport[event])) {
  16897. var divElm = document.createElement('div');
  16898. eventSupport[event] = 'on' + event in divElm;
  16899. }
  16900. return eventSupport[event];
  16901. },
  16902. csp: csp(),
  16903. vendorPrefix: vendorPrefix,
  16904. transitions: transitions,
  16905. animations: animations,
  16906. android: android
  16907. };
  16908. }];
  16909. }
  16910. var $templateRequestMinErr = minErr('$compile');
  16911. /**
  16912. * @ngdoc provider
  16913. * @name $templateRequestProvider
  16914. * @description
  16915. * Used to configure the options passed to the {@link $http} service when making a template request.
  16916. *
  16917. * For example, it can be used for specifying the "Accept" header that is sent to the server, when
  16918. * requesting a template.
  16919. */
  16920. function $TemplateRequestProvider() {
  16921. var httpOptions;
  16922. /**
  16923. * @ngdoc method
  16924. * @name $templateRequestProvider#httpOptions
  16925. * @description
  16926. * The options to be passed to the {@link $http} service when making the request.
  16927. * You can use this to override options such as the "Accept" header for template requests.
  16928. *
  16929. * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
  16930. * options if not overridden here.
  16931. *
  16932. * @param {string=} value new value for the {@link $http} options.
  16933. * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.
  16934. */
  16935. this.httpOptions = function(val) {
  16936. if (val) {
  16937. httpOptions = val;
  16938. return this;
  16939. }
  16940. return httpOptions;
  16941. };
  16942. /**
  16943. * @ngdoc service
  16944. * @name $templateRequest
  16945. *
  16946. * @description
  16947. * The `$templateRequest` service runs security checks then downloads the provided template using
  16948. * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
  16949. * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
  16950. * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
  16951. * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
  16952. * when `tpl` is of type string and `$templateCache` has the matching entry.
  16953. *
  16954. * If you want to pass custom options to the `$http` service, such as setting the Accept header you
  16955. * can configure this via {@link $templateRequestProvider#httpOptions}.
  16956. *
  16957. * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
  16958. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  16959. *
  16960. * @return {Promise} a promise for the HTTP response data of the given URL.
  16961. *
  16962. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  16963. */
  16964. this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
  16965. function handleRequestFn(tpl, ignoreRequestError) {
  16966. handleRequestFn.totalPendingRequests++;
  16967. // We consider the template cache holds only trusted templates, so
  16968. // there's no need to go through whitelisting again for keys that already
  16969. // are included in there. This also makes Angular accept any script
  16970. // directive, no matter its name. However, we still need to unwrap trusted
  16971. // types.
  16972. if (!isString(tpl) || !$templateCache.get(tpl)) {
  16973. tpl = $sce.getTrustedResourceUrl(tpl);
  16974. }
  16975. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  16976. if (isArray(transformResponse)) {
  16977. transformResponse = transformResponse.filter(function(transformer) {
  16978. return transformer !== defaultHttpResponseTransform;
  16979. });
  16980. } else if (transformResponse === defaultHttpResponseTransform) {
  16981. transformResponse = null;
  16982. }
  16983. return $http.get(tpl, extend({
  16984. cache: $templateCache,
  16985. transformResponse: transformResponse
  16986. }, httpOptions))
  16987. ['finally'](function() {
  16988. handleRequestFn.totalPendingRequests--;
  16989. })
  16990. .then(function(response) {
  16991. $templateCache.put(tpl, response.data);
  16992. return response.data;
  16993. }, handleError);
  16994. function handleError(resp) {
  16995. if (!ignoreRequestError) {
  16996. throw $templateRequestMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
  16997. tpl, resp.status, resp.statusText);
  16998. }
  16999. return $q.reject(resp);
  17000. }
  17001. }
  17002. handleRequestFn.totalPendingRequests = 0;
  17003. return handleRequestFn;
  17004. }];
  17005. }
  17006. function $$TestabilityProvider() {
  17007. this.$get = ['$rootScope', '$browser', '$location',
  17008. function($rootScope, $browser, $location) {
  17009. /**
  17010. * @name $testability
  17011. *
  17012. * @description
  17013. * The private $$testability service provides a collection of methods for use when debugging
  17014. * or by automated test and debugging tools.
  17015. */
  17016. var testability = {};
  17017. /**
  17018. * @name $$testability#findBindings
  17019. *
  17020. * @description
  17021. * Returns an array of elements that are bound (via ng-bind or {{}})
  17022. * to expressions matching the input.
  17023. *
  17024. * @param {Element} element The element root to search from.
  17025. * @param {string} expression The binding expression to match.
  17026. * @param {boolean} opt_exactMatch If true, only returns exact matches
  17027. * for the expression. Filters and whitespace are ignored.
  17028. */
  17029. testability.findBindings = function(element, expression, opt_exactMatch) {
  17030. var bindings = element.getElementsByClassName('ng-binding');
  17031. var matches = [];
  17032. forEach(bindings, function(binding) {
  17033. var dataBinding = angular.element(binding).data('$binding');
  17034. if (dataBinding) {
  17035. forEach(dataBinding, function(bindingName) {
  17036. if (opt_exactMatch) {
  17037. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  17038. if (matcher.test(bindingName)) {
  17039. matches.push(binding);
  17040. }
  17041. } else {
  17042. if (bindingName.indexOf(expression) != -1) {
  17043. matches.push(binding);
  17044. }
  17045. }
  17046. });
  17047. }
  17048. });
  17049. return matches;
  17050. };
  17051. /**
  17052. * @name $$testability#findModels
  17053. *
  17054. * @description
  17055. * Returns an array of elements that are two-way found via ng-model to
  17056. * expressions matching the input.
  17057. *
  17058. * @param {Element} element The element root to search from.
  17059. * @param {string} expression The model expression to match.
  17060. * @param {boolean} opt_exactMatch If true, only returns exact matches
  17061. * for the expression.
  17062. */
  17063. testability.findModels = function(element, expression, opt_exactMatch) {
  17064. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  17065. for (var p = 0; p < prefixes.length; ++p) {
  17066. var attributeEquals = opt_exactMatch ? '=' : '*=';
  17067. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  17068. var elements = element.querySelectorAll(selector);
  17069. if (elements.length) {
  17070. return elements;
  17071. }
  17072. }
  17073. };
  17074. /**
  17075. * @name $$testability#getLocation
  17076. *
  17077. * @description
  17078. * Shortcut for getting the location in a browser agnostic way. Returns
  17079. * the path, search, and hash. (e.g. /path?a=b#hash)
  17080. */
  17081. testability.getLocation = function() {
  17082. return $location.url();
  17083. };
  17084. /**
  17085. * @name $$testability#setLocation
  17086. *
  17087. * @description
  17088. * Shortcut for navigating to a location without doing a full page reload.
  17089. *
  17090. * @param {string} url The location url (path, search and hash,
  17091. * e.g. /path?a=b#hash) to go to.
  17092. */
  17093. testability.setLocation = function(url) {
  17094. if (url !== $location.url()) {
  17095. $location.url(url);
  17096. $rootScope.$digest();
  17097. }
  17098. };
  17099. /**
  17100. * @name $$testability#whenStable
  17101. *
  17102. * @description
  17103. * Calls the callback when $timeout and $http requests are completed.
  17104. *
  17105. * @param {function} callback
  17106. */
  17107. testability.whenStable = function(callback) {
  17108. $browser.notifyWhenNoOutstandingRequests(callback);
  17109. };
  17110. return testability;
  17111. }];
  17112. }
  17113. function $TimeoutProvider() {
  17114. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  17115. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  17116. var deferreds = {};
  17117. /**
  17118. * @ngdoc service
  17119. * @name $timeout
  17120. *
  17121. * @description
  17122. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  17123. * block and delegates any exceptions to
  17124. * {@link ng.$exceptionHandler $exceptionHandler} service.
  17125. *
  17126. * The return value of calling `$timeout` is a promise, which will be resolved when
  17127. * the delay has passed and the timeout function, if provided, is executed.
  17128. *
  17129. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  17130. *
  17131. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  17132. * synchronously flush the queue of deferred functions.
  17133. *
  17134. * If you only want a promise that will be resolved after some specified delay
  17135. * then you can call `$timeout` without the `fn` function.
  17136. *
  17137. * @param {function()=} fn A function, whose execution should be delayed.
  17138. * @param {number=} [delay=0] Delay in milliseconds.
  17139. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  17140. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  17141. * @param {...*=} Pass additional parameters to the executed function.
  17142. * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise
  17143. * will be resolved with the return value of the `fn` function.
  17144. *
  17145. */
  17146. function timeout(fn, delay, invokeApply) {
  17147. if (!isFunction(fn)) {
  17148. invokeApply = delay;
  17149. delay = fn;
  17150. fn = noop;
  17151. }
  17152. var args = sliceArgs(arguments, 3),
  17153. skipApply = (isDefined(invokeApply) && !invokeApply),
  17154. deferred = (skipApply ? $$q : $q).defer(),
  17155. promise = deferred.promise,
  17156. timeoutId;
  17157. timeoutId = $browser.defer(function() {
  17158. try {
  17159. deferred.resolve(fn.apply(null, args));
  17160. } catch (e) {
  17161. deferred.reject(e);
  17162. $exceptionHandler(e);
  17163. }
  17164. finally {
  17165. delete deferreds[promise.$$timeoutId];
  17166. }
  17167. if (!skipApply) $rootScope.$apply();
  17168. }, delay);
  17169. promise.$$timeoutId = timeoutId;
  17170. deferreds[timeoutId] = deferred;
  17171. return promise;
  17172. }
  17173. /**
  17174. * @ngdoc method
  17175. * @name $timeout#cancel
  17176. *
  17177. * @description
  17178. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  17179. * resolved with a rejection.
  17180. *
  17181. * @param {Promise=} promise Promise returned by the `$timeout` function.
  17182. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  17183. * canceled.
  17184. */
  17185. timeout.cancel = function(promise) {
  17186. if (promise && promise.$$timeoutId in deferreds) {
  17187. deferreds[promise.$$timeoutId].reject('canceled');
  17188. delete deferreds[promise.$$timeoutId];
  17189. return $browser.defer.cancel(promise.$$timeoutId);
  17190. }
  17191. return false;
  17192. };
  17193. return timeout;
  17194. }];
  17195. }
  17196. // NOTE: The usage of window and document instead of $window and $document here is
  17197. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  17198. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  17199. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  17200. // doesn't know about mocked locations and resolves URLs to the real document - which is
  17201. // exactly the behavior needed here. There is little value is mocking these out for this
  17202. // service.
  17203. var urlParsingNode = document.createElement("a");
  17204. var originUrl = urlResolve(window.location.href);
  17205. /**
  17206. *
  17207. * Implementation Notes for non-IE browsers
  17208. * ----------------------------------------
  17209. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  17210. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  17211. * URL will be resolved into an absolute URL in the context of the application document.
  17212. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  17213. * properties are all populated to reflect the normalized URL. This approach has wide
  17214. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  17215. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  17216. *
  17217. * Implementation Notes for IE
  17218. * ---------------------------
  17219. * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
  17220. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  17221. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  17222. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  17223. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  17224. * properties such as protocol, hostname, port, etc.
  17225. *
  17226. * References:
  17227. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  17228. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  17229. * http://url.spec.whatwg.org/#urlutils
  17230. * https://github.com/angular/angular.js/pull/2902
  17231. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  17232. *
  17233. * @kind function
  17234. * @param {string} url The URL to be parsed.
  17235. * @description Normalizes and parses a URL.
  17236. * @returns {object} Returns the normalized URL as a dictionary.
  17237. *
  17238. * | member name | Description |
  17239. * |---------------|----------------|
  17240. * | href | A normalized version of the provided URL if it was not an absolute URL |
  17241. * | protocol | The protocol including the trailing colon |
  17242. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  17243. * | search | The search params, minus the question mark |
  17244. * | hash | The hash string, minus the hash symbol
  17245. * | hostname | The hostname
  17246. * | port | The port, without ":"
  17247. * | pathname | The pathname, beginning with "/"
  17248. *
  17249. */
  17250. function urlResolve(url) {
  17251. var href = url;
  17252. if (msie) {
  17253. // Normalize before parse. Refer Implementation Notes on why this is
  17254. // done in two steps on IE.
  17255. urlParsingNode.setAttribute("href", href);
  17256. href = urlParsingNode.href;
  17257. }
  17258. urlParsingNode.setAttribute('href', href);
  17259. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  17260. return {
  17261. href: urlParsingNode.href,
  17262. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  17263. host: urlParsingNode.host,
  17264. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  17265. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  17266. hostname: urlParsingNode.hostname,
  17267. port: urlParsingNode.port,
  17268. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  17269. ? urlParsingNode.pathname
  17270. : '/' + urlParsingNode.pathname
  17271. };
  17272. }
  17273. /**
  17274. * Parse a request URL and determine whether this is a same-origin request as the application document.
  17275. *
  17276. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  17277. * or a parsed URL object.
  17278. * @returns {boolean} Whether the request is for the same origin as the application document.
  17279. */
  17280. function urlIsSameOrigin(requestUrl) {
  17281. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  17282. return (parsed.protocol === originUrl.protocol &&
  17283. parsed.host === originUrl.host);
  17284. }
  17285. /**
  17286. * @ngdoc service
  17287. * @name $window
  17288. *
  17289. * @description
  17290. * A reference to the browser's `window` object. While `window`
  17291. * is globally available in JavaScript, it causes testability problems, because
  17292. * it is a global variable. In angular we always refer to it through the
  17293. * `$window` service, so it may be overridden, removed or mocked for testing.
  17294. *
  17295. * Expressions, like the one defined for the `ngClick` directive in the example
  17296. * below, are evaluated with respect to the current scope. Therefore, there is
  17297. * no risk of inadvertently coding in a dependency on a global value in such an
  17298. * expression.
  17299. *
  17300. * @example
  17301. <example module="windowExample">
  17302. <file name="index.html">
  17303. <script>
  17304. angular.module('windowExample', [])
  17305. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  17306. $scope.greeting = 'Hello, World!';
  17307. $scope.doGreeting = function(greeting) {
  17308. $window.alert(greeting);
  17309. };
  17310. }]);
  17311. </script>
  17312. <div ng-controller="ExampleController">
  17313. <input type="text" ng-model="greeting" aria-label="greeting" />
  17314. <button ng-click="doGreeting(greeting)">ALERT</button>
  17315. </div>
  17316. </file>
  17317. <file name="protractor.js" type="protractor">
  17318. it('should display the greeting in the input box', function() {
  17319. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  17320. // If we click the button it will block the test runner
  17321. // element(':button').click();
  17322. });
  17323. </file>
  17324. </example>
  17325. */
  17326. function $WindowProvider() {
  17327. this.$get = valueFn(window);
  17328. }
  17329. /**
  17330. * @name $$cookieReader
  17331. * @requires $document
  17332. *
  17333. * @description
  17334. * This is a private service for reading cookies used by $http and ngCookies
  17335. *
  17336. * @return {Object} a key/value map of the current cookies
  17337. */
  17338. function $$CookieReader($document) {
  17339. var rawDocument = $document[0] || {};
  17340. var lastCookies = {};
  17341. var lastCookieString = '';
  17342. function safeDecodeURIComponent(str) {
  17343. try {
  17344. return decodeURIComponent(str);
  17345. } catch (e) {
  17346. return str;
  17347. }
  17348. }
  17349. return function() {
  17350. var cookieArray, cookie, i, index, name;
  17351. var currentCookieString = rawDocument.cookie || '';
  17352. if (currentCookieString !== lastCookieString) {
  17353. lastCookieString = currentCookieString;
  17354. cookieArray = lastCookieString.split('; ');
  17355. lastCookies = {};
  17356. for (i = 0; i < cookieArray.length; i++) {
  17357. cookie = cookieArray[i];
  17358. index = cookie.indexOf('=');
  17359. if (index > 0) { //ignore nameless cookies
  17360. name = safeDecodeURIComponent(cookie.substring(0, index));
  17361. // the first value that is seen for a cookie is the most
  17362. // specific one. values for the same cookie name that
  17363. // follow are for less specific paths.
  17364. if (isUndefined(lastCookies[name])) {
  17365. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  17366. }
  17367. }
  17368. }
  17369. }
  17370. return lastCookies;
  17371. };
  17372. }
  17373. $$CookieReader.$inject = ['$document'];
  17374. function $$CookieReaderProvider() {
  17375. this.$get = $$CookieReader;
  17376. }
  17377. /* global currencyFilter: true,
  17378. dateFilter: true,
  17379. filterFilter: true,
  17380. jsonFilter: true,
  17381. limitToFilter: true,
  17382. lowercaseFilter: true,
  17383. numberFilter: true,
  17384. orderByFilter: true,
  17385. uppercaseFilter: true,
  17386. */
  17387. /**
  17388. * @ngdoc provider
  17389. * @name $filterProvider
  17390. * @description
  17391. *
  17392. * Filters are just functions which transform input to an output. However filters need to be
  17393. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  17394. * annotated with dependencies and is responsible for creating a filter function.
  17395. *
  17396. * <div class="alert alert-warning">
  17397. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  17398. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  17399. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  17400. * (`myapp_subsection_filterx`).
  17401. * </div>
  17402. *
  17403. * ```js
  17404. * // Filter registration
  17405. * function MyModule($provide, $filterProvider) {
  17406. * // create a service to demonstrate injection (not always needed)
  17407. * $provide.value('greet', function(name){
  17408. * return 'Hello ' + name + '!';
  17409. * });
  17410. *
  17411. * // register a filter factory which uses the
  17412. * // greet service to demonstrate DI.
  17413. * $filterProvider.register('greet', function(greet){
  17414. * // return the filter function which uses the greet service
  17415. * // to generate salutation
  17416. * return function(text) {
  17417. * // filters need to be forgiving so check input validity
  17418. * return text && greet(text) || text;
  17419. * };
  17420. * });
  17421. * }
  17422. * ```
  17423. *
  17424. * The filter function is registered with the `$injector` under the filter name suffix with
  17425. * `Filter`.
  17426. *
  17427. * ```js
  17428. * it('should be the same instance', inject(
  17429. * function($filterProvider) {
  17430. * $filterProvider.register('reverse', function(){
  17431. * return ...;
  17432. * });
  17433. * },
  17434. * function($filter, reverseFilter) {
  17435. * expect($filter('reverse')).toBe(reverseFilter);
  17436. * });
  17437. * ```
  17438. *
  17439. *
  17440. * For more information about how angular filters work, and how to create your own filters, see
  17441. * {@link guide/filter Filters} in the Angular Developer Guide.
  17442. */
  17443. /**
  17444. * @ngdoc service
  17445. * @name $filter
  17446. * @kind function
  17447. * @description
  17448. * Filters are used for formatting data displayed to the user.
  17449. *
  17450. * The general syntax in templates is as follows:
  17451. *
  17452. * {{ expression [| filter_name[:parameter_value] ... ] }}
  17453. *
  17454. * @param {String} name Name of the filter function to retrieve
  17455. * @return {Function} the filter function
  17456. * @example
  17457. <example name="$filter" module="filterExample">
  17458. <file name="index.html">
  17459. <div ng-controller="MainCtrl">
  17460. <h3>{{ originalText }}</h3>
  17461. <h3>{{ filteredText }}</h3>
  17462. </div>
  17463. </file>
  17464. <file name="script.js">
  17465. angular.module('filterExample', [])
  17466. .controller('MainCtrl', function($scope, $filter) {
  17467. $scope.originalText = 'hello';
  17468. $scope.filteredText = $filter('uppercase')($scope.originalText);
  17469. });
  17470. </file>
  17471. </example>
  17472. */
  17473. $FilterProvider.$inject = ['$provide'];
  17474. function $FilterProvider($provide) {
  17475. var suffix = 'Filter';
  17476. /**
  17477. * @ngdoc method
  17478. * @name $filterProvider#register
  17479. * @param {string|Object} name Name of the filter function, or an object map of filters where
  17480. * the keys are the filter names and the values are the filter factories.
  17481. *
  17482. * <div class="alert alert-warning">
  17483. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  17484. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  17485. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  17486. * (`myapp_subsection_filterx`).
  17487. * </div>
  17488. * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
  17489. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  17490. * of the registered filter instances.
  17491. */
  17492. function register(name, factory) {
  17493. if (isObject(name)) {
  17494. var filters = {};
  17495. forEach(name, function(filter, key) {
  17496. filters[key] = register(key, filter);
  17497. });
  17498. return filters;
  17499. } else {
  17500. return $provide.factory(name + suffix, factory);
  17501. }
  17502. }
  17503. this.register = register;
  17504. this.$get = ['$injector', function($injector) {
  17505. return function(name) {
  17506. return $injector.get(name + suffix);
  17507. };
  17508. }];
  17509. ////////////////////////////////////////
  17510. /* global
  17511. currencyFilter: false,
  17512. dateFilter: false,
  17513. filterFilter: false,
  17514. jsonFilter: false,
  17515. limitToFilter: false,
  17516. lowercaseFilter: false,
  17517. numberFilter: false,
  17518. orderByFilter: false,
  17519. uppercaseFilter: false,
  17520. */
  17521. register('currency', currencyFilter);
  17522. register('date', dateFilter);
  17523. register('filter', filterFilter);
  17524. register('json', jsonFilter);
  17525. register('limitTo', limitToFilter);
  17526. register('lowercase', lowercaseFilter);
  17527. register('number', numberFilter);
  17528. register('orderBy', orderByFilter);
  17529. register('uppercase', uppercaseFilter);
  17530. }
  17531. /**
  17532. * @ngdoc filter
  17533. * @name filter
  17534. * @kind function
  17535. *
  17536. * @description
  17537. * Selects a subset of items from `array` and returns it as a new array.
  17538. *
  17539. * @param {Array} array The source array.
  17540. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  17541. * `array`.
  17542. *
  17543. * Can be one of:
  17544. *
  17545. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  17546. * objects with string properties in `array` that match this string will be returned. This also
  17547. * applies to nested object properties.
  17548. * The predicate can be negated by prefixing the string with `!`.
  17549. *
  17550. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  17551. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  17552. * which have property `name` containing "M" and property `phone` containing "1". A special
  17553. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  17554. * property of the object or its nested object properties. That's equivalent to the simple
  17555. * substring match with a `string` as described above. The predicate can be negated by prefixing
  17556. * the string with `!`.
  17557. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  17558. * not containing "M".
  17559. *
  17560. * Note that a named property will match properties on the same level only, while the special
  17561. * `$` property will match properties on the same level or deeper. E.g. an array item like
  17562. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  17563. * **will** be matched by `{$: 'John'}`.
  17564. *
  17565. * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
  17566. * The function is called for each element of the array, with the element, its index, and
  17567. * the entire array itself as arguments.
  17568. *
  17569. * The final result is an array of those elements that the predicate returned true for.
  17570. *
  17571. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  17572. * determining if the expected value (from the filter expression) and actual value (from
  17573. * the object in the array) should be considered a match.
  17574. *
  17575. * Can be one of:
  17576. *
  17577. * - `function(actual, expected)`:
  17578. * The function will be given the object value and the predicate value to compare and
  17579. * should return true if both values should be considered equal.
  17580. *
  17581. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  17582. * This is essentially strict comparison of expected and actual.
  17583. *
  17584. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  17585. * insensitive way.
  17586. *
  17587. * Primitive values are converted to strings. Objects are not compared against primitives,
  17588. * unless they have a custom `toString` method (e.g. `Date` objects).
  17589. *
  17590. * @example
  17591. <example>
  17592. <file name="index.html">
  17593. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  17594. {name:'Mary', phone:'800-BIG-MARY'},
  17595. {name:'Mike', phone:'555-4321'},
  17596. {name:'Adam', phone:'555-5678'},
  17597. {name:'Julie', phone:'555-8765'},
  17598. {name:'Juliette', phone:'555-5678'}]"></div>
  17599. <label>Search: <input ng-model="searchText"></label>
  17600. <table id="searchTextResults">
  17601. <tr><th>Name</th><th>Phone</th></tr>
  17602. <tr ng-repeat="friend in friends | filter:searchText">
  17603. <td>{{friend.name}}</td>
  17604. <td>{{friend.phone}}</td>
  17605. </tr>
  17606. </table>
  17607. <hr>
  17608. <label>Any: <input ng-model="search.$"></label> <br>
  17609. <label>Name only <input ng-model="search.name"></label><br>
  17610. <label>Phone only <input ng-model="search.phone"></label><br>
  17611. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  17612. <table id="searchObjResults">
  17613. <tr><th>Name</th><th>Phone</th></tr>
  17614. <tr ng-repeat="friendObj in friends | filter:search:strict">
  17615. <td>{{friendObj.name}}</td>
  17616. <td>{{friendObj.phone}}</td>
  17617. </tr>
  17618. </table>
  17619. </file>
  17620. <file name="protractor.js" type="protractor">
  17621. var expectFriendNames = function(expectedNames, key) {
  17622. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  17623. arr.forEach(function(wd, i) {
  17624. expect(wd.getText()).toMatch(expectedNames[i]);
  17625. });
  17626. });
  17627. };
  17628. it('should search across all fields when filtering with a string', function() {
  17629. var searchText = element(by.model('searchText'));
  17630. searchText.clear();
  17631. searchText.sendKeys('m');
  17632. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  17633. searchText.clear();
  17634. searchText.sendKeys('76');
  17635. expectFriendNames(['John', 'Julie'], 'friend');
  17636. });
  17637. it('should search in specific fields when filtering with a predicate object', function() {
  17638. var searchAny = element(by.model('search.$'));
  17639. searchAny.clear();
  17640. searchAny.sendKeys('i');
  17641. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  17642. });
  17643. it('should use a equal comparison when comparator is true', function() {
  17644. var searchName = element(by.model('search.name'));
  17645. var strict = element(by.model('strict'));
  17646. searchName.clear();
  17647. searchName.sendKeys('Julie');
  17648. strict.click();
  17649. expectFriendNames(['Julie'], 'friendObj');
  17650. });
  17651. </file>
  17652. </example>
  17653. */
  17654. function filterFilter() {
  17655. return function(array, expression, comparator) {
  17656. if (!isArrayLike(array)) {
  17657. if (array == null) {
  17658. return array;
  17659. } else {
  17660. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  17661. }
  17662. }
  17663. var expressionType = getTypeForFilter(expression);
  17664. var predicateFn;
  17665. var matchAgainstAnyProp;
  17666. switch (expressionType) {
  17667. case 'function':
  17668. predicateFn = expression;
  17669. break;
  17670. case 'boolean':
  17671. case 'null':
  17672. case 'number':
  17673. case 'string':
  17674. matchAgainstAnyProp = true;
  17675. //jshint -W086
  17676. case 'object':
  17677. //jshint +W086
  17678. predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
  17679. break;
  17680. default:
  17681. return array;
  17682. }
  17683. return Array.prototype.filter.call(array, predicateFn);
  17684. };
  17685. }
  17686. // Helper functions for `filterFilter`
  17687. function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
  17688. var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
  17689. var predicateFn;
  17690. if (comparator === true) {
  17691. comparator = equals;
  17692. } else if (!isFunction(comparator)) {
  17693. comparator = function(actual, expected) {
  17694. if (isUndefined(actual)) {
  17695. // No substring matching against `undefined`
  17696. return false;
  17697. }
  17698. if ((actual === null) || (expected === null)) {
  17699. // No substring matching against `null`; only match against `null`
  17700. return actual === expected;
  17701. }
  17702. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  17703. // Should not compare primitives against objects, unless they have custom `toString` method
  17704. return false;
  17705. }
  17706. actual = lowercase('' + actual);
  17707. expected = lowercase('' + expected);
  17708. return actual.indexOf(expected) !== -1;
  17709. };
  17710. }
  17711. predicateFn = function(item) {
  17712. if (shouldMatchPrimitives && !isObject(item)) {
  17713. return deepCompare(item, expression.$, comparator, false);
  17714. }
  17715. return deepCompare(item, expression, comparator, matchAgainstAnyProp);
  17716. };
  17717. return predicateFn;
  17718. }
  17719. function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
  17720. var actualType = getTypeForFilter(actual);
  17721. var expectedType = getTypeForFilter(expected);
  17722. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  17723. return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
  17724. } else if (isArray(actual)) {
  17725. // In case `actual` is an array, consider it a match
  17726. // if ANY of it's items matches `expected`
  17727. return actual.some(function(item) {
  17728. return deepCompare(item, expected, comparator, matchAgainstAnyProp);
  17729. });
  17730. }
  17731. switch (actualType) {
  17732. case 'object':
  17733. var key;
  17734. if (matchAgainstAnyProp) {
  17735. for (key in actual) {
  17736. if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
  17737. return true;
  17738. }
  17739. }
  17740. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
  17741. } else if (expectedType === 'object') {
  17742. for (key in expected) {
  17743. var expectedVal = expected[key];
  17744. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  17745. continue;
  17746. }
  17747. var matchAnyProperty = key === '$';
  17748. var actualVal = matchAnyProperty ? actual : actual[key];
  17749. if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
  17750. return false;
  17751. }
  17752. }
  17753. return true;
  17754. } else {
  17755. return comparator(actual, expected);
  17756. }
  17757. break;
  17758. case 'function':
  17759. return false;
  17760. default:
  17761. return comparator(actual, expected);
  17762. }
  17763. }
  17764. // Used for easily differentiating between `null` and actual `object`
  17765. function getTypeForFilter(val) {
  17766. return (val === null) ? 'null' : typeof val;
  17767. }
  17768. var MAX_DIGITS = 22;
  17769. var DECIMAL_SEP = '.';
  17770. var ZERO_CHAR = '0';
  17771. /**
  17772. * @ngdoc filter
  17773. * @name currency
  17774. * @kind function
  17775. *
  17776. * @description
  17777. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  17778. * symbol for current locale is used.
  17779. *
  17780. * @param {number} amount Input to filter.
  17781. * @param {string=} symbol Currency symbol or identifier to be displayed.
  17782. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  17783. * @returns {string} Formatted number.
  17784. *
  17785. *
  17786. * @example
  17787. <example module="currencyExample">
  17788. <file name="index.html">
  17789. <script>
  17790. angular.module('currencyExample', [])
  17791. .controller('ExampleController', ['$scope', function($scope) {
  17792. $scope.amount = 1234.56;
  17793. }]);
  17794. </script>
  17795. <div ng-controller="ExampleController">
  17796. <input type="number" ng-model="amount" aria-label="amount"> <br>
  17797. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  17798. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
  17799. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  17800. </div>
  17801. </file>
  17802. <file name="protractor.js" type="protractor">
  17803. it('should init with 1234.56', function() {
  17804. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  17805. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  17806. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  17807. });
  17808. it('should update', function() {
  17809. if (browser.params.browser == 'safari') {
  17810. // Safari does not understand the minus key. See
  17811. // https://github.com/angular/protractor/issues/481
  17812. return;
  17813. }
  17814. element(by.model('amount')).clear();
  17815. element(by.model('amount')).sendKeys('-1234');
  17816. expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
  17817. expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
  17818. expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
  17819. });
  17820. </file>
  17821. </example>
  17822. */
  17823. currencyFilter.$inject = ['$locale'];
  17824. function currencyFilter($locale) {
  17825. var formats = $locale.NUMBER_FORMATS;
  17826. return function(amount, currencySymbol, fractionSize) {
  17827. if (isUndefined(currencySymbol)) {
  17828. currencySymbol = formats.CURRENCY_SYM;
  17829. }
  17830. if (isUndefined(fractionSize)) {
  17831. fractionSize = formats.PATTERNS[1].maxFrac;
  17832. }
  17833. // if null or undefined pass it through
  17834. return (amount == null)
  17835. ? amount
  17836. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  17837. replace(/\u00A4/g, currencySymbol);
  17838. };
  17839. }
  17840. /**
  17841. * @ngdoc filter
  17842. * @name number
  17843. * @kind function
  17844. *
  17845. * @description
  17846. * Formats a number as text.
  17847. *
  17848. * If the input is null or undefined, it will just be returned.
  17849. * If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively.
  17850. * If the input is not a number an empty string is returned.
  17851. *
  17852. *
  17853. * @param {number|string} number Number to format.
  17854. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  17855. * If this is not provided then the fraction size is computed from the current locale's number
  17856. * formatting pattern. In the case of the default locale, it will be 3.
  17857. * @returns {string} Number rounded to fractionSize and places a “,” after each third digit.
  17858. *
  17859. * @example
  17860. <example module="numberFilterExample">
  17861. <file name="index.html">
  17862. <script>
  17863. angular.module('numberFilterExample', [])
  17864. .controller('ExampleController', ['$scope', function($scope) {
  17865. $scope.val = 1234.56789;
  17866. }]);
  17867. </script>
  17868. <div ng-controller="ExampleController">
  17869. <label>Enter number: <input ng-model='val'></label><br>
  17870. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  17871. No fractions: <span>{{val | number:0}}</span><br>
  17872. Negative number: <span>{{-val | number:4}}</span>
  17873. </div>
  17874. </file>
  17875. <file name="protractor.js" type="protractor">
  17876. it('should format numbers', function() {
  17877. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  17878. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  17879. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  17880. });
  17881. it('should update', function() {
  17882. element(by.model('val')).clear();
  17883. element(by.model('val')).sendKeys('3374.333');
  17884. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  17885. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  17886. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  17887. });
  17888. </file>
  17889. </example>
  17890. */
  17891. numberFilter.$inject = ['$locale'];
  17892. function numberFilter($locale) {
  17893. var formats = $locale.NUMBER_FORMATS;
  17894. return function(number, fractionSize) {
  17895. // if null or undefined pass it through
  17896. return (number == null)
  17897. ? number
  17898. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  17899. fractionSize);
  17900. };
  17901. }
  17902. /**
  17903. * Parse a number (as a string) into three components that can be used
  17904. * for formatting the number.
  17905. *
  17906. * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)
  17907. *
  17908. * @param {string} numStr The number to parse
  17909. * @return {object} An object describing this number, containing the following keys:
  17910. * - d : an array of digits containing leading zeros as necessary
  17911. * - i : the number of the digits in `d` that are to the left of the decimal point
  17912. * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`
  17913. *
  17914. */
  17915. function parse(numStr) {
  17916. var exponent = 0, digits, numberOfIntegerDigits;
  17917. var i, j, zeros;
  17918. // Decimal point?
  17919. if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {
  17920. numStr = numStr.replace(DECIMAL_SEP, '');
  17921. }
  17922. // Exponential form?
  17923. if ((i = numStr.search(/e/i)) > 0) {
  17924. // Work out the exponent.
  17925. if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i;
  17926. numberOfIntegerDigits += +numStr.slice(i + 1);
  17927. numStr = numStr.substring(0, i);
  17928. } else if (numberOfIntegerDigits < 0) {
  17929. // There was no decimal point or exponent so it is an integer.
  17930. numberOfIntegerDigits = numStr.length;
  17931. }
  17932. // Count the number of leading zeros.
  17933. for (i = 0; numStr.charAt(i) == ZERO_CHAR; i++) {/* jshint noempty: false */}
  17934. if (i == (zeros = numStr.length)) {
  17935. // The digits are all zero.
  17936. digits = [0];
  17937. numberOfIntegerDigits = 1;
  17938. } else {
  17939. // Count the number of trailing zeros
  17940. zeros--;
  17941. while (numStr.charAt(zeros) == ZERO_CHAR) zeros--;
  17942. // Trailing zeros are insignificant so ignore them
  17943. numberOfIntegerDigits -= i;
  17944. digits = [];
  17945. // Convert string to array of digits without leading/trailing zeros.
  17946. for (j = 0; i <= zeros; i++, j++) {
  17947. digits[j] = +numStr.charAt(i);
  17948. }
  17949. }
  17950. // If the number overflows the maximum allowed digits then use an exponent.
  17951. if (numberOfIntegerDigits > MAX_DIGITS) {
  17952. digits = digits.splice(0, MAX_DIGITS - 1);
  17953. exponent = numberOfIntegerDigits - 1;
  17954. numberOfIntegerDigits = 1;
  17955. }
  17956. return { d: digits, e: exponent, i: numberOfIntegerDigits };
  17957. }
  17958. /**
  17959. * Round the parsed number to the specified number of decimal places
  17960. * This function changed the parsedNumber in-place
  17961. */
  17962. function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
  17963. var digits = parsedNumber.d;
  17964. var fractionLen = digits.length - parsedNumber.i;
  17965. // determine fractionSize if it is not specified; `+fractionSize` converts it to a number
  17966. fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
  17967. // The index of the digit to where rounding is to occur
  17968. var roundAt = fractionSize + parsedNumber.i;
  17969. var digit = digits[roundAt];
  17970. if (roundAt > 0) {
  17971. // Drop fractional digits beyond `roundAt`
  17972. digits.splice(Math.max(parsedNumber.i, roundAt));
  17973. // Set non-fractional digits beyond `roundAt` to 0
  17974. for (var j = roundAt; j < digits.length; j++) {
  17975. digits[j] = 0;
  17976. }
  17977. } else {
  17978. // We rounded to zero so reset the parsedNumber
  17979. fractionLen = Math.max(0, fractionLen);
  17980. parsedNumber.i = 1;
  17981. digits.length = Math.max(1, roundAt = fractionSize + 1);
  17982. digits[0] = 0;
  17983. for (var i = 1; i < roundAt; i++) digits[i] = 0;
  17984. }
  17985. if (digit >= 5) {
  17986. if (roundAt - 1 < 0) {
  17987. for (var k = 0; k > roundAt; k--) {
  17988. digits.unshift(0);
  17989. parsedNumber.i++;
  17990. }
  17991. digits.unshift(1);
  17992. parsedNumber.i++;
  17993. } else {
  17994. digits[roundAt - 1]++;
  17995. }
  17996. }
  17997. // Pad out with zeros to get the required fraction length
  17998. for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);
  17999. // Do any carrying, e.g. a digit was rounded up to 10
  18000. var carry = digits.reduceRight(function(carry, d, i, digits) {
  18001. d = d + carry;
  18002. digits[i] = d % 10;
  18003. return Math.floor(d / 10);
  18004. }, 0);
  18005. if (carry) {
  18006. digits.unshift(carry);
  18007. parsedNumber.i++;
  18008. }
  18009. }
  18010. /**
  18011. * Format a number into a string
  18012. * @param {number} number The number to format
  18013. * @param {{
  18014. * minFrac, // the minimum number of digits required in the fraction part of the number
  18015. * maxFrac, // the maximum number of digits required in the fraction part of the number
  18016. * gSize, // number of digits in each group of separated digits
  18017. * lgSize, // number of digits in the last group of digits before the decimal separator
  18018. * negPre, // the string to go in front of a negative number (e.g. `-` or `(`))
  18019. * posPre, // the string to go in front of a positive number
  18020. * negSuf, // the string to go after a negative number (e.g. `)`)
  18021. * posSuf // the string to go after a positive number
  18022. * }} pattern
  18023. * @param {string} groupSep The string to separate groups of number (e.g. `,`)
  18024. * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`)
  18025. * @param {[type]} fractionSize The size of the fractional part of the number
  18026. * @return {string} The number formatted as a string
  18027. */
  18028. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  18029. if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';
  18030. var isInfinity = !isFinite(number);
  18031. var isZero = false;
  18032. var numStr = Math.abs(number) + '',
  18033. formattedText = '',
  18034. parsedNumber;
  18035. if (isInfinity) {
  18036. formattedText = '\u221e';
  18037. } else {
  18038. parsedNumber = parse(numStr);
  18039. roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);
  18040. var digits = parsedNumber.d;
  18041. var integerLen = parsedNumber.i;
  18042. var exponent = parsedNumber.e;
  18043. var decimals = [];
  18044. isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);
  18045. // pad zeros for small numbers
  18046. while (integerLen < 0) {
  18047. digits.unshift(0);
  18048. integerLen++;
  18049. }
  18050. // extract decimals digits
  18051. if (integerLen > 0) {
  18052. decimals = digits.splice(integerLen);
  18053. } else {
  18054. decimals = digits;
  18055. digits = [0];
  18056. }
  18057. // format the integer digits with grouping separators
  18058. var groups = [];
  18059. if (digits.length >= pattern.lgSize) {
  18060. groups.unshift(digits.splice(-pattern.lgSize).join(''));
  18061. }
  18062. while (digits.length > pattern.gSize) {
  18063. groups.unshift(digits.splice(-pattern.gSize).join(''));
  18064. }
  18065. if (digits.length) {
  18066. groups.unshift(digits.join(''));
  18067. }
  18068. formattedText = groups.join(groupSep);
  18069. // append the decimal digits
  18070. if (decimals.length) {
  18071. formattedText += decimalSep + decimals.join('');
  18072. }
  18073. if (exponent) {
  18074. formattedText += 'e+' + exponent;
  18075. }
  18076. }
  18077. if (number < 0 && !isZero) {
  18078. return pattern.negPre + formattedText + pattern.negSuf;
  18079. } else {
  18080. return pattern.posPre + formattedText + pattern.posSuf;
  18081. }
  18082. }
  18083. function padNumber(num, digits, trim, negWrap) {
  18084. var neg = '';
  18085. if (num < 0 || (negWrap && num <= 0)) {
  18086. if (negWrap) {
  18087. num = -num + 1;
  18088. } else {
  18089. num = -num;
  18090. neg = '-';
  18091. }
  18092. }
  18093. num = '' + num;
  18094. while (num.length < digits) num = ZERO_CHAR + num;
  18095. if (trim) {
  18096. num = num.substr(num.length - digits);
  18097. }
  18098. return neg + num;
  18099. }
  18100. function dateGetter(name, size, offset, trim, negWrap) {
  18101. offset = offset || 0;
  18102. return function(date) {
  18103. var value = date['get' + name]();
  18104. if (offset > 0 || value > -offset) {
  18105. value += offset;
  18106. }
  18107. if (value === 0 && offset == -12) value = 12;
  18108. return padNumber(value, size, trim, negWrap);
  18109. };
  18110. }
  18111. function dateStrGetter(name, shortForm, standAlone) {
  18112. return function(date, formats) {
  18113. var value = date['get' + name]();
  18114. var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : '');
  18115. var get = uppercase(propPrefix + name);
  18116. return formats[get][value];
  18117. };
  18118. }
  18119. function timeZoneGetter(date, formats, offset) {
  18120. var zone = -1 * offset;
  18121. var paddedZone = (zone >= 0) ? "+" : "";
  18122. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  18123. padNumber(Math.abs(zone % 60), 2);
  18124. return paddedZone;
  18125. }
  18126. function getFirstThursdayOfYear(year) {
  18127. // 0 = index of January
  18128. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  18129. // 4 = index of Thursday (+1 to account for 1st = 5)
  18130. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  18131. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  18132. }
  18133. function getThursdayThisWeek(datetime) {
  18134. return new Date(datetime.getFullYear(), datetime.getMonth(),
  18135. // 4 = index of Thursday
  18136. datetime.getDate() + (4 - datetime.getDay()));
  18137. }
  18138. function weekGetter(size) {
  18139. return function(date) {
  18140. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  18141. thisThurs = getThursdayThisWeek(date);
  18142. var diff = +thisThurs - +firstThurs,
  18143. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  18144. return padNumber(result, size);
  18145. };
  18146. }
  18147. function ampmGetter(date, formats) {
  18148. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  18149. }
  18150. function eraGetter(date, formats) {
  18151. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  18152. }
  18153. function longEraGetter(date, formats) {
  18154. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  18155. }
  18156. var DATE_FORMATS = {
  18157. yyyy: dateGetter('FullYear', 4, 0, false, true),
  18158. yy: dateGetter('FullYear', 2, 0, true, true),
  18159. y: dateGetter('FullYear', 1, 0, false, true),
  18160. MMMM: dateStrGetter('Month'),
  18161. MMM: dateStrGetter('Month', true),
  18162. MM: dateGetter('Month', 2, 1),
  18163. M: dateGetter('Month', 1, 1),
  18164. LLLL: dateStrGetter('Month', false, true),
  18165. dd: dateGetter('Date', 2),
  18166. d: dateGetter('Date', 1),
  18167. HH: dateGetter('Hours', 2),
  18168. H: dateGetter('Hours', 1),
  18169. hh: dateGetter('Hours', 2, -12),
  18170. h: dateGetter('Hours', 1, -12),
  18171. mm: dateGetter('Minutes', 2),
  18172. m: dateGetter('Minutes', 1),
  18173. ss: dateGetter('Seconds', 2),
  18174. s: dateGetter('Seconds', 1),
  18175. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  18176. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  18177. sss: dateGetter('Milliseconds', 3),
  18178. EEEE: dateStrGetter('Day'),
  18179. EEE: dateStrGetter('Day', true),
  18180. a: ampmGetter,
  18181. Z: timeZoneGetter,
  18182. ww: weekGetter(2),
  18183. w: weekGetter(1),
  18184. G: eraGetter,
  18185. GG: eraGetter,
  18186. GGG: eraGetter,
  18187. GGGG: longEraGetter
  18188. };
  18189. var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
  18190. NUMBER_STRING = /^\-?\d+$/;
  18191. /**
  18192. * @ngdoc filter
  18193. * @name date
  18194. * @kind function
  18195. *
  18196. * @description
  18197. * Formats `date` to a string based on the requested `format`.
  18198. *
  18199. * `format` string can be composed of the following elements:
  18200. *
  18201. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  18202. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  18203. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  18204. * * `'MMMM'`: Month in year (January-December)
  18205. * * `'MMM'`: Month in year (Jan-Dec)
  18206. * * `'MM'`: Month in year, padded (01-12)
  18207. * * `'M'`: Month in year (1-12)
  18208. * * `'LLLL'`: Stand-alone month in year (January-December)
  18209. * * `'dd'`: Day in month, padded (01-31)
  18210. * * `'d'`: Day in month (1-31)
  18211. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  18212. * * `'EEE'`: Day in Week, (Sun-Sat)
  18213. * * `'HH'`: Hour in day, padded (00-23)
  18214. * * `'H'`: Hour in day (0-23)
  18215. * * `'hh'`: Hour in AM/PM, padded (01-12)
  18216. * * `'h'`: Hour in AM/PM, (1-12)
  18217. * * `'mm'`: Minute in hour, padded (00-59)
  18218. * * `'m'`: Minute in hour (0-59)
  18219. * * `'ss'`: Second in minute, padded (00-59)
  18220. * * `'s'`: Second in minute (0-59)
  18221. * * `'sss'`: Millisecond in second, padded (000-999)
  18222. * * `'a'`: AM/PM marker
  18223. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  18224. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  18225. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  18226. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  18227. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  18228. *
  18229. * `format` string can also be one of the following predefined
  18230. * {@link guide/i18n localizable formats}:
  18231. *
  18232. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  18233. * (e.g. Sep 3, 2010 12:05:08 PM)
  18234. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  18235. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  18236. * (e.g. Friday, September 3, 2010)
  18237. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  18238. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  18239. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  18240. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  18241. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  18242. *
  18243. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  18244. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  18245. * (e.g. `"h 'o''clock'"`).
  18246. *
  18247. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  18248. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  18249. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  18250. * specified in the string input, the time is considered to be in the local timezone.
  18251. * @param {string=} format Formatting rules (see Description). If not specified,
  18252. * `mediumDate` is used.
  18253. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  18254. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  18255. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  18256. * If not specified, the timezone of the browser will be used.
  18257. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  18258. *
  18259. * @example
  18260. <example>
  18261. <file name="index.html">
  18262. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  18263. <span>{{1288323623006 | date:'medium'}}</span><br>
  18264. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  18265. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  18266. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  18267. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  18268. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  18269. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  18270. </file>
  18271. <file name="protractor.js" type="protractor">
  18272. it('should format date', function() {
  18273. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  18274. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  18275. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  18276. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  18277. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  18278. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  18279. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  18280. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  18281. });
  18282. </file>
  18283. </example>
  18284. */
  18285. dateFilter.$inject = ['$locale'];
  18286. function dateFilter($locale) {
  18287. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  18288. // 1 2 3 4 5 6 7 8 9 10 11
  18289. function jsonStringToDate(string) {
  18290. var match;
  18291. if (match = string.match(R_ISO8601_STR)) {
  18292. var date = new Date(0),
  18293. tzHour = 0,
  18294. tzMin = 0,
  18295. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  18296. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  18297. if (match[9]) {
  18298. tzHour = toInt(match[9] + match[10]);
  18299. tzMin = toInt(match[9] + match[11]);
  18300. }
  18301. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  18302. var h = toInt(match[4] || 0) - tzHour;
  18303. var m = toInt(match[5] || 0) - tzMin;
  18304. var s = toInt(match[6] || 0);
  18305. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  18306. timeSetter.call(date, h, m, s, ms);
  18307. return date;
  18308. }
  18309. return string;
  18310. }
  18311. return function(date, format, timezone) {
  18312. var text = '',
  18313. parts = [],
  18314. fn, match;
  18315. format = format || 'mediumDate';
  18316. format = $locale.DATETIME_FORMATS[format] || format;
  18317. if (isString(date)) {
  18318. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  18319. }
  18320. if (isNumber(date)) {
  18321. date = new Date(date);
  18322. }
  18323. if (!isDate(date) || !isFinite(date.getTime())) {
  18324. return date;
  18325. }
  18326. while (format) {
  18327. match = DATE_FORMATS_SPLIT.exec(format);
  18328. if (match) {
  18329. parts = concat(parts, match, 1);
  18330. format = parts.pop();
  18331. } else {
  18332. parts.push(format);
  18333. format = null;
  18334. }
  18335. }
  18336. var dateTimezoneOffset = date.getTimezoneOffset();
  18337. if (timezone) {
  18338. dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  18339. date = convertTimezoneToLocal(date, timezone, true);
  18340. }
  18341. forEach(parts, function(value) {
  18342. fn = DATE_FORMATS[value];
  18343. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  18344. : value === "''" ? "'" : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  18345. });
  18346. return text;
  18347. };
  18348. }
  18349. /**
  18350. * @ngdoc filter
  18351. * @name json
  18352. * @kind function
  18353. *
  18354. * @description
  18355. * Allows you to convert a JavaScript object into JSON string.
  18356. *
  18357. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  18358. * the binding is automatically converted to JSON.
  18359. *
  18360. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  18361. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  18362. * @returns {string} JSON string.
  18363. *
  18364. *
  18365. * @example
  18366. <example>
  18367. <file name="index.html">
  18368. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  18369. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  18370. </file>
  18371. <file name="protractor.js" type="protractor">
  18372. it('should jsonify filtered objects', function() {
  18373. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  18374. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  18375. });
  18376. </file>
  18377. </example>
  18378. *
  18379. */
  18380. function jsonFilter() {
  18381. return function(object, spacing) {
  18382. if (isUndefined(spacing)) {
  18383. spacing = 2;
  18384. }
  18385. return toJson(object, spacing);
  18386. };
  18387. }
  18388. /**
  18389. * @ngdoc filter
  18390. * @name lowercase
  18391. * @kind function
  18392. * @description
  18393. * Converts string to lowercase.
  18394. * @see angular.lowercase
  18395. */
  18396. var lowercaseFilter = valueFn(lowercase);
  18397. /**
  18398. * @ngdoc filter
  18399. * @name uppercase
  18400. * @kind function
  18401. * @description
  18402. * Converts string to uppercase.
  18403. * @see angular.uppercase
  18404. */
  18405. var uppercaseFilter = valueFn(uppercase);
  18406. /**
  18407. * @ngdoc filter
  18408. * @name limitTo
  18409. * @kind function
  18410. *
  18411. * @description
  18412. * Creates a new array or string containing only a specified number of elements. The elements
  18413. * are taken from either the beginning or the end of the source array, string or number, as specified by
  18414. * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
  18415. * converted to a string.
  18416. *
  18417. * @param {Array|string|number} input Source array, string or number to be limited.
  18418. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  18419. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  18420. * If the number is negative, `limit` number of items from the end of the source array/string
  18421. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  18422. * the input will be returned unchanged.
  18423. * @param {(string|number)=} begin Index at which to begin limitation. As a negative index, `begin`
  18424. * indicates an offset from the end of `input`. Defaults to `0`.
  18425. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  18426. * had less than `limit` elements.
  18427. *
  18428. * @example
  18429. <example module="limitToExample">
  18430. <file name="index.html">
  18431. <script>
  18432. angular.module('limitToExample', [])
  18433. .controller('ExampleController', ['$scope', function($scope) {
  18434. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  18435. $scope.letters = "abcdefghi";
  18436. $scope.longNumber = 2345432342;
  18437. $scope.numLimit = 3;
  18438. $scope.letterLimit = 3;
  18439. $scope.longNumberLimit = 3;
  18440. }]);
  18441. </script>
  18442. <div ng-controller="ExampleController">
  18443. <label>
  18444. Limit {{numbers}} to:
  18445. <input type="number" step="1" ng-model="numLimit">
  18446. </label>
  18447. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  18448. <label>
  18449. Limit {{letters}} to:
  18450. <input type="number" step="1" ng-model="letterLimit">
  18451. </label>
  18452. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  18453. <label>
  18454. Limit {{longNumber}} to:
  18455. <input type="number" step="1" ng-model="longNumberLimit">
  18456. </label>
  18457. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  18458. </div>
  18459. </file>
  18460. <file name="protractor.js" type="protractor">
  18461. var numLimitInput = element(by.model('numLimit'));
  18462. var letterLimitInput = element(by.model('letterLimit'));
  18463. var longNumberLimitInput = element(by.model('longNumberLimit'));
  18464. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  18465. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  18466. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  18467. it('should limit the number array to first three items', function() {
  18468. expect(numLimitInput.getAttribute('value')).toBe('3');
  18469. expect(letterLimitInput.getAttribute('value')).toBe('3');
  18470. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  18471. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  18472. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  18473. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  18474. });
  18475. // There is a bug in safari and protractor that doesn't like the minus key
  18476. // it('should update the output when -3 is entered', function() {
  18477. // numLimitInput.clear();
  18478. // numLimitInput.sendKeys('-3');
  18479. // letterLimitInput.clear();
  18480. // letterLimitInput.sendKeys('-3');
  18481. // longNumberLimitInput.clear();
  18482. // longNumberLimitInput.sendKeys('-3');
  18483. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  18484. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  18485. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  18486. // });
  18487. it('should not exceed the maximum size of input array', function() {
  18488. numLimitInput.clear();
  18489. numLimitInput.sendKeys('100');
  18490. letterLimitInput.clear();
  18491. letterLimitInput.sendKeys('100');
  18492. longNumberLimitInput.clear();
  18493. longNumberLimitInput.sendKeys('100');
  18494. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  18495. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  18496. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  18497. });
  18498. </file>
  18499. </example>
  18500. */
  18501. function limitToFilter() {
  18502. return function(input, limit, begin) {
  18503. if (Math.abs(Number(limit)) === Infinity) {
  18504. limit = Number(limit);
  18505. } else {
  18506. limit = toInt(limit);
  18507. }
  18508. if (isNaN(limit)) return input;
  18509. if (isNumber(input)) input = input.toString();
  18510. if (!isArray(input) && !isString(input)) return input;
  18511. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  18512. begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
  18513. if (limit >= 0) {
  18514. return input.slice(begin, begin + limit);
  18515. } else {
  18516. if (begin === 0) {
  18517. return input.slice(limit, input.length);
  18518. } else {
  18519. return input.slice(Math.max(0, begin + limit), begin);
  18520. }
  18521. }
  18522. };
  18523. }
  18524. /**
  18525. * @ngdoc filter
  18526. * @name orderBy
  18527. * @kind function
  18528. *
  18529. * @description
  18530. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  18531. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  18532. * as expected, make sure they are actually being saved as numbers and not strings.
  18533. * Array-like values (e.g. NodeLists, jQuery objects, TypedArrays, Strings, etc) are also supported.
  18534. *
  18535. * @param {Array} array The array (or array-like object) to sort.
  18536. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
  18537. * used by the comparator to determine the order of elements.
  18538. *
  18539. * Can be one of:
  18540. *
  18541. * - `function`: Getter function. The result of this function will be sorted using the
  18542. * `<`, `===`, `>` operator.
  18543. * - `string`: An Angular expression. The result of this expression is used to compare elements
  18544. * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
  18545. * 3 first characters of a property called `name`). The result of a constant expression
  18546. * is interpreted as a property name to be used in comparisons (for example `"special name"`
  18547. * to sort object by the value of their `special name` property). An expression can be
  18548. * optionally prefixed with `+` or `-` to control ascending or descending sort order
  18549. * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
  18550. * element itself is used to compare where sorting.
  18551. * - `Array`: An array of function or string predicates. The first predicate in the array
  18552. * is used for sorting, but when two items are equivalent, the next predicate is used.
  18553. *
  18554. * If the predicate is missing or empty then it defaults to `'+'`.
  18555. *
  18556. * @param {boolean=} reverse Reverse the order of the array.
  18557. * @returns {Array} Sorted copy of the source array.
  18558. *
  18559. *
  18560. * @example
  18561. * The example below demonstrates a simple ngRepeat, where the data is sorted
  18562. * by age in descending order (predicate is set to `'-age'`).
  18563. * `reverse` is not set, which means it defaults to `false`.
  18564. <example module="orderByExample">
  18565. <file name="index.html">
  18566. <div ng-controller="ExampleController">
  18567. <table class="friend">
  18568. <tr>
  18569. <th>Name</th>
  18570. <th>Phone Number</th>
  18571. <th>Age</th>
  18572. </tr>
  18573. <tr ng-repeat="friend in friends | orderBy:'-age'">
  18574. <td>{{friend.name}}</td>
  18575. <td>{{friend.phone}}</td>
  18576. <td>{{friend.age}}</td>
  18577. </tr>
  18578. </table>
  18579. </div>
  18580. </file>
  18581. <file name="script.js">
  18582. angular.module('orderByExample', [])
  18583. .controller('ExampleController', ['$scope', function($scope) {
  18584. $scope.friends =
  18585. [{name:'John', phone:'555-1212', age:10},
  18586. {name:'Mary', phone:'555-9876', age:19},
  18587. {name:'Mike', phone:'555-4321', age:21},
  18588. {name:'Adam', phone:'555-5678', age:35},
  18589. {name:'Julie', phone:'555-8765', age:29}];
  18590. }]);
  18591. </file>
  18592. </example>
  18593. *
  18594. * The predicate and reverse parameters can be controlled dynamically through scope properties,
  18595. * as shown in the next example.
  18596. * @example
  18597. <example module="orderByExample">
  18598. <file name="index.html">
  18599. <div ng-controller="ExampleController">
  18600. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  18601. <hr/>
  18602. <button ng-click="predicate=''">Set to unsorted</button>
  18603. <table class="friend">
  18604. <tr>
  18605. <th>
  18606. <button ng-click="order('name')">Name</button>
  18607. <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
  18608. </th>
  18609. <th>
  18610. <button ng-click="order('phone')">Phone Number</button>
  18611. <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
  18612. </th>
  18613. <th>
  18614. <button ng-click="order('age')">Age</button>
  18615. <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
  18616. </th>
  18617. </tr>
  18618. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  18619. <td>{{friend.name}}</td>
  18620. <td>{{friend.phone}}</td>
  18621. <td>{{friend.age}}</td>
  18622. </tr>
  18623. </table>
  18624. </div>
  18625. </file>
  18626. <file name="script.js">
  18627. angular.module('orderByExample', [])
  18628. .controller('ExampleController', ['$scope', function($scope) {
  18629. $scope.friends =
  18630. [{name:'John', phone:'555-1212', age:10},
  18631. {name:'Mary', phone:'555-9876', age:19},
  18632. {name:'Mike', phone:'555-4321', age:21},
  18633. {name:'Adam', phone:'555-5678', age:35},
  18634. {name:'Julie', phone:'555-8765', age:29}];
  18635. $scope.predicate = 'age';
  18636. $scope.reverse = true;
  18637. $scope.order = function(predicate) {
  18638. $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
  18639. $scope.predicate = predicate;
  18640. };
  18641. }]);
  18642. </file>
  18643. <file name="style.css">
  18644. .sortorder:after {
  18645. content: '\25b2';
  18646. }
  18647. .sortorder.reverse:after {
  18648. content: '\25bc';
  18649. }
  18650. </file>
  18651. </example>
  18652. *
  18653. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  18654. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  18655. * desired parameters.
  18656. *
  18657. * Example:
  18658. *
  18659. * @example
  18660. <example module="orderByExample">
  18661. <file name="index.html">
  18662. <div ng-controller="ExampleController">
  18663. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  18664. <table class="friend">
  18665. <tr>
  18666. <th>
  18667. <button ng-click="order('name')">Name</button>
  18668. <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
  18669. </th>
  18670. <th>
  18671. <button ng-click="order('phone')">Phone Number</button>
  18672. <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
  18673. </th>
  18674. <th>
  18675. <button ng-click="order('age')">Age</button>
  18676. <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
  18677. </th>
  18678. </tr>
  18679. <tr ng-repeat="friend in friends">
  18680. <td>{{friend.name}}</td>
  18681. <td>{{friend.phone}}</td>
  18682. <td>{{friend.age}}</td>
  18683. </tr>
  18684. </table>
  18685. </div>
  18686. </file>
  18687. <file name="script.js">
  18688. angular.module('orderByExample', [])
  18689. .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
  18690. var orderBy = $filter('orderBy');
  18691. $scope.friends = [
  18692. { name: 'John', phone: '555-1212', age: 10 },
  18693. { name: 'Mary', phone: '555-9876', age: 19 },
  18694. { name: 'Mike', phone: '555-4321', age: 21 },
  18695. { name: 'Adam', phone: '555-5678', age: 35 },
  18696. { name: 'Julie', phone: '555-8765', age: 29 }
  18697. ];
  18698. $scope.order = function(predicate) {
  18699. $scope.predicate = predicate;
  18700. $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
  18701. $scope.friends = orderBy($scope.friends, predicate, $scope.reverse);
  18702. };
  18703. $scope.order('age', true);
  18704. }]);
  18705. </file>
  18706. <file name="style.css">
  18707. .sortorder:after {
  18708. content: '\25b2';
  18709. }
  18710. .sortorder.reverse:after {
  18711. content: '\25bc';
  18712. }
  18713. </file>
  18714. </example>
  18715. */
  18716. orderByFilter.$inject = ['$parse'];
  18717. function orderByFilter($parse) {
  18718. return function(array, sortPredicate, reverseOrder) {
  18719. if (array == null) return array;
  18720. if (!isArrayLike(array)) {
  18721. throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
  18722. }
  18723. if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
  18724. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  18725. var predicates = processPredicates(sortPredicate, reverseOrder);
  18726. // Add a predicate at the end that evaluates to the element index. This makes the
  18727. // sort stable as it works as a tie-breaker when all the input predicates cannot
  18728. // distinguish between two elements.
  18729. predicates.push({ get: function() { return {}; }, descending: reverseOrder ? -1 : 1});
  18730. // The next three lines are a version of a Swartzian Transform idiom from Perl
  18731. // (sometimes called the Decorate-Sort-Undecorate idiom)
  18732. // See https://en.wikipedia.org/wiki/Schwartzian_transform
  18733. var compareValues = Array.prototype.map.call(array, getComparisonObject);
  18734. compareValues.sort(doComparison);
  18735. array = compareValues.map(function(item) { return item.value; });
  18736. return array;
  18737. function getComparisonObject(value, index) {
  18738. return {
  18739. value: value,
  18740. predicateValues: predicates.map(function(predicate) {
  18741. return getPredicateValue(predicate.get(value), index);
  18742. })
  18743. };
  18744. }
  18745. function doComparison(v1, v2) {
  18746. var result = 0;
  18747. for (var index=0, length = predicates.length; index < length; ++index) {
  18748. result = compare(v1.predicateValues[index], v2.predicateValues[index]) * predicates[index].descending;
  18749. if (result) break;
  18750. }
  18751. return result;
  18752. }
  18753. };
  18754. function processPredicates(sortPredicate, reverseOrder) {
  18755. reverseOrder = reverseOrder ? -1 : 1;
  18756. return sortPredicate.map(function(predicate) {
  18757. var descending = 1, get = identity;
  18758. if (isFunction(predicate)) {
  18759. get = predicate;
  18760. } else if (isString(predicate)) {
  18761. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  18762. descending = predicate.charAt(0) == '-' ? -1 : 1;
  18763. predicate = predicate.substring(1);
  18764. }
  18765. if (predicate !== '') {
  18766. get = $parse(predicate);
  18767. if (get.constant) {
  18768. var key = get();
  18769. get = function(value) { return value[key]; };
  18770. }
  18771. }
  18772. }
  18773. return { get: get, descending: descending * reverseOrder };
  18774. });
  18775. }
  18776. function isPrimitive(value) {
  18777. switch (typeof value) {
  18778. case 'number': /* falls through */
  18779. case 'boolean': /* falls through */
  18780. case 'string':
  18781. return true;
  18782. default:
  18783. return false;
  18784. }
  18785. }
  18786. function objectValue(value, index) {
  18787. // If `valueOf` is a valid function use that
  18788. if (typeof value.valueOf === 'function') {
  18789. value = value.valueOf();
  18790. if (isPrimitive(value)) return value;
  18791. }
  18792. // If `toString` is a valid function and not the one from `Object.prototype` use that
  18793. if (hasCustomToString(value)) {
  18794. value = value.toString();
  18795. if (isPrimitive(value)) return value;
  18796. }
  18797. // We have a basic object so we use the position of the object in the collection
  18798. return index;
  18799. }
  18800. function getPredicateValue(value, index) {
  18801. var type = typeof value;
  18802. if (value === null) {
  18803. type = 'string';
  18804. value = 'null';
  18805. } else if (type === 'string') {
  18806. value = value.toLowerCase();
  18807. } else if (type === 'object') {
  18808. value = objectValue(value, index);
  18809. }
  18810. return { value: value, type: type };
  18811. }
  18812. function compare(v1, v2) {
  18813. var result = 0;
  18814. if (v1.type === v2.type) {
  18815. if (v1.value !== v2.value) {
  18816. result = v1.value < v2.value ? -1 : 1;
  18817. }
  18818. } else {
  18819. result = v1.type < v2.type ? -1 : 1;
  18820. }
  18821. return result;
  18822. }
  18823. }
  18824. function ngDirective(directive) {
  18825. if (isFunction(directive)) {
  18826. directive = {
  18827. link: directive
  18828. };
  18829. }
  18830. directive.restrict = directive.restrict || 'AC';
  18831. return valueFn(directive);
  18832. }
  18833. /**
  18834. * @ngdoc directive
  18835. * @name a
  18836. * @restrict E
  18837. *
  18838. * @description
  18839. * Modifies the default behavior of the html A tag so that the default action is prevented when
  18840. * the href attribute is empty.
  18841. *
  18842. * This change permits the easy creation of action links with the `ngClick` directive
  18843. * without changing the location or causing page reloads, e.g.:
  18844. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  18845. */
  18846. var htmlAnchorDirective = valueFn({
  18847. restrict: 'E',
  18848. compile: function(element, attr) {
  18849. if (!attr.href && !attr.xlinkHref) {
  18850. return function(scope, element) {
  18851. // If the linked element is not an anchor tag anymore, do nothing
  18852. if (element[0].nodeName.toLowerCase() !== 'a') return;
  18853. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  18854. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  18855. 'xlink:href' : 'href';
  18856. element.on('click', function(event) {
  18857. // if we have no href url, then don't navigate anywhere.
  18858. if (!element.attr(href)) {
  18859. event.preventDefault();
  18860. }
  18861. });
  18862. };
  18863. }
  18864. }
  18865. });
  18866. /**
  18867. * @ngdoc directive
  18868. * @name ngHref
  18869. * @restrict A
  18870. * @priority 99
  18871. *
  18872. * @description
  18873. * Using Angular markup like `{{hash}}` in an href attribute will
  18874. * make the link go to the wrong URL if the user clicks it before
  18875. * Angular has a chance to replace the `{{hash}}` markup with its
  18876. * value. Until Angular replaces the markup the link will be broken
  18877. * and will most likely return a 404 error. The `ngHref` directive
  18878. * solves this problem.
  18879. *
  18880. * The wrong way to write it:
  18881. * ```html
  18882. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  18883. * ```
  18884. *
  18885. * The correct way to write it:
  18886. * ```html
  18887. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  18888. * ```
  18889. *
  18890. * @element A
  18891. * @param {template} ngHref any string which can contain `{{}}` markup.
  18892. *
  18893. * @example
  18894. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  18895. * in links and their different behaviors:
  18896. <example>
  18897. <file name="index.html">
  18898. <input ng-model="value" /><br />
  18899. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  18900. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  18901. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  18902. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  18903. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  18904. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  18905. </file>
  18906. <file name="protractor.js" type="protractor">
  18907. it('should execute ng-click but not reload when href without value', function() {
  18908. element(by.id('link-1')).click();
  18909. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  18910. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  18911. });
  18912. it('should execute ng-click but not reload when href empty string', function() {
  18913. element(by.id('link-2')).click();
  18914. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  18915. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  18916. });
  18917. it('should execute ng-click and change url when ng-href specified', function() {
  18918. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  18919. element(by.id('link-3')).click();
  18920. // At this point, we navigate away from an Angular page, so we need
  18921. // to use browser.driver to get the base webdriver.
  18922. browser.wait(function() {
  18923. return browser.driver.getCurrentUrl().then(function(url) {
  18924. return url.match(/\/123$/);
  18925. });
  18926. }, 5000, 'page should navigate to /123');
  18927. });
  18928. it('should execute ng-click but not reload when href empty string and name specified', function() {
  18929. element(by.id('link-4')).click();
  18930. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  18931. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  18932. });
  18933. it('should execute ng-click but not reload when no href but name specified', function() {
  18934. element(by.id('link-5')).click();
  18935. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  18936. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  18937. });
  18938. it('should only change url when only ng-href', function() {
  18939. element(by.model('value')).clear();
  18940. element(by.model('value')).sendKeys('6');
  18941. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  18942. element(by.id('link-6')).click();
  18943. // At this point, we navigate away from an Angular page, so we need
  18944. // to use browser.driver to get the base webdriver.
  18945. browser.wait(function() {
  18946. return browser.driver.getCurrentUrl().then(function(url) {
  18947. return url.match(/\/6$/);
  18948. });
  18949. }, 5000, 'page should navigate to /6');
  18950. });
  18951. </file>
  18952. </example>
  18953. */
  18954. /**
  18955. * @ngdoc directive
  18956. * @name ngSrc
  18957. * @restrict A
  18958. * @priority 99
  18959. *
  18960. * @description
  18961. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  18962. * work right: The browser will fetch from the URL with the literal
  18963. * text `{{hash}}` until Angular replaces the expression inside
  18964. * `{{hash}}`. The `ngSrc` directive solves this problem.
  18965. *
  18966. * The buggy way to write it:
  18967. * ```html
  18968. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  18969. * ```
  18970. *
  18971. * The correct way to write it:
  18972. * ```html
  18973. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  18974. * ```
  18975. *
  18976. * @element IMG
  18977. * @param {template} ngSrc any string which can contain `{{}}` markup.
  18978. */
  18979. /**
  18980. * @ngdoc directive
  18981. * @name ngSrcset
  18982. * @restrict A
  18983. * @priority 99
  18984. *
  18985. * @description
  18986. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  18987. * work right: The browser will fetch from the URL with the literal
  18988. * text `{{hash}}` until Angular replaces the expression inside
  18989. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  18990. *
  18991. * The buggy way to write it:
  18992. * ```html
  18993. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  18994. * ```
  18995. *
  18996. * The correct way to write it:
  18997. * ```html
  18998. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  18999. * ```
  19000. *
  19001. * @element IMG
  19002. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  19003. */
  19004. /**
  19005. * @ngdoc directive
  19006. * @name ngDisabled
  19007. * @restrict A
  19008. * @priority 100
  19009. *
  19010. * @description
  19011. *
  19012. * This directive sets the `disabled` attribute on the element if the
  19013. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  19014. *
  19015. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  19016. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  19017. *
  19018. * @example
  19019. <example>
  19020. <file name="index.html">
  19021. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  19022. <button ng-model="button" ng-disabled="checked">Button</button>
  19023. </file>
  19024. <file name="protractor.js" type="protractor">
  19025. it('should toggle button', function() {
  19026. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  19027. element(by.model('checked')).click();
  19028. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  19029. });
  19030. </file>
  19031. </example>
  19032. *
  19033. * @element INPUT
  19034. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  19035. * then the `disabled` attribute will be set on the element
  19036. */
  19037. /**
  19038. * @ngdoc directive
  19039. * @name ngChecked
  19040. * @restrict A
  19041. * @priority 100
  19042. *
  19043. * @description
  19044. * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
  19045. *
  19046. * Note that this directive should not be used together with {@link ngModel `ngModel`},
  19047. * as this can lead to unexpected behavior.
  19048. *
  19049. * A special directive is necessary because we cannot use interpolation inside the `checked`
  19050. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  19051. *
  19052. * @example
  19053. <example>
  19054. <file name="index.html">
  19055. <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
  19056. <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
  19057. </file>
  19058. <file name="protractor.js" type="protractor">
  19059. it('should check both checkBoxes', function() {
  19060. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  19061. element(by.model('master')).click();
  19062. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  19063. });
  19064. </file>
  19065. </example>
  19066. *
  19067. * @element INPUT
  19068. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  19069. * then the `checked` attribute will be set on the element
  19070. */
  19071. /**
  19072. * @ngdoc directive
  19073. * @name ngReadonly
  19074. * @restrict A
  19075. * @priority 100
  19076. *
  19077. * @description
  19078. *
  19079. * Sets the `readOnly` attribute on the element, if the expression inside `ngReadonly` is truthy.
  19080. *
  19081. * A special directive is necessary because we cannot use interpolation inside the `readOnly`
  19082. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  19083. *
  19084. * @example
  19085. <example>
  19086. <file name="index.html">
  19087. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  19088. <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
  19089. </file>
  19090. <file name="protractor.js" type="protractor">
  19091. it('should toggle readonly attr', function() {
  19092. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  19093. element(by.model('checked')).click();
  19094. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  19095. });
  19096. </file>
  19097. </example>
  19098. *
  19099. * @element INPUT
  19100. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  19101. * then special attribute "readonly" will be set on the element
  19102. */
  19103. /**
  19104. * @ngdoc directive
  19105. * @name ngSelected
  19106. * @restrict A
  19107. * @priority 100
  19108. *
  19109. * @description
  19110. *
  19111. * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy.
  19112. *
  19113. * A special directive is necessary because we cannot use interpolation inside the `selected`
  19114. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  19115. *
  19116. * @example
  19117. <example>
  19118. <file name="index.html">
  19119. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  19120. <select aria-label="ngSelected demo">
  19121. <option>Hello!</option>
  19122. <option id="greet" ng-selected="selected">Greetings!</option>
  19123. </select>
  19124. </file>
  19125. <file name="protractor.js" type="protractor">
  19126. it('should select Greetings!', function() {
  19127. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  19128. element(by.model('selected')).click();
  19129. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  19130. });
  19131. </file>
  19132. </example>
  19133. *
  19134. * @element OPTION
  19135. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  19136. * then special attribute "selected" will be set on the element
  19137. */
  19138. /**
  19139. * @ngdoc directive
  19140. * @name ngOpen
  19141. * @restrict A
  19142. * @priority 100
  19143. *
  19144. * @description
  19145. *
  19146. * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy.
  19147. *
  19148. * A special directive is necessary because we cannot use interpolation inside the `open`
  19149. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  19150. *
  19151. * @example
  19152. <example>
  19153. <file name="index.html">
  19154. <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
  19155. <details id="details" ng-open="open">
  19156. <summary>Show/Hide me</summary>
  19157. </details>
  19158. </file>
  19159. <file name="protractor.js" type="protractor">
  19160. it('should toggle open', function() {
  19161. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  19162. element(by.model('open')).click();
  19163. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  19164. });
  19165. </file>
  19166. </example>
  19167. *
  19168. * @element DETAILS
  19169. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  19170. * then special attribute "open" will be set on the element
  19171. */
  19172. var ngAttributeAliasDirectives = {};
  19173. // boolean attrs are evaluated
  19174. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  19175. // binding to multiple is not supported
  19176. if (propName == "multiple") return;
  19177. function defaultLinkFn(scope, element, attr) {
  19178. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  19179. attr.$set(attrName, !!value);
  19180. });
  19181. }
  19182. var normalized = directiveNormalize('ng-' + attrName);
  19183. var linkFn = defaultLinkFn;
  19184. if (propName === 'checked') {
  19185. linkFn = function(scope, element, attr) {
  19186. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  19187. if (attr.ngModel !== attr[normalized]) {
  19188. defaultLinkFn(scope, element, attr);
  19189. }
  19190. };
  19191. }
  19192. ngAttributeAliasDirectives[normalized] = function() {
  19193. return {
  19194. restrict: 'A',
  19195. priority: 100,
  19196. link: linkFn
  19197. };
  19198. };
  19199. });
  19200. // aliased input attrs are evaluated
  19201. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  19202. ngAttributeAliasDirectives[ngAttr] = function() {
  19203. return {
  19204. priority: 100,
  19205. link: function(scope, element, attr) {
  19206. //special case ngPattern when a literal regular expression value
  19207. //is used as the expression (this way we don't have to watch anything).
  19208. if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
  19209. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  19210. if (match) {
  19211. attr.$set("ngPattern", new RegExp(match[1], match[2]));
  19212. return;
  19213. }
  19214. }
  19215. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  19216. attr.$set(ngAttr, value);
  19217. });
  19218. }
  19219. };
  19220. };
  19221. });
  19222. // ng-src, ng-srcset, ng-href are interpolated
  19223. forEach(['src', 'srcset', 'href'], function(attrName) {
  19224. var normalized = directiveNormalize('ng-' + attrName);
  19225. ngAttributeAliasDirectives[normalized] = function() {
  19226. return {
  19227. priority: 99, // it needs to run after the attributes are interpolated
  19228. link: function(scope, element, attr) {
  19229. var propName = attrName,
  19230. name = attrName;
  19231. if (attrName === 'href' &&
  19232. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  19233. name = 'xlinkHref';
  19234. attr.$attr[name] = 'xlink:href';
  19235. propName = null;
  19236. }
  19237. attr.$observe(normalized, function(value) {
  19238. if (!value) {
  19239. if (attrName === 'href') {
  19240. attr.$set(name, null);
  19241. }
  19242. return;
  19243. }
  19244. attr.$set(name, value);
  19245. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  19246. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  19247. // to set the property as well to achieve the desired effect.
  19248. // we use attr[attrName] value since $set can sanitize the url.
  19249. if (msie && propName) element.prop(propName, attr[name]);
  19250. });
  19251. }
  19252. };
  19253. };
  19254. });
  19255. /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
  19256. */
  19257. var nullFormCtrl = {
  19258. $addControl: noop,
  19259. $$renameControl: nullFormRenameControl,
  19260. $removeControl: noop,
  19261. $setValidity: noop,
  19262. $setDirty: noop,
  19263. $setPristine: noop,
  19264. $setSubmitted: noop
  19265. },
  19266. SUBMITTED_CLASS = 'ng-submitted';
  19267. function nullFormRenameControl(control, name) {
  19268. control.$name = name;
  19269. }
  19270. /**
  19271. * @ngdoc type
  19272. * @name form.FormController
  19273. *
  19274. * @property {boolean} $pristine True if user has not interacted with the form yet.
  19275. * @property {boolean} $dirty True if user has already interacted with the form.
  19276. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  19277. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  19278. * @property {boolean} $pending True if at least one containing control or form is pending.
  19279. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  19280. *
  19281. * @property {Object} $error Is an object hash, containing references to controls or
  19282. * forms with failing validators, where:
  19283. *
  19284. * - keys are validation tokens (error names),
  19285. * - values are arrays of controls or forms that have a failing validator for given error name.
  19286. *
  19287. * Built-in validation tokens:
  19288. *
  19289. * - `email`
  19290. * - `max`
  19291. * - `maxlength`
  19292. * - `min`
  19293. * - `minlength`
  19294. * - `number`
  19295. * - `pattern`
  19296. * - `required`
  19297. * - `url`
  19298. * - `date`
  19299. * - `datetimelocal`
  19300. * - `time`
  19301. * - `week`
  19302. * - `month`
  19303. *
  19304. * @description
  19305. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  19306. * such as being valid/invalid or dirty/pristine.
  19307. *
  19308. * Each {@link ng.directive:form form} directive creates an instance
  19309. * of `FormController`.
  19310. *
  19311. */
  19312. //asks for $scope to fool the BC controller module
  19313. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  19314. function FormController(element, attrs, $scope, $animate, $interpolate) {
  19315. var form = this,
  19316. controls = [];
  19317. // init state
  19318. form.$error = {};
  19319. form.$$success = {};
  19320. form.$pending = undefined;
  19321. form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
  19322. form.$dirty = false;
  19323. form.$pristine = true;
  19324. form.$valid = true;
  19325. form.$invalid = false;
  19326. form.$submitted = false;
  19327. form.$$parentForm = nullFormCtrl;
  19328. /**
  19329. * @ngdoc method
  19330. * @name form.FormController#$rollbackViewValue
  19331. *
  19332. * @description
  19333. * Rollback all form controls pending updates to the `$modelValue`.
  19334. *
  19335. * Updates may be pending by a debounced event or because the input is waiting for a some future
  19336. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  19337. * a form that uses `ng-model-options` to pend updates.
  19338. */
  19339. form.$rollbackViewValue = function() {
  19340. forEach(controls, function(control) {
  19341. control.$rollbackViewValue();
  19342. });
  19343. };
  19344. /**
  19345. * @ngdoc method
  19346. * @name form.FormController#$commitViewValue
  19347. *
  19348. * @description
  19349. * Commit all form controls pending updates to the `$modelValue`.
  19350. *
  19351. * Updates may be pending by a debounced event or because the input is waiting for a some future
  19352. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  19353. * usually handles calling this in response to input events.
  19354. */
  19355. form.$commitViewValue = function() {
  19356. forEach(controls, function(control) {
  19357. control.$commitViewValue();
  19358. });
  19359. };
  19360. /**
  19361. * @ngdoc method
  19362. * @name form.FormController#$addControl
  19363. * @param {object} control control object, either a {@link form.FormController} or an
  19364. * {@link ngModel.NgModelController}
  19365. *
  19366. * @description
  19367. * Register a control with the form. Input elements using ngModelController do this automatically
  19368. * when they are linked.
  19369. *
  19370. * Note that the current state of the control will not be reflected on the new parent form. This
  19371. * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
  19372. * state.
  19373. *
  19374. * However, if the method is used programmatically, for example by adding dynamically created controls,
  19375. * or controls that have been previously removed without destroying their corresponding DOM element,
  19376. * it's the developers responsibility to make sure the current state propagates to the parent form.
  19377. *
  19378. * For example, if an input control is added that is already `$dirty` and has `$error` properties,
  19379. * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
  19380. */
  19381. form.$addControl = function(control) {
  19382. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  19383. // and not added to the scope. Now we throw an error.
  19384. assertNotHasOwnProperty(control.$name, 'input');
  19385. controls.push(control);
  19386. if (control.$name) {
  19387. form[control.$name] = control;
  19388. }
  19389. control.$$parentForm = form;
  19390. };
  19391. // Private API: rename a form control
  19392. form.$$renameControl = function(control, newName) {
  19393. var oldName = control.$name;
  19394. if (form[oldName] === control) {
  19395. delete form[oldName];
  19396. }
  19397. form[newName] = control;
  19398. control.$name = newName;
  19399. };
  19400. /**
  19401. * @ngdoc method
  19402. * @name form.FormController#$removeControl
  19403. * @param {object} control control object, either a {@link form.FormController} or an
  19404. * {@link ngModel.NgModelController}
  19405. *
  19406. * @description
  19407. * Deregister a control from the form.
  19408. *
  19409. * Input elements using ngModelController do this automatically when they are destroyed.
  19410. *
  19411. * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
  19412. * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
  19413. * different from case to case. For example, removing the only `$dirty` control from a form may or
  19414. * may not mean that the form is still `$dirty`.
  19415. */
  19416. form.$removeControl = function(control) {
  19417. if (control.$name && form[control.$name] === control) {
  19418. delete form[control.$name];
  19419. }
  19420. forEach(form.$pending, function(value, name) {
  19421. form.$setValidity(name, null, control);
  19422. });
  19423. forEach(form.$error, function(value, name) {
  19424. form.$setValidity(name, null, control);
  19425. });
  19426. forEach(form.$$success, function(value, name) {
  19427. form.$setValidity(name, null, control);
  19428. });
  19429. arrayRemove(controls, control);
  19430. control.$$parentForm = nullFormCtrl;
  19431. };
  19432. /**
  19433. * @ngdoc method
  19434. * @name form.FormController#$setValidity
  19435. *
  19436. * @description
  19437. * Sets the validity of a form control.
  19438. *
  19439. * This method will also propagate to parent forms.
  19440. */
  19441. addSetValidityMethod({
  19442. ctrl: this,
  19443. $element: element,
  19444. set: function(object, property, controller) {
  19445. var list = object[property];
  19446. if (!list) {
  19447. object[property] = [controller];
  19448. } else {
  19449. var index = list.indexOf(controller);
  19450. if (index === -1) {
  19451. list.push(controller);
  19452. }
  19453. }
  19454. },
  19455. unset: function(object, property, controller) {
  19456. var list = object[property];
  19457. if (!list) {
  19458. return;
  19459. }
  19460. arrayRemove(list, controller);
  19461. if (list.length === 0) {
  19462. delete object[property];
  19463. }
  19464. },
  19465. $animate: $animate
  19466. });
  19467. /**
  19468. * @ngdoc method
  19469. * @name form.FormController#$setDirty
  19470. *
  19471. * @description
  19472. * Sets the form to a dirty state.
  19473. *
  19474. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  19475. * state (ng-dirty class). This method will also propagate to parent forms.
  19476. */
  19477. form.$setDirty = function() {
  19478. $animate.removeClass(element, PRISTINE_CLASS);
  19479. $animate.addClass(element, DIRTY_CLASS);
  19480. form.$dirty = true;
  19481. form.$pristine = false;
  19482. form.$$parentForm.$setDirty();
  19483. };
  19484. /**
  19485. * @ngdoc method
  19486. * @name form.FormController#$setPristine
  19487. *
  19488. * @description
  19489. * Sets the form to its pristine state.
  19490. *
  19491. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  19492. * state (ng-pristine class). This method will also propagate to all the controls contained
  19493. * in this form.
  19494. *
  19495. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  19496. * saving or resetting it.
  19497. */
  19498. form.$setPristine = function() {
  19499. $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  19500. form.$dirty = false;
  19501. form.$pristine = true;
  19502. form.$submitted = false;
  19503. forEach(controls, function(control) {
  19504. control.$setPristine();
  19505. });
  19506. };
  19507. /**
  19508. * @ngdoc method
  19509. * @name form.FormController#$setUntouched
  19510. *
  19511. * @description
  19512. * Sets the form to its untouched state.
  19513. *
  19514. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  19515. * untouched state (ng-untouched class).
  19516. *
  19517. * Setting a form controls back to their untouched state is often useful when setting the form
  19518. * back to its pristine state.
  19519. */
  19520. form.$setUntouched = function() {
  19521. forEach(controls, function(control) {
  19522. control.$setUntouched();
  19523. });
  19524. };
  19525. /**
  19526. * @ngdoc method
  19527. * @name form.FormController#$setSubmitted
  19528. *
  19529. * @description
  19530. * Sets the form to its submitted state.
  19531. */
  19532. form.$setSubmitted = function() {
  19533. $animate.addClass(element, SUBMITTED_CLASS);
  19534. form.$submitted = true;
  19535. form.$$parentForm.$setSubmitted();
  19536. };
  19537. }
  19538. /**
  19539. * @ngdoc directive
  19540. * @name ngForm
  19541. * @restrict EAC
  19542. *
  19543. * @description
  19544. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  19545. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  19546. * sub-group of controls needs to be determined.
  19547. *
  19548. * Note: the purpose of `ngForm` is to group controls,
  19549. * but not to be a replacement for the `<form>` tag with all of its capabilities
  19550. * (e.g. posting to the server, ...).
  19551. *
  19552. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  19553. * related scope, under this name.
  19554. *
  19555. */
  19556. /**
  19557. * @ngdoc directive
  19558. * @name form
  19559. * @restrict E
  19560. *
  19561. * @description
  19562. * Directive that instantiates
  19563. * {@link form.FormController FormController}.
  19564. *
  19565. * If the `name` attribute is specified, the form controller is published onto the current scope under
  19566. * this name.
  19567. *
  19568. * # Alias: {@link ng.directive:ngForm `ngForm`}
  19569. *
  19570. * In Angular, forms can be nested. This means that the outer form is valid when all of the child
  19571. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  19572. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to
  19573. * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group
  19574. * of controls needs to be determined.
  19575. *
  19576. * # CSS classes
  19577. * - `ng-valid` is set if the form is valid.
  19578. * - `ng-invalid` is set if the form is invalid.
  19579. * - `ng-pending` is set if the form is pending.
  19580. * - `ng-pristine` is set if the form is pristine.
  19581. * - `ng-dirty` is set if the form is dirty.
  19582. * - `ng-submitted` is set if the form was submitted.
  19583. *
  19584. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  19585. *
  19586. *
  19587. * # Submitting a form and preventing the default action
  19588. *
  19589. * Since the role of forms in client-side Angular applications is different than in classical
  19590. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  19591. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  19592. * to handle the form submission in an application-specific way.
  19593. *
  19594. * For this reason, Angular prevents the default action (form submission to the server) unless the
  19595. * `<form>` element has an `action` attribute specified.
  19596. *
  19597. * You can use one of the following two ways to specify what javascript method should be called when
  19598. * a form is submitted:
  19599. *
  19600. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  19601. * - {@link ng.directive:ngClick ngClick} directive on the first
  19602. * button or input field of type submit (input[type=submit])
  19603. *
  19604. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  19605. * or {@link ng.directive:ngClick ngClick} directives.
  19606. * This is because of the following form submission rules in the HTML specification:
  19607. *
  19608. * - If a form has only one input field then hitting enter in this field triggers form submit
  19609. * (`ngSubmit`)
  19610. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  19611. * doesn't trigger submit
  19612. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  19613. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  19614. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  19615. *
  19616. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  19617. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  19618. * to have access to the updated model.
  19619. *
  19620. * ## Animation Hooks
  19621. *
  19622. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  19623. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  19624. * other validations that are performed within the form. Animations in ngForm are similar to how
  19625. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  19626. * as JS animations.
  19627. *
  19628. * The following example shows a simple way to utilize CSS transitions to style a form element
  19629. * that has been rendered as invalid after it has been validated:
  19630. *
  19631. * <pre>
  19632. * //be sure to include ngAnimate as a module to hook into more
  19633. * //advanced animations
  19634. * .my-form {
  19635. * transition:0.5s linear all;
  19636. * background: white;
  19637. * }
  19638. * .my-form.ng-invalid {
  19639. * background: red;
  19640. * color:white;
  19641. * }
  19642. * </pre>
  19643. *
  19644. * @example
  19645. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  19646. <file name="index.html">
  19647. <script>
  19648. angular.module('formExample', [])
  19649. .controller('FormController', ['$scope', function($scope) {
  19650. $scope.userType = 'guest';
  19651. }]);
  19652. </script>
  19653. <style>
  19654. .my-form {
  19655. transition:all linear 0.5s;
  19656. background: transparent;
  19657. }
  19658. .my-form.ng-invalid {
  19659. background: red;
  19660. }
  19661. </style>
  19662. <form name="myForm" ng-controller="FormController" class="my-form">
  19663. userType: <input name="input" ng-model="userType" required>
  19664. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  19665. <code>userType = {{userType}}</code><br>
  19666. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  19667. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  19668. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  19669. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  19670. </form>
  19671. </file>
  19672. <file name="protractor.js" type="protractor">
  19673. it('should initialize to model', function() {
  19674. var userType = element(by.binding('userType'));
  19675. var valid = element(by.binding('myForm.input.$valid'));
  19676. expect(userType.getText()).toContain('guest');
  19677. expect(valid.getText()).toContain('true');
  19678. });
  19679. it('should be invalid if empty', function() {
  19680. var userType = element(by.binding('userType'));
  19681. var valid = element(by.binding('myForm.input.$valid'));
  19682. var userInput = element(by.model('userType'));
  19683. userInput.clear();
  19684. userInput.sendKeys('');
  19685. expect(userType.getText()).toEqual('userType =');
  19686. expect(valid.getText()).toContain('false');
  19687. });
  19688. </file>
  19689. </example>
  19690. *
  19691. * @param {string=} name Name of the form. If specified, the form controller will be published into
  19692. * related scope, under this name.
  19693. */
  19694. var formDirectiveFactory = function(isNgForm) {
  19695. return ['$timeout', '$parse', function($timeout, $parse) {
  19696. var formDirective = {
  19697. name: 'form',
  19698. restrict: isNgForm ? 'EAC' : 'E',
  19699. require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
  19700. controller: FormController,
  19701. compile: function ngFormCompile(formElement, attr) {
  19702. // Setup initial state of the control
  19703. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  19704. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  19705. return {
  19706. pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
  19707. var controller = ctrls[0];
  19708. // if `action` attr is not present on the form, prevent the default action (submission)
  19709. if (!('action' in attr)) {
  19710. // we can't use jq events because if a form is destroyed during submission the default
  19711. // action is not prevented. see #1238
  19712. //
  19713. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  19714. // page reload if the form was destroyed by submission of the form via a click handler
  19715. // on a button in the form. Looks like an IE9 specific bug.
  19716. var handleFormSubmission = function(event) {
  19717. scope.$apply(function() {
  19718. controller.$commitViewValue();
  19719. controller.$setSubmitted();
  19720. });
  19721. event.preventDefault();
  19722. };
  19723. addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  19724. // unregister the preventDefault listener so that we don't not leak memory but in a
  19725. // way that will achieve the prevention of the default action.
  19726. formElement.on('$destroy', function() {
  19727. $timeout(function() {
  19728. removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  19729. }, 0, false);
  19730. });
  19731. }
  19732. var parentFormCtrl = ctrls[1] || controller.$$parentForm;
  19733. parentFormCtrl.$addControl(controller);
  19734. var setter = nameAttr ? getSetter(controller.$name) : noop;
  19735. if (nameAttr) {
  19736. setter(scope, controller);
  19737. attr.$observe(nameAttr, function(newValue) {
  19738. if (controller.$name === newValue) return;
  19739. setter(scope, undefined);
  19740. controller.$$parentForm.$$renameControl(controller, newValue);
  19741. setter = getSetter(controller.$name);
  19742. setter(scope, controller);
  19743. });
  19744. }
  19745. formElement.on('$destroy', function() {
  19746. controller.$$parentForm.$removeControl(controller);
  19747. setter(scope, undefined);
  19748. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  19749. });
  19750. }
  19751. };
  19752. }
  19753. };
  19754. return formDirective;
  19755. function getSetter(expression) {
  19756. if (expression === '') {
  19757. //create an assignable expression, so forms with an empty name can be renamed later
  19758. return $parse('this[""]').assign;
  19759. }
  19760. return $parse(expression).assign || noop;
  19761. }
  19762. }];
  19763. };
  19764. var formDirective = formDirectiveFactory();
  19765. var ngFormDirective = formDirectiveFactory(true);
  19766. /* global VALID_CLASS: false,
  19767. INVALID_CLASS: false,
  19768. PRISTINE_CLASS: false,
  19769. DIRTY_CLASS: false,
  19770. UNTOUCHED_CLASS: false,
  19771. TOUCHED_CLASS: false,
  19772. ngModelMinErr: false,
  19773. */
  19774. // Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  19775. 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)$/;
  19776. // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
  19777. // Note: We are being more lenient, because browsers are too.
  19778. // 1. Scheme
  19779. // 2. Slashes
  19780. // 3. Username
  19781. // 4. Password
  19782. // 5. Hostname
  19783. // 6. Port
  19784. // 7. Path
  19785. // 8. Query
  19786. // 9. Fragment
  19787. // 1111111111111111 222 333333 44444 555555555555555555555555 666 77777777 8888888 999
  19788. var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+\])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
  19789. 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;
  19790. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
  19791. var DATE_REGEXP = /^(\d{4,})-(\d{2})-(\d{2})$/;
  19792. var DATETIMELOCAL_REGEXP = /^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  19793. var WEEK_REGEXP = /^(\d{4,})-W(\d\d)$/;
  19794. var MONTH_REGEXP = /^(\d{4,})-(\d\d)$/;
  19795. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  19796. var PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown';
  19797. var PARTIAL_VALIDATION_TYPES = createMap();
  19798. forEach('date,datetime-local,month,time,week'.split(','), function(type) {
  19799. PARTIAL_VALIDATION_TYPES[type] = true;
  19800. });
  19801. var inputType = {
  19802. /**
  19803. * @ngdoc input
  19804. * @name input[text]
  19805. *
  19806. * @description
  19807. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  19808. *
  19809. *
  19810. * @param {string} ngModel Assignable angular expression to data-bind to.
  19811. * @param {string=} name Property name of the form under which the control is published.
  19812. * @param {string=} required Adds `required` validation error key if the value is not entered.
  19813. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19814. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19815. * `required` when you want to data-bind to the `required` attribute.
  19816. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19817. * minlength.
  19818. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19819. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19820. * any length.
  19821. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19822. * that contains the regular expression body that will be converted to a regular expression
  19823. * as in the ngPattern directive.
  19824. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  19825. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  19826. * If the expression evaluates to a RegExp object, then this is used directly.
  19827. * If the expression evaluates to a string, then it will be converted to a RegExp
  19828. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19829. * `new RegExp('^abc$')`.<br />
  19830. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19831. * start at the index of the last search's match, thus not taking the whole input value into
  19832. * account.
  19833. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19834. * interaction with the input element.
  19835. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  19836. * This parameter is ignored for input[type=password] controls, which will never trim the
  19837. * input.
  19838. *
  19839. * @example
  19840. <example name="text-input-directive" module="textInputExample">
  19841. <file name="index.html">
  19842. <script>
  19843. angular.module('textInputExample', [])
  19844. .controller('ExampleController', ['$scope', function($scope) {
  19845. $scope.example = {
  19846. text: 'guest',
  19847. word: /^\s*\w*\s*$/
  19848. };
  19849. }]);
  19850. </script>
  19851. <form name="myForm" ng-controller="ExampleController">
  19852. <label>Single word:
  19853. <input type="text" name="input" ng-model="example.text"
  19854. ng-pattern="example.word" required ng-trim="false">
  19855. </label>
  19856. <div role="alert">
  19857. <span class="error" ng-show="myForm.input.$error.required">
  19858. Required!</span>
  19859. <span class="error" ng-show="myForm.input.$error.pattern">
  19860. Single word only!</span>
  19861. </div>
  19862. <tt>text = {{example.text}}</tt><br/>
  19863. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19864. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19865. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19866. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19867. </form>
  19868. </file>
  19869. <file name="protractor.js" type="protractor">
  19870. var text = element(by.binding('example.text'));
  19871. var valid = element(by.binding('myForm.input.$valid'));
  19872. var input = element(by.model('example.text'));
  19873. it('should initialize to model', function() {
  19874. expect(text.getText()).toContain('guest');
  19875. expect(valid.getText()).toContain('true');
  19876. });
  19877. it('should be invalid if empty', function() {
  19878. input.clear();
  19879. input.sendKeys('');
  19880. expect(text.getText()).toEqual('text =');
  19881. expect(valid.getText()).toContain('false');
  19882. });
  19883. it('should be invalid if multi word', function() {
  19884. input.clear();
  19885. input.sendKeys('hello world');
  19886. expect(valid.getText()).toContain('false');
  19887. });
  19888. </file>
  19889. </example>
  19890. */
  19891. 'text': textInputType,
  19892. /**
  19893. * @ngdoc input
  19894. * @name input[date]
  19895. *
  19896. * @description
  19897. * Input with date validation and transformation. In browsers that do not yet support
  19898. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  19899. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  19900. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  19901. * expected input format via a placeholder or label.
  19902. *
  19903. * The model must always be a Date object, otherwise Angular will throw an error.
  19904. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  19905. *
  19906. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  19907. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  19908. *
  19909. * @param {string} ngModel Assignable angular expression to data-bind to.
  19910. * @param {string=} name Property name of the form under which the control is published.
  19911. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  19912. * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  19913. * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
  19914. * constraint validation.
  19915. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  19916. * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  19917. * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
  19918. * constraint validation.
  19919. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
  19920. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  19921. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
  19922. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  19923. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19924. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19925. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19926. * `required` when you want to data-bind to the `required` attribute.
  19927. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19928. * interaction with the input element.
  19929. *
  19930. * @example
  19931. <example name="date-input-directive" module="dateInputExample">
  19932. <file name="index.html">
  19933. <script>
  19934. angular.module('dateInputExample', [])
  19935. .controller('DateController', ['$scope', function($scope) {
  19936. $scope.example = {
  19937. value: new Date(2013, 9, 22)
  19938. };
  19939. }]);
  19940. </script>
  19941. <form name="myForm" ng-controller="DateController as dateCtrl">
  19942. <label for="exampleInput">Pick a date in 2013:</label>
  19943. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  19944. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  19945. <div role="alert">
  19946. <span class="error" ng-show="myForm.input.$error.required">
  19947. Required!</span>
  19948. <span class="error" ng-show="myForm.input.$error.date">
  19949. Not a valid date!</span>
  19950. </div>
  19951. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  19952. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19953. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19954. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19955. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19956. </form>
  19957. </file>
  19958. <file name="protractor.js" type="protractor">
  19959. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  19960. var valid = element(by.binding('myForm.input.$valid'));
  19961. var input = element(by.model('example.value'));
  19962. // currently protractor/webdriver does not support
  19963. // sending keys to all known HTML5 input controls
  19964. // for various browsers (see https://github.com/angular/protractor/issues/562).
  19965. function setInput(val) {
  19966. // set the value of the element and force validation.
  19967. var scr = "var ipt = document.getElementById('exampleInput'); " +
  19968. "ipt.value = '" + val + "';" +
  19969. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  19970. browser.executeScript(scr);
  19971. }
  19972. it('should initialize to model', function() {
  19973. expect(value.getText()).toContain('2013-10-22');
  19974. expect(valid.getText()).toContain('myForm.input.$valid = true');
  19975. });
  19976. it('should be invalid if empty', function() {
  19977. setInput('');
  19978. expect(value.getText()).toEqual('value =');
  19979. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19980. });
  19981. it('should be invalid if over max', function() {
  19982. setInput('2015-01-01');
  19983. expect(value.getText()).toContain('');
  19984. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19985. });
  19986. </file>
  19987. </example>
  19988. */
  19989. 'date': createDateInputType('date', DATE_REGEXP,
  19990. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  19991. 'yyyy-MM-dd'),
  19992. /**
  19993. * @ngdoc input
  19994. * @name input[datetime-local]
  19995. *
  19996. * @description
  19997. * Input with datetime validation and transformation. In browsers that do not yet support
  19998. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  19999. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  20000. *
  20001. * The model must always be a Date object, otherwise Angular will throw an error.
  20002. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  20003. *
  20004. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  20005. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  20006. *
  20007. * @param {string} ngModel Assignable angular expression to data-bind to.
  20008. * @param {string=} name Property name of the form under which the control is published.
  20009. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  20010. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  20011. * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  20012. * Note that `min` will also add native HTML5 constraint validation.
  20013. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  20014. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  20015. * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  20016. * Note that `max` will also add native HTML5 constraint validation.
  20017. * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
  20018. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  20019. * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
  20020. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  20021. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20022. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20023. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20024. * `required` when you want to data-bind to the `required` attribute.
  20025. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20026. * interaction with the input element.
  20027. *
  20028. * @example
  20029. <example name="datetimelocal-input-directive" module="dateExample">
  20030. <file name="index.html">
  20031. <script>
  20032. angular.module('dateExample', [])
  20033. .controller('DateController', ['$scope', function($scope) {
  20034. $scope.example = {
  20035. value: new Date(2010, 11, 28, 14, 57)
  20036. };
  20037. }]);
  20038. </script>
  20039. <form name="myForm" ng-controller="DateController as dateCtrl">
  20040. <label for="exampleInput">Pick a date between in 2013:</label>
  20041. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  20042. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  20043. <div role="alert">
  20044. <span class="error" ng-show="myForm.input.$error.required">
  20045. Required!</span>
  20046. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  20047. Not a valid date!</span>
  20048. </div>
  20049. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  20050. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  20051. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  20052. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20053. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20054. </form>
  20055. </file>
  20056. <file name="protractor.js" type="protractor">
  20057. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  20058. var valid = element(by.binding('myForm.input.$valid'));
  20059. var input = element(by.model('example.value'));
  20060. // currently protractor/webdriver does not support
  20061. // sending keys to all known HTML5 input controls
  20062. // for various browsers (https://github.com/angular/protractor/issues/562).
  20063. function setInput(val) {
  20064. // set the value of the element and force validation.
  20065. var scr = "var ipt = document.getElementById('exampleInput'); " +
  20066. "ipt.value = '" + val + "';" +
  20067. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  20068. browser.executeScript(scr);
  20069. }
  20070. it('should initialize to model', function() {
  20071. expect(value.getText()).toContain('2010-12-28T14:57:00');
  20072. expect(valid.getText()).toContain('myForm.input.$valid = true');
  20073. });
  20074. it('should be invalid if empty', function() {
  20075. setInput('');
  20076. expect(value.getText()).toEqual('value =');
  20077. expect(valid.getText()).toContain('myForm.input.$valid = false');
  20078. });
  20079. it('should be invalid if over max', function() {
  20080. setInput('2015-01-01T23:59:00');
  20081. expect(value.getText()).toContain('');
  20082. expect(valid.getText()).toContain('myForm.input.$valid = false');
  20083. });
  20084. </file>
  20085. </example>
  20086. */
  20087. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  20088. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  20089. 'yyyy-MM-ddTHH:mm:ss.sss'),
  20090. /**
  20091. * @ngdoc input
  20092. * @name input[time]
  20093. *
  20094. * @description
  20095. * Input with time validation and transformation. In browsers that do not yet support
  20096. * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  20097. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  20098. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  20099. *
  20100. * The model must always be a Date object, otherwise Angular will throw an error.
  20101. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  20102. *
  20103. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  20104. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  20105. *
  20106. * @param {string} ngModel Assignable angular expression to data-bind to.
  20107. * @param {string=} name Property name of the form under which the control is published.
  20108. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  20109. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  20110. * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
  20111. * native HTML5 constraint validation.
  20112. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  20113. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  20114. * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
  20115. * native HTML5 constraint validation.
  20116. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
  20117. * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  20118. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
  20119. * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  20120. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20121. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20122. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20123. * `required` when you want to data-bind to the `required` attribute.
  20124. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20125. * interaction with the input element.
  20126. *
  20127. * @example
  20128. <example name="time-input-directive" module="timeExample">
  20129. <file name="index.html">
  20130. <script>
  20131. angular.module('timeExample', [])
  20132. .controller('DateController', ['$scope', function($scope) {
  20133. $scope.example = {
  20134. value: new Date(1970, 0, 1, 14, 57, 0)
  20135. };
  20136. }]);
  20137. </script>
  20138. <form name="myForm" ng-controller="DateController as dateCtrl">
  20139. <label for="exampleInput">Pick a time between 8am and 5pm:</label>
  20140. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  20141. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  20142. <div role="alert">
  20143. <span class="error" ng-show="myForm.input.$error.required">
  20144. Required!</span>
  20145. <span class="error" ng-show="myForm.input.$error.time">
  20146. Not a valid date!</span>
  20147. </div>
  20148. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  20149. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  20150. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  20151. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20152. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20153. </form>
  20154. </file>
  20155. <file name="protractor.js" type="protractor">
  20156. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  20157. var valid = element(by.binding('myForm.input.$valid'));
  20158. var input = element(by.model('example.value'));
  20159. // currently protractor/webdriver does not support
  20160. // sending keys to all known HTML5 input controls
  20161. // for various browsers (https://github.com/angular/protractor/issues/562).
  20162. function setInput(val) {
  20163. // set the value of the element and force validation.
  20164. var scr = "var ipt = document.getElementById('exampleInput'); " +
  20165. "ipt.value = '" + val + "';" +
  20166. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  20167. browser.executeScript(scr);
  20168. }
  20169. it('should initialize to model', function() {
  20170. expect(value.getText()).toContain('14:57:00');
  20171. expect(valid.getText()).toContain('myForm.input.$valid = true');
  20172. });
  20173. it('should be invalid if empty', function() {
  20174. setInput('');
  20175. expect(value.getText()).toEqual('value =');
  20176. expect(valid.getText()).toContain('myForm.input.$valid = false');
  20177. });
  20178. it('should be invalid if over max', function() {
  20179. setInput('23:59:00');
  20180. expect(value.getText()).toContain('');
  20181. expect(valid.getText()).toContain('myForm.input.$valid = false');
  20182. });
  20183. </file>
  20184. </example>
  20185. */
  20186. 'time': createDateInputType('time', TIME_REGEXP,
  20187. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  20188. 'HH:mm:ss.sss'),
  20189. /**
  20190. * @ngdoc input
  20191. * @name input[week]
  20192. *
  20193. * @description
  20194. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  20195. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  20196. * week format (yyyy-W##), for example: `2013-W02`.
  20197. *
  20198. * The model must always be a Date object, otherwise Angular will throw an error.
  20199. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  20200. *
  20201. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  20202. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  20203. *
  20204. * @param {string} ngModel Assignable angular expression to data-bind to.
  20205. * @param {string=} name Property name of the form under which the control is published.
  20206. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  20207. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  20208. * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
  20209. * native HTML5 constraint validation.
  20210. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  20211. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  20212. * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
  20213. * native HTML5 constraint validation.
  20214. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  20215. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  20216. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  20217. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  20218. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20219. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20220. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20221. * `required` when you want to data-bind to the `required` attribute.
  20222. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20223. * interaction with the input element.
  20224. *
  20225. * @example
  20226. <example name="week-input-directive" module="weekExample">
  20227. <file name="index.html">
  20228. <script>
  20229. angular.module('weekExample', [])
  20230. .controller('DateController', ['$scope', function($scope) {
  20231. $scope.example = {
  20232. value: new Date(2013, 0, 3)
  20233. };
  20234. }]);
  20235. </script>
  20236. <form name="myForm" ng-controller="DateController as dateCtrl">
  20237. <label>Pick a date between in 2013:
  20238. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  20239. placeholder="YYYY-W##" min="2012-W32"
  20240. max="2013-W52" required />
  20241. </label>
  20242. <div role="alert">
  20243. <span class="error" ng-show="myForm.input.$error.required">
  20244. Required!</span>
  20245. <span class="error" ng-show="myForm.input.$error.week">
  20246. Not a valid date!</span>
  20247. </div>
  20248. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  20249. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  20250. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  20251. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20252. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20253. </form>
  20254. </file>
  20255. <file name="protractor.js" type="protractor">
  20256. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  20257. var valid = element(by.binding('myForm.input.$valid'));
  20258. var input = element(by.model('example.value'));
  20259. // currently protractor/webdriver does not support
  20260. // sending keys to all known HTML5 input controls
  20261. // for various browsers (https://github.com/angular/protractor/issues/562).
  20262. function setInput(val) {
  20263. // set the value of the element and force validation.
  20264. var scr = "var ipt = document.getElementById('exampleInput'); " +
  20265. "ipt.value = '" + val + "';" +
  20266. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  20267. browser.executeScript(scr);
  20268. }
  20269. it('should initialize to model', function() {
  20270. expect(value.getText()).toContain('2013-W01');
  20271. expect(valid.getText()).toContain('myForm.input.$valid = true');
  20272. });
  20273. it('should be invalid if empty', function() {
  20274. setInput('');
  20275. expect(value.getText()).toEqual('value =');
  20276. expect(valid.getText()).toContain('myForm.input.$valid = false');
  20277. });
  20278. it('should be invalid if over max', function() {
  20279. setInput('2015-W01');
  20280. expect(value.getText()).toContain('');
  20281. expect(valid.getText()).toContain('myForm.input.$valid = false');
  20282. });
  20283. </file>
  20284. </example>
  20285. */
  20286. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  20287. /**
  20288. * @ngdoc input
  20289. * @name input[month]
  20290. *
  20291. * @description
  20292. * Input with month validation and transformation. In browsers that do not yet support
  20293. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  20294. * month format (yyyy-MM), for example: `2009-01`.
  20295. *
  20296. * The model must always be a Date object, otherwise Angular will throw an error.
  20297. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  20298. * If the model is not set to the first of the month, the next view to model update will set it
  20299. * to the first of the month.
  20300. *
  20301. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  20302. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  20303. *
  20304. * @param {string} ngModel Assignable angular expression to data-bind to.
  20305. * @param {string=} name Property name of the form under which the control is published.
  20306. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  20307. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  20308. * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
  20309. * native HTML5 constraint validation.
  20310. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  20311. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  20312. * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
  20313. * native HTML5 constraint validation.
  20314. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  20315. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  20316. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  20317. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  20318. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20319. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20320. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20321. * `required` when you want to data-bind to the `required` attribute.
  20322. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20323. * interaction with the input element.
  20324. *
  20325. * @example
  20326. <example name="month-input-directive" module="monthExample">
  20327. <file name="index.html">
  20328. <script>
  20329. angular.module('monthExample', [])
  20330. .controller('DateController', ['$scope', function($scope) {
  20331. $scope.example = {
  20332. value: new Date(2013, 9, 1)
  20333. };
  20334. }]);
  20335. </script>
  20336. <form name="myForm" ng-controller="DateController as dateCtrl">
  20337. <label for="exampleInput">Pick a month in 2013:</label>
  20338. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  20339. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  20340. <div role="alert">
  20341. <span class="error" ng-show="myForm.input.$error.required">
  20342. Required!</span>
  20343. <span class="error" ng-show="myForm.input.$error.month">
  20344. Not a valid month!</span>
  20345. </div>
  20346. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  20347. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  20348. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  20349. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20350. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20351. </form>
  20352. </file>
  20353. <file name="protractor.js" type="protractor">
  20354. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  20355. var valid = element(by.binding('myForm.input.$valid'));
  20356. var input = element(by.model('example.value'));
  20357. // currently protractor/webdriver does not support
  20358. // sending keys to all known HTML5 input controls
  20359. // for various browsers (https://github.com/angular/protractor/issues/562).
  20360. function setInput(val) {
  20361. // set the value of the element and force validation.
  20362. var scr = "var ipt = document.getElementById('exampleInput'); " +
  20363. "ipt.value = '" + val + "';" +
  20364. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  20365. browser.executeScript(scr);
  20366. }
  20367. it('should initialize to model', function() {
  20368. expect(value.getText()).toContain('2013-10');
  20369. expect(valid.getText()).toContain('myForm.input.$valid = true');
  20370. });
  20371. it('should be invalid if empty', function() {
  20372. setInput('');
  20373. expect(value.getText()).toEqual('value =');
  20374. expect(valid.getText()).toContain('myForm.input.$valid = false');
  20375. });
  20376. it('should be invalid if over max', function() {
  20377. setInput('2015-01');
  20378. expect(value.getText()).toContain('');
  20379. expect(valid.getText()).toContain('myForm.input.$valid = false');
  20380. });
  20381. </file>
  20382. </example>
  20383. */
  20384. 'month': createDateInputType('month', MONTH_REGEXP,
  20385. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  20386. 'yyyy-MM'),
  20387. /**
  20388. * @ngdoc input
  20389. * @name input[number]
  20390. *
  20391. * @description
  20392. * Text input with number validation and transformation. Sets the `number` validation
  20393. * error if not a valid number.
  20394. *
  20395. * <div class="alert alert-warning">
  20396. * The model must always be of type `number` otherwise Angular will throw an error.
  20397. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  20398. * error docs for more information and an example of how to convert your model if necessary.
  20399. * </div>
  20400. *
  20401. * ## Issues with HTML5 constraint validation
  20402. *
  20403. * In browsers that follow the
  20404. * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
  20405. * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
  20406. * If a non-number is entered in the input, the browser will report the value as an empty string,
  20407. * which means the view / model values in `ngModel` and subsequently the scope value
  20408. * will also be an empty string.
  20409. *
  20410. *
  20411. * @param {string} ngModel Assignable angular expression to data-bind to.
  20412. * @param {string=} name Property name of the form under which the control is published.
  20413. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  20414. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  20415. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20416. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20417. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20418. * `required` when you want to data-bind to the `required` attribute.
  20419. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  20420. * minlength.
  20421. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  20422. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  20423. * any length.
  20424. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  20425. * that contains the regular expression body that will be converted to a regular expression
  20426. * as in the ngPattern directive.
  20427. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  20428. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  20429. * If the expression evaluates to a RegExp object, then this is used directly.
  20430. * If the expression evaluates to a string, then it will be converted to a RegExp
  20431. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  20432. * `new RegExp('^abc$')`.<br />
  20433. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  20434. * start at the index of the last search's match, thus not taking the whole input value into
  20435. * account.
  20436. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20437. * interaction with the input element.
  20438. *
  20439. * @example
  20440. <example name="number-input-directive" module="numberExample">
  20441. <file name="index.html">
  20442. <script>
  20443. angular.module('numberExample', [])
  20444. .controller('ExampleController', ['$scope', function($scope) {
  20445. $scope.example = {
  20446. value: 12
  20447. };
  20448. }]);
  20449. </script>
  20450. <form name="myForm" ng-controller="ExampleController">
  20451. <label>Number:
  20452. <input type="number" name="input" ng-model="example.value"
  20453. min="0" max="99" required>
  20454. </label>
  20455. <div role="alert">
  20456. <span class="error" ng-show="myForm.input.$error.required">
  20457. Required!</span>
  20458. <span class="error" ng-show="myForm.input.$error.number">
  20459. Not valid number!</span>
  20460. </div>
  20461. <tt>value = {{example.value}}</tt><br/>
  20462. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  20463. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  20464. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20465. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20466. </form>
  20467. </file>
  20468. <file name="protractor.js" type="protractor">
  20469. var value = element(by.binding('example.value'));
  20470. var valid = element(by.binding('myForm.input.$valid'));
  20471. var input = element(by.model('example.value'));
  20472. it('should initialize to model', function() {
  20473. expect(value.getText()).toContain('12');
  20474. expect(valid.getText()).toContain('true');
  20475. });
  20476. it('should be invalid if empty', function() {
  20477. input.clear();
  20478. input.sendKeys('');
  20479. expect(value.getText()).toEqual('value =');
  20480. expect(valid.getText()).toContain('false');
  20481. });
  20482. it('should be invalid if over max', function() {
  20483. input.clear();
  20484. input.sendKeys('123');
  20485. expect(value.getText()).toEqual('value =');
  20486. expect(valid.getText()).toContain('false');
  20487. });
  20488. </file>
  20489. </example>
  20490. */
  20491. 'number': numberInputType,
  20492. /**
  20493. * @ngdoc input
  20494. * @name input[url]
  20495. *
  20496. * @description
  20497. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  20498. * valid URL.
  20499. *
  20500. * <div class="alert alert-warning">
  20501. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  20502. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  20503. * the built-in validators (see the {@link guide/forms Forms guide})
  20504. * </div>
  20505. *
  20506. * @param {string} ngModel Assignable angular expression to data-bind to.
  20507. * @param {string=} name Property name of the form under which the control is published.
  20508. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20509. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20510. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20511. * `required` when you want to data-bind to the `required` attribute.
  20512. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  20513. * minlength.
  20514. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  20515. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  20516. * any length.
  20517. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  20518. * that contains the regular expression body that will be converted to a regular expression
  20519. * as in the ngPattern directive.
  20520. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  20521. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  20522. * If the expression evaluates to a RegExp object, then this is used directly.
  20523. * If the expression evaluates to a string, then it will be converted to a RegExp
  20524. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  20525. * `new RegExp('^abc$')`.<br />
  20526. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  20527. * start at the index of the last search's match, thus not taking the whole input value into
  20528. * account.
  20529. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20530. * interaction with the input element.
  20531. *
  20532. * @example
  20533. <example name="url-input-directive" module="urlExample">
  20534. <file name="index.html">
  20535. <script>
  20536. angular.module('urlExample', [])
  20537. .controller('ExampleController', ['$scope', function($scope) {
  20538. $scope.url = {
  20539. text: 'http://google.com'
  20540. };
  20541. }]);
  20542. </script>
  20543. <form name="myForm" ng-controller="ExampleController">
  20544. <label>URL:
  20545. <input type="url" name="input" ng-model="url.text" required>
  20546. <label>
  20547. <div role="alert">
  20548. <span class="error" ng-show="myForm.input.$error.required">
  20549. Required!</span>
  20550. <span class="error" ng-show="myForm.input.$error.url">
  20551. Not valid url!</span>
  20552. </div>
  20553. <tt>text = {{url.text}}</tt><br/>
  20554. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  20555. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  20556. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20557. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20558. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  20559. </form>
  20560. </file>
  20561. <file name="protractor.js" type="protractor">
  20562. var text = element(by.binding('url.text'));
  20563. var valid = element(by.binding('myForm.input.$valid'));
  20564. var input = element(by.model('url.text'));
  20565. it('should initialize to model', function() {
  20566. expect(text.getText()).toContain('http://google.com');
  20567. expect(valid.getText()).toContain('true');
  20568. });
  20569. it('should be invalid if empty', function() {
  20570. input.clear();
  20571. input.sendKeys('');
  20572. expect(text.getText()).toEqual('text =');
  20573. expect(valid.getText()).toContain('false');
  20574. });
  20575. it('should be invalid if not url', function() {
  20576. input.clear();
  20577. input.sendKeys('box');
  20578. expect(valid.getText()).toContain('false');
  20579. });
  20580. </file>
  20581. </example>
  20582. */
  20583. 'url': urlInputType,
  20584. /**
  20585. * @ngdoc input
  20586. * @name input[email]
  20587. *
  20588. * @description
  20589. * Text input with email validation. Sets the `email` validation error key if not a valid email
  20590. * address.
  20591. *
  20592. * <div class="alert alert-warning">
  20593. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  20594. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  20595. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  20596. * </div>
  20597. *
  20598. * @param {string} ngModel Assignable angular expression to data-bind to.
  20599. * @param {string=} name Property name of the form under which the control is published.
  20600. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20601. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20602. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20603. * `required` when you want to data-bind to the `required` attribute.
  20604. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  20605. * minlength.
  20606. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  20607. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  20608. * any length.
  20609. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  20610. * that contains the regular expression body that will be converted to a regular expression
  20611. * as in the ngPattern directive.
  20612. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  20613. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  20614. * If the expression evaluates to a RegExp object, then this is used directly.
  20615. * If the expression evaluates to a string, then it will be converted to a RegExp
  20616. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  20617. * `new RegExp('^abc$')`.<br />
  20618. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  20619. * start at the index of the last search's match, thus not taking the whole input value into
  20620. * account.
  20621. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20622. * interaction with the input element.
  20623. *
  20624. * @example
  20625. <example name="email-input-directive" module="emailExample">
  20626. <file name="index.html">
  20627. <script>
  20628. angular.module('emailExample', [])
  20629. .controller('ExampleController', ['$scope', function($scope) {
  20630. $scope.email = {
  20631. text: 'me@example.com'
  20632. };
  20633. }]);
  20634. </script>
  20635. <form name="myForm" ng-controller="ExampleController">
  20636. <label>Email:
  20637. <input type="email" name="input" ng-model="email.text" required>
  20638. </label>
  20639. <div role="alert">
  20640. <span class="error" ng-show="myForm.input.$error.required">
  20641. Required!</span>
  20642. <span class="error" ng-show="myForm.input.$error.email">
  20643. Not valid email!</span>
  20644. </div>
  20645. <tt>text = {{email.text}}</tt><br/>
  20646. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  20647. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  20648. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20649. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20650. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  20651. </form>
  20652. </file>
  20653. <file name="protractor.js" type="protractor">
  20654. var text = element(by.binding('email.text'));
  20655. var valid = element(by.binding('myForm.input.$valid'));
  20656. var input = element(by.model('email.text'));
  20657. it('should initialize to model', function() {
  20658. expect(text.getText()).toContain('me@example.com');
  20659. expect(valid.getText()).toContain('true');
  20660. });
  20661. it('should be invalid if empty', function() {
  20662. input.clear();
  20663. input.sendKeys('');
  20664. expect(text.getText()).toEqual('text =');
  20665. expect(valid.getText()).toContain('false');
  20666. });
  20667. it('should be invalid if not email', function() {
  20668. input.clear();
  20669. input.sendKeys('xxx');
  20670. expect(valid.getText()).toContain('false');
  20671. });
  20672. </file>
  20673. </example>
  20674. */
  20675. 'email': emailInputType,
  20676. /**
  20677. * @ngdoc input
  20678. * @name input[radio]
  20679. *
  20680. * @description
  20681. * HTML radio button.
  20682. *
  20683. * @param {string} ngModel Assignable angular expression to data-bind to.
  20684. * @param {string} value The value to which the `ngModel` expression should be set when selected.
  20685. * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
  20686. * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
  20687. * @param {string=} name Property name of the form under which the control is published.
  20688. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20689. * interaction with the input element.
  20690. * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
  20691. * is selected. Should be used instead of the `value` attribute if you need
  20692. * a non-string `ngModel` (`boolean`, `array`, ...).
  20693. *
  20694. * @example
  20695. <example name="radio-input-directive" module="radioExample">
  20696. <file name="index.html">
  20697. <script>
  20698. angular.module('radioExample', [])
  20699. .controller('ExampleController', ['$scope', function($scope) {
  20700. $scope.color = {
  20701. name: 'blue'
  20702. };
  20703. $scope.specialValue = {
  20704. "id": "12345",
  20705. "value": "green"
  20706. };
  20707. }]);
  20708. </script>
  20709. <form name="myForm" ng-controller="ExampleController">
  20710. <label>
  20711. <input type="radio" ng-model="color.name" value="red">
  20712. Red
  20713. </label><br/>
  20714. <label>
  20715. <input type="radio" ng-model="color.name" ng-value="specialValue">
  20716. Green
  20717. </label><br/>
  20718. <label>
  20719. <input type="radio" ng-model="color.name" value="blue">
  20720. Blue
  20721. </label><br/>
  20722. <tt>color = {{color.name | json}}</tt><br/>
  20723. </form>
  20724. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  20725. </file>
  20726. <file name="protractor.js" type="protractor">
  20727. it('should change state', function() {
  20728. var color = element(by.binding('color.name'));
  20729. expect(color.getText()).toContain('blue');
  20730. element.all(by.model('color.name')).get(0).click();
  20731. expect(color.getText()).toContain('red');
  20732. });
  20733. </file>
  20734. </example>
  20735. */
  20736. 'radio': radioInputType,
  20737. /**
  20738. * @ngdoc input
  20739. * @name input[checkbox]
  20740. *
  20741. * @description
  20742. * HTML checkbox.
  20743. *
  20744. * @param {string} ngModel Assignable angular expression to data-bind to.
  20745. * @param {string=} name Property name of the form under which the control is published.
  20746. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  20747. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  20748. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20749. * interaction with the input element.
  20750. *
  20751. * @example
  20752. <example name="checkbox-input-directive" module="checkboxExample">
  20753. <file name="index.html">
  20754. <script>
  20755. angular.module('checkboxExample', [])
  20756. .controller('ExampleController', ['$scope', function($scope) {
  20757. $scope.checkboxModel = {
  20758. value1 : true,
  20759. value2 : 'YES'
  20760. };
  20761. }]);
  20762. </script>
  20763. <form name="myForm" ng-controller="ExampleController">
  20764. <label>Value1:
  20765. <input type="checkbox" ng-model="checkboxModel.value1">
  20766. </label><br/>
  20767. <label>Value2:
  20768. <input type="checkbox" ng-model="checkboxModel.value2"
  20769. ng-true-value="'YES'" ng-false-value="'NO'">
  20770. </label><br/>
  20771. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  20772. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  20773. </form>
  20774. </file>
  20775. <file name="protractor.js" type="protractor">
  20776. it('should change state', function() {
  20777. var value1 = element(by.binding('checkboxModel.value1'));
  20778. var value2 = element(by.binding('checkboxModel.value2'));
  20779. expect(value1.getText()).toContain('true');
  20780. expect(value2.getText()).toContain('YES');
  20781. element(by.model('checkboxModel.value1')).click();
  20782. element(by.model('checkboxModel.value2')).click();
  20783. expect(value1.getText()).toContain('false');
  20784. expect(value2.getText()).toContain('NO');
  20785. });
  20786. </file>
  20787. </example>
  20788. */
  20789. 'checkbox': checkboxInputType,
  20790. 'hidden': noop,
  20791. 'button': noop,
  20792. 'submit': noop,
  20793. 'reset': noop,
  20794. 'file': noop
  20795. };
  20796. function stringBasedInputType(ctrl) {
  20797. ctrl.$formatters.push(function(value) {
  20798. return ctrl.$isEmpty(value) ? value : value.toString();
  20799. });
  20800. }
  20801. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  20802. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  20803. stringBasedInputType(ctrl);
  20804. }
  20805. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  20806. var type = lowercase(element[0].type);
  20807. // In composition mode, users are still inputing intermediate text buffer,
  20808. // hold the listener until composition is done.
  20809. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  20810. if (!$sniffer.android) {
  20811. var composing = false;
  20812. element.on('compositionstart', function() {
  20813. composing = true;
  20814. });
  20815. element.on('compositionend', function() {
  20816. composing = false;
  20817. listener();
  20818. });
  20819. }
  20820. var timeout;
  20821. var listener = function(ev) {
  20822. if (timeout) {
  20823. $browser.defer.cancel(timeout);
  20824. timeout = null;
  20825. }
  20826. if (composing) return;
  20827. var value = element.val(),
  20828. event = ev && ev.type;
  20829. // By default we will trim the value
  20830. // If the attribute ng-trim exists we will avoid trimming
  20831. // If input type is 'password', the value is never trimmed
  20832. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  20833. value = trim(value);
  20834. }
  20835. // If a control is suffering from bad input (due to native validators), browsers discard its
  20836. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  20837. // control's value is the same empty value twice in a row.
  20838. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  20839. ctrl.$setViewValue(value, event);
  20840. }
  20841. };
  20842. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  20843. // input event on backspace, delete or cut
  20844. if ($sniffer.hasEvent('input')) {
  20845. element.on('input', listener);
  20846. } else {
  20847. var deferListener = function(ev, input, origValue) {
  20848. if (!timeout) {
  20849. timeout = $browser.defer(function() {
  20850. timeout = null;
  20851. if (!input || input.value !== origValue) {
  20852. listener(ev);
  20853. }
  20854. });
  20855. }
  20856. };
  20857. element.on('keydown', function(event) {
  20858. var key = event.keyCode;
  20859. // ignore
  20860. // command modifiers arrows
  20861. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  20862. deferListener(event, this, this.value);
  20863. });
  20864. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  20865. if ($sniffer.hasEvent('paste')) {
  20866. element.on('paste cut', deferListener);
  20867. }
  20868. }
  20869. // if user paste into input using mouse on older browser
  20870. // or form autocomplete on newer browser, we need "change" event to catch it
  20871. element.on('change', listener);
  20872. // Some native input types (date-family) have the ability to change validity without
  20873. // firing any input/change events.
  20874. // For these event types, when native validators are present and the browser supports the type,
  20875. // check for validity changes on various DOM events.
  20876. if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) {
  20877. element.on(PARTIAL_VALIDATION_EVENTS, function(ev) {
  20878. if (!timeout) {
  20879. var validity = this[VALIDITY_STATE_PROPERTY];
  20880. var origBadInput = validity.badInput;
  20881. var origTypeMismatch = validity.typeMismatch;
  20882. timeout = $browser.defer(function() {
  20883. timeout = null;
  20884. if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) {
  20885. listener(ev);
  20886. }
  20887. });
  20888. }
  20889. });
  20890. }
  20891. ctrl.$render = function() {
  20892. // Workaround for Firefox validation #12102.
  20893. var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
  20894. if (element.val() !== value) {
  20895. element.val(value);
  20896. }
  20897. };
  20898. }
  20899. function weekParser(isoWeek, existingDate) {
  20900. if (isDate(isoWeek)) {
  20901. return isoWeek;
  20902. }
  20903. if (isString(isoWeek)) {
  20904. WEEK_REGEXP.lastIndex = 0;
  20905. var parts = WEEK_REGEXP.exec(isoWeek);
  20906. if (parts) {
  20907. var year = +parts[1],
  20908. week = +parts[2],
  20909. hours = 0,
  20910. minutes = 0,
  20911. seconds = 0,
  20912. milliseconds = 0,
  20913. firstThurs = getFirstThursdayOfYear(year),
  20914. addDays = (week - 1) * 7;
  20915. if (existingDate) {
  20916. hours = existingDate.getHours();
  20917. minutes = existingDate.getMinutes();
  20918. seconds = existingDate.getSeconds();
  20919. milliseconds = existingDate.getMilliseconds();
  20920. }
  20921. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  20922. }
  20923. }
  20924. return NaN;
  20925. }
  20926. function createDateParser(regexp, mapping) {
  20927. return function(iso, date) {
  20928. var parts, map;
  20929. if (isDate(iso)) {
  20930. return iso;
  20931. }
  20932. if (isString(iso)) {
  20933. // When a date is JSON'ified to wraps itself inside of an extra
  20934. // set of double quotes. This makes the date parsing code unable
  20935. // to match the date string and parse it as a date.
  20936. if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
  20937. iso = iso.substring(1, iso.length - 1);
  20938. }
  20939. if (ISO_DATE_REGEXP.test(iso)) {
  20940. return new Date(iso);
  20941. }
  20942. regexp.lastIndex = 0;
  20943. parts = regexp.exec(iso);
  20944. if (parts) {
  20945. parts.shift();
  20946. if (date) {
  20947. map = {
  20948. yyyy: date.getFullYear(),
  20949. MM: date.getMonth() + 1,
  20950. dd: date.getDate(),
  20951. HH: date.getHours(),
  20952. mm: date.getMinutes(),
  20953. ss: date.getSeconds(),
  20954. sss: date.getMilliseconds() / 1000
  20955. };
  20956. } else {
  20957. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  20958. }
  20959. forEach(parts, function(part, index) {
  20960. if (index < mapping.length) {
  20961. map[mapping[index]] = +part;
  20962. }
  20963. });
  20964. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  20965. }
  20966. }
  20967. return NaN;
  20968. };
  20969. }
  20970. function createDateInputType(type, regexp, parseDate, format) {
  20971. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  20972. badInputChecker(scope, element, attr, ctrl);
  20973. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  20974. var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
  20975. var previousDate;
  20976. ctrl.$$parserName = type;
  20977. ctrl.$parsers.push(function(value) {
  20978. if (ctrl.$isEmpty(value)) return null;
  20979. if (regexp.test(value)) {
  20980. // Note: We cannot read ctrl.$modelValue, as there might be a different
  20981. // parser/formatter in the processing chain so that the model
  20982. // contains some different data format!
  20983. var parsedDate = parseDate(value, previousDate);
  20984. if (timezone) {
  20985. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  20986. }
  20987. return parsedDate;
  20988. }
  20989. return undefined;
  20990. });
  20991. ctrl.$formatters.push(function(value) {
  20992. if (value && !isDate(value)) {
  20993. throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  20994. }
  20995. if (isValidDate(value)) {
  20996. previousDate = value;
  20997. if (previousDate && timezone) {
  20998. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  20999. }
  21000. return $filter('date')(value, format, timezone);
  21001. } else {
  21002. previousDate = null;
  21003. return '';
  21004. }
  21005. });
  21006. if (isDefined(attr.min) || attr.ngMin) {
  21007. var minVal;
  21008. ctrl.$validators.min = function(value) {
  21009. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  21010. };
  21011. attr.$observe('min', function(val) {
  21012. minVal = parseObservedDateValue(val);
  21013. ctrl.$validate();
  21014. });
  21015. }
  21016. if (isDefined(attr.max) || attr.ngMax) {
  21017. var maxVal;
  21018. ctrl.$validators.max = function(value) {
  21019. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  21020. };
  21021. attr.$observe('max', function(val) {
  21022. maxVal = parseObservedDateValue(val);
  21023. ctrl.$validate();
  21024. });
  21025. }
  21026. function isValidDate(value) {
  21027. // Invalid Date: getTime() returns NaN
  21028. return value && !(value.getTime && value.getTime() !== value.getTime());
  21029. }
  21030. function parseObservedDateValue(val) {
  21031. return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
  21032. }
  21033. };
  21034. }
  21035. function badInputChecker(scope, element, attr, ctrl) {
  21036. var node = element[0];
  21037. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  21038. if (nativeValidation) {
  21039. ctrl.$parsers.push(function(value) {
  21040. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  21041. return validity.badInput || validity.typeMismatch ? undefined : value;
  21042. });
  21043. }
  21044. }
  21045. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  21046. badInputChecker(scope, element, attr, ctrl);
  21047. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  21048. ctrl.$$parserName = 'number';
  21049. ctrl.$parsers.push(function(value) {
  21050. if (ctrl.$isEmpty(value)) return null;
  21051. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  21052. return undefined;
  21053. });
  21054. ctrl.$formatters.push(function(value) {
  21055. if (!ctrl.$isEmpty(value)) {
  21056. if (!isNumber(value)) {
  21057. throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  21058. }
  21059. value = value.toString();
  21060. }
  21061. return value;
  21062. });
  21063. if (isDefined(attr.min) || attr.ngMin) {
  21064. var minVal;
  21065. ctrl.$validators.min = function(value) {
  21066. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  21067. };
  21068. attr.$observe('min', function(val) {
  21069. if (isDefined(val) && !isNumber(val)) {
  21070. val = parseFloat(val, 10);
  21071. }
  21072. minVal = isNumber(val) && !isNaN(val) ? val : undefined;
  21073. // TODO(matsko): implement validateLater to reduce number of validations
  21074. ctrl.$validate();
  21075. });
  21076. }
  21077. if (isDefined(attr.max) || attr.ngMax) {
  21078. var maxVal;
  21079. ctrl.$validators.max = function(value) {
  21080. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  21081. };
  21082. attr.$observe('max', function(val) {
  21083. if (isDefined(val) && !isNumber(val)) {
  21084. val = parseFloat(val, 10);
  21085. }
  21086. maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
  21087. // TODO(matsko): implement validateLater to reduce number of validations
  21088. ctrl.$validate();
  21089. });
  21090. }
  21091. }
  21092. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  21093. // Note: no badInputChecker here by purpose as `url` is only a validation
  21094. // in browsers, i.e. we can always read out input.value even if it is not valid!
  21095. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  21096. stringBasedInputType(ctrl);
  21097. ctrl.$$parserName = 'url';
  21098. ctrl.$validators.url = function(modelValue, viewValue) {
  21099. var value = modelValue || viewValue;
  21100. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  21101. };
  21102. }
  21103. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  21104. // Note: no badInputChecker here by purpose as `url` is only a validation
  21105. // in browsers, i.e. we can always read out input.value even if it is not valid!
  21106. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  21107. stringBasedInputType(ctrl);
  21108. ctrl.$$parserName = 'email';
  21109. ctrl.$validators.email = function(modelValue, viewValue) {
  21110. var value = modelValue || viewValue;
  21111. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  21112. };
  21113. }
  21114. function radioInputType(scope, element, attr, ctrl) {
  21115. // make the name unique, if not defined
  21116. if (isUndefined(attr.name)) {
  21117. element.attr('name', nextUid());
  21118. }
  21119. var listener = function(ev) {
  21120. if (element[0].checked) {
  21121. ctrl.$setViewValue(attr.value, ev && ev.type);
  21122. }
  21123. };
  21124. element.on('click', listener);
  21125. ctrl.$render = function() {
  21126. var value = attr.value;
  21127. element[0].checked = (value == ctrl.$viewValue);
  21128. };
  21129. attr.$observe('value', ctrl.$render);
  21130. }
  21131. function parseConstantExpr($parse, context, name, expression, fallback) {
  21132. var parseFn;
  21133. if (isDefined(expression)) {
  21134. parseFn = $parse(expression);
  21135. if (!parseFn.constant) {
  21136. throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  21137. '`{1}`.', name, expression);
  21138. }
  21139. return parseFn(context);
  21140. }
  21141. return fallback;
  21142. }
  21143. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  21144. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  21145. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  21146. var listener = function(ev) {
  21147. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  21148. };
  21149. element.on('click', listener);
  21150. ctrl.$render = function() {
  21151. element[0].checked = ctrl.$viewValue;
  21152. };
  21153. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  21154. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  21155. // it to a boolean.
  21156. ctrl.$isEmpty = function(value) {
  21157. return value === false;
  21158. };
  21159. ctrl.$formatters.push(function(value) {
  21160. return equals(value, trueValue);
  21161. });
  21162. ctrl.$parsers.push(function(value) {
  21163. return value ? trueValue : falseValue;
  21164. });
  21165. }
  21166. /**
  21167. * @ngdoc directive
  21168. * @name textarea
  21169. * @restrict E
  21170. *
  21171. * @description
  21172. * HTML textarea element control with angular data-binding. The data-binding and validation
  21173. * properties of this element are exactly the same as those of the
  21174. * {@link ng.directive:input input element}.
  21175. *
  21176. * @param {string} ngModel Assignable angular expression to data-bind to.
  21177. * @param {string=} name Property name of the form under which the control is published.
  21178. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21179. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21180. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21181. * `required` when you want to data-bind to the `required` attribute.
  21182. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21183. * minlength.
  21184. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21185. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  21186. * length.
  21187. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21188. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21189. * If the expression evaluates to a RegExp object, then this is used directly.
  21190. * If the expression evaluates to a string, then it will be converted to a RegExp
  21191. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21192. * `new RegExp('^abc$')`.<br />
  21193. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21194. * start at the index of the last search's match, thus not taking the whole input value into
  21195. * account.
  21196. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21197. * interaction with the input element.
  21198. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  21199. */
  21200. /**
  21201. * @ngdoc directive
  21202. * @name input
  21203. * @restrict E
  21204. *
  21205. * @description
  21206. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  21207. * input state control, and validation.
  21208. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  21209. *
  21210. * <div class="alert alert-warning">
  21211. * **Note:** Not every feature offered is available for all input types.
  21212. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  21213. * </div>
  21214. *
  21215. * @param {string} ngModel Assignable angular expression to data-bind to.
  21216. * @param {string=} name Property name of the form under which the control is published.
  21217. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21218. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  21219. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21220. * minlength.
  21221. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21222. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  21223. * length.
  21224. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21225. * value does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21226. * If the expression evaluates to a RegExp object, then this is used directly.
  21227. * If the expression evaluates to a string, then it will be converted to a RegExp
  21228. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21229. * `new RegExp('^abc$')`.<br />
  21230. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21231. * start at the index of the last search's match, thus not taking the whole input value into
  21232. * account.
  21233. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21234. * interaction with the input element.
  21235. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  21236. * This parameter is ignored for input[type=password] controls, which will never trim the
  21237. * input.
  21238. *
  21239. * @example
  21240. <example name="input-directive" module="inputExample">
  21241. <file name="index.html">
  21242. <script>
  21243. angular.module('inputExample', [])
  21244. .controller('ExampleController', ['$scope', function($scope) {
  21245. $scope.user = {name: 'guest', last: 'visitor'};
  21246. }]);
  21247. </script>
  21248. <div ng-controller="ExampleController">
  21249. <form name="myForm">
  21250. <label>
  21251. User name:
  21252. <input type="text" name="userName" ng-model="user.name" required>
  21253. </label>
  21254. <div role="alert">
  21255. <span class="error" ng-show="myForm.userName.$error.required">
  21256. Required!</span>
  21257. </div>
  21258. <label>
  21259. Last name:
  21260. <input type="text" name="lastName" ng-model="user.last"
  21261. ng-minlength="3" ng-maxlength="10">
  21262. </label>
  21263. <div role="alert">
  21264. <span class="error" ng-show="myForm.lastName.$error.minlength">
  21265. Too short!</span>
  21266. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  21267. Too long!</span>
  21268. </div>
  21269. </form>
  21270. <hr>
  21271. <tt>user = {{user}}</tt><br/>
  21272. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  21273. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  21274. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  21275. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  21276. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21277. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21278. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  21279. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  21280. </div>
  21281. </file>
  21282. <file name="protractor.js" type="protractor">
  21283. var user = element(by.exactBinding('user'));
  21284. var userNameValid = element(by.binding('myForm.userName.$valid'));
  21285. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  21286. var lastNameError = element(by.binding('myForm.lastName.$error'));
  21287. var formValid = element(by.binding('myForm.$valid'));
  21288. var userNameInput = element(by.model('user.name'));
  21289. var userLastInput = element(by.model('user.last'));
  21290. it('should initialize to model', function() {
  21291. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  21292. expect(userNameValid.getText()).toContain('true');
  21293. expect(formValid.getText()).toContain('true');
  21294. });
  21295. it('should be invalid if empty when required', function() {
  21296. userNameInput.clear();
  21297. userNameInput.sendKeys('');
  21298. expect(user.getText()).toContain('{"last":"visitor"}');
  21299. expect(userNameValid.getText()).toContain('false');
  21300. expect(formValid.getText()).toContain('false');
  21301. });
  21302. it('should be valid if empty when min length is set', function() {
  21303. userLastInput.clear();
  21304. userLastInput.sendKeys('');
  21305. expect(user.getText()).toContain('{"name":"guest","last":""}');
  21306. expect(lastNameValid.getText()).toContain('true');
  21307. expect(formValid.getText()).toContain('true');
  21308. });
  21309. it('should be invalid if less than required min length', function() {
  21310. userLastInput.clear();
  21311. userLastInput.sendKeys('xx');
  21312. expect(user.getText()).toContain('{"name":"guest"}');
  21313. expect(lastNameValid.getText()).toContain('false');
  21314. expect(lastNameError.getText()).toContain('minlength');
  21315. expect(formValid.getText()).toContain('false');
  21316. });
  21317. it('should be invalid if longer than max length', function() {
  21318. userLastInput.clear();
  21319. userLastInput.sendKeys('some ridiculously long name');
  21320. expect(user.getText()).toContain('{"name":"guest"}');
  21321. expect(lastNameValid.getText()).toContain('false');
  21322. expect(lastNameError.getText()).toContain('maxlength');
  21323. expect(formValid.getText()).toContain('false');
  21324. });
  21325. </file>
  21326. </example>
  21327. */
  21328. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  21329. function($browser, $sniffer, $filter, $parse) {
  21330. return {
  21331. restrict: 'E',
  21332. require: ['?ngModel'],
  21333. link: {
  21334. pre: function(scope, element, attr, ctrls) {
  21335. if (ctrls[0]) {
  21336. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  21337. $browser, $filter, $parse);
  21338. }
  21339. }
  21340. }
  21341. };
  21342. }];
  21343. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  21344. /**
  21345. * @ngdoc directive
  21346. * @name ngValue
  21347. *
  21348. * @description
  21349. * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
  21350. * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
  21351. * the bound value.
  21352. *
  21353. * `ngValue` is useful when dynamically generating lists of radio buttons using
  21354. * {@link ngRepeat `ngRepeat`}, as shown below.
  21355. *
  21356. * Likewise, `ngValue` can be used to generate `<option>` elements for
  21357. * the {@link select `select`} element. In that case however, only strings are supported
  21358. * for the `value `attribute, so the resulting `ngModel` will always be a string.
  21359. * Support for `select` models with non-string values is available via `ngOptions`.
  21360. *
  21361. * @element input
  21362. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  21363. * of the `input` element
  21364. *
  21365. * @example
  21366. <example name="ngValue-directive" module="valueExample">
  21367. <file name="index.html">
  21368. <script>
  21369. angular.module('valueExample', [])
  21370. .controller('ExampleController', ['$scope', function($scope) {
  21371. $scope.names = ['pizza', 'unicorns', 'robots'];
  21372. $scope.my = { favorite: 'unicorns' };
  21373. }]);
  21374. </script>
  21375. <form ng-controller="ExampleController">
  21376. <h2>Which is your favorite?</h2>
  21377. <label ng-repeat="name in names" for="{{name}}">
  21378. {{name}}
  21379. <input type="radio"
  21380. ng-model="my.favorite"
  21381. ng-value="name"
  21382. id="{{name}}"
  21383. name="favorite">
  21384. </label>
  21385. <div>You chose {{my.favorite}}</div>
  21386. </form>
  21387. </file>
  21388. <file name="protractor.js" type="protractor">
  21389. var favorite = element(by.binding('my.favorite'));
  21390. it('should initialize to model', function() {
  21391. expect(favorite.getText()).toContain('unicorns');
  21392. });
  21393. it('should bind the values to the inputs', function() {
  21394. element.all(by.model('my.favorite')).get(0).click();
  21395. expect(favorite.getText()).toContain('pizza');
  21396. });
  21397. </file>
  21398. </example>
  21399. */
  21400. var ngValueDirective = function() {
  21401. return {
  21402. restrict: 'A',
  21403. priority: 100,
  21404. compile: function(tpl, tplAttr) {
  21405. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  21406. return function ngValueConstantLink(scope, elm, attr) {
  21407. attr.$set('value', scope.$eval(attr.ngValue));
  21408. };
  21409. } else {
  21410. return function ngValueLink(scope, elm, attr) {
  21411. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  21412. attr.$set('value', value);
  21413. });
  21414. };
  21415. }
  21416. }
  21417. };
  21418. };
  21419. /**
  21420. * @ngdoc directive
  21421. * @name ngBind
  21422. * @restrict AC
  21423. *
  21424. * @description
  21425. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  21426. * with the value of a given expression, and to update the text content when the value of that
  21427. * expression changes.
  21428. *
  21429. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  21430. * `{{ expression }}` which is similar but less verbose.
  21431. *
  21432. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  21433. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  21434. * element attribute, it makes the bindings invisible to the user while the page is loading.
  21435. *
  21436. * An alternative solution to this problem would be using the
  21437. * {@link ng.directive:ngCloak ngCloak} directive.
  21438. *
  21439. *
  21440. * @element ANY
  21441. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  21442. *
  21443. * @example
  21444. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  21445. <example module="bindExample">
  21446. <file name="index.html">
  21447. <script>
  21448. angular.module('bindExample', [])
  21449. .controller('ExampleController', ['$scope', function($scope) {
  21450. $scope.name = 'Whirled';
  21451. }]);
  21452. </script>
  21453. <div ng-controller="ExampleController">
  21454. <label>Enter name: <input type="text" ng-model="name"></label><br>
  21455. Hello <span ng-bind="name"></span>!
  21456. </div>
  21457. </file>
  21458. <file name="protractor.js" type="protractor">
  21459. it('should check ng-bind', function() {
  21460. var nameInput = element(by.model('name'));
  21461. expect(element(by.binding('name')).getText()).toBe('Whirled');
  21462. nameInput.clear();
  21463. nameInput.sendKeys('world');
  21464. expect(element(by.binding('name')).getText()).toBe('world');
  21465. });
  21466. </file>
  21467. </example>
  21468. */
  21469. var ngBindDirective = ['$compile', function($compile) {
  21470. return {
  21471. restrict: 'AC',
  21472. compile: function ngBindCompile(templateElement) {
  21473. $compile.$$addBindingClass(templateElement);
  21474. return function ngBindLink(scope, element, attr) {
  21475. $compile.$$addBindingInfo(element, attr.ngBind);
  21476. element = element[0];
  21477. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  21478. element.textContent = isUndefined(value) ? '' : value;
  21479. });
  21480. };
  21481. }
  21482. };
  21483. }];
  21484. /**
  21485. * @ngdoc directive
  21486. * @name ngBindTemplate
  21487. *
  21488. * @description
  21489. * The `ngBindTemplate` directive specifies that the element
  21490. * text content should be replaced with the interpolation of the template
  21491. * in the `ngBindTemplate` attribute.
  21492. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  21493. * expressions. This directive is needed since some HTML elements
  21494. * (such as TITLE and OPTION) cannot contain SPAN elements.
  21495. *
  21496. * @element ANY
  21497. * @param {string} ngBindTemplate template of form
  21498. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  21499. *
  21500. * @example
  21501. * Try it here: enter text in text box and watch the greeting change.
  21502. <example module="bindExample">
  21503. <file name="index.html">
  21504. <script>
  21505. angular.module('bindExample', [])
  21506. .controller('ExampleController', ['$scope', function($scope) {
  21507. $scope.salutation = 'Hello';
  21508. $scope.name = 'World';
  21509. }]);
  21510. </script>
  21511. <div ng-controller="ExampleController">
  21512. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  21513. <label>Name: <input type="text" ng-model="name"></label><br>
  21514. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  21515. </div>
  21516. </file>
  21517. <file name="protractor.js" type="protractor">
  21518. it('should check ng-bind', function() {
  21519. var salutationElem = element(by.binding('salutation'));
  21520. var salutationInput = element(by.model('salutation'));
  21521. var nameInput = element(by.model('name'));
  21522. expect(salutationElem.getText()).toBe('Hello World!');
  21523. salutationInput.clear();
  21524. salutationInput.sendKeys('Greetings');
  21525. nameInput.clear();
  21526. nameInput.sendKeys('user');
  21527. expect(salutationElem.getText()).toBe('Greetings user!');
  21528. });
  21529. </file>
  21530. </example>
  21531. */
  21532. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  21533. return {
  21534. compile: function ngBindTemplateCompile(templateElement) {
  21535. $compile.$$addBindingClass(templateElement);
  21536. return function ngBindTemplateLink(scope, element, attr) {
  21537. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  21538. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  21539. element = element[0];
  21540. attr.$observe('ngBindTemplate', function(value) {
  21541. element.textContent = isUndefined(value) ? '' : value;
  21542. });
  21543. };
  21544. }
  21545. };
  21546. }];
  21547. /**
  21548. * @ngdoc directive
  21549. * @name ngBindHtml
  21550. *
  21551. * @description
  21552. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  21553. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  21554. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  21555. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  21556. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  21557. *
  21558. * You may also bypass sanitization for values you know are safe. To do so, bind to
  21559. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  21560. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  21561. *
  21562. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  21563. * will have an exception (instead of an exploit.)
  21564. *
  21565. * @element ANY
  21566. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  21567. *
  21568. * @example
  21569. <example module="bindHtmlExample" deps="angular-sanitize.js">
  21570. <file name="index.html">
  21571. <div ng-controller="ExampleController">
  21572. <p ng-bind-html="myHTML"></p>
  21573. </div>
  21574. </file>
  21575. <file name="script.js">
  21576. angular.module('bindHtmlExample', ['ngSanitize'])
  21577. .controller('ExampleController', ['$scope', function($scope) {
  21578. $scope.myHTML =
  21579. 'I am an <code>HTML</code>string with ' +
  21580. '<a href="#">links!</a> and other <em>stuff</em>';
  21581. }]);
  21582. </file>
  21583. <file name="protractor.js" type="protractor">
  21584. it('should check ng-bind-html', function() {
  21585. expect(element(by.binding('myHTML')).getText()).toBe(
  21586. 'I am an HTMLstring with links! and other stuff');
  21587. });
  21588. </file>
  21589. </example>
  21590. */
  21591. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  21592. return {
  21593. restrict: 'A',
  21594. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  21595. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  21596. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
  21597. return (value || '').toString();
  21598. });
  21599. $compile.$$addBindingClass(tElement);
  21600. return function ngBindHtmlLink(scope, element, attr) {
  21601. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  21602. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  21603. // we re-evaluate the expr because we want a TrustedValueHolderType
  21604. // for $sce, not a string
  21605. element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
  21606. });
  21607. };
  21608. }
  21609. };
  21610. }];
  21611. /**
  21612. * @ngdoc directive
  21613. * @name ngChange
  21614. *
  21615. * @description
  21616. * Evaluate the given expression when the user changes the input.
  21617. * The expression is evaluated immediately, unlike the JavaScript onchange event
  21618. * which only triggers at the end of a change (usually, when the user leaves the
  21619. * form element or presses the return key).
  21620. *
  21621. * The `ngChange` expression is only evaluated when a change in the input value causes
  21622. * a new value to be committed to the model.
  21623. *
  21624. * It will not be evaluated:
  21625. * * if the value returned from the `$parsers` transformation pipeline has not changed
  21626. * * if the input has continued to be invalid since the model will stay `null`
  21627. * * if the model is changed programmatically and not by a change to the input value
  21628. *
  21629. *
  21630. * Note, this directive requires `ngModel` to be present.
  21631. *
  21632. * @element input
  21633. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  21634. * in input value.
  21635. *
  21636. * @example
  21637. * <example name="ngChange-directive" module="changeExample">
  21638. * <file name="index.html">
  21639. * <script>
  21640. * angular.module('changeExample', [])
  21641. * .controller('ExampleController', ['$scope', function($scope) {
  21642. * $scope.counter = 0;
  21643. * $scope.change = function() {
  21644. * $scope.counter++;
  21645. * };
  21646. * }]);
  21647. * </script>
  21648. * <div ng-controller="ExampleController">
  21649. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  21650. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  21651. * <label for="ng-change-example2">Confirmed</label><br />
  21652. * <tt>debug = {{confirmed}}</tt><br/>
  21653. * <tt>counter = {{counter}}</tt><br/>
  21654. * </div>
  21655. * </file>
  21656. * <file name="protractor.js" type="protractor">
  21657. * var counter = element(by.binding('counter'));
  21658. * var debug = element(by.binding('confirmed'));
  21659. *
  21660. * it('should evaluate the expression if changing from view', function() {
  21661. * expect(counter.getText()).toContain('0');
  21662. *
  21663. * element(by.id('ng-change-example1')).click();
  21664. *
  21665. * expect(counter.getText()).toContain('1');
  21666. * expect(debug.getText()).toContain('true');
  21667. * });
  21668. *
  21669. * it('should not evaluate the expression if changing from model', function() {
  21670. * element(by.id('ng-change-example2')).click();
  21671. * expect(counter.getText()).toContain('0');
  21672. * expect(debug.getText()).toContain('true');
  21673. * });
  21674. * </file>
  21675. * </example>
  21676. */
  21677. var ngChangeDirective = valueFn({
  21678. restrict: 'A',
  21679. require: 'ngModel',
  21680. link: function(scope, element, attr, ctrl) {
  21681. ctrl.$viewChangeListeners.push(function() {
  21682. scope.$eval(attr.ngChange);
  21683. });
  21684. }
  21685. });
  21686. function classDirective(name, selector) {
  21687. name = 'ngClass' + name;
  21688. return ['$animate', function($animate) {
  21689. return {
  21690. restrict: 'AC',
  21691. link: function(scope, element, attr) {
  21692. var oldVal;
  21693. scope.$watch(attr[name], ngClassWatchAction, true);
  21694. attr.$observe('class', function(value) {
  21695. ngClassWatchAction(scope.$eval(attr[name]));
  21696. });
  21697. if (name !== 'ngClass') {
  21698. scope.$watch('$index', function($index, old$index) {
  21699. // jshint bitwise: false
  21700. var mod = $index & 1;
  21701. if (mod !== (old$index & 1)) {
  21702. var classes = arrayClasses(scope.$eval(attr[name]));
  21703. mod === selector ?
  21704. addClasses(classes) :
  21705. removeClasses(classes);
  21706. }
  21707. });
  21708. }
  21709. function addClasses(classes) {
  21710. var newClasses = digestClassCounts(classes, 1);
  21711. attr.$addClass(newClasses);
  21712. }
  21713. function removeClasses(classes) {
  21714. var newClasses = digestClassCounts(classes, -1);
  21715. attr.$removeClass(newClasses);
  21716. }
  21717. function digestClassCounts(classes, count) {
  21718. // Use createMap() to prevent class assumptions involving property
  21719. // names in Object.prototype
  21720. var classCounts = element.data('$classCounts') || createMap();
  21721. var classesToUpdate = [];
  21722. forEach(classes, function(className) {
  21723. if (count > 0 || classCounts[className]) {
  21724. classCounts[className] = (classCounts[className] || 0) + count;
  21725. if (classCounts[className] === +(count > 0)) {
  21726. classesToUpdate.push(className);
  21727. }
  21728. }
  21729. });
  21730. element.data('$classCounts', classCounts);
  21731. return classesToUpdate.join(' ');
  21732. }
  21733. function updateClasses(oldClasses, newClasses) {
  21734. var toAdd = arrayDifference(newClasses, oldClasses);
  21735. var toRemove = arrayDifference(oldClasses, newClasses);
  21736. toAdd = digestClassCounts(toAdd, 1);
  21737. toRemove = digestClassCounts(toRemove, -1);
  21738. if (toAdd && toAdd.length) {
  21739. $animate.addClass(element, toAdd);
  21740. }
  21741. if (toRemove && toRemove.length) {
  21742. $animate.removeClass(element, toRemove);
  21743. }
  21744. }
  21745. function ngClassWatchAction(newVal) {
  21746. if (selector === true || scope.$index % 2 === selector) {
  21747. var newClasses = arrayClasses(newVal || []);
  21748. if (!oldVal) {
  21749. addClasses(newClasses);
  21750. } else if (!equals(newVal,oldVal)) {
  21751. var oldClasses = arrayClasses(oldVal);
  21752. updateClasses(oldClasses, newClasses);
  21753. }
  21754. }
  21755. oldVal = shallowCopy(newVal);
  21756. }
  21757. }
  21758. };
  21759. function arrayDifference(tokens1, tokens2) {
  21760. var values = [];
  21761. outer:
  21762. for (var i = 0; i < tokens1.length; i++) {
  21763. var token = tokens1[i];
  21764. for (var j = 0; j < tokens2.length; j++) {
  21765. if (token == tokens2[j]) continue outer;
  21766. }
  21767. values.push(token);
  21768. }
  21769. return values;
  21770. }
  21771. function arrayClasses(classVal) {
  21772. var classes = [];
  21773. if (isArray(classVal)) {
  21774. forEach(classVal, function(v) {
  21775. classes = classes.concat(arrayClasses(v));
  21776. });
  21777. return classes;
  21778. } else if (isString(classVal)) {
  21779. return classVal.split(' ');
  21780. } else if (isObject(classVal)) {
  21781. forEach(classVal, function(v, k) {
  21782. if (v) {
  21783. classes = classes.concat(k.split(' '));
  21784. }
  21785. });
  21786. return classes;
  21787. }
  21788. return classVal;
  21789. }
  21790. }];
  21791. }
  21792. /**
  21793. * @ngdoc directive
  21794. * @name ngClass
  21795. * @restrict AC
  21796. *
  21797. * @description
  21798. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  21799. * an expression that represents all classes to be added.
  21800. *
  21801. * The directive operates in three different ways, depending on which of three types the expression
  21802. * evaluates to:
  21803. *
  21804. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  21805. * names.
  21806. *
  21807. * 2. If the expression evaluates to an object, then for each key-value pair of the
  21808. * object with a truthy value the corresponding key is used as a class name.
  21809. *
  21810. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  21811. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  21812. * to give you more control over what CSS classes appear. See the code below for an example of this.
  21813. *
  21814. *
  21815. * The directive won't add duplicate classes if a particular class was already set.
  21816. *
  21817. * When the expression changes, the previously added classes are removed and only then are the
  21818. * new classes added.
  21819. *
  21820. * @animations
  21821. * | Animation | Occurs |
  21822. * |----------------------------------|-------------------------------------|
  21823. * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element |
  21824. * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element |
  21825. *
  21826. * @element ANY
  21827. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  21828. * of the evaluation can be a string representing space delimited class
  21829. * names, an array, or a map of class names to boolean values. In the case of a map, the
  21830. * names of the properties whose values are truthy will be added as css classes to the
  21831. * element.
  21832. *
  21833. * @example Example that demonstrates basic bindings via ngClass directive.
  21834. <example>
  21835. <file name="index.html">
  21836. <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
  21837. <label>
  21838. <input type="checkbox" ng-model="deleted">
  21839. deleted (apply "strike" class)
  21840. </label><br>
  21841. <label>
  21842. <input type="checkbox" ng-model="important">
  21843. important (apply "bold" class)
  21844. </label><br>
  21845. <label>
  21846. <input type="checkbox" ng-model="error">
  21847. error (apply "has-error" class)
  21848. </label>
  21849. <hr>
  21850. <p ng-class="style">Using String Syntax</p>
  21851. <input type="text" ng-model="style"
  21852. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  21853. <hr>
  21854. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  21855. <input ng-model="style1"
  21856. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  21857. <input ng-model="style2"
  21858. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  21859. <input ng-model="style3"
  21860. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  21861. <hr>
  21862. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  21863. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  21864. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  21865. </file>
  21866. <file name="style.css">
  21867. .strike {
  21868. text-decoration: line-through;
  21869. }
  21870. .bold {
  21871. font-weight: bold;
  21872. }
  21873. .red {
  21874. color: red;
  21875. }
  21876. .has-error {
  21877. color: red;
  21878. background-color: yellow;
  21879. }
  21880. .orange {
  21881. color: orange;
  21882. }
  21883. </file>
  21884. <file name="protractor.js" type="protractor">
  21885. var ps = element.all(by.css('p'));
  21886. it('should let you toggle the class', function() {
  21887. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  21888. expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
  21889. element(by.model('important')).click();
  21890. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  21891. element(by.model('error')).click();
  21892. expect(ps.first().getAttribute('class')).toMatch(/has-error/);
  21893. });
  21894. it('should let you toggle string example', function() {
  21895. expect(ps.get(1).getAttribute('class')).toBe('');
  21896. element(by.model('style')).clear();
  21897. element(by.model('style')).sendKeys('red');
  21898. expect(ps.get(1).getAttribute('class')).toBe('red');
  21899. });
  21900. it('array example should have 3 classes', function() {
  21901. expect(ps.get(2).getAttribute('class')).toBe('');
  21902. element(by.model('style1')).sendKeys('bold');
  21903. element(by.model('style2')).sendKeys('strike');
  21904. element(by.model('style3')).sendKeys('red');
  21905. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  21906. });
  21907. it('array with map example should have 2 classes', function() {
  21908. expect(ps.last().getAttribute('class')).toBe('');
  21909. element(by.model('style4')).sendKeys('bold');
  21910. element(by.model('warning')).click();
  21911. expect(ps.last().getAttribute('class')).toBe('bold orange');
  21912. });
  21913. </file>
  21914. </example>
  21915. ## Animations
  21916. The example below demonstrates how to perform animations using ngClass.
  21917. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  21918. <file name="index.html">
  21919. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  21920. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  21921. <br>
  21922. <span class="base-class" ng-class="myVar">Sample Text</span>
  21923. </file>
  21924. <file name="style.css">
  21925. .base-class {
  21926. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21927. }
  21928. .base-class.my-class {
  21929. color: red;
  21930. font-size:3em;
  21931. }
  21932. </file>
  21933. <file name="protractor.js" type="protractor">
  21934. it('should check ng-class', function() {
  21935. expect(element(by.css('.base-class')).getAttribute('class')).not.
  21936. toMatch(/my-class/);
  21937. element(by.id('setbtn')).click();
  21938. expect(element(by.css('.base-class')).getAttribute('class')).
  21939. toMatch(/my-class/);
  21940. element(by.id('clearbtn')).click();
  21941. expect(element(by.css('.base-class')).getAttribute('class')).not.
  21942. toMatch(/my-class/);
  21943. });
  21944. </file>
  21945. </example>
  21946. ## ngClass and pre-existing CSS3 Transitions/Animations
  21947. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  21948. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  21949. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  21950. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  21951. {@link $animate#removeClass $animate.removeClass}.
  21952. */
  21953. var ngClassDirective = classDirective('', true);
  21954. /**
  21955. * @ngdoc directive
  21956. * @name ngClassOdd
  21957. * @restrict AC
  21958. *
  21959. * @description
  21960. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  21961. * {@link ng.directive:ngClass ngClass}, except they work in
  21962. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  21963. *
  21964. * This directive can be applied only within the scope of an
  21965. * {@link ng.directive:ngRepeat ngRepeat}.
  21966. *
  21967. * @element ANY
  21968. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  21969. * of the evaluation can be a string representing space delimited class names or an array.
  21970. *
  21971. * @example
  21972. <example>
  21973. <file name="index.html">
  21974. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  21975. <li ng-repeat="name in names">
  21976. <span ng-class-odd="'odd'" ng-class-even="'even'">
  21977. {{name}}
  21978. </span>
  21979. </li>
  21980. </ol>
  21981. </file>
  21982. <file name="style.css">
  21983. .odd {
  21984. color: red;
  21985. }
  21986. .even {
  21987. color: blue;
  21988. }
  21989. </file>
  21990. <file name="protractor.js" type="protractor">
  21991. it('should check ng-class-odd and ng-class-even', function() {
  21992. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  21993. toMatch(/odd/);
  21994. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  21995. toMatch(/even/);
  21996. });
  21997. </file>
  21998. </example>
  21999. */
  22000. var ngClassOddDirective = classDirective('Odd', 0);
  22001. /**
  22002. * @ngdoc directive
  22003. * @name ngClassEven
  22004. * @restrict AC
  22005. *
  22006. * @description
  22007. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  22008. * {@link ng.directive:ngClass ngClass}, except they work in
  22009. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  22010. *
  22011. * This directive can be applied only within the scope of an
  22012. * {@link ng.directive:ngRepeat ngRepeat}.
  22013. *
  22014. * @element ANY
  22015. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  22016. * result of the evaluation can be a string representing space delimited class names or an array.
  22017. *
  22018. * @example
  22019. <example>
  22020. <file name="index.html">
  22021. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  22022. <li ng-repeat="name in names">
  22023. <span ng-class-odd="'odd'" ng-class-even="'even'">
  22024. {{name}} &nbsp; &nbsp; &nbsp;
  22025. </span>
  22026. </li>
  22027. </ol>
  22028. </file>
  22029. <file name="style.css">
  22030. .odd {
  22031. color: red;
  22032. }
  22033. .even {
  22034. color: blue;
  22035. }
  22036. </file>
  22037. <file name="protractor.js" type="protractor">
  22038. it('should check ng-class-odd and ng-class-even', function() {
  22039. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  22040. toMatch(/odd/);
  22041. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  22042. toMatch(/even/);
  22043. });
  22044. </file>
  22045. </example>
  22046. */
  22047. var ngClassEvenDirective = classDirective('Even', 1);
  22048. /**
  22049. * @ngdoc directive
  22050. * @name ngCloak
  22051. * @restrict AC
  22052. *
  22053. * @description
  22054. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  22055. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  22056. * directive to avoid the undesirable flicker effect caused by the html template display.
  22057. *
  22058. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  22059. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  22060. * of the browser view.
  22061. *
  22062. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  22063. * `angular.min.js`.
  22064. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  22065. *
  22066. * ```css
  22067. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  22068. * display: none !important;
  22069. * }
  22070. * ```
  22071. *
  22072. * When this css rule is loaded by the browser, all html elements (including their children) that
  22073. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  22074. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  22075. * the compiled element visible.
  22076. *
  22077. * For the best result, the `angular.js` script must be loaded in the head section of the html
  22078. * document; alternatively, the css rule above must be included in the external stylesheet of the
  22079. * application.
  22080. *
  22081. * @element ANY
  22082. *
  22083. * @example
  22084. <example>
  22085. <file name="index.html">
  22086. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  22087. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  22088. </file>
  22089. <file name="protractor.js" type="protractor">
  22090. it('should remove the template directive and css class', function() {
  22091. expect($('#template1').getAttribute('ng-cloak')).
  22092. toBeNull();
  22093. expect($('#template2').getAttribute('ng-cloak')).
  22094. toBeNull();
  22095. });
  22096. </file>
  22097. </example>
  22098. *
  22099. */
  22100. var ngCloakDirective = ngDirective({
  22101. compile: function(element, attr) {
  22102. attr.$set('ngCloak', undefined);
  22103. element.removeClass('ng-cloak');
  22104. }
  22105. });
  22106. /**
  22107. * @ngdoc directive
  22108. * @name ngController
  22109. *
  22110. * @description
  22111. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  22112. * supports the principles behind the Model-View-Controller design pattern.
  22113. *
  22114. * MVC components in angular:
  22115. *
  22116. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  22117. * are accessed through bindings.
  22118. * * View — The template (HTML with data bindings) that is rendered into the View.
  22119. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  22120. * logic behind the application to decorate the scope with functions and values
  22121. *
  22122. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  22123. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  22124. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  22125. * and executed twice.
  22126. *
  22127. * @element ANY
  22128. * @scope
  22129. * @priority 500
  22130. * @param {expression} ngController Name of a constructor function registered with the current
  22131. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  22132. * that on the current scope evaluates to a constructor function.
  22133. *
  22134. * The controller instance can be published into a scope property by specifying
  22135. * `ng-controller="as propertyName"`.
  22136. *
  22137. * If the current `$controllerProvider` is configured to use globals (via
  22138. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  22139. * also be the name of a globally accessible constructor function (not recommended).
  22140. *
  22141. * @example
  22142. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  22143. * greeting are methods declared on the controller (see source tab). These methods can
  22144. * easily be called from the angular markup. Any changes to the data are automatically reflected
  22145. * in the View without the need for a manual update.
  22146. *
  22147. * Two different declaration styles are included below:
  22148. *
  22149. * * one binds methods and properties directly onto the controller using `this`:
  22150. * `ng-controller="SettingsController1 as settings"`
  22151. * * one injects `$scope` into the controller:
  22152. * `ng-controller="SettingsController2"`
  22153. *
  22154. * The second option is more common in the Angular community, and is generally used in boilerplates
  22155. * and in this guide. However, there are advantages to binding properties directly to the controller
  22156. * and avoiding scope.
  22157. *
  22158. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  22159. * multiple controllers apply to an element.
  22160. * * If you are writing your controllers as classes you have easier access to the properties and
  22161. * methods, which will appear on the scope, from inside the controller code.
  22162. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  22163. * inheritance masking primitives.
  22164. *
  22165. * This example demonstrates the `controller as` syntax.
  22166. *
  22167. * <example name="ngControllerAs" module="controllerAsExample">
  22168. * <file name="index.html">
  22169. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  22170. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  22171. * <button ng-click="settings.greet()">greet</button><br/>
  22172. * Contact:
  22173. * <ul>
  22174. * <li ng-repeat="contact in settings.contacts">
  22175. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  22176. * <option>phone</option>
  22177. * <option>email</option>
  22178. * </select>
  22179. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  22180. * <button ng-click="settings.clearContact(contact)">clear</button>
  22181. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  22182. * </li>
  22183. * <li><button ng-click="settings.addContact()">add</button></li>
  22184. * </ul>
  22185. * </div>
  22186. * </file>
  22187. * <file name="app.js">
  22188. * angular.module('controllerAsExample', [])
  22189. * .controller('SettingsController1', SettingsController1);
  22190. *
  22191. * function SettingsController1() {
  22192. * this.name = "John Smith";
  22193. * this.contacts = [
  22194. * {type: 'phone', value: '408 555 1212'},
  22195. * {type: 'email', value: 'john.smith@example.org'} ];
  22196. * }
  22197. *
  22198. * SettingsController1.prototype.greet = function() {
  22199. * alert(this.name);
  22200. * };
  22201. *
  22202. * SettingsController1.prototype.addContact = function() {
  22203. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  22204. * };
  22205. *
  22206. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  22207. * var index = this.contacts.indexOf(contactToRemove);
  22208. * this.contacts.splice(index, 1);
  22209. * };
  22210. *
  22211. * SettingsController1.prototype.clearContact = function(contact) {
  22212. * contact.type = 'phone';
  22213. * contact.value = '';
  22214. * };
  22215. * </file>
  22216. * <file name="protractor.js" type="protractor">
  22217. * it('should check controller as', function() {
  22218. * var container = element(by.id('ctrl-as-exmpl'));
  22219. * expect(container.element(by.model('settings.name'))
  22220. * .getAttribute('value')).toBe('John Smith');
  22221. *
  22222. * var firstRepeat =
  22223. * container.element(by.repeater('contact in settings.contacts').row(0));
  22224. * var secondRepeat =
  22225. * container.element(by.repeater('contact in settings.contacts').row(1));
  22226. *
  22227. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  22228. * .toBe('408 555 1212');
  22229. *
  22230. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  22231. * .toBe('john.smith@example.org');
  22232. *
  22233. * firstRepeat.element(by.buttonText('clear')).click();
  22234. *
  22235. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  22236. * .toBe('');
  22237. *
  22238. * container.element(by.buttonText('add')).click();
  22239. *
  22240. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  22241. * .element(by.model('contact.value'))
  22242. * .getAttribute('value'))
  22243. * .toBe('yourname@example.org');
  22244. * });
  22245. * </file>
  22246. * </example>
  22247. *
  22248. * This example demonstrates the "attach to `$scope`" style of controller.
  22249. *
  22250. * <example name="ngController" module="controllerExample">
  22251. * <file name="index.html">
  22252. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  22253. * <label>Name: <input type="text" ng-model="name"/></label>
  22254. * <button ng-click="greet()">greet</button><br/>
  22255. * Contact:
  22256. * <ul>
  22257. * <li ng-repeat="contact in contacts">
  22258. * <select ng-model="contact.type" id="select_{{$index}}">
  22259. * <option>phone</option>
  22260. * <option>email</option>
  22261. * </select>
  22262. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  22263. * <button ng-click="clearContact(contact)">clear</button>
  22264. * <button ng-click="removeContact(contact)">X</button>
  22265. * </li>
  22266. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  22267. * </ul>
  22268. * </div>
  22269. * </file>
  22270. * <file name="app.js">
  22271. * angular.module('controllerExample', [])
  22272. * .controller('SettingsController2', ['$scope', SettingsController2]);
  22273. *
  22274. * function SettingsController2($scope) {
  22275. * $scope.name = "John Smith";
  22276. * $scope.contacts = [
  22277. * {type:'phone', value:'408 555 1212'},
  22278. * {type:'email', value:'john.smith@example.org'} ];
  22279. *
  22280. * $scope.greet = function() {
  22281. * alert($scope.name);
  22282. * };
  22283. *
  22284. * $scope.addContact = function() {
  22285. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  22286. * };
  22287. *
  22288. * $scope.removeContact = function(contactToRemove) {
  22289. * var index = $scope.contacts.indexOf(contactToRemove);
  22290. * $scope.contacts.splice(index, 1);
  22291. * };
  22292. *
  22293. * $scope.clearContact = function(contact) {
  22294. * contact.type = 'phone';
  22295. * contact.value = '';
  22296. * };
  22297. * }
  22298. * </file>
  22299. * <file name="protractor.js" type="protractor">
  22300. * it('should check controller', function() {
  22301. * var container = element(by.id('ctrl-exmpl'));
  22302. *
  22303. * expect(container.element(by.model('name'))
  22304. * .getAttribute('value')).toBe('John Smith');
  22305. *
  22306. * var firstRepeat =
  22307. * container.element(by.repeater('contact in contacts').row(0));
  22308. * var secondRepeat =
  22309. * container.element(by.repeater('contact in contacts').row(1));
  22310. *
  22311. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  22312. * .toBe('408 555 1212');
  22313. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  22314. * .toBe('john.smith@example.org');
  22315. *
  22316. * firstRepeat.element(by.buttonText('clear')).click();
  22317. *
  22318. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  22319. * .toBe('');
  22320. *
  22321. * container.element(by.buttonText('add')).click();
  22322. *
  22323. * expect(container.element(by.repeater('contact in contacts').row(2))
  22324. * .element(by.model('contact.value'))
  22325. * .getAttribute('value'))
  22326. * .toBe('yourname@example.org');
  22327. * });
  22328. * </file>
  22329. *</example>
  22330. */
  22331. var ngControllerDirective = [function() {
  22332. return {
  22333. restrict: 'A',
  22334. scope: true,
  22335. controller: '@',
  22336. priority: 500
  22337. };
  22338. }];
  22339. /**
  22340. * @ngdoc directive
  22341. * @name ngCsp
  22342. *
  22343. * @element html
  22344. * @description
  22345. *
  22346. * Angular has some features that can break certain
  22347. * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
  22348. *
  22349. * If you intend to implement these rules then you must tell Angular not to use these features.
  22350. *
  22351. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  22352. *
  22353. *
  22354. * The following rules affect Angular:
  22355. *
  22356. * * `unsafe-eval`: this rule forbids apps to use `eval` or `Function(string)` generated functions
  22357. * (among other things). Angular makes use of this in the {@link $parse} service to provide a 30%
  22358. * increase in the speed of evaluating Angular expressions.
  22359. *
  22360. * * `unsafe-inline`: this rule forbids apps from inject custom styles into the document. Angular
  22361. * makes use of this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}).
  22362. * To make these directives work when a CSP rule is blocking inline styles, you must link to the
  22363. * `angular-csp.css` in your HTML manually.
  22364. *
  22365. * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking unsafe-eval
  22366. * and automatically deactivates this feature in the {@link $parse} service. This autodetection,
  22367. * however, triggers a CSP error to be logged in the console:
  22368. *
  22369. * ```
  22370. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  22371. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  22372. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  22373. * ```
  22374. *
  22375. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  22376. * directive on an element of the HTML document that appears before the `<script>` tag that loads
  22377. * the `angular.js` file.
  22378. *
  22379. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  22380. *
  22381. * You can specify which of the CSP related Angular features should be deactivated by providing
  22382. * a value for the `ng-csp` attribute. The options are as follows:
  22383. *
  22384. * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
  22385. *
  22386. * * no-unsafe-eval: this stops Angular from optimizing $parse with unsafe eval of strings
  22387. *
  22388. * You can use these values in the following combinations:
  22389. *
  22390. *
  22391. * * No declaration means that Angular will assume that you can do inline styles, but it will do
  22392. * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous versions
  22393. * of Angular.
  22394. *
  22395. * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
  22396. * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous versions
  22397. * of Angular.
  22398. *
  22399. * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can inject
  22400. * inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
  22401. *
  22402. * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
  22403. * run eval - no automatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
  22404. *
  22405. * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
  22406. * styles nor use eval, which is the same as an empty: ng-csp.
  22407. * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
  22408. *
  22409. * @example
  22410. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  22411. ```html
  22412. <!doctype html>
  22413. <html ng-app ng-csp>
  22414. ...
  22415. ...
  22416. </html>
  22417. ```
  22418. * @example
  22419. // Note: the suffix `.csp` in the example name triggers
  22420. // csp mode in our http server!
  22421. <example name="example.csp" module="cspExample" ng-csp="true">
  22422. <file name="index.html">
  22423. <div ng-controller="MainController as ctrl">
  22424. <div>
  22425. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  22426. <span id="counter">
  22427. {{ctrl.counter}}
  22428. </span>
  22429. </div>
  22430. <div>
  22431. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  22432. <span id="evilError">
  22433. {{ctrl.evilError}}
  22434. </span>
  22435. </div>
  22436. </div>
  22437. </file>
  22438. <file name="script.js">
  22439. angular.module('cspExample', [])
  22440. .controller('MainController', function() {
  22441. this.counter = 0;
  22442. this.inc = function() {
  22443. this.counter++;
  22444. };
  22445. this.evil = function() {
  22446. // jshint evil:true
  22447. try {
  22448. eval('1+2');
  22449. } catch (e) {
  22450. this.evilError = e.message;
  22451. }
  22452. };
  22453. });
  22454. </file>
  22455. <file name="protractor.js" type="protractor">
  22456. var util, webdriver;
  22457. var incBtn = element(by.id('inc'));
  22458. var counter = element(by.id('counter'));
  22459. var evilBtn = element(by.id('evil'));
  22460. var evilError = element(by.id('evilError'));
  22461. function getAndClearSevereErrors() {
  22462. return browser.manage().logs().get('browser').then(function(browserLog) {
  22463. return browserLog.filter(function(logEntry) {
  22464. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  22465. });
  22466. });
  22467. }
  22468. function clearErrors() {
  22469. getAndClearSevereErrors();
  22470. }
  22471. function expectNoErrors() {
  22472. getAndClearSevereErrors().then(function(filteredLog) {
  22473. expect(filteredLog.length).toEqual(0);
  22474. if (filteredLog.length) {
  22475. console.log('browser console errors: ' + util.inspect(filteredLog));
  22476. }
  22477. });
  22478. }
  22479. function expectError(regex) {
  22480. getAndClearSevereErrors().then(function(filteredLog) {
  22481. var found = false;
  22482. filteredLog.forEach(function(log) {
  22483. if (log.message.match(regex)) {
  22484. found = true;
  22485. }
  22486. });
  22487. if (!found) {
  22488. throw new Error('expected an error that matches ' + regex);
  22489. }
  22490. });
  22491. }
  22492. beforeEach(function() {
  22493. util = require('util');
  22494. webdriver = require('protractor/node_modules/selenium-webdriver');
  22495. });
  22496. // For now, we only test on Chrome,
  22497. // as Safari does not load the page with Protractor's injected scripts,
  22498. // and Firefox webdriver always disables content security policy (#6358)
  22499. if (browser.params.browser !== 'chrome') {
  22500. return;
  22501. }
  22502. it('should not report errors when the page is loaded', function() {
  22503. // clear errors so we are not dependent on previous tests
  22504. clearErrors();
  22505. // Need to reload the page as the page is already loaded when
  22506. // we come here
  22507. browser.driver.getCurrentUrl().then(function(url) {
  22508. browser.get(url);
  22509. });
  22510. expectNoErrors();
  22511. });
  22512. it('should evaluate expressions', function() {
  22513. expect(counter.getText()).toEqual('0');
  22514. incBtn.click();
  22515. expect(counter.getText()).toEqual('1');
  22516. expectNoErrors();
  22517. });
  22518. it('should throw and report an error when using "eval"', function() {
  22519. evilBtn.click();
  22520. expect(evilError.getText()).toMatch(/Content Security Policy/);
  22521. expectError(/Content Security Policy/);
  22522. });
  22523. </file>
  22524. </example>
  22525. */
  22526. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  22527. // bootstrap the system (before $parse is instantiated), for this reason we just have
  22528. // the csp() fn that looks for the `ng-csp` attribute anywhere in the current doc
  22529. /**
  22530. * @ngdoc directive
  22531. * @name ngClick
  22532. *
  22533. * @description
  22534. * The ngClick directive allows you to specify custom behavior when
  22535. * an element is clicked.
  22536. *
  22537. * @element ANY
  22538. * @priority 0
  22539. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  22540. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  22541. *
  22542. * @example
  22543. <example>
  22544. <file name="index.html">
  22545. <button ng-click="count = count + 1" ng-init="count=0">
  22546. Increment
  22547. </button>
  22548. <span>
  22549. count: {{count}}
  22550. </span>
  22551. </file>
  22552. <file name="protractor.js" type="protractor">
  22553. it('should check ng-click', function() {
  22554. expect(element(by.binding('count')).getText()).toMatch('0');
  22555. element(by.css('button')).click();
  22556. expect(element(by.binding('count')).getText()).toMatch('1');
  22557. });
  22558. </file>
  22559. </example>
  22560. */
  22561. /*
  22562. * A collection of directives that allows creation of custom event handlers that are defined as
  22563. * angular expressions and are compiled and executed within the current scope.
  22564. */
  22565. var ngEventDirectives = {};
  22566. // For events that might fire synchronously during DOM manipulation
  22567. // we need to execute their event handlers asynchronously using $evalAsync,
  22568. // so that they are not executed in an inconsistent state.
  22569. var forceAsyncEvents = {
  22570. 'blur': true,
  22571. 'focus': true
  22572. };
  22573. forEach(
  22574. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  22575. function(eventName) {
  22576. var directiveName = directiveNormalize('ng-' + eventName);
  22577. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  22578. return {
  22579. restrict: 'A',
  22580. compile: function($element, attr) {
  22581. // We expose the powerful $event object on the scope that provides access to the Window,
  22582. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  22583. // checks at the cost of speed since event handler expressions are not executed as
  22584. // frequently as regular change detection.
  22585. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
  22586. return function ngEventHandler(scope, element) {
  22587. element.on(eventName, function(event) {
  22588. var callback = function() {
  22589. fn(scope, {$event:event});
  22590. };
  22591. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  22592. scope.$evalAsync(callback);
  22593. } else {
  22594. scope.$apply(callback);
  22595. }
  22596. });
  22597. };
  22598. }
  22599. };
  22600. }];
  22601. }
  22602. );
  22603. /**
  22604. * @ngdoc directive
  22605. * @name ngDblclick
  22606. *
  22607. * @description
  22608. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  22609. *
  22610. * @element ANY
  22611. * @priority 0
  22612. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  22613. * a dblclick. (The Event object is available as `$event`)
  22614. *
  22615. * @example
  22616. <example>
  22617. <file name="index.html">
  22618. <button ng-dblclick="count = count + 1" ng-init="count=0">
  22619. Increment (on double click)
  22620. </button>
  22621. count: {{count}}
  22622. </file>
  22623. </example>
  22624. */
  22625. /**
  22626. * @ngdoc directive
  22627. * @name ngMousedown
  22628. *
  22629. * @description
  22630. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  22631. *
  22632. * @element ANY
  22633. * @priority 0
  22634. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  22635. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  22636. *
  22637. * @example
  22638. <example>
  22639. <file name="index.html">
  22640. <button ng-mousedown="count = count + 1" ng-init="count=0">
  22641. Increment (on mouse down)
  22642. </button>
  22643. count: {{count}}
  22644. </file>
  22645. </example>
  22646. */
  22647. /**
  22648. * @ngdoc directive
  22649. * @name ngMouseup
  22650. *
  22651. * @description
  22652. * Specify custom behavior on mouseup event.
  22653. *
  22654. * @element ANY
  22655. * @priority 0
  22656. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  22657. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  22658. *
  22659. * @example
  22660. <example>
  22661. <file name="index.html">
  22662. <button ng-mouseup="count = count + 1" ng-init="count=0">
  22663. Increment (on mouse up)
  22664. </button>
  22665. count: {{count}}
  22666. </file>
  22667. </example>
  22668. */
  22669. /**
  22670. * @ngdoc directive
  22671. * @name ngMouseover
  22672. *
  22673. * @description
  22674. * Specify custom behavior on mouseover event.
  22675. *
  22676. * @element ANY
  22677. * @priority 0
  22678. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  22679. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  22680. *
  22681. * @example
  22682. <example>
  22683. <file name="index.html">
  22684. <button ng-mouseover="count = count + 1" ng-init="count=0">
  22685. Increment (when mouse is over)
  22686. </button>
  22687. count: {{count}}
  22688. </file>
  22689. </example>
  22690. */
  22691. /**
  22692. * @ngdoc directive
  22693. * @name ngMouseenter
  22694. *
  22695. * @description
  22696. * Specify custom behavior on mouseenter event.
  22697. *
  22698. * @element ANY
  22699. * @priority 0
  22700. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  22701. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  22702. *
  22703. * @example
  22704. <example>
  22705. <file name="index.html">
  22706. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  22707. Increment (when mouse enters)
  22708. </button>
  22709. count: {{count}}
  22710. </file>
  22711. </example>
  22712. */
  22713. /**
  22714. * @ngdoc directive
  22715. * @name ngMouseleave
  22716. *
  22717. * @description
  22718. * Specify custom behavior on mouseleave event.
  22719. *
  22720. * @element ANY
  22721. * @priority 0
  22722. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  22723. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  22724. *
  22725. * @example
  22726. <example>
  22727. <file name="index.html">
  22728. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  22729. Increment (when mouse leaves)
  22730. </button>
  22731. count: {{count}}
  22732. </file>
  22733. </example>
  22734. */
  22735. /**
  22736. * @ngdoc directive
  22737. * @name ngMousemove
  22738. *
  22739. * @description
  22740. * Specify custom behavior on mousemove event.
  22741. *
  22742. * @element ANY
  22743. * @priority 0
  22744. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  22745. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  22746. *
  22747. * @example
  22748. <example>
  22749. <file name="index.html">
  22750. <button ng-mousemove="count = count + 1" ng-init="count=0">
  22751. Increment (when mouse moves)
  22752. </button>
  22753. count: {{count}}
  22754. </file>
  22755. </example>
  22756. */
  22757. /**
  22758. * @ngdoc directive
  22759. * @name ngKeydown
  22760. *
  22761. * @description
  22762. * Specify custom behavior on keydown event.
  22763. *
  22764. * @element ANY
  22765. * @priority 0
  22766. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  22767. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  22768. *
  22769. * @example
  22770. <example>
  22771. <file name="index.html">
  22772. <input ng-keydown="count = count + 1" ng-init="count=0">
  22773. key down count: {{count}}
  22774. </file>
  22775. </example>
  22776. */
  22777. /**
  22778. * @ngdoc directive
  22779. * @name ngKeyup
  22780. *
  22781. * @description
  22782. * Specify custom behavior on keyup event.
  22783. *
  22784. * @element ANY
  22785. * @priority 0
  22786. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  22787. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  22788. *
  22789. * @example
  22790. <example>
  22791. <file name="index.html">
  22792. <p>Typing in the input box below updates the key count</p>
  22793. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  22794. <p>Typing in the input box below updates the keycode</p>
  22795. <input ng-keyup="event=$event">
  22796. <p>event keyCode: {{ event.keyCode }}</p>
  22797. <p>event altKey: {{ event.altKey }}</p>
  22798. </file>
  22799. </example>
  22800. */
  22801. /**
  22802. * @ngdoc directive
  22803. * @name ngKeypress
  22804. *
  22805. * @description
  22806. * Specify custom behavior on keypress event.
  22807. *
  22808. * @element ANY
  22809. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  22810. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  22811. * and can be interrogated for keyCode, altKey, etc.)
  22812. *
  22813. * @example
  22814. <example>
  22815. <file name="index.html">
  22816. <input ng-keypress="count = count + 1" ng-init="count=0">
  22817. key press count: {{count}}
  22818. </file>
  22819. </example>
  22820. */
  22821. /**
  22822. * @ngdoc directive
  22823. * @name ngSubmit
  22824. *
  22825. * @description
  22826. * Enables binding angular expressions to onsubmit events.
  22827. *
  22828. * Additionally it prevents the default action (which for form means sending the request to the
  22829. * server and reloading the current page), but only if the form does not contain `action`,
  22830. * `data-action`, or `x-action` attributes.
  22831. *
  22832. * <div class="alert alert-warning">
  22833. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  22834. * `ngSubmit` handlers together. See the
  22835. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  22836. * for a detailed discussion of when `ngSubmit` may be triggered.
  22837. * </div>
  22838. *
  22839. * @element form
  22840. * @priority 0
  22841. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  22842. * ({@link guide/expression#-event- Event object is available as `$event`})
  22843. *
  22844. * @example
  22845. <example module="submitExample">
  22846. <file name="index.html">
  22847. <script>
  22848. angular.module('submitExample', [])
  22849. .controller('ExampleController', ['$scope', function($scope) {
  22850. $scope.list = [];
  22851. $scope.text = 'hello';
  22852. $scope.submit = function() {
  22853. if ($scope.text) {
  22854. $scope.list.push(this.text);
  22855. $scope.text = '';
  22856. }
  22857. };
  22858. }]);
  22859. </script>
  22860. <form ng-submit="submit()" ng-controller="ExampleController">
  22861. Enter text and hit enter:
  22862. <input type="text" ng-model="text" name="text" />
  22863. <input type="submit" id="submit" value="Submit" />
  22864. <pre>list={{list}}</pre>
  22865. </form>
  22866. </file>
  22867. <file name="protractor.js" type="protractor">
  22868. it('should check ng-submit', function() {
  22869. expect(element(by.binding('list')).getText()).toBe('list=[]');
  22870. element(by.css('#submit')).click();
  22871. expect(element(by.binding('list')).getText()).toContain('hello');
  22872. expect(element(by.model('text')).getAttribute('value')).toBe('');
  22873. });
  22874. it('should ignore empty strings', function() {
  22875. expect(element(by.binding('list')).getText()).toBe('list=[]');
  22876. element(by.css('#submit')).click();
  22877. element(by.css('#submit')).click();
  22878. expect(element(by.binding('list')).getText()).toContain('hello');
  22879. });
  22880. </file>
  22881. </example>
  22882. */
  22883. /**
  22884. * @ngdoc directive
  22885. * @name ngFocus
  22886. *
  22887. * @description
  22888. * Specify custom behavior on focus event.
  22889. *
  22890. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  22891. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  22892. * during an `$apply` to ensure a consistent state.
  22893. *
  22894. * @element window, input, select, textarea, a
  22895. * @priority 0
  22896. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  22897. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  22898. *
  22899. * @example
  22900. * See {@link ng.directive:ngClick ngClick}
  22901. */
  22902. /**
  22903. * @ngdoc directive
  22904. * @name ngBlur
  22905. *
  22906. * @description
  22907. * Specify custom behavior on blur event.
  22908. *
  22909. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  22910. * an element has lost focus.
  22911. *
  22912. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  22913. * (e.g. removing a focussed input),
  22914. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  22915. * during an `$apply` to ensure a consistent state.
  22916. *
  22917. * @element window, input, select, textarea, a
  22918. * @priority 0
  22919. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  22920. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  22921. *
  22922. * @example
  22923. * See {@link ng.directive:ngClick ngClick}
  22924. */
  22925. /**
  22926. * @ngdoc directive
  22927. * @name ngCopy
  22928. *
  22929. * @description
  22930. * Specify custom behavior on copy event.
  22931. *
  22932. * @element window, input, select, textarea, a
  22933. * @priority 0
  22934. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  22935. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  22936. *
  22937. * @example
  22938. <example>
  22939. <file name="index.html">
  22940. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  22941. copied: {{copied}}
  22942. </file>
  22943. </example>
  22944. */
  22945. /**
  22946. * @ngdoc directive
  22947. * @name ngCut
  22948. *
  22949. * @description
  22950. * Specify custom behavior on cut event.
  22951. *
  22952. * @element window, input, select, textarea, a
  22953. * @priority 0
  22954. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  22955. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  22956. *
  22957. * @example
  22958. <example>
  22959. <file name="index.html">
  22960. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  22961. cut: {{cut}}
  22962. </file>
  22963. </example>
  22964. */
  22965. /**
  22966. * @ngdoc directive
  22967. * @name ngPaste
  22968. *
  22969. * @description
  22970. * Specify custom behavior on paste event.
  22971. *
  22972. * @element window, input, select, textarea, a
  22973. * @priority 0
  22974. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  22975. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  22976. *
  22977. * @example
  22978. <example>
  22979. <file name="index.html">
  22980. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  22981. pasted: {{paste}}
  22982. </file>
  22983. </example>
  22984. */
  22985. /**
  22986. * @ngdoc directive
  22987. * @name ngIf
  22988. * @restrict A
  22989. * @multiElement
  22990. *
  22991. * @description
  22992. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  22993. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  22994. * value then the element is removed from the DOM, otherwise a clone of the
  22995. * element is reinserted into the DOM.
  22996. *
  22997. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  22998. * element in the DOM rather than changing its visibility via the `display` css property. A common
  22999. * case when this difference is significant is when using css selectors that rely on an element's
  23000. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  23001. *
  23002. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  23003. * is created when the element is restored. The scope created within `ngIf` inherits from
  23004. * its parent scope using
  23005. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  23006. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  23007. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  23008. * variable within the child scope will override (hide) the value in the parent scope.
  23009. *
  23010. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  23011. * is if an element's class attribute is directly modified after it's compiled, using something like
  23012. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  23013. * the added class will be lost because the original compiled state is used to regenerate the element.
  23014. *
  23015. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  23016. * and `leave` effects.
  23017. *
  23018. * @animations
  23019. * | Animation | Occurs |
  23020. * |----------------------------------|-------------------------------------|
  23021. * | {@link ng.$animate#enter enter} | just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container |
  23022. * | {@link ng.$animate#leave leave} | just before the `ngIf` contents are removed from the DOM |
  23023. *
  23024. * @element ANY
  23025. * @scope
  23026. * @priority 600
  23027. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  23028. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  23029. * element is added to the DOM tree.
  23030. *
  23031. * @example
  23032. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  23033. <file name="index.html">
  23034. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  23035. Show when checked:
  23036. <span ng-if="checked" class="animate-if">
  23037. This is removed when the checkbox is unchecked.
  23038. </span>
  23039. </file>
  23040. <file name="animations.css">
  23041. .animate-if {
  23042. background:white;
  23043. border:1px solid black;
  23044. padding:10px;
  23045. }
  23046. .animate-if.ng-enter, .animate-if.ng-leave {
  23047. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  23048. }
  23049. .animate-if.ng-enter,
  23050. .animate-if.ng-leave.ng-leave-active {
  23051. opacity:0;
  23052. }
  23053. .animate-if.ng-leave,
  23054. .animate-if.ng-enter.ng-enter-active {
  23055. opacity:1;
  23056. }
  23057. </file>
  23058. </example>
  23059. */
  23060. var ngIfDirective = ['$animate', '$compile', function($animate, $compile) {
  23061. return {
  23062. multiElement: true,
  23063. transclude: 'element',
  23064. priority: 600,
  23065. terminal: true,
  23066. restrict: 'A',
  23067. $$tlb: true,
  23068. link: function($scope, $element, $attr, ctrl, $transclude) {
  23069. var block, childScope, previousElements;
  23070. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  23071. if (value) {
  23072. if (!childScope) {
  23073. $transclude(function(clone, newScope) {
  23074. childScope = newScope;
  23075. clone[clone.length++] = $compile.$$createComment('end ngIf', $attr.ngIf);
  23076. // Note: We only need the first/last node of the cloned nodes.
  23077. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  23078. // by a directive with templateUrl when its template arrives.
  23079. block = {
  23080. clone: clone
  23081. };
  23082. $animate.enter(clone, $element.parent(), $element);
  23083. });
  23084. }
  23085. } else {
  23086. if (previousElements) {
  23087. previousElements.remove();
  23088. previousElements = null;
  23089. }
  23090. if (childScope) {
  23091. childScope.$destroy();
  23092. childScope = null;
  23093. }
  23094. if (block) {
  23095. previousElements = getBlockNodes(block.clone);
  23096. $animate.leave(previousElements).then(function() {
  23097. previousElements = null;
  23098. });
  23099. block = null;
  23100. }
  23101. }
  23102. });
  23103. }
  23104. };
  23105. }];
  23106. /**
  23107. * @ngdoc directive
  23108. * @name ngInclude
  23109. * @restrict ECA
  23110. *
  23111. * @description
  23112. * Fetches, compiles and includes an external HTML fragment.
  23113. *
  23114. * By default, the template URL is restricted to the same domain and protocol as the
  23115. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  23116. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  23117. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  23118. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  23119. * ng.$sce Strict Contextual Escaping}.
  23120. *
  23121. * In addition, the browser's
  23122. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  23123. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  23124. * policy may further restrict whether the template is successfully loaded.
  23125. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  23126. * access on some browsers.
  23127. *
  23128. * @animations
  23129. * | Animation | Occurs |
  23130. * |----------------------------------|-------------------------------------|
  23131. * | {@link ng.$animate#enter enter} | when the expression changes, on the new include |
  23132. * | {@link ng.$animate#leave leave} | when the expression changes, on the old include |
  23133. *
  23134. * The enter and leave animation occur concurrently.
  23135. *
  23136. * @scope
  23137. * @priority 400
  23138. *
  23139. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  23140. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  23141. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  23142. * <div class="alert alert-warning">
  23143. * **Note:** When using onload on SVG elements in IE11, the browser will try to call
  23144. * a function with the name on the window element, which will usually throw a
  23145. * "function is undefined" error. To fix this, you can instead use `data-onload` or a
  23146. * different form that {@link guide/directive#normalization matches} `onload`.
  23147. * </div>
  23148. *
  23149. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  23150. * $anchorScroll} to scroll the viewport after the content is loaded.
  23151. *
  23152. * - If the attribute is not set, disable scrolling.
  23153. * - If the attribute is set without value, enable scrolling.
  23154. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  23155. *
  23156. * @example
  23157. <example module="includeExample" deps="angular-animate.js" animations="true">
  23158. <file name="index.html">
  23159. <div ng-controller="ExampleController">
  23160. <select ng-model="template" ng-options="t.name for t in templates">
  23161. <option value="">(blank)</option>
  23162. </select>
  23163. url of the template: <code>{{template.url}}</code>
  23164. <hr/>
  23165. <div class="slide-animate-container">
  23166. <div class="slide-animate" ng-include="template.url"></div>
  23167. </div>
  23168. </div>
  23169. </file>
  23170. <file name="script.js">
  23171. angular.module('includeExample', ['ngAnimate'])
  23172. .controller('ExampleController', ['$scope', function($scope) {
  23173. $scope.templates =
  23174. [ { name: 'template1.html', url: 'template1.html'},
  23175. { name: 'template2.html', url: 'template2.html'} ];
  23176. $scope.template = $scope.templates[0];
  23177. }]);
  23178. </file>
  23179. <file name="template1.html">
  23180. Content of template1.html
  23181. </file>
  23182. <file name="template2.html">
  23183. Content of template2.html
  23184. </file>
  23185. <file name="animations.css">
  23186. .slide-animate-container {
  23187. position:relative;
  23188. background:white;
  23189. border:1px solid black;
  23190. height:40px;
  23191. overflow:hidden;
  23192. }
  23193. .slide-animate {
  23194. padding:10px;
  23195. }
  23196. .slide-animate.ng-enter, .slide-animate.ng-leave {
  23197. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  23198. position:absolute;
  23199. top:0;
  23200. left:0;
  23201. right:0;
  23202. bottom:0;
  23203. display:block;
  23204. padding:10px;
  23205. }
  23206. .slide-animate.ng-enter {
  23207. top:-50px;
  23208. }
  23209. .slide-animate.ng-enter.ng-enter-active {
  23210. top:0;
  23211. }
  23212. .slide-animate.ng-leave {
  23213. top:0;
  23214. }
  23215. .slide-animate.ng-leave.ng-leave-active {
  23216. top:50px;
  23217. }
  23218. </file>
  23219. <file name="protractor.js" type="protractor">
  23220. var templateSelect = element(by.model('template'));
  23221. var includeElem = element(by.css('[ng-include]'));
  23222. it('should load template1.html', function() {
  23223. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  23224. });
  23225. it('should load template2.html', function() {
  23226. if (browser.params.browser == 'firefox') {
  23227. // Firefox can't handle using selects
  23228. // See https://github.com/angular/protractor/issues/480
  23229. return;
  23230. }
  23231. templateSelect.click();
  23232. templateSelect.all(by.css('option')).get(2).click();
  23233. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  23234. });
  23235. it('should change to blank', function() {
  23236. if (browser.params.browser == 'firefox') {
  23237. // Firefox can't handle using selects
  23238. return;
  23239. }
  23240. templateSelect.click();
  23241. templateSelect.all(by.css('option')).get(0).click();
  23242. expect(includeElem.isPresent()).toBe(false);
  23243. });
  23244. </file>
  23245. </example>
  23246. */
  23247. /**
  23248. * @ngdoc event
  23249. * @name ngInclude#$includeContentRequested
  23250. * @eventType emit on the scope ngInclude was declared in
  23251. * @description
  23252. * Emitted every time the ngInclude content is requested.
  23253. *
  23254. * @param {Object} angularEvent Synthetic event object.
  23255. * @param {String} src URL of content to load.
  23256. */
  23257. /**
  23258. * @ngdoc event
  23259. * @name ngInclude#$includeContentLoaded
  23260. * @eventType emit on the current ngInclude scope
  23261. * @description
  23262. * Emitted every time the ngInclude content is reloaded.
  23263. *
  23264. * @param {Object} angularEvent Synthetic event object.
  23265. * @param {String} src URL of content to load.
  23266. */
  23267. /**
  23268. * @ngdoc event
  23269. * @name ngInclude#$includeContentError
  23270. * @eventType emit on the scope ngInclude was declared in
  23271. * @description
  23272. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  23273. *
  23274. * @param {Object} angularEvent Synthetic event object.
  23275. * @param {String} src URL of content to load.
  23276. */
  23277. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
  23278. function($templateRequest, $anchorScroll, $animate) {
  23279. return {
  23280. restrict: 'ECA',
  23281. priority: 400,
  23282. terminal: true,
  23283. transclude: 'element',
  23284. controller: angular.noop,
  23285. compile: function(element, attr) {
  23286. var srcExp = attr.ngInclude || attr.src,
  23287. onloadExp = attr.onload || '',
  23288. autoScrollExp = attr.autoscroll;
  23289. return function(scope, $element, $attr, ctrl, $transclude) {
  23290. var changeCounter = 0,
  23291. currentScope,
  23292. previousElement,
  23293. currentElement;
  23294. var cleanupLastIncludeContent = function() {
  23295. if (previousElement) {
  23296. previousElement.remove();
  23297. previousElement = null;
  23298. }
  23299. if (currentScope) {
  23300. currentScope.$destroy();
  23301. currentScope = null;
  23302. }
  23303. if (currentElement) {
  23304. $animate.leave(currentElement).then(function() {
  23305. previousElement = null;
  23306. });
  23307. previousElement = currentElement;
  23308. currentElement = null;
  23309. }
  23310. };
  23311. scope.$watch(srcExp, function ngIncludeWatchAction(src) {
  23312. var afterAnimation = function() {
  23313. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  23314. $anchorScroll();
  23315. }
  23316. };
  23317. var thisChangeId = ++changeCounter;
  23318. if (src) {
  23319. //set the 2nd param to true to ignore the template request error so that the inner
  23320. //contents and scope can be cleaned up.
  23321. $templateRequest(src, true).then(function(response) {
  23322. if (scope.$$destroyed) return;
  23323. if (thisChangeId !== changeCounter) return;
  23324. var newScope = scope.$new();
  23325. ctrl.template = response;
  23326. // Note: This will also link all children of ng-include that were contained in the original
  23327. // html. If that content contains controllers, ... they could pollute/change the scope.
  23328. // However, using ng-include on an element with additional content does not make sense...
  23329. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  23330. // function is called before linking the content, which would apply child
  23331. // directives to non existing elements.
  23332. var clone = $transclude(newScope, function(clone) {
  23333. cleanupLastIncludeContent();
  23334. $animate.enter(clone, null, $element).then(afterAnimation);
  23335. });
  23336. currentScope = newScope;
  23337. currentElement = clone;
  23338. currentScope.$emit('$includeContentLoaded', src);
  23339. scope.$eval(onloadExp);
  23340. }, function() {
  23341. if (scope.$$destroyed) return;
  23342. if (thisChangeId === changeCounter) {
  23343. cleanupLastIncludeContent();
  23344. scope.$emit('$includeContentError', src);
  23345. }
  23346. });
  23347. scope.$emit('$includeContentRequested', src);
  23348. } else {
  23349. cleanupLastIncludeContent();
  23350. ctrl.template = null;
  23351. }
  23352. });
  23353. };
  23354. }
  23355. };
  23356. }];
  23357. // This directive is called during the $transclude call of the first `ngInclude` directive.
  23358. // It will replace and compile the content of the element with the loaded template.
  23359. // We need this directive so that the element content is already filled when
  23360. // the link function of another directive on the same element as ngInclude
  23361. // is called.
  23362. var ngIncludeFillContentDirective = ['$compile',
  23363. function($compile) {
  23364. return {
  23365. restrict: 'ECA',
  23366. priority: -400,
  23367. require: 'ngInclude',
  23368. link: function(scope, $element, $attr, ctrl) {
  23369. if (toString.call($element[0]).match(/SVG/)) {
  23370. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  23371. // support innerHTML, so detect this here and try to generate the contents
  23372. // specially.
  23373. $element.empty();
  23374. $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
  23375. function namespaceAdaptedClone(clone) {
  23376. $element.append(clone);
  23377. }, {futureParentElement: $element});
  23378. return;
  23379. }
  23380. $element.html(ctrl.template);
  23381. $compile($element.contents())(scope);
  23382. }
  23383. };
  23384. }];
  23385. /**
  23386. * @ngdoc directive
  23387. * @name ngInit
  23388. * @restrict AC
  23389. *
  23390. * @description
  23391. * The `ngInit` directive allows you to evaluate an expression in the
  23392. * current scope.
  23393. *
  23394. * <div class="alert alert-danger">
  23395. * This directive can be abused to add unnecessary amounts of logic into your templates.
  23396. * There are only a few appropriate uses of `ngInit`, such as for aliasing special properties of
  23397. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below; and for injecting data via
  23398. * server side scripting. Besides these few cases, you should use {@link guide/controller controllers}
  23399. * rather than `ngInit` to initialize values on a scope.
  23400. * </div>
  23401. *
  23402. * <div class="alert alert-warning">
  23403. * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
  23404. * sure you have parentheses to ensure correct operator precedence:
  23405. * <pre class="prettyprint">
  23406. * `<div ng-init="test1 = ($index | toString)"></div>`
  23407. * </pre>
  23408. * </div>
  23409. *
  23410. * @priority 450
  23411. *
  23412. * @element ANY
  23413. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  23414. *
  23415. * @example
  23416. <example module="initExample">
  23417. <file name="index.html">
  23418. <script>
  23419. angular.module('initExample', [])
  23420. .controller('ExampleController', ['$scope', function($scope) {
  23421. $scope.list = [['a', 'b'], ['c', 'd']];
  23422. }]);
  23423. </script>
  23424. <div ng-controller="ExampleController">
  23425. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  23426. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  23427. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  23428. </div>
  23429. </div>
  23430. </div>
  23431. </file>
  23432. <file name="protractor.js" type="protractor">
  23433. it('should alias index positions', function() {
  23434. var elements = element.all(by.css('.example-init'));
  23435. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  23436. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  23437. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  23438. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  23439. });
  23440. </file>
  23441. </example>
  23442. */
  23443. var ngInitDirective = ngDirective({
  23444. priority: 450,
  23445. compile: function() {
  23446. return {
  23447. pre: function(scope, element, attrs) {
  23448. scope.$eval(attrs.ngInit);
  23449. }
  23450. };
  23451. }
  23452. });
  23453. /**
  23454. * @ngdoc directive
  23455. * @name ngList
  23456. *
  23457. * @description
  23458. * Text input that converts between a delimited string and an array of strings. The default
  23459. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  23460. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  23461. *
  23462. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  23463. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  23464. * list item is respected. This implies that the user of the directive is responsible for
  23465. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  23466. * tab or newline character.
  23467. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  23468. * when joining the list items back together) and whitespace around each list item is stripped
  23469. * before it is added to the model.
  23470. *
  23471. * ### Example with Validation
  23472. *
  23473. * <example name="ngList-directive" module="listExample">
  23474. * <file name="app.js">
  23475. * angular.module('listExample', [])
  23476. * .controller('ExampleController', ['$scope', function($scope) {
  23477. * $scope.names = ['morpheus', 'neo', 'trinity'];
  23478. * }]);
  23479. * </file>
  23480. * <file name="index.html">
  23481. * <form name="myForm" ng-controller="ExampleController">
  23482. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  23483. * <span role="alert">
  23484. * <span class="error" ng-show="myForm.namesInput.$error.required">
  23485. * Required!</span>
  23486. * </span>
  23487. * <br>
  23488. * <tt>names = {{names}}</tt><br/>
  23489. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  23490. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  23491. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23492. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23493. * </form>
  23494. * </file>
  23495. * <file name="protractor.js" type="protractor">
  23496. * var listInput = element(by.model('names'));
  23497. * var names = element(by.exactBinding('names'));
  23498. * var valid = element(by.binding('myForm.namesInput.$valid'));
  23499. * var error = element(by.css('span.error'));
  23500. *
  23501. * it('should initialize to model', function() {
  23502. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  23503. * expect(valid.getText()).toContain('true');
  23504. * expect(error.getCssValue('display')).toBe('none');
  23505. * });
  23506. *
  23507. * it('should be invalid if empty', function() {
  23508. * listInput.clear();
  23509. * listInput.sendKeys('');
  23510. *
  23511. * expect(names.getText()).toContain('');
  23512. * expect(valid.getText()).toContain('false');
  23513. * expect(error.getCssValue('display')).not.toBe('none');
  23514. * });
  23515. * </file>
  23516. * </example>
  23517. *
  23518. * ### Example - splitting on newline
  23519. * <example name="ngList-directive-newlines">
  23520. * <file name="index.html">
  23521. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  23522. * <pre>{{ list | json }}</pre>
  23523. * </file>
  23524. * <file name="protractor.js" type="protractor">
  23525. * it("should split the text by newlines", function() {
  23526. * var listInput = element(by.model('list'));
  23527. * var output = element(by.binding('list | json'));
  23528. * listInput.sendKeys('abc\ndef\nghi');
  23529. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  23530. * });
  23531. * </file>
  23532. * </example>
  23533. *
  23534. * @element input
  23535. * @param {string=} ngList optional delimiter that should be used to split the value.
  23536. */
  23537. var ngListDirective = function() {
  23538. return {
  23539. restrict: 'A',
  23540. priority: 100,
  23541. require: 'ngModel',
  23542. link: function(scope, element, attr, ctrl) {
  23543. // We want to control whitespace trimming so we use this convoluted approach
  23544. // to access the ngList attribute, which doesn't pre-trim the attribute
  23545. var ngList = element.attr(attr.$attr.ngList) || ', ';
  23546. var trimValues = attr.ngTrim !== 'false';
  23547. var separator = trimValues ? trim(ngList) : ngList;
  23548. var parse = function(viewValue) {
  23549. // If the viewValue is invalid (say required but empty) it will be `undefined`
  23550. if (isUndefined(viewValue)) return;
  23551. var list = [];
  23552. if (viewValue) {
  23553. forEach(viewValue.split(separator), function(value) {
  23554. if (value) list.push(trimValues ? trim(value) : value);
  23555. });
  23556. }
  23557. return list;
  23558. };
  23559. ctrl.$parsers.push(parse);
  23560. ctrl.$formatters.push(function(value) {
  23561. if (isArray(value)) {
  23562. return value.join(ngList);
  23563. }
  23564. return undefined;
  23565. });
  23566. // Override the standard $isEmpty because an empty array means the input is empty.
  23567. ctrl.$isEmpty = function(value) {
  23568. return !value || !value.length;
  23569. };
  23570. }
  23571. };
  23572. };
  23573. /* global VALID_CLASS: true,
  23574. INVALID_CLASS: true,
  23575. PRISTINE_CLASS: true,
  23576. DIRTY_CLASS: true,
  23577. UNTOUCHED_CLASS: true,
  23578. TOUCHED_CLASS: true,
  23579. */
  23580. var VALID_CLASS = 'ng-valid',
  23581. INVALID_CLASS = 'ng-invalid',
  23582. PRISTINE_CLASS = 'ng-pristine',
  23583. DIRTY_CLASS = 'ng-dirty',
  23584. UNTOUCHED_CLASS = 'ng-untouched',
  23585. TOUCHED_CLASS = 'ng-touched',
  23586. PENDING_CLASS = 'ng-pending',
  23587. EMPTY_CLASS = 'ng-empty',
  23588. NOT_EMPTY_CLASS = 'ng-not-empty';
  23589. var ngModelMinErr = minErr('ngModel');
  23590. /**
  23591. * @ngdoc type
  23592. * @name ngModel.NgModelController
  23593. *
  23594. * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
  23595. * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
  23596. * is set.
  23597. * @property {*} $modelValue The value in the model that the control is bound to.
  23598. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  23599. the control reads value from the DOM. The functions are called in array order, each passing
  23600. its return value through to the next. The last return value is forwarded to the
  23601. {@link ngModel.NgModelController#$validators `$validators`} collection.
  23602. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  23603. `$viewValue`}.
  23604. Returning `undefined` from a parser means a parse error occurred. In that case,
  23605. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  23606. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  23607. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  23608. *
  23609. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  23610. the model value changes. The functions are called in reverse array order, each passing the value through to the
  23611. next. The last return value is used as the actual DOM value.
  23612. Used to format / convert values for display in the control.
  23613. * ```js
  23614. * function formatter(value) {
  23615. * if (value) {
  23616. * return value.toUpperCase();
  23617. * }
  23618. * }
  23619. * ngModel.$formatters.push(formatter);
  23620. * ```
  23621. *
  23622. * @property {Object.<string, function>} $validators A collection of validators that are applied
  23623. * whenever the model value changes. The key value within the object refers to the name of the
  23624. * validator while the function refers to the validation operation. The validation operation is
  23625. * provided with the model value as an argument and must return a true or false value depending
  23626. * on the response of that validation.
  23627. *
  23628. * ```js
  23629. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  23630. * var value = modelValue || viewValue;
  23631. * return /[0-9]+/.test(value) &&
  23632. * /[a-z]+/.test(value) &&
  23633. * /[A-Z]+/.test(value) &&
  23634. * /\W+/.test(value);
  23635. * };
  23636. * ```
  23637. *
  23638. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  23639. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  23640. * is expected to return a promise when it is run during the model validation process. Once the promise
  23641. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  23642. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  23643. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  23644. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  23645. * will only run once all synchronous validators have passed.
  23646. *
  23647. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  23648. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  23649. *
  23650. * ```js
  23651. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  23652. * var value = modelValue || viewValue;
  23653. *
  23654. * // Lookup user by username
  23655. * return $http.get('/api/users/' + value).
  23656. * then(function resolved() {
  23657. * //username exists, this means validation fails
  23658. * return $q.reject('exists');
  23659. * }, function rejected() {
  23660. * //username does not exist, therefore this validation passes
  23661. * return true;
  23662. * });
  23663. * };
  23664. * ```
  23665. *
  23666. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  23667. * view value has changed. It is called with no arguments, and its return value is ignored.
  23668. * This can be used in place of additional $watches against the model value.
  23669. *
  23670. * @property {Object} $error An object hash with all failing validator ids as keys.
  23671. * @property {Object} $pending An object hash with all pending validator ids as keys.
  23672. *
  23673. * @property {boolean} $untouched True if control has not lost focus yet.
  23674. * @property {boolean} $touched True if control has lost focus.
  23675. * @property {boolean} $pristine True if user has not interacted with the control yet.
  23676. * @property {boolean} $dirty True if user has already interacted with the control.
  23677. * @property {boolean} $valid True if there is no error.
  23678. * @property {boolean} $invalid True if at least one error on the control.
  23679. * @property {string} $name The name attribute of the control.
  23680. *
  23681. * @description
  23682. *
  23683. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  23684. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  23685. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  23686. * listening to DOM events.
  23687. * Such DOM related logic should be provided by other directives which make use of
  23688. * `NgModelController` for data-binding to control elements.
  23689. * Angular provides this DOM logic for most {@link input `input`} elements.
  23690. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  23691. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  23692. *
  23693. * @example
  23694. * ### Custom Control Example
  23695. * This example shows how to use `NgModelController` with a custom control to achieve
  23696. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  23697. * collaborate together to achieve the desired result.
  23698. *
  23699. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  23700. * contents be edited in place by the user.
  23701. *
  23702. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  23703. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  23704. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  23705. * that content using the `$sce` service.
  23706. *
  23707. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  23708. <file name="style.css">
  23709. [contenteditable] {
  23710. border: 1px solid black;
  23711. background-color: white;
  23712. min-height: 20px;
  23713. }
  23714. .ng-invalid {
  23715. border: 1px solid red;
  23716. }
  23717. </file>
  23718. <file name="script.js">
  23719. angular.module('customControl', ['ngSanitize']).
  23720. directive('contenteditable', ['$sce', function($sce) {
  23721. return {
  23722. restrict: 'A', // only activate on element attribute
  23723. require: '?ngModel', // get a hold of NgModelController
  23724. link: function(scope, element, attrs, ngModel) {
  23725. if (!ngModel) return; // do nothing if no ng-model
  23726. // Specify how UI should be updated
  23727. ngModel.$render = function() {
  23728. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  23729. };
  23730. // Listen for change events to enable binding
  23731. element.on('blur keyup change', function() {
  23732. scope.$evalAsync(read);
  23733. });
  23734. read(); // initialize
  23735. // Write data to the model
  23736. function read() {
  23737. var html = element.html();
  23738. // When we clear the content editable the browser leaves a <br> behind
  23739. // If strip-br attribute is provided then we strip this out
  23740. if ( attrs.stripBr && html == '<br>' ) {
  23741. html = '';
  23742. }
  23743. ngModel.$setViewValue(html);
  23744. }
  23745. }
  23746. };
  23747. }]);
  23748. </file>
  23749. <file name="index.html">
  23750. <form name="myForm">
  23751. <div contenteditable
  23752. name="myWidget" ng-model="userContent"
  23753. strip-br="true"
  23754. required>Change me!</div>
  23755. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  23756. <hr>
  23757. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  23758. </form>
  23759. </file>
  23760. <file name="protractor.js" type="protractor">
  23761. it('should data-bind and become invalid', function() {
  23762. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  23763. // SafariDriver can't handle contenteditable
  23764. // and Firefox driver can't clear contenteditables very well
  23765. return;
  23766. }
  23767. var contentEditable = element(by.css('[contenteditable]'));
  23768. var content = 'Change me!';
  23769. expect(contentEditable.getText()).toEqual(content);
  23770. contentEditable.clear();
  23771. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  23772. expect(contentEditable.getText()).toEqual('');
  23773. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  23774. });
  23775. </file>
  23776. * </example>
  23777. *
  23778. *
  23779. */
  23780. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
  23781. function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
  23782. this.$viewValue = Number.NaN;
  23783. this.$modelValue = Number.NaN;
  23784. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  23785. this.$validators = {};
  23786. this.$asyncValidators = {};
  23787. this.$parsers = [];
  23788. this.$formatters = [];
  23789. this.$viewChangeListeners = [];
  23790. this.$untouched = true;
  23791. this.$touched = false;
  23792. this.$pristine = true;
  23793. this.$dirty = false;
  23794. this.$valid = true;
  23795. this.$invalid = false;
  23796. this.$error = {}; // keep invalid keys here
  23797. this.$$success = {}; // keep valid keys here
  23798. this.$pending = undefined; // keep pending keys here
  23799. this.$name = $interpolate($attr.name || '', false)($scope);
  23800. this.$$parentForm = nullFormCtrl;
  23801. var parsedNgModel = $parse($attr.ngModel),
  23802. parsedNgModelAssign = parsedNgModel.assign,
  23803. ngModelGet = parsedNgModel,
  23804. ngModelSet = parsedNgModelAssign,
  23805. pendingDebounce = null,
  23806. parserValid,
  23807. ctrl = this;
  23808. this.$$setOptions = function(options) {
  23809. ctrl.$options = options;
  23810. if (options && options.getterSetter) {
  23811. var invokeModelGetter = $parse($attr.ngModel + '()'),
  23812. invokeModelSetter = $parse($attr.ngModel + '($$$p)');
  23813. ngModelGet = function($scope) {
  23814. var modelValue = parsedNgModel($scope);
  23815. if (isFunction(modelValue)) {
  23816. modelValue = invokeModelGetter($scope);
  23817. }
  23818. return modelValue;
  23819. };
  23820. ngModelSet = function($scope, newValue) {
  23821. if (isFunction(parsedNgModel($scope))) {
  23822. invokeModelSetter($scope, {$$$p: newValue});
  23823. } else {
  23824. parsedNgModelAssign($scope, newValue);
  23825. }
  23826. };
  23827. } else if (!parsedNgModel.assign) {
  23828. throw ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  23829. $attr.ngModel, startingTag($element));
  23830. }
  23831. };
  23832. /**
  23833. * @ngdoc method
  23834. * @name ngModel.NgModelController#$render
  23835. *
  23836. * @description
  23837. * Called when the view needs to be updated. It is expected that the user of the ng-model
  23838. * directive will implement this method.
  23839. *
  23840. * The `$render()` method is invoked in the following situations:
  23841. *
  23842. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  23843. * committed value then `$render()` is called to update the input control.
  23844. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  23845. * the `$viewValue` are different from last time.
  23846. *
  23847. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  23848. * `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue`
  23849. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  23850. * invoked if you only change a property on the objects.
  23851. */
  23852. this.$render = noop;
  23853. /**
  23854. * @ngdoc method
  23855. * @name ngModel.NgModelController#$isEmpty
  23856. *
  23857. * @description
  23858. * This is called when we need to determine if the value of an input is empty.
  23859. *
  23860. * For instance, the required directive does this to work out if the input has data or not.
  23861. *
  23862. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  23863. *
  23864. * You can override this for input directives whose concept of being empty is different from the
  23865. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  23866. * implies empty.
  23867. *
  23868. * @param {*} value The value of the input to check for emptiness.
  23869. * @returns {boolean} True if `value` is "empty".
  23870. */
  23871. this.$isEmpty = function(value) {
  23872. return isUndefined(value) || value === '' || value === null || value !== value;
  23873. };
  23874. this.$$updateEmptyClasses = function(value) {
  23875. if (ctrl.$isEmpty(value)) {
  23876. $animate.removeClass($element, NOT_EMPTY_CLASS);
  23877. $animate.addClass($element, EMPTY_CLASS);
  23878. } else {
  23879. $animate.removeClass($element, EMPTY_CLASS);
  23880. $animate.addClass($element, NOT_EMPTY_CLASS);
  23881. }
  23882. };
  23883. var currentValidationRunId = 0;
  23884. /**
  23885. * @ngdoc method
  23886. * @name ngModel.NgModelController#$setValidity
  23887. *
  23888. * @description
  23889. * Change the validity state, and notify the form.
  23890. *
  23891. * This method can be called within $parsers/$formatters or a custom validation implementation.
  23892. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  23893. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  23894. *
  23895. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  23896. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  23897. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  23898. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  23899. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  23900. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  23901. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  23902. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  23903. * Skipped is used by Angular when validators do not run because of parse errors and
  23904. * when `$asyncValidators` do not run because any of the `$validators` failed.
  23905. */
  23906. addSetValidityMethod({
  23907. ctrl: this,
  23908. $element: $element,
  23909. set: function(object, property) {
  23910. object[property] = true;
  23911. },
  23912. unset: function(object, property) {
  23913. delete object[property];
  23914. },
  23915. $animate: $animate
  23916. });
  23917. /**
  23918. * @ngdoc method
  23919. * @name ngModel.NgModelController#$setPristine
  23920. *
  23921. * @description
  23922. * Sets the control to its pristine state.
  23923. *
  23924. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  23925. * state (`ng-pristine` class). A model is considered to be pristine when the control
  23926. * has not been changed from when first compiled.
  23927. */
  23928. this.$setPristine = function() {
  23929. ctrl.$dirty = false;
  23930. ctrl.$pristine = true;
  23931. $animate.removeClass($element, DIRTY_CLASS);
  23932. $animate.addClass($element, PRISTINE_CLASS);
  23933. };
  23934. /**
  23935. * @ngdoc method
  23936. * @name ngModel.NgModelController#$setDirty
  23937. *
  23938. * @description
  23939. * Sets the control to its dirty state.
  23940. *
  23941. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  23942. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  23943. * from when first compiled.
  23944. */
  23945. this.$setDirty = function() {
  23946. ctrl.$dirty = true;
  23947. ctrl.$pristine = false;
  23948. $animate.removeClass($element, PRISTINE_CLASS);
  23949. $animate.addClass($element, DIRTY_CLASS);
  23950. ctrl.$$parentForm.$setDirty();
  23951. };
  23952. /**
  23953. * @ngdoc method
  23954. * @name ngModel.NgModelController#$setUntouched
  23955. *
  23956. * @description
  23957. * Sets the control to its untouched state.
  23958. *
  23959. * This method can be called to remove the `ng-touched` class and set the control to its
  23960. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  23961. * by default, however this function can be used to restore that state if the model has
  23962. * already been touched by the user.
  23963. */
  23964. this.$setUntouched = function() {
  23965. ctrl.$touched = false;
  23966. ctrl.$untouched = true;
  23967. $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  23968. };
  23969. /**
  23970. * @ngdoc method
  23971. * @name ngModel.NgModelController#$setTouched
  23972. *
  23973. * @description
  23974. * Sets the control to its touched state.
  23975. *
  23976. * This method can be called to remove the `ng-untouched` class and set the control to its
  23977. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  23978. * first focused the control element and then shifted focus away from the control (blur event).
  23979. */
  23980. this.$setTouched = function() {
  23981. ctrl.$touched = true;
  23982. ctrl.$untouched = false;
  23983. $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  23984. };
  23985. /**
  23986. * @ngdoc method
  23987. * @name ngModel.NgModelController#$rollbackViewValue
  23988. *
  23989. * @description
  23990. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  23991. * which may be caused by a pending debounced event or because the input is waiting for a some
  23992. * future event.
  23993. *
  23994. * If you have an input that uses `ng-model-options` to set up debounced updates or updates that
  23995. * depend on special events such as blur, you can have a situation where there is a period when
  23996. * the `$viewValue` is out of sync with the ngModel's `$modelValue`.
  23997. *
  23998. * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update
  23999. * and reset the input to the last committed view value.
  24000. *
  24001. * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`
  24002. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  24003. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  24004. *
  24005. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  24006. * input which may have such events pending. This is important in order to make sure that the
  24007. * input field will be updated with the new model value and any pending operations are cancelled.
  24008. *
  24009. * <example name="ng-model-cancel-update" module="cancel-update-example">
  24010. * <file name="app.js">
  24011. * angular.module('cancel-update-example', [])
  24012. *
  24013. * .controller('CancelUpdateController', ['$scope', function($scope) {
  24014. * $scope.model = {};
  24015. *
  24016. * $scope.setEmpty = function(e, value, rollback) {
  24017. * if (e.keyCode == 27) {
  24018. * e.preventDefault();
  24019. * if (rollback) {
  24020. * $scope.myForm[value].$rollbackViewValue();
  24021. * }
  24022. * $scope.model[value] = '';
  24023. * }
  24024. * };
  24025. * }]);
  24026. * </file>
  24027. * <file name="index.html">
  24028. * <div ng-controller="CancelUpdateController">
  24029. * <p>Both of these inputs are only updated if they are blurred. Hitting escape should
  24030. * empty them. Follow these steps and observe the difference:</p>
  24031. * <ol>
  24032. * <li>Type something in the input. You will see that the model is not yet updated</li>
  24033. * <li>Press the Escape key.
  24034. * <ol>
  24035. * <li> In the first example, nothing happens, because the model is already '', and no
  24036. * update is detected. If you blur the input, the model will be set to the current view.
  24037. * </li>
  24038. * <li> In the second example, the pending update is cancelled, and the input is set back
  24039. * to the last committed view value (''). Blurring the input does nothing.
  24040. * </li>
  24041. * </ol>
  24042. * </li>
  24043. * </ol>
  24044. *
  24045. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  24046. * <div>
  24047. * <p id="inputDescription1">Without $rollbackViewValue():</p>
  24048. * <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1"
  24049. * ng-keydown="setEmpty($event, 'value1')">
  24050. * value1: "{{ model.value1 }}"
  24051. * </div>
  24052. *
  24053. * <div>
  24054. * <p id="inputDescription2">With $rollbackViewValue():</p>
  24055. * <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2"
  24056. * ng-keydown="setEmpty($event, 'value2', true)">
  24057. * value2: "{{ model.value2 }}"
  24058. * </div>
  24059. * </form>
  24060. * </div>
  24061. * </file>
  24062. <file name="style.css">
  24063. div {
  24064. display: table-cell;
  24065. }
  24066. div:nth-child(1) {
  24067. padding-right: 30px;
  24068. }
  24069. </file>
  24070. * </example>
  24071. */
  24072. this.$rollbackViewValue = function() {
  24073. $timeout.cancel(pendingDebounce);
  24074. ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
  24075. ctrl.$render();
  24076. };
  24077. /**
  24078. * @ngdoc method
  24079. * @name ngModel.NgModelController#$validate
  24080. *
  24081. * @description
  24082. * Runs each of the registered validators (first synchronous validators and then
  24083. * asynchronous validators).
  24084. * If the validity changes to invalid, the model will be set to `undefined`,
  24085. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  24086. * If the validity changes to valid, it will set the model to the last available valid
  24087. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  24088. */
  24089. this.$validate = function() {
  24090. // ignore $validate before model is initialized
  24091. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  24092. return;
  24093. }
  24094. var viewValue = ctrl.$$lastCommittedViewValue;
  24095. // Note: we use the $$rawModelValue as $modelValue might have been
  24096. // set to undefined during a view -> model update that found validation
  24097. // errors. We can't parse the view here, since that could change
  24098. // the model although neither viewValue nor the model on the scope changed
  24099. var modelValue = ctrl.$$rawModelValue;
  24100. var prevValid = ctrl.$valid;
  24101. var prevModelValue = ctrl.$modelValue;
  24102. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  24103. ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
  24104. // If there was no change in validity, don't update the model
  24105. // This prevents changing an invalid modelValue to undefined
  24106. if (!allowInvalid && prevValid !== allValid) {
  24107. // Note: Don't check ctrl.$valid here, as we could have
  24108. // external validators (e.g. calculated on the server),
  24109. // that just call $setValidity and need the model value
  24110. // to calculate their validity.
  24111. ctrl.$modelValue = allValid ? modelValue : undefined;
  24112. if (ctrl.$modelValue !== prevModelValue) {
  24113. ctrl.$$writeModelToScope();
  24114. }
  24115. }
  24116. });
  24117. };
  24118. this.$$runValidators = function(modelValue, viewValue, doneCallback) {
  24119. currentValidationRunId++;
  24120. var localValidationRunId = currentValidationRunId;
  24121. // check parser error
  24122. if (!processParseErrors()) {
  24123. validationDone(false);
  24124. return;
  24125. }
  24126. if (!processSyncValidators()) {
  24127. validationDone(false);
  24128. return;
  24129. }
  24130. processAsyncValidators();
  24131. function processParseErrors() {
  24132. var errorKey = ctrl.$$parserName || 'parse';
  24133. if (isUndefined(parserValid)) {
  24134. setValidity(errorKey, null);
  24135. } else {
  24136. if (!parserValid) {
  24137. forEach(ctrl.$validators, function(v, name) {
  24138. setValidity(name, null);
  24139. });
  24140. forEach(ctrl.$asyncValidators, function(v, name) {
  24141. setValidity(name, null);
  24142. });
  24143. }
  24144. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  24145. setValidity(errorKey, parserValid);
  24146. return parserValid;
  24147. }
  24148. return true;
  24149. }
  24150. function processSyncValidators() {
  24151. var syncValidatorsValid = true;
  24152. forEach(ctrl.$validators, function(validator, name) {
  24153. var result = validator(modelValue, viewValue);
  24154. syncValidatorsValid = syncValidatorsValid && result;
  24155. setValidity(name, result);
  24156. });
  24157. if (!syncValidatorsValid) {
  24158. forEach(ctrl.$asyncValidators, function(v, name) {
  24159. setValidity(name, null);
  24160. });
  24161. return false;
  24162. }
  24163. return true;
  24164. }
  24165. function processAsyncValidators() {
  24166. var validatorPromises = [];
  24167. var allValid = true;
  24168. forEach(ctrl.$asyncValidators, function(validator, name) {
  24169. var promise = validator(modelValue, viewValue);
  24170. if (!isPromiseLike(promise)) {
  24171. throw ngModelMinErr('nopromise',
  24172. "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
  24173. }
  24174. setValidity(name, undefined);
  24175. validatorPromises.push(promise.then(function() {
  24176. setValidity(name, true);
  24177. }, function() {
  24178. allValid = false;
  24179. setValidity(name, false);
  24180. }));
  24181. });
  24182. if (!validatorPromises.length) {
  24183. validationDone(true);
  24184. } else {
  24185. $q.all(validatorPromises).then(function() {
  24186. validationDone(allValid);
  24187. }, noop);
  24188. }
  24189. }
  24190. function setValidity(name, isValid) {
  24191. if (localValidationRunId === currentValidationRunId) {
  24192. ctrl.$setValidity(name, isValid);
  24193. }
  24194. }
  24195. function validationDone(allValid) {
  24196. if (localValidationRunId === currentValidationRunId) {
  24197. doneCallback(allValid);
  24198. }
  24199. }
  24200. };
  24201. /**
  24202. * @ngdoc method
  24203. * @name ngModel.NgModelController#$commitViewValue
  24204. *
  24205. * @description
  24206. * Commit a pending update to the `$modelValue`.
  24207. *
  24208. * Updates may be pending by a debounced event or because the input is waiting for a some future
  24209. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  24210. * usually handles calling this in response to input events.
  24211. */
  24212. this.$commitViewValue = function() {
  24213. var viewValue = ctrl.$viewValue;
  24214. $timeout.cancel(pendingDebounce);
  24215. // If the view value has not changed then we should just exit, except in the case where there is
  24216. // a native validator on the element. In this case the validation state may have changed even though
  24217. // the viewValue has stayed empty.
  24218. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
  24219. return;
  24220. }
  24221. ctrl.$$updateEmptyClasses(viewValue);
  24222. ctrl.$$lastCommittedViewValue = viewValue;
  24223. // change to dirty
  24224. if (ctrl.$pristine) {
  24225. this.$setDirty();
  24226. }
  24227. this.$$parseAndValidate();
  24228. };
  24229. this.$$parseAndValidate = function() {
  24230. var viewValue = ctrl.$$lastCommittedViewValue;
  24231. var modelValue = viewValue;
  24232. parserValid = isUndefined(modelValue) ? undefined : true;
  24233. if (parserValid) {
  24234. for (var i = 0; i < ctrl.$parsers.length; i++) {
  24235. modelValue = ctrl.$parsers[i](modelValue);
  24236. if (isUndefined(modelValue)) {
  24237. parserValid = false;
  24238. break;
  24239. }
  24240. }
  24241. }
  24242. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  24243. // ctrl.$modelValue has not been touched yet...
  24244. ctrl.$modelValue = ngModelGet($scope);
  24245. }
  24246. var prevModelValue = ctrl.$modelValue;
  24247. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  24248. ctrl.$$rawModelValue = modelValue;
  24249. if (allowInvalid) {
  24250. ctrl.$modelValue = modelValue;
  24251. writeToModelIfNeeded();
  24252. }
  24253. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  24254. // This can happen if e.g. $setViewValue is called from inside a parser
  24255. ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
  24256. if (!allowInvalid) {
  24257. // Note: Don't check ctrl.$valid here, as we could have
  24258. // external validators (e.g. calculated on the server),
  24259. // that just call $setValidity and need the model value
  24260. // to calculate their validity.
  24261. ctrl.$modelValue = allValid ? modelValue : undefined;
  24262. writeToModelIfNeeded();
  24263. }
  24264. });
  24265. function writeToModelIfNeeded() {
  24266. if (ctrl.$modelValue !== prevModelValue) {
  24267. ctrl.$$writeModelToScope();
  24268. }
  24269. }
  24270. };
  24271. this.$$writeModelToScope = function() {
  24272. ngModelSet($scope, ctrl.$modelValue);
  24273. forEach(ctrl.$viewChangeListeners, function(listener) {
  24274. try {
  24275. listener();
  24276. } catch (e) {
  24277. $exceptionHandler(e);
  24278. }
  24279. });
  24280. };
  24281. /**
  24282. * @ngdoc method
  24283. * @name ngModel.NgModelController#$setViewValue
  24284. *
  24285. * @description
  24286. * Update the view value.
  24287. *
  24288. * This method should be called when a control wants to change the view value; typically,
  24289. * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
  24290. * directive calls it when the value of the input changes and {@link ng.directive:select select}
  24291. * calls it when an option is selected.
  24292. *
  24293. * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
  24294. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  24295. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  24296. * **expression** specified in the `ng-model` attribute. Lastly, all the registered change listeners,
  24297. * in the `$viewChangeListeners` list, are called.
  24298. *
  24299. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  24300. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  24301. * `updateOn` events is triggered on the DOM element.
  24302. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  24303. * directive is used with a custom debounce for this particular event.
  24304. * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
  24305. * is specified, once the timer runs out.
  24306. *
  24307. * When used with standard inputs, the view value will always be a string (which is in some cases
  24308. * parsed into another type, such as a `Date` object for `input[date]`.)
  24309. * However, custom controls might also pass objects to this method. In this case, we should make
  24310. * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
  24311. * perform a deep watch of objects, it only looks for a change of identity. If you only change
  24312. * the property of the object then ngModel will not realize that the object has changed and
  24313. * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
  24314. * not change properties of the copy once it has been passed to `$setViewValue`.
  24315. * Otherwise you may cause the model value on the scope to change incorrectly.
  24316. *
  24317. * <div class="alert alert-info">
  24318. * In any case, the value passed to the method should always reflect the current value
  24319. * of the control. For example, if you are calling `$setViewValue` for an input element,
  24320. * you should pass the input DOM value. Otherwise, the control and the scope model become
  24321. * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
  24322. * the control's DOM value in any way. If we want to change the control's DOM value
  24323. * programmatically, we should update the `ngModel` scope expression. Its new value will be
  24324. * picked up by the model controller, which will run it through the `$formatters`, `$render` it
  24325. * to update the DOM, and finally call `$validate` on it.
  24326. * </div>
  24327. *
  24328. * @param {*} value value from the view.
  24329. * @param {string} trigger Event that triggered the update.
  24330. */
  24331. this.$setViewValue = function(value, trigger) {
  24332. ctrl.$viewValue = value;
  24333. if (!ctrl.$options || ctrl.$options.updateOnDefault) {
  24334. ctrl.$$debounceViewValueCommit(trigger);
  24335. }
  24336. };
  24337. this.$$debounceViewValueCommit = function(trigger) {
  24338. var debounceDelay = 0,
  24339. options = ctrl.$options,
  24340. debounce;
  24341. if (options && isDefined(options.debounce)) {
  24342. debounce = options.debounce;
  24343. if (isNumber(debounce)) {
  24344. debounceDelay = debounce;
  24345. } else if (isNumber(debounce[trigger])) {
  24346. debounceDelay = debounce[trigger];
  24347. } else if (isNumber(debounce['default'])) {
  24348. debounceDelay = debounce['default'];
  24349. }
  24350. }
  24351. $timeout.cancel(pendingDebounce);
  24352. if (debounceDelay) {
  24353. pendingDebounce = $timeout(function() {
  24354. ctrl.$commitViewValue();
  24355. }, debounceDelay);
  24356. } else if ($rootScope.$$phase) {
  24357. ctrl.$commitViewValue();
  24358. } else {
  24359. $scope.$apply(function() {
  24360. ctrl.$commitViewValue();
  24361. });
  24362. }
  24363. };
  24364. // model -> value
  24365. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  24366. // 1. scope value is 'a'
  24367. // 2. user enters 'b'
  24368. // 3. ng-change kicks in and reverts scope value to 'a'
  24369. // -> scope value did not change since the last digest as
  24370. // ng-change executes in apply phase
  24371. // 4. view should be changed back to 'a'
  24372. $scope.$watch(function ngModelWatch() {
  24373. var modelValue = ngModelGet($scope);
  24374. // if scope model value and ngModel value are out of sync
  24375. // TODO(perf): why not move this to the action fn?
  24376. if (modelValue !== ctrl.$modelValue &&
  24377. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  24378. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  24379. ) {
  24380. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  24381. parserValid = undefined;
  24382. var formatters = ctrl.$formatters,
  24383. idx = formatters.length;
  24384. var viewValue = modelValue;
  24385. while (idx--) {
  24386. viewValue = formatters[idx](viewValue);
  24387. }
  24388. if (ctrl.$viewValue !== viewValue) {
  24389. ctrl.$$updateEmptyClasses(viewValue);
  24390. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  24391. ctrl.$render();
  24392. ctrl.$$runValidators(modelValue, viewValue, noop);
  24393. }
  24394. }
  24395. return modelValue;
  24396. });
  24397. }];
  24398. /**
  24399. * @ngdoc directive
  24400. * @name ngModel
  24401. *
  24402. * @element input
  24403. * @priority 1
  24404. *
  24405. * @description
  24406. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  24407. * property on the scope using {@link ngModel.NgModelController NgModelController},
  24408. * which is created and exposed by this directive.
  24409. *
  24410. * `ngModel` is responsible for:
  24411. *
  24412. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  24413. * require.
  24414. * - Providing validation behavior (i.e. required, number, email, url).
  24415. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  24416. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
  24417. * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
  24418. * - Registering the control with its parent {@link ng.directive:form form}.
  24419. *
  24420. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  24421. * current scope. If the property doesn't already exist on this scope, it will be created
  24422. * implicitly and added to the scope.
  24423. *
  24424. * For best practices on using `ngModel`, see:
  24425. *
  24426. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  24427. *
  24428. * For basic examples, how to use `ngModel`, see:
  24429. *
  24430. * - {@link ng.directive:input input}
  24431. * - {@link input[text] text}
  24432. * - {@link input[checkbox] checkbox}
  24433. * - {@link input[radio] radio}
  24434. * - {@link input[number] number}
  24435. * - {@link input[email] email}
  24436. * - {@link input[url] url}
  24437. * - {@link input[date] date}
  24438. * - {@link input[datetime-local] datetime-local}
  24439. * - {@link input[time] time}
  24440. * - {@link input[month] month}
  24441. * - {@link input[week] week}
  24442. * - {@link ng.directive:select select}
  24443. * - {@link ng.directive:textarea textarea}
  24444. *
  24445. * # Complex Models (objects or collections)
  24446. *
  24447. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  24448. * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the
  24449. * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered.
  24450. *
  24451. * The model must be assigned an entirely new object or collection before a re-rendering will occur.
  24452. *
  24453. * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression
  24454. * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or
  24455. * if the select is given the `multiple` attribute.
  24456. *
  24457. * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the
  24458. * first level of the object (or only changing the properties of an item in the collection if it's an array) will still
  24459. * not trigger a re-rendering of the model.
  24460. *
  24461. * # CSS classes
  24462. * The following CSS classes are added and removed on the associated input/select/textarea element
  24463. * depending on the validity of the model.
  24464. *
  24465. * - `ng-valid`: the model is valid
  24466. * - `ng-invalid`: the model is invalid
  24467. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  24468. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  24469. * - `ng-pristine`: the control hasn't been interacted with yet
  24470. * - `ng-dirty`: the control has been interacted with
  24471. * - `ng-touched`: the control has been blurred
  24472. * - `ng-untouched`: the control hasn't been blurred
  24473. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  24474. * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
  24475. * by the {@link ngModel.NgModelController#$isEmpty} method
  24476. * - `ng-not-empty`: the view contains a non-empty value
  24477. *
  24478. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  24479. *
  24480. * ## Animation Hooks
  24481. *
  24482. * Animations within models are triggered when any of the associated CSS classes are added and removed
  24483. * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
  24484. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  24485. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  24486. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  24487. *
  24488. * The following example shows a simple way to utilize CSS transitions to style an input element
  24489. * that has been rendered as invalid after it has been validated:
  24490. *
  24491. * <pre>
  24492. * //be sure to include ngAnimate as a module to hook into more
  24493. * //advanced animations
  24494. * .my-input {
  24495. * transition:0.5s linear all;
  24496. * background: white;
  24497. * }
  24498. * .my-input.ng-invalid {
  24499. * background: red;
  24500. * color:white;
  24501. * }
  24502. * </pre>
  24503. *
  24504. * @example
  24505. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  24506. <file name="index.html">
  24507. <script>
  24508. angular.module('inputExample', [])
  24509. .controller('ExampleController', ['$scope', function($scope) {
  24510. $scope.val = '1';
  24511. }]);
  24512. </script>
  24513. <style>
  24514. .my-input {
  24515. transition:all linear 0.5s;
  24516. background: transparent;
  24517. }
  24518. .my-input.ng-invalid {
  24519. color:white;
  24520. background: red;
  24521. }
  24522. </style>
  24523. <p id="inputDescription">
  24524. Update input to see transitions when valid/invalid.
  24525. Integer is a valid value.
  24526. </p>
  24527. <form name="testForm" ng-controller="ExampleController">
  24528. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  24529. aria-describedby="inputDescription" />
  24530. </form>
  24531. </file>
  24532. * </example>
  24533. *
  24534. * ## Binding to a getter/setter
  24535. *
  24536. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  24537. * function that returns a representation of the model when called with zero arguments, and sets
  24538. * the internal state of a model when called with an argument. It's sometimes useful to use this
  24539. * for models that have an internal representation that's different from what the model exposes
  24540. * to the view.
  24541. *
  24542. * <div class="alert alert-success">
  24543. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  24544. * frequently than other parts of your code.
  24545. * </div>
  24546. *
  24547. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  24548. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  24549. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  24550. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  24551. *
  24552. * The following example shows how to use `ngModel` with a getter/setter:
  24553. *
  24554. * @example
  24555. * <example name="ngModel-getter-setter" module="getterSetterExample">
  24556. <file name="index.html">
  24557. <div ng-controller="ExampleController">
  24558. <form name="userForm">
  24559. <label>Name:
  24560. <input type="text" name="userName"
  24561. ng-model="user.name"
  24562. ng-model-options="{ getterSetter: true }" />
  24563. </label>
  24564. </form>
  24565. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  24566. </div>
  24567. </file>
  24568. <file name="app.js">
  24569. angular.module('getterSetterExample', [])
  24570. .controller('ExampleController', ['$scope', function($scope) {
  24571. var _name = 'Brian';
  24572. $scope.user = {
  24573. name: function(newName) {
  24574. // Note that newName can be undefined for two reasons:
  24575. // 1. Because it is called as a getter and thus called with no arguments
  24576. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  24577. // input is invalid
  24578. return arguments.length ? (_name = newName) : _name;
  24579. }
  24580. };
  24581. }]);
  24582. </file>
  24583. * </example>
  24584. */
  24585. var ngModelDirective = ['$rootScope', function($rootScope) {
  24586. return {
  24587. restrict: 'A',
  24588. require: ['ngModel', '^?form', '^?ngModelOptions'],
  24589. controller: NgModelController,
  24590. // Prelink needs to run before any input directive
  24591. // so that we can set the NgModelOptions in NgModelController
  24592. // before anyone else uses it.
  24593. priority: 1,
  24594. compile: function ngModelCompile(element) {
  24595. // Setup initial state of the control
  24596. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  24597. return {
  24598. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  24599. var modelCtrl = ctrls[0],
  24600. formCtrl = ctrls[1] || modelCtrl.$$parentForm;
  24601. modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
  24602. // notify others, especially parent forms
  24603. formCtrl.$addControl(modelCtrl);
  24604. attr.$observe('name', function(newValue) {
  24605. if (modelCtrl.$name !== newValue) {
  24606. modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
  24607. }
  24608. });
  24609. scope.$on('$destroy', function() {
  24610. modelCtrl.$$parentForm.$removeControl(modelCtrl);
  24611. });
  24612. },
  24613. post: function ngModelPostLink(scope, element, attr, ctrls) {
  24614. var modelCtrl = ctrls[0];
  24615. if (modelCtrl.$options && modelCtrl.$options.updateOn) {
  24616. element.on(modelCtrl.$options.updateOn, function(ev) {
  24617. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  24618. });
  24619. }
  24620. element.on('blur', function() {
  24621. if (modelCtrl.$touched) return;
  24622. if ($rootScope.$$phase) {
  24623. scope.$evalAsync(modelCtrl.$setTouched);
  24624. } else {
  24625. scope.$apply(modelCtrl.$setTouched);
  24626. }
  24627. });
  24628. }
  24629. };
  24630. }
  24631. };
  24632. }];
  24633. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  24634. /**
  24635. * @ngdoc directive
  24636. * @name ngModelOptions
  24637. *
  24638. * @description
  24639. * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
  24640. * events that will trigger a model update and/or a debouncing delay so that the actual update only
  24641. * takes place when a timer expires; this timer will be reset after another change takes place.
  24642. *
  24643. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  24644. * be different from the value in the actual model. This means that if you update the model you
  24645. * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
  24646. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  24647. *
  24648. * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
  24649. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  24650. * important because `form` controllers are published to the related scope under the name in their
  24651. * `name` attribute.
  24652. *
  24653. * Any pending changes will take place immediately when an enclosing form is submitted via the
  24654. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  24655. * to have access to the updated model.
  24656. *
  24657. * `ngModelOptions` has an effect on the element it's declared on and its descendants.
  24658. *
  24659. * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
  24660. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  24661. * events using an space delimited list. There is a special event called `default` that
  24662. * matches the default events belonging of the control.
  24663. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  24664. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  24665. * custom value for each event. For example:
  24666. * `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
  24667. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  24668. * not validate correctly instead of the default behavior of setting the model to undefined.
  24669. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  24670. `ngModel` as getters/setters.
  24671. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  24672. * `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
  24673. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  24674. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  24675. * If not specified, the timezone of the browser will be used.
  24676. *
  24677. * @example
  24678. The following example shows how to override immediate updates. Changes on the inputs within the
  24679. form will update the model only when the control loses focus (blur event). If `escape` key is
  24680. pressed while the input field is focused, the value is reset to the value in the current model.
  24681. <example name="ngModelOptions-directive-blur" module="optionsExample">
  24682. <file name="index.html">
  24683. <div ng-controller="ExampleController">
  24684. <form name="userForm">
  24685. <label>Name:
  24686. <input type="text" name="userName"
  24687. ng-model="user.name"
  24688. ng-model-options="{ updateOn: 'blur' }"
  24689. ng-keyup="cancel($event)" />
  24690. </label><br />
  24691. <label>Other data:
  24692. <input type="text" ng-model="user.data" />
  24693. </label><br />
  24694. </form>
  24695. <pre>user.name = <span ng-bind="user.name"></span></pre>
  24696. <pre>user.data = <span ng-bind="user.data"></span></pre>
  24697. </div>
  24698. </file>
  24699. <file name="app.js">
  24700. angular.module('optionsExample', [])
  24701. .controller('ExampleController', ['$scope', function($scope) {
  24702. $scope.user = { name: 'John', data: '' };
  24703. $scope.cancel = function(e) {
  24704. if (e.keyCode == 27) {
  24705. $scope.userForm.userName.$rollbackViewValue();
  24706. }
  24707. };
  24708. }]);
  24709. </file>
  24710. <file name="protractor.js" type="protractor">
  24711. var model = element(by.binding('user.name'));
  24712. var input = element(by.model('user.name'));
  24713. var other = element(by.model('user.data'));
  24714. it('should allow custom events', function() {
  24715. input.sendKeys(' Doe');
  24716. input.click();
  24717. expect(model.getText()).toEqual('John');
  24718. other.click();
  24719. expect(model.getText()).toEqual('John Doe');
  24720. });
  24721. it('should $rollbackViewValue when model changes', function() {
  24722. input.sendKeys(' Doe');
  24723. expect(input.getAttribute('value')).toEqual('John Doe');
  24724. input.sendKeys(protractor.Key.ESCAPE);
  24725. expect(input.getAttribute('value')).toEqual('John');
  24726. other.click();
  24727. expect(model.getText()).toEqual('John');
  24728. });
  24729. </file>
  24730. </example>
  24731. This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
  24732. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  24733. <example name="ngModelOptions-directive-debounce" module="optionsExample">
  24734. <file name="index.html">
  24735. <div ng-controller="ExampleController">
  24736. <form name="userForm">
  24737. <label>Name:
  24738. <input type="text" name="userName"
  24739. ng-model="user.name"
  24740. ng-model-options="{ debounce: 1000 }" />
  24741. </label>
  24742. <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
  24743. <br />
  24744. </form>
  24745. <pre>user.name = <span ng-bind="user.name"></span></pre>
  24746. </div>
  24747. </file>
  24748. <file name="app.js">
  24749. angular.module('optionsExample', [])
  24750. .controller('ExampleController', ['$scope', function($scope) {
  24751. $scope.user = { name: 'Igor' };
  24752. }]);
  24753. </file>
  24754. </example>
  24755. This one shows how to bind to getter/setters:
  24756. <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  24757. <file name="index.html">
  24758. <div ng-controller="ExampleController">
  24759. <form name="userForm">
  24760. <label>Name:
  24761. <input type="text" name="userName"
  24762. ng-model="user.name"
  24763. ng-model-options="{ getterSetter: true }" />
  24764. </label>
  24765. </form>
  24766. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  24767. </div>
  24768. </file>
  24769. <file name="app.js">
  24770. angular.module('getterSetterExample', [])
  24771. .controller('ExampleController', ['$scope', function($scope) {
  24772. var _name = 'Brian';
  24773. $scope.user = {
  24774. name: function(newName) {
  24775. // Note that newName can be undefined for two reasons:
  24776. // 1. Because it is called as a getter and thus called with no arguments
  24777. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  24778. // input is invalid
  24779. return arguments.length ? (_name = newName) : _name;
  24780. }
  24781. };
  24782. }]);
  24783. </file>
  24784. </example>
  24785. */
  24786. var ngModelOptionsDirective = function() {
  24787. return {
  24788. restrict: 'A',
  24789. controller: ['$scope', '$attrs', function($scope, $attrs) {
  24790. var that = this;
  24791. this.$options = copy($scope.$eval($attrs.ngModelOptions));
  24792. // Allow adding/overriding bound events
  24793. if (isDefined(this.$options.updateOn)) {
  24794. this.$options.updateOnDefault = false;
  24795. // extract "default" pseudo-event from list of events that can trigger a model update
  24796. this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
  24797. that.$options.updateOnDefault = true;
  24798. return ' ';
  24799. }));
  24800. } else {
  24801. this.$options.updateOnDefault = true;
  24802. }
  24803. }]
  24804. };
  24805. };
  24806. // helper methods
  24807. function addSetValidityMethod(context) {
  24808. var ctrl = context.ctrl,
  24809. $element = context.$element,
  24810. classCache = {},
  24811. set = context.set,
  24812. unset = context.unset,
  24813. $animate = context.$animate;
  24814. classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
  24815. ctrl.$setValidity = setValidity;
  24816. function setValidity(validationErrorKey, state, controller) {
  24817. if (isUndefined(state)) {
  24818. createAndSet('$pending', validationErrorKey, controller);
  24819. } else {
  24820. unsetAndCleanup('$pending', validationErrorKey, controller);
  24821. }
  24822. if (!isBoolean(state)) {
  24823. unset(ctrl.$error, validationErrorKey, controller);
  24824. unset(ctrl.$$success, validationErrorKey, controller);
  24825. } else {
  24826. if (state) {
  24827. unset(ctrl.$error, validationErrorKey, controller);
  24828. set(ctrl.$$success, validationErrorKey, controller);
  24829. } else {
  24830. set(ctrl.$error, validationErrorKey, controller);
  24831. unset(ctrl.$$success, validationErrorKey, controller);
  24832. }
  24833. }
  24834. if (ctrl.$pending) {
  24835. cachedToggleClass(PENDING_CLASS, true);
  24836. ctrl.$valid = ctrl.$invalid = undefined;
  24837. toggleValidationCss('', null);
  24838. } else {
  24839. cachedToggleClass(PENDING_CLASS, false);
  24840. ctrl.$valid = isObjectEmpty(ctrl.$error);
  24841. ctrl.$invalid = !ctrl.$valid;
  24842. toggleValidationCss('', ctrl.$valid);
  24843. }
  24844. // re-read the state as the set/unset methods could have
  24845. // combined state in ctrl.$error[validationError] (used for forms),
  24846. // where setting/unsetting only increments/decrements the value,
  24847. // and does not replace it.
  24848. var combinedState;
  24849. if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
  24850. combinedState = undefined;
  24851. } else if (ctrl.$error[validationErrorKey]) {
  24852. combinedState = false;
  24853. } else if (ctrl.$$success[validationErrorKey]) {
  24854. combinedState = true;
  24855. } else {
  24856. combinedState = null;
  24857. }
  24858. toggleValidationCss(validationErrorKey, combinedState);
  24859. ctrl.$$parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
  24860. }
  24861. function createAndSet(name, value, controller) {
  24862. if (!ctrl[name]) {
  24863. ctrl[name] = {};
  24864. }
  24865. set(ctrl[name], value, controller);
  24866. }
  24867. function unsetAndCleanup(name, value, controller) {
  24868. if (ctrl[name]) {
  24869. unset(ctrl[name], value, controller);
  24870. }
  24871. if (isObjectEmpty(ctrl[name])) {
  24872. ctrl[name] = undefined;
  24873. }
  24874. }
  24875. function cachedToggleClass(className, switchValue) {
  24876. if (switchValue && !classCache[className]) {
  24877. $animate.addClass($element, className);
  24878. classCache[className] = true;
  24879. } else if (!switchValue && classCache[className]) {
  24880. $animate.removeClass($element, className);
  24881. classCache[className] = false;
  24882. }
  24883. }
  24884. function toggleValidationCss(validationErrorKey, isValid) {
  24885. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  24886. cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
  24887. cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
  24888. }
  24889. }
  24890. function isObjectEmpty(obj) {
  24891. if (obj) {
  24892. for (var prop in obj) {
  24893. if (obj.hasOwnProperty(prop)) {
  24894. return false;
  24895. }
  24896. }
  24897. }
  24898. return true;
  24899. }
  24900. /**
  24901. * @ngdoc directive
  24902. * @name ngNonBindable
  24903. * @restrict AC
  24904. * @priority 1000
  24905. *
  24906. * @description
  24907. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  24908. * DOM element. This is useful if the element contains what appears to be Angular directives and
  24909. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  24910. * displays snippets of code, for instance.
  24911. *
  24912. * @element ANY
  24913. *
  24914. * @example
  24915. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  24916. * but the one wrapped in `ngNonBindable` is left alone.
  24917. *
  24918. * @example
  24919. <example>
  24920. <file name="index.html">
  24921. <div>Normal: {{1 + 2}}</div>
  24922. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  24923. </file>
  24924. <file name="protractor.js" type="protractor">
  24925. it('should check ng-non-bindable', function() {
  24926. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  24927. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  24928. });
  24929. </file>
  24930. </example>
  24931. */
  24932. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  24933. /* global jqLiteRemove */
  24934. var ngOptionsMinErr = minErr('ngOptions');
  24935. /**
  24936. * @ngdoc directive
  24937. * @name ngOptions
  24938. * @restrict A
  24939. *
  24940. * @description
  24941. *
  24942. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  24943. * elements for the `<select>` element using the array or object obtained by evaluating the
  24944. * `ngOptions` comprehension expression.
  24945. *
  24946. * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
  24947. * similar result. However, `ngOptions` provides some benefits such as reducing memory and
  24948. * increasing speed by not creating a new scope for each repeated instance, as well as providing
  24949. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  24950. * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
  24951. * to a non-string value. This is because an option element can only be bound to string values at
  24952. * present.
  24953. *
  24954. * When an item in the `<select>` menu is selected, the array element or object property
  24955. * represented by the selected option will be bound to the model identified by the `ngModel`
  24956. * directive.
  24957. *
  24958. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  24959. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  24960. * option. See example below for demonstration.
  24961. *
  24962. * ## Complex Models (objects or collections)
  24963. *
  24964. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  24965. * binding the select to a model that is an object or a collection.
  24966. *
  24967. * One issue occurs if you want to preselect an option. For example, if you set
  24968. * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
  24969. * because the objects are not identical. So by default, you should always reference the item in your collection
  24970. * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
  24971. *
  24972. * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
  24973. * of the item not by reference, but by the result of the `track by` expression. For example, if your
  24974. * collection items have an id property, you would `track by item.id`.
  24975. *
  24976. * A different issue with objects or collections is that ngModel won't detect if an object property or
  24977. * a collection item changes. For that reason, `ngOptions` additionally watches the model using
  24978. * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
  24979. * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
  24980. * has not changed identity, but only a property on the object or an item in the collection changes.
  24981. *
  24982. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  24983. * if the model is an array). This means that changing a property deeper than the first level inside the
  24984. * object/collection will not trigger a re-rendering.
  24985. *
  24986. * ## `select` **`as`**
  24987. *
  24988. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  24989. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  24990. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  24991. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  24992. *
  24993. *
  24994. * ### `select` **`as`** and **`track by`**
  24995. *
  24996. * <div class="alert alert-warning">
  24997. * Be careful when using `select` **`as`** and **`track by`** in the same expression.
  24998. * </div>
  24999. *
  25000. * Given this array of items on the $scope:
  25001. *
  25002. * ```js
  25003. * $scope.items = [{
  25004. * id: 1,
  25005. * label: 'aLabel',
  25006. * subItem: { name: 'aSubItem' }
  25007. * }, {
  25008. * id: 2,
  25009. * label: 'bLabel',
  25010. * subItem: { name: 'bSubItem' }
  25011. * }];
  25012. * ```
  25013. *
  25014. * This will work:
  25015. *
  25016. * ```html
  25017. * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
  25018. * ```
  25019. * ```js
  25020. * $scope.selected = $scope.items[0];
  25021. * ```
  25022. *
  25023. * but this will not work:
  25024. *
  25025. * ```html
  25026. * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
  25027. * ```
  25028. * ```js
  25029. * $scope.selected = $scope.items[0].subItem;
  25030. * ```
  25031. *
  25032. * In both examples, the **`track by`** expression is applied successfully to each `item` in the
  25033. * `items` array. Because the selected option has been set programmatically in the controller, the
  25034. * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
  25035. * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
  25036. * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
  25037. * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
  25038. * is not matched against any `<option>` and the `<select>` appears as having no selected value.
  25039. *
  25040. *
  25041. * @param {string} ngModel Assignable angular expression to data-bind to.
  25042. * @param {string=} name Property name of the form under which the control is published.
  25043. * @param {string=} required The control is considered valid only if value is entered.
  25044. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  25045. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  25046. * `required` when you want to data-bind to the `required` attribute.
  25047. * @param {comprehension_expression=} ngOptions in one of the following forms:
  25048. *
  25049. * * for array data sources:
  25050. * * `label` **`for`** `value` **`in`** `array`
  25051. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  25052. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  25053. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  25054. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  25055. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  25056. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  25057. * (for including a filter with `track by`)
  25058. * * for object data sources:
  25059. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  25060. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  25061. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  25062. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  25063. * * `select` **`as`** `label` **`group by`** `group`
  25064. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  25065. * * `select` **`as`** `label` **`disable when`** `disable`
  25066. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  25067. *
  25068. * Where:
  25069. *
  25070. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  25071. * * `value`: local variable which will refer to each item in the `array` or each property value
  25072. * of `object` during iteration.
  25073. * * `key`: local variable which will refer to a property name in `object` during iteration.
  25074. * * `label`: The result of this expression will be the label for `<option>` element. The
  25075. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  25076. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  25077. * element. If not specified, `select` expression will default to `value`.
  25078. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  25079. * DOM element.
  25080. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  25081. * element. Return `true` to disable.
  25082. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  25083. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  25084. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  25085. * even when the options are recreated (e.g. reloaded from the server).
  25086. *
  25087. * @example
  25088. <example module="selectExample">
  25089. <file name="index.html">
  25090. <script>
  25091. angular.module('selectExample', [])
  25092. .controller('ExampleController', ['$scope', function($scope) {
  25093. $scope.colors = [
  25094. {name:'black', shade:'dark'},
  25095. {name:'white', shade:'light', notAnOption: true},
  25096. {name:'red', shade:'dark'},
  25097. {name:'blue', shade:'dark', notAnOption: true},
  25098. {name:'yellow', shade:'light', notAnOption: false}
  25099. ];
  25100. $scope.myColor = $scope.colors[2]; // red
  25101. }]);
  25102. </script>
  25103. <div ng-controller="ExampleController">
  25104. <ul>
  25105. <li ng-repeat="color in colors">
  25106. <label>Name: <input ng-model="color.name"></label>
  25107. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  25108. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  25109. </li>
  25110. <li>
  25111. <button ng-click="colors.push({})">add</button>
  25112. </li>
  25113. </ul>
  25114. <hr/>
  25115. <label>Color (null not allowed):
  25116. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  25117. </label><br/>
  25118. <label>Color (null allowed):
  25119. <span class="nullable">
  25120. <select ng-model="myColor" ng-options="color.name for color in colors">
  25121. <option value="">-- choose color --</option>
  25122. </select>
  25123. </span></label><br/>
  25124. <label>Color grouped by shade:
  25125. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  25126. </select>
  25127. </label><br/>
  25128. <label>Color grouped by shade, with some disabled:
  25129. <select ng-model="myColor"
  25130. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  25131. </select>
  25132. </label><br/>
  25133. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  25134. <br/>
  25135. <hr/>
  25136. Currently selected: {{ {selected_color:myColor} }}
  25137. <div style="border:solid 1px black; height:20px"
  25138. ng-style="{'background-color':myColor.name}">
  25139. </div>
  25140. </div>
  25141. </file>
  25142. <file name="protractor.js" type="protractor">
  25143. it('should check ng-options', function() {
  25144. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  25145. element.all(by.model('myColor')).first().click();
  25146. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  25147. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  25148. element(by.css('.nullable select[ng-model="myColor"]')).click();
  25149. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  25150. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  25151. });
  25152. </file>
  25153. </example>
  25154. */
  25155. // jshint maxlen: false
  25156. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
  25157. 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]+?))?$/;
  25158. // 1: value expression (valueFn)
  25159. // 2: label expression (displayFn)
  25160. // 3: group by expression (groupByFn)
  25161. // 4: disable when expression (disableWhenFn)
  25162. // 5: array item variable name
  25163. // 6: object item key variable name
  25164. // 7: object item value variable name
  25165. // 8: collection expression
  25166. // 9: track by expression
  25167. // jshint maxlen: 100
  25168. var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
  25169. function parseOptionsExpression(optionsExp, selectElement, scope) {
  25170. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  25171. if (!(match)) {
  25172. throw ngOptionsMinErr('iexp',
  25173. "Expected expression in form of " +
  25174. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  25175. " but got '{0}'. Element: {1}",
  25176. optionsExp, startingTag(selectElement));
  25177. }
  25178. // Extract the parts from the ngOptions expression
  25179. // The variable name for the value of the item in the collection
  25180. var valueName = match[5] || match[7];
  25181. // The variable name for the key of the item in the collection
  25182. var keyName = match[6];
  25183. // An expression that generates the viewValue for an option if there is a label expression
  25184. var selectAs = / as /.test(match[0]) && match[1];
  25185. // An expression that is used to track the id of each object in the options collection
  25186. var trackBy = match[9];
  25187. // An expression that generates the viewValue for an option if there is no label expression
  25188. var valueFn = $parse(match[2] ? match[1] : valueName);
  25189. var selectAsFn = selectAs && $parse(selectAs);
  25190. var viewValueFn = selectAsFn || valueFn;
  25191. var trackByFn = trackBy && $parse(trackBy);
  25192. // Get the value by which we are going to track the option
  25193. // if we have a trackFn then use that (passing scope and locals)
  25194. // otherwise just hash the given viewValue
  25195. var getTrackByValueFn = trackBy ?
  25196. function(value, locals) { return trackByFn(scope, locals); } :
  25197. function getHashOfValue(value) { return hashKey(value); };
  25198. var getTrackByValue = function(value, key) {
  25199. return getTrackByValueFn(value, getLocals(value, key));
  25200. };
  25201. var displayFn = $parse(match[2] || match[1]);
  25202. var groupByFn = $parse(match[3] || '');
  25203. var disableWhenFn = $parse(match[4] || '');
  25204. var valuesFn = $parse(match[8]);
  25205. var locals = {};
  25206. var getLocals = keyName ? function(value, key) {
  25207. locals[keyName] = key;
  25208. locals[valueName] = value;
  25209. return locals;
  25210. } : function(value) {
  25211. locals[valueName] = value;
  25212. return locals;
  25213. };
  25214. function Option(selectValue, viewValue, label, group, disabled) {
  25215. this.selectValue = selectValue;
  25216. this.viewValue = viewValue;
  25217. this.label = label;
  25218. this.group = group;
  25219. this.disabled = disabled;
  25220. }
  25221. function getOptionValuesKeys(optionValues) {
  25222. var optionValuesKeys;
  25223. if (!keyName && isArrayLike(optionValues)) {
  25224. optionValuesKeys = optionValues;
  25225. } else {
  25226. // if object, extract keys, in enumeration order, unsorted
  25227. optionValuesKeys = [];
  25228. for (var itemKey in optionValues) {
  25229. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  25230. optionValuesKeys.push(itemKey);
  25231. }
  25232. }
  25233. }
  25234. return optionValuesKeys;
  25235. }
  25236. return {
  25237. trackBy: trackBy,
  25238. getTrackByValue: getTrackByValue,
  25239. getWatchables: $parse(valuesFn, function(optionValues) {
  25240. // Create a collection of things that we would like to watch (watchedArray)
  25241. // so that they can all be watched using a single $watchCollection
  25242. // that only runs the handler once if anything changes
  25243. var watchedArray = [];
  25244. optionValues = optionValues || [];
  25245. var optionValuesKeys = getOptionValuesKeys(optionValues);
  25246. var optionValuesLength = optionValuesKeys.length;
  25247. for (var index = 0; index < optionValuesLength; index++) {
  25248. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  25249. var value = optionValues[key];
  25250. var locals = getLocals(value, key);
  25251. var selectValue = getTrackByValueFn(value, locals);
  25252. watchedArray.push(selectValue);
  25253. // Only need to watch the displayFn if there is a specific label expression
  25254. if (match[2] || match[1]) {
  25255. var label = displayFn(scope, locals);
  25256. watchedArray.push(label);
  25257. }
  25258. // Only need to watch the disableWhenFn if there is a specific disable expression
  25259. if (match[4]) {
  25260. var disableWhen = disableWhenFn(scope, locals);
  25261. watchedArray.push(disableWhen);
  25262. }
  25263. }
  25264. return watchedArray;
  25265. }),
  25266. getOptions: function() {
  25267. var optionItems = [];
  25268. var selectValueMap = {};
  25269. // The option values were already computed in the `getWatchables` fn,
  25270. // which must have been called to trigger `getOptions`
  25271. var optionValues = valuesFn(scope) || [];
  25272. var optionValuesKeys = getOptionValuesKeys(optionValues);
  25273. var optionValuesLength = optionValuesKeys.length;
  25274. for (var index = 0; index < optionValuesLength; index++) {
  25275. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  25276. var value = optionValues[key];
  25277. var locals = getLocals(value, key);
  25278. var viewValue = viewValueFn(scope, locals);
  25279. var selectValue = getTrackByValueFn(viewValue, locals);
  25280. var label = displayFn(scope, locals);
  25281. var group = groupByFn(scope, locals);
  25282. var disabled = disableWhenFn(scope, locals);
  25283. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  25284. optionItems.push(optionItem);
  25285. selectValueMap[selectValue] = optionItem;
  25286. }
  25287. return {
  25288. items: optionItems,
  25289. selectValueMap: selectValueMap,
  25290. getOptionFromViewValue: function(value) {
  25291. return selectValueMap[getTrackByValue(value)];
  25292. },
  25293. getViewValueFromOption: function(option) {
  25294. // If the viewValue could be an object that may be mutated by the application,
  25295. // we need to make a copy and not return the reference to the value on the option.
  25296. return trackBy ? angular.copy(option.viewValue) : option.viewValue;
  25297. }
  25298. };
  25299. }
  25300. };
  25301. }
  25302. // we can't just jqLite('<option>') since jqLite is not smart enough
  25303. // to create it in <select> and IE barfs otherwise.
  25304. var optionTemplate = document.createElement('option'),
  25305. optGroupTemplate = document.createElement('optgroup');
  25306. function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
  25307. var selectCtrl = ctrls[0];
  25308. var ngModelCtrl = ctrls[1];
  25309. var multiple = attr.multiple;
  25310. // The emptyOption allows the application developer to provide their own custom "empty"
  25311. // option when the viewValue does not match any of the option values.
  25312. var emptyOption;
  25313. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  25314. if (children[i].value === '') {
  25315. emptyOption = children.eq(i);
  25316. break;
  25317. }
  25318. }
  25319. var providedEmptyOption = !!emptyOption;
  25320. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  25321. unknownOption.val('?');
  25322. var options;
  25323. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  25324. var renderEmptyOption = function() {
  25325. if (!providedEmptyOption) {
  25326. selectElement.prepend(emptyOption);
  25327. }
  25328. selectElement.val('');
  25329. emptyOption.prop('selected', true); // needed for IE
  25330. emptyOption.attr('selected', true);
  25331. };
  25332. var removeEmptyOption = function() {
  25333. if (!providedEmptyOption) {
  25334. emptyOption.remove();
  25335. }
  25336. };
  25337. var renderUnknownOption = function() {
  25338. selectElement.prepend(unknownOption);
  25339. selectElement.val('?');
  25340. unknownOption.prop('selected', true); // needed for IE
  25341. unknownOption.attr('selected', true);
  25342. };
  25343. var removeUnknownOption = function() {
  25344. unknownOption.remove();
  25345. };
  25346. // Update the controller methods for multiple selectable options
  25347. if (!multiple) {
  25348. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  25349. var option = options.getOptionFromViewValue(value);
  25350. if (option && !option.disabled) {
  25351. // Don't update the option when it is already selected.
  25352. // For example, the browser will select the first option by default. In that case,
  25353. // most properties are set automatically - except the `selected` attribute, which we
  25354. // set always
  25355. if (selectElement[0].value !== option.selectValue) {
  25356. removeUnknownOption();
  25357. removeEmptyOption();
  25358. selectElement[0].value = option.selectValue;
  25359. option.element.selected = true;
  25360. }
  25361. option.element.setAttribute('selected', 'selected');
  25362. } else {
  25363. if (value === null || providedEmptyOption) {
  25364. removeUnknownOption();
  25365. renderEmptyOption();
  25366. } else {
  25367. removeEmptyOption();
  25368. renderUnknownOption();
  25369. }
  25370. }
  25371. };
  25372. selectCtrl.readValue = function readNgOptionsValue() {
  25373. var selectedOption = options.selectValueMap[selectElement.val()];
  25374. if (selectedOption && !selectedOption.disabled) {
  25375. removeEmptyOption();
  25376. removeUnknownOption();
  25377. return options.getViewValueFromOption(selectedOption);
  25378. }
  25379. return null;
  25380. };
  25381. // If we are using `track by` then we must watch the tracked value on the model
  25382. // since ngModel only watches for object identity change
  25383. if (ngOptions.trackBy) {
  25384. scope.$watch(
  25385. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  25386. function() { ngModelCtrl.$render(); }
  25387. );
  25388. }
  25389. } else {
  25390. ngModelCtrl.$isEmpty = function(value) {
  25391. return !value || value.length === 0;
  25392. };
  25393. selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
  25394. options.items.forEach(function(option) {
  25395. option.element.selected = false;
  25396. });
  25397. if (value) {
  25398. value.forEach(function(item) {
  25399. var option = options.getOptionFromViewValue(item);
  25400. if (option && !option.disabled) option.element.selected = true;
  25401. });
  25402. }
  25403. };
  25404. selectCtrl.readValue = function readNgOptionsMultiple() {
  25405. var selectedValues = selectElement.val() || [],
  25406. selections = [];
  25407. forEach(selectedValues, function(value) {
  25408. var option = options.selectValueMap[value];
  25409. if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
  25410. });
  25411. return selections;
  25412. };
  25413. // If we are using `track by` then we must watch these tracked values on the model
  25414. // since ngModel only watches for object identity change
  25415. if (ngOptions.trackBy) {
  25416. scope.$watchCollection(function() {
  25417. if (isArray(ngModelCtrl.$viewValue)) {
  25418. return ngModelCtrl.$viewValue.map(function(value) {
  25419. return ngOptions.getTrackByValue(value);
  25420. });
  25421. }
  25422. }, function() {
  25423. ngModelCtrl.$render();
  25424. });
  25425. }
  25426. }
  25427. if (providedEmptyOption) {
  25428. // we need to remove it before calling selectElement.empty() because otherwise IE will
  25429. // remove the label from the element. wtf?
  25430. emptyOption.remove();
  25431. // compile the element since there might be bindings in it
  25432. $compile(emptyOption)(scope);
  25433. // remove the class, which is added automatically because we recompile the element and it
  25434. // becomes the compilation root
  25435. emptyOption.removeClass('ng-scope');
  25436. } else {
  25437. emptyOption = jqLite(optionTemplate.cloneNode(false));
  25438. }
  25439. // We need to do this here to ensure that the options object is defined
  25440. // when we first hit it in writeNgOptionsValue
  25441. updateOptions();
  25442. // We will re-render the option elements if the option values or labels change
  25443. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  25444. // ------------------------------------------------------------------ //
  25445. function updateOptionElement(option, element) {
  25446. option.element = element;
  25447. element.disabled = option.disabled;
  25448. // NOTE: The label must be set before the value, otherwise IE10/11/EDGE create unresponsive
  25449. // selects in certain circumstances when multiple selects are next to each other and display
  25450. // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
  25451. // See https://github.com/angular/angular.js/issues/11314 for more info.
  25452. // This is unfortunately untestable with unit / e2e tests
  25453. if (option.label !== element.label) {
  25454. element.label = option.label;
  25455. element.textContent = option.label;
  25456. }
  25457. if (option.value !== element.value) element.value = option.selectValue;
  25458. }
  25459. function addOrReuseElement(parent, current, type, templateElement) {
  25460. var element;
  25461. // Check whether we can reuse the next element
  25462. if (current && lowercase(current.nodeName) === type) {
  25463. // The next element is the right type so reuse it
  25464. element = current;
  25465. } else {
  25466. // The next element is not the right type so create a new one
  25467. element = templateElement.cloneNode(false);
  25468. if (!current) {
  25469. // There are no more elements so just append it to the select
  25470. parent.appendChild(element);
  25471. } else {
  25472. // The next element is not a group so insert the new one
  25473. parent.insertBefore(element, current);
  25474. }
  25475. }
  25476. return element;
  25477. }
  25478. function removeExcessElements(current) {
  25479. var next;
  25480. while (current) {
  25481. next = current.nextSibling;
  25482. jqLiteRemove(current);
  25483. current = next;
  25484. }
  25485. }
  25486. function skipEmptyAndUnknownOptions(current) {
  25487. var emptyOption_ = emptyOption && emptyOption[0];
  25488. var unknownOption_ = unknownOption && unknownOption[0];
  25489. // We cannot rely on the extracted empty option being the same as the compiled empty option,
  25490. // because the compiled empty option might have been replaced by a comment because
  25491. // it had an "element" transclusion directive on it (such as ngIf)
  25492. if (emptyOption_ || unknownOption_) {
  25493. while (current &&
  25494. (current === emptyOption_ ||
  25495. current === unknownOption_ ||
  25496. current.nodeType === NODE_TYPE_COMMENT ||
  25497. (nodeName_(current) === 'option' && current.value === ''))) {
  25498. current = current.nextSibling;
  25499. }
  25500. }
  25501. return current;
  25502. }
  25503. function updateOptions() {
  25504. var previousValue = options && selectCtrl.readValue();
  25505. options = ngOptions.getOptions();
  25506. var groupMap = {};
  25507. var currentElement = selectElement[0].firstChild;
  25508. // Ensure that the empty option is always there if it was explicitly provided
  25509. if (providedEmptyOption) {
  25510. selectElement.prepend(emptyOption);
  25511. }
  25512. currentElement = skipEmptyAndUnknownOptions(currentElement);
  25513. options.items.forEach(function updateOption(option) {
  25514. var group;
  25515. var groupElement;
  25516. var optionElement;
  25517. if (isDefined(option.group)) {
  25518. // This option is to live in a group
  25519. // See if we have already created this group
  25520. group = groupMap[option.group];
  25521. if (!group) {
  25522. // We have not already created this group
  25523. groupElement = addOrReuseElement(selectElement[0],
  25524. currentElement,
  25525. 'optgroup',
  25526. optGroupTemplate);
  25527. // Move to the next element
  25528. currentElement = groupElement.nextSibling;
  25529. // Update the label on the group element
  25530. groupElement.label = option.group;
  25531. // Store it for use later
  25532. group = groupMap[option.group] = {
  25533. groupElement: groupElement,
  25534. currentOptionElement: groupElement.firstChild
  25535. };
  25536. }
  25537. // So now we have a group for this option we add the option to the group
  25538. optionElement = addOrReuseElement(group.groupElement,
  25539. group.currentOptionElement,
  25540. 'option',
  25541. optionTemplate);
  25542. updateOptionElement(option, optionElement);
  25543. // Move to the next element
  25544. group.currentOptionElement = optionElement.nextSibling;
  25545. } else {
  25546. // This option is not in a group
  25547. optionElement = addOrReuseElement(selectElement[0],
  25548. currentElement,
  25549. 'option',
  25550. optionTemplate);
  25551. updateOptionElement(option, optionElement);
  25552. // Move to the next element
  25553. currentElement = optionElement.nextSibling;
  25554. }
  25555. });
  25556. // Now remove all excess options and group
  25557. Object.keys(groupMap).forEach(function(key) {
  25558. removeExcessElements(groupMap[key].currentOptionElement);
  25559. });
  25560. removeExcessElements(currentElement);
  25561. ngModelCtrl.$render();
  25562. // Check to see if the value has changed due to the update to the options
  25563. if (!ngModelCtrl.$isEmpty(previousValue)) {
  25564. var nextValue = selectCtrl.readValue();
  25565. var isNotPrimitive = ngOptions.trackBy || multiple;
  25566. if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
  25567. ngModelCtrl.$setViewValue(nextValue);
  25568. ngModelCtrl.$render();
  25569. }
  25570. }
  25571. }
  25572. }
  25573. return {
  25574. restrict: 'A',
  25575. terminal: true,
  25576. require: ['select', 'ngModel'],
  25577. link: {
  25578. pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
  25579. // Deactivate the SelectController.register method to prevent
  25580. // option directives from accidentally registering themselves
  25581. // (and unwanted $destroy handlers etc.)
  25582. ctrls[0].registerOption = noop;
  25583. },
  25584. post: ngOptionsPostLink
  25585. }
  25586. };
  25587. }];
  25588. /**
  25589. * @ngdoc directive
  25590. * @name ngPluralize
  25591. * @restrict EA
  25592. *
  25593. * @description
  25594. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  25595. * These rules are bundled with angular.js, but can be overridden
  25596. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  25597. * by specifying the mappings between
  25598. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  25599. * and the strings to be displayed.
  25600. *
  25601. * # Plural categories and explicit number rules
  25602. * There are two
  25603. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  25604. * in Angular's default en-US locale: "one" and "other".
  25605. *
  25606. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  25607. * any number that is not 1), an explicit number rule can only match one number. For example, the
  25608. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  25609. * and explicit number rules throughout the rest of this documentation.
  25610. *
  25611. * # Configuring ngPluralize
  25612. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  25613. * You can also provide an optional attribute, `offset`.
  25614. *
  25615. * The value of the `count` attribute can be either a string or an {@link guide/expression
  25616. * Angular expression}; these are evaluated on the current scope for its bound value.
  25617. *
  25618. * The `when` attribute specifies the mappings between plural categories and the actual
  25619. * string to be displayed. The value of the attribute should be a JSON object.
  25620. *
  25621. * The following example shows how to configure ngPluralize:
  25622. *
  25623. * ```html
  25624. * <ng-pluralize count="personCount"
  25625. when="{'0': 'Nobody is viewing.',
  25626. * 'one': '1 person is viewing.',
  25627. * 'other': '{} people are viewing.'}">
  25628. * </ng-pluralize>
  25629. *```
  25630. *
  25631. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  25632. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  25633. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  25634. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  25635. * show "a dozen people are viewing".
  25636. *
  25637. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  25638. * into pluralized strings. In the previous example, Angular will replace `{}` with
  25639. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  25640. * for <span ng-non-bindable>{{numberExpression}}</span>.
  25641. *
  25642. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  25643. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  25644. *
  25645. * # Configuring ngPluralize with offset
  25646. * The `offset` attribute allows further customization of pluralized text, which can result in
  25647. * a better user experience. For example, instead of the message "4 people are viewing this document",
  25648. * you might display "John, Kate and 2 others are viewing this document".
  25649. * The offset attribute allows you to offset a number by any desired value.
  25650. * Let's take a look at an example:
  25651. *
  25652. * ```html
  25653. * <ng-pluralize count="personCount" offset=2
  25654. * when="{'0': 'Nobody is viewing.',
  25655. * '1': '{{person1}} is viewing.',
  25656. * '2': '{{person1}} and {{person2}} are viewing.',
  25657. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  25658. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  25659. * </ng-pluralize>
  25660. * ```
  25661. *
  25662. * Notice that we are still using two plural categories(one, other), but we added
  25663. * three explicit number rules 0, 1 and 2.
  25664. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  25665. * When three people view the document, no explicit number rule is found, so
  25666. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  25667. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  25668. * is shown.
  25669. *
  25670. * Note that when you specify offsets, you must provide explicit number rules for
  25671. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  25672. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  25673. * plural categories "one" and "other".
  25674. *
  25675. * @param {string|expression} count The variable to be bound to.
  25676. * @param {string} when The mapping between plural category to its corresponding strings.
  25677. * @param {number=} offset Offset to deduct from the total number.
  25678. *
  25679. * @example
  25680. <example module="pluralizeExample">
  25681. <file name="index.html">
  25682. <script>
  25683. angular.module('pluralizeExample', [])
  25684. .controller('ExampleController', ['$scope', function($scope) {
  25685. $scope.person1 = 'Igor';
  25686. $scope.person2 = 'Misko';
  25687. $scope.personCount = 1;
  25688. }]);
  25689. </script>
  25690. <div ng-controller="ExampleController">
  25691. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  25692. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  25693. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  25694. <!--- Example with simple pluralization rules for en locale --->
  25695. Without Offset:
  25696. <ng-pluralize count="personCount"
  25697. when="{'0': 'Nobody is viewing.',
  25698. 'one': '1 person is viewing.',
  25699. 'other': '{} people are viewing.'}">
  25700. </ng-pluralize><br>
  25701. <!--- Example with offset --->
  25702. With Offset(2):
  25703. <ng-pluralize count="personCount" offset=2
  25704. when="{'0': 'Nobody is viewing.',
  25705. '1': '{{person1}} is viewing.',
  25706. '2': '{{person1}} and {{person2}} are viewing.',
  25707. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  25708. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  25709. </ng-pluralize>
  25710. </div>
  25711. </file>
  25712. <file name="protractor.js" type="protractor">
  25713. it('should show correct pluralized string', function() {
  25714. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  25715. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  25716. var countInput = element(by.model('personCount'));
  25717. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  25718. expect(withOffset.getText()).toEqual('Igor is viewing.');
  25719. countInput.clear();
  25720. countInput.sendKeys('0');
  25721. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  25722. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  25723. countInput.clear();
  25724. countInput.sendKeys('2');
  25725. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  25726. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  25727. countInput.clear();
  25728. countInput.sendKeys('3');
  25729. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  25730. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  25731. countInput.clear();
  25732. countInput.sendKeys('4');
  25733. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  25734. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  25735. });
  25736. it('should show data-bound names', function() {
  25737. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  25738. var personCount = element(by.model('personCount'));
  25739. var person1 = element(by.model('person1'));
  25740. var person2 = element(by.model('person2'));
  25741. personCount.clear();
  25742. personCount.sendKeys('4');
  25743. person1.clear();
  25744. person1.sendKeys('Di');
  25745. person2.clear();
  25746. person2.sendKeys('Vojta');
  25747. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  25748. });
  25749. </file>
  25750. </example>
  25751. */
  25752. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  25753. var BRACE = /{}/g,
  25754. IS_WHEN = /^when(Minus)?(.+)$/;
  25755. return {
  25756. link: function(scope, element, attr) {
  25757. var numberExp = attr.count,
  25758. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  25759. offset = attr.offset || 0,
  25760. whens = scope.$eval(whenExp) || {},
  25761. whensExpFns = {},
  25762. startSymbol = $interpolate.startSymbol(),
  25763. endSymbol = $interpolate.endSymbol(),
  25764. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  25765. watchRemover = angular.noop,
  25766. lastCount;
  25767. forEach(attr, function(expression, attributeName) {
  25768. var tmpMatch = IS_WHEN.exec(attributeName);
  25769. if (tmpMatch) {
  25770. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  25771. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  25772. }
  25773. });
  25774. forEach(whens, function(expression, key) {
  25775. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  25776. });
  25777. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  25778. var count = parseFloat(newVal);
  25779. var countIsNaN = isNaN(count);
  25780. if (!countIsNaN && !(count in whens)) {
  25781. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  25782. // Otherwise, check it against pluralization rules in $locale service.
  25783. count = $locale.pluralCat(count - offset);
  25784. }
  25785. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  25786. // In JS `NaN !== NaN`, so we have to explicitly check.
  25787. if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {
  25788. watchRemover();
  25789. var whenExpFn = whensExpFns[count];
  25790. if (isUndefined(whenExpFn)) {
  25791. if (newVal != null) {
  25792. $log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp);
  25793. }
  25794. watchRemover = noop;
  25795. updateElementText();
  25796. } else {
  25797. watchRemover = scope.$watch(whenExpFn, updateElementText);
  25798. }
  25799. lastCount = count;
  25800. }
  25801. });
  25802. function updateElementText(newText) {
  25803. element.text(newText || '');
  25804. }
  25805. }
  25806. };
  25807. }];
  25808. /**
  25809. * @ngdoc directive
  25810. * @name ngRepeat
  25811. * @multiElement
  25812. *
  25813. * @description
  25814. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  25815. * instance gets its own scope, where the given loop variable is set to the current collection item,
  25816. * and `$index` is set to the item index or key.
  25817. *
  25818. * Special properties are exposed on the local scope of each template instance, including:
  25819. *
  25820. * | Variable | Type | Details |
  25821. * |-----------|-----------------|-----------------------------------------------------------------------------|
  25822. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  25823. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  25824. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  25825. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  25826. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  25827. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  25828. *
  25829. * <div class="alert alert-info">
  25830. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  25831. * This may be useful when, for instance, nesting ngRepeats.
  25832. * </div>
  25833. *
  25834. *
  25835. * # Iterating over object properties
  25836. *
  25837. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  25838. * syntax:
  25839. *
  25840. * ```js
  25841. * <div ng-repeat="(key, value) in myObj"> ... </div>
  25842. * ```
  25843. *
  25844. * However, there are a limitations compared to array iteration:
  25845. *
  25846. * - The JavaScript specification does not define the order of keys
  25847. * returned for an object, so Angular relies on the order returned by the browser
  25848. * when running `for key in myObj`. Browsers generally follow the strategy of providing
  25849. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  25850. * and reinstated. See the
  25851. * [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
  25852. *
  25853. * - `ngRepeat` will silently *ignore* object keys starting with `$`, because
  25854. * it's a prefix used by Angular for public (`$`) and private (`$$`) properties.
  25855. *
  25856. * - The built-in filters {@link ng.orderBy orderBy} and {@link ng.filter filter} do not work with
  25857. * objects, and will throw if used with one.
  25858. *
  25859. * If you are hitting any of these limitations, the recommended workaround is to convert your object into an array
  25860. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  25861. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  25862. * or implement a `$watch` on the object yourself.
  25863. *
  25864. *
  25865. * # Tracking and Duplicates
  25866. *
  25867. * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
  25868. * the collection. When a change happens, ngRepeat then makes the corresponding changes to the DOM:
  25869. *
  25870. * * When an item is added, a new instance of the template is added to the DOM.
  25871. * * When an item is removed, its template instance is removed from the DOM.
  25872. * * When items are reordered, their respective templates are reordered in the DOM.
  25873. *
  25874. * To minimize creation of DOM elements, `ngRepeat` uses a function
  25875. * to "keep track" of all items in the collection and their corresponding DOM elements.
  25876. * For example, if an item is added to the collection, ngRepeat will know that all other items
  25877. * already have DOM elements, and will not re-render them.
  25878. *
  25879. * The default tracking function (which tracks items by their identity) does not allow
  25880. * duplicate items in arrays. This is because when there are duplicates, it is not possible
  25881. * to maintain a one-to-one mapping between collection items and DOM elements.
  25882. *
  25883. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  25884. * with your own using the `track by` expression.
  25885. *
  25886. * For example, you may track items by the index of each item in the collection, using the
  25887. * special scope property `$index`:
  25888. * ```html
  25889. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  25890. * {{n}}
  25891. * </div>
  25892. * ```
  25893. *
  25894. * You may also use arbitrary expressions in `track by`, including references to custom functions
  25895. * on the scope:
  25896. * ```html
  25897. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  25898. * {{n}}
  25899. * </div>
  25900. * ```
  25901. *
  25902. * <div class="alert alert-success">
  25903. * If you are working with objects that have an identifier property, you should track
  25904. * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
  25905. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  25906. * JavaScript objects in the collection have been substituted for new ones. For large collections,
  25907. * this significantly improves rendering performance. If you don't have a unique identifier,
  25908. * `track by $index` can also provide a performance boost.
  25909. * </div>
  25910. * ```html
  25911. * <div ng-repeat="model in collection track by model.id">
  25912. * {{model.name}}
  25913. * </div>
  25914. * ```
  25915. *
  25916. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  25917. * `$id` function, which tracks items by their identity:
  25918. * ```html
  25919. * <div ng-repeat="obj in collection track by $id(obj)">
  25920. * {{obj.prop}}
  25921. * </div>
  25922. * ```
  25923. *
  25924. * <div class="alert alert-warning">
  25925. * **Note:** `track by` must always be the last expression:
  25926. * </div>
  25927. * ```
  25928. * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
  25929. * {{model.name}}
  25930. * </div>
  25931. * ```
  25932. *
  25933. * # Special repeat start and end points
  25934. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  25935. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  25936. * 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)
  25937. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  25938. *
  25939. * The example below makes use of this feature:
  25940. * ```html
  25941. * <header ng-repeat-start="item in items">
  25942. * Header {{ item }}
  25943. * </header>
  25944. * <div class="body">
  25945. * Body {{ item }}
  25946. * </div>
  25947. * <footer ng-repeat-end>
  25948. * Footer {{ item }}
  25949. * </footer>
  25950. * ```
  25951. *
  25952. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  25953. * ```html
  25954. * <header>
  25955. * Header A
  25956. * </header>
  25957. * <div class="body">
  25958. * Body A
  25959. * </div>
  25960. * <footer>
  25961. * Footer A
  25962. * </footer>
  25963. * <header>
  25964. * Header B
  25965. * </header>
  25966. * <div class="body">
  25967. * Body B
  25968. * </div>
  25969. * <footer>
  25970. * Footer B
  25971. * </footer>
  25972. * ```
  25973. *
  25974. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  25975. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  25976. *
  25977. * @animations
  25978. * | Animation | Occurs |
  25979. * |----------------------------------|-------------------------------------|
  25980. * | {@link ng.$animate#enter enter} | when a new item is added to the list or when an item is revealed after a filter |
  25981. * | {@link ng.$animate#leave leave} | when an item is removed from the list or when an item is filtered out |
  25982. * | {@link ng.$animate#move move } | when an adjacent item is filtered out causing a reorder or when the item contents are reordered |
  25983. *
  25984. * See the example below for defining CSS animations with ngRepeat.
  25985. *
  25986. * @element ANY
  25987. * @scope
  25988. * @priority 1000
  25989. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  25990. * formats are currently supported:
  25991. *
  25992. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  25993. * is a scope expression giving the collection to enumerate.
  25994. *
  25995. * For example: `album in artist.albums`.
  25996. *
  25997. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  25998. * and `expression` is the scope expression giving the collection to enumerate.
  25999. *
  26000. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  26001. *
  26002. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  26003. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  26004. * is specified, ng-repeat associates elements by identity. It is an error to have
  26005. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  26006. * mapped to the same DOM element, which is not possible.)
  26007. *
  26008. * Note that the tracking expression must come last, after any filters, and the alias expression.
  26009. *
  26010. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  26011. * will be associated by item identity in the array.
  26012. *
  26013. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  26014. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  26015. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  26016. * element in the same way in the DOM.
  26017. *
  26018. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  26019. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  26020. * property is same.
  26021. *
  26022. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  26023. * to items in conjunction with a tracking expression.
  26024. *
  26025. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  26026. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  26027. * when a filter is active on the repeater, but the filtered result set is empty.
  26028. *
  26029. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  26030. * the items have been processed through the filter.
  26031. *
  26032. * 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
  26033. * (and not as operator, inside an expression).
  26034. *
  26035. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
  26036. *
  26037. * @example
  26038. * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed
  26039. * results by name. New (entering) and removed (leaving) items are animated.
  26040. <example module="ngRepeat" name="ngRepeat" deps="angular-animate.js" animations="true">
  26041. <file name="index.html">
  26042. <div ng-controller="repeatController">
  26043. I have {{friends.length}} friends. They are:
  26044. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  26045. <ul class="example-animate-container">
  26046. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  26047. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  26048. </li>
  26049. <li class="animate-repeat" ng-if="results.length == 0">
  26050. <strong>No results found...</strong>
  26051. </li>
  26052. </ul>
  26053. </div>
  26054. </file>
  26055. <file name="script.js">
  26056. angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
  26057. $scope.friends = [
  26058. {name:'John', age:25, gender:'boy'},
  26059. {name:'Jessie', age:30, gender:'girl'},
  26060. {name:'Johanna', age:28, gender:'girl'},
  26061. {name:'Joy', age:15, gender:'girl'},
  26062. {name:'Mary', age:28, gender:'girl'},
  26063. {name:'Peter', age:95, gender:'boy'},
  26064. {name:'Sebastian', age:50, gender:'boy'},
  26065. {name:'Erika', age:27, gender:'girl'},
  26066. {name:'Patrick', age:40, gender:'boy'},
  26067. {name:'Samantha', age:60, gender:'girl'}
  26068. ];
  26069. });
  26070. </file>
  26071. <file name="animations.css">
  26072. .example-animate-container {
  26073. background:white;
  26074. border:1px solid black;
  26075. list-style:none;
  26076. margin:0;
  26077. padding:0 10px;
  26078. }
  26079. .animate-repeat {
  26080. line-height:30px;
  26081. list-style:none;
  26082. box-sizing:border-box;
  26083. }
  26084. .animate-repeat.ng-move,
  26085. .animate-repeat.ng-enter,
  26086. .animate-repeat.ng-leave {
  26087. transition:all linear 0.5s;
  26088. }
  26089. .animate-repeat.ng-leave.ng-leave-active,
  26090. .animate-repeat.ng-move,
  26091. .animate-repeat.ng-enter {
  26092. opacity:0;
  26093. max-height:0;
  26094. }
  26095. .animate-repeat.ng-leave,
  26096. .animate-repeat.ng-move.ng-move-active,
  26097. .animate-repeat.ng-enter.ng-enter-active {
  26098. opacity:1;
  26099. max-height:30px;
  26100. }
  26101. </file>
  26102. <file name="protractor.js" type="protractor">
  26103. var friends = element.all(by.repeater('friend in friends'));
  26104. it('should render initial data set', function() {
  26105. expect(friends.count()).toBe(10);
  26106. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  26107. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  26108. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  26109. expect(element(by.binding('friends.length')).getText())
  26110. .toMatch("I have 10 friends. They are:");
  26111. });
  26112. it('should update repeater when filter predicate changes', function() {
  26113. expect(friends.count()).toBe(10);
  26114. element(by.model('q')).sendKeys('ma');
  26115. expect(friends.count()).toBe(2);
  26116. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  26117. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  26118. });
  26119. </file>
  26120. </example>
  26121. */
  26122. var ngRepeatDirective = ['$parse', '$animate', '$compile', function($parse, $animate, $compile) {
  26123. var NG_REMOVED = '$$NG_REMOVED';
  26124. var ngRepeatMinErr = minErr('ngRepeat');
  26125. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  26126. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  26127. scope[valueIdentifier] = value;
  26128. if (keyIdentifier) scope[keyIdentifier] = key;
  26129. scope.$index = index;
  26130. scope.$first = (index === 0);
  26131. scope.$last = (index === (arrayLength - 1));
  26132. scope.$middle = !(scope.$first || scope.$last);
  26133. // jshint bitwise: false
  26134. scope.$odd = !(scope.$even = (index&1) === 0);
  26135. // jshint bitwise: true
  26136. };
  26137. var getBlockStart = function(block) {
  26138. return block.clone[0];
  26139. };
  26140. var getBlockEnd = function(block) {
  26141. return block.clone[block.clone.length - 1];
  26142. };
  26143. return {
  26144. restrict: 'A',
  26145. multiElement: true,
  26146. transclude: 'element',
  26147. priority: 1000,
  26148. terminal: true,
  26149. $$tlb: true,
  26150. compile: function ngRepeatCompile($element, $attr) {
  26151. var expression = $attr.ngRepeat;
  26152. var ngRepeatEndComment = $compile.$$createComment('end ngRepeat', expression);
  26153. 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*$/);
  26154. if (!match) {
  26155. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  26156. expression);
  26157. }
  26158. var lhs = match[1];
  26159. var rhs = match[2];
  26160. var aliasAs = match[3];
  26161. var trackByExp = match[4];
  26162. match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
  26163. if (!match) {
  26164. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  26165. lhs);
  26166. }
  26167. var valueIdentifier = match[3] || match[1];
  26168. var keyIdentifier = match[2];
  26169. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  26170. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  26171. throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
  26172. aliasAs);
  26173. }
  26174. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  26175. var hashFnLocals = {$id: hashKey};
  26176. if (trackByExp) {
  26177. trackByExpGetter = $parse(trackByExp);
  26178. } else {
  26179. trackByIdArrayFn = function(key, value) {
  26180. return hashKey(value);
  26181. };
  26182. trackByIdObjFn = function(key) {
  26183. return key;
  26184. };
  26185. }
  26186. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  26187. if (trackByExpGetter) {
  26188. trackByIdExpFn = function(key, value, index) {
  26189. // assign key, value, and $index to the locals so that they can be used in hash functions
  26190. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  26191. hashFnLocals[valueIdentifier] = value;
  26192. hashFnLocals.$index = index;
  26193. return trackByExpGetter($scope, hashFnLocals);
  26194. };
  26195. }
  26196. // Store a list of elements from previous run. This is a hash where key is the item from the
  26197. // iterator, and the value is objects with following properties.
  26198. // - scope: bound scope
  26199. // - element: previous element.
  26200. // - index: position
  26201. //
  26202. // We are using no-proto object so that we don't need to guard against inherited props via
  26203. // hasOwnProperty.
  26204. var lastBlockMap = createMap();
  26205. //watch props
  26206. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  26207. var index, length,
  26208. previousNode = $element[0], // node that cloned nodes should be inserted after
  26209. // initialized to the comment node anchor
  26210. nextNode,
  26211. // Same as lastBlockMap but it has the current state. It will become the
  26212. // lastBlockMap on the next iteration.
  26213. nextBlockMap = createMap(),
  26214. collectionLength,
  26215. key, value, // key/value of iteration
  26216. trackById,
  26217. trackByIdFn,
  26218. collectionKeys,
  26219. block, // last object information {scope, element, id}
  26220. nextBlockOrder,
  26221. elementsToRemove;
  26222. if (aliasAs) {
  26223. $scope[aliasAs] = collection;
  26224. }
  26225. if (isArrayLike(collection)) {
  26226. collectionKeys = collection;
  26227. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  26228. } else {
  26229. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  26230. // if object, extract keys, in enumeration order, unsorted
  26231. collectionKeys = [];
  26232. for (var itemKey in collection) {
  26233. if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
  26234. collectionKeys.push(itemKey);
  26235. }
  26236. }
  26237. }
  26238. collectionLength = collectionKeys.length;
  26239. nextBlockOrder = new Array(collectionLength);
  26240. // locate existing items
  26241. for (index = 0; index < collectionLength; index++) {
  26242. key = (collection === collectionKeys) ? index : collectionKeys[index];
  26243. value = collection[key];
  26244. trackById = trackByIdFn(key, value, index);
  26245. if (lastBlockMap[trackById]) {
  26246. // found previously seen block
  26247. block = lastBlockMap[trackById];
  26248. delete lastBlockMap[trackById];
  26249. nextBlockMap[trackById] = block;
  26250. nextBlockOrder[index] = block;
  26251. } else if (nextBlockMap[trackById]) {
  26252. // if collision detected. restore lastBlockMap and throw an error
  26253. forEach(nextBlockOrder, function(block) {
  26254. if (block && block.scope) lastBlockMap[block.id] = block;
  26255. });
  26256. throw ngRepeatMinErr('dupes',
  26257. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  26258. expression, trackById, value);
  26259. } else {
  26260. // new never before seen block
  26261. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  26262. nextBlockMap[trackById] = true;
  26263. }
  26264. }
  26265. // remove leftover items
  26266. for (var blockKey in lastBlockMap) {
  26267. block = lastBlockMap[blockKey];
  26268. elementsToRemove = getBlockNodes(block.clone);
  26269. $animate.leave(elementsToRemove);
  26270. if (elementsToRemove[0].parentNode) {
  26271. // if the element was not removed yet because of pending animation, mark it as deleted
  26272. // so that we can ignore it later
  26273. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  26274. elementsToRemove[index][NG_REMOVED] = true;
  26275. }
  26276. }
  26277. block.scope.$destroy();
  26278. }
  26279. // we are not using forEach for perf reasons (trying to avoid #call)
  26280. for (index = 0; index < collectionLength; index++) {
  26281. key = (collection === collectionKeys) ? index : collectionKeys[index];
  26282. value = collection[key];
  26283. block = nextBlockOrder[index];
  26284. if (block.scope) {
  26285. // if we have already seen this object, then we need to reuse the
  26286. // associated scope/element
  26287. nextNode = previousNode;
  26288. // skip nodes that are already pending removal via leave animation
  26289. do {
  26290. nextNode = nextNode.nextSibling;
  26291. } while (nextNode && nextNode[NG_REMOVED]);
  26292. if (getBlockStart(block) != nextNode) {
  26293. // existing item which got moved
  26294. $animate.move(getBlockNodes(block.clone), null, previousNode);
  26295. }
  26296. previousNode = getBlockEnd(block);
  26297. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  26298. } else {
  26299. // new item which we don't know about
  26300. $transclude(function ngRepeatTransclude(clone, scope) {
  26301. block.scope = scope;
  26302. // http://jsperf.com/clone-vs-createcomment
  26303. var endNode = ngRepeatEndComment.cloneNode(false);
  26304. clone[clone.length++] = endNode;
  26305. $animate.enter(clone, null, previousNode);
  26306. previousNode = endNode;
  26307. // Note: We only need the first/last node of the cloned nodes.
  26308. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  26309. // by a directive with templateUrl when its template arrives.
  26310. block.clone = clone;
  26311. nextBlockMap[block.id] = block;
  26312. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  26313. });
  26314. }
  26315. }
  26316. lastBlockMap = nextBlockMap;
  26317. });
  26318. };
  26319. }
  26320. };
  26321. }];
  26322. var NG_HIDE_CLASS = 'ng-hide';
  26323. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  26324. /**
  26325. * @ngdoc directive
  26326. * @name ngShow
  26327. * @multiElement
  26328. *
  26329. * @description
  26330. * The `ngShow` directive shows or hides the given HTML element based on the expression
  26331. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  26332. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  26333. * in AngularJS and sets the display style to none (using an !important flag).
  26334. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  26335. *
  26336. * ```html
  26337. * <!-- when $scope.myValue is truthy (element is visible) -->
  26338. * <div ng-show="myValue"></div>
  26339. *
  26340. * <!-- when $scope.myValue is falsy (element is hidden) -->
  26341. * <div ng-show="myValue" class="ng-hide"></div>
  26342. * ```
  26343. *
  26344. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
  26345. * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
  26346. * from the element causing the element not to appear hidden.
  26347. *
  26348. * ## Why is !important used?
  26349. *
  26350. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  26351. * can be easily overridden by heavier selectors. For example, something as simple
  26352. * as changing the display style on a HTML list item would make hidden elements appear visible.
  26353. * This also becomes a bigger issue when dealing with CSS frameworks.
  26354. *
  26355. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  26356. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  26357. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  26358. *
  26359. * ### Overriding `.ng-hide`
  26360. *
  26361. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  26362. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  26363. * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
  26364. * with extra animation classes that can be added.
  26365. *
  26366. * ```css
  26367. * .ng-hide:not(.ng-hide-animate) {
  26368. * /&#42; this is just another form of hiding an element &#42;/
  26369. * display: block!important;
  26370. * position: absolute;
  26371. * top: -9999px;
  26372. * left: -9999px;
  26373. * }
  26374. * ```
  26375. *
  26376. * By default you don't need to override in CSS anything and the animations will work around the display style.
  26377. *
  26378. * ## A note about animations with `ngShow`
  26379. *
  26380. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  26381. * is true and false. This system works like the animation system present with ngClass except that
  26382. * you must also include the !important flag to override the display property
  26383. * so that you can perform an animation when the element is hidden during the time of the animation.
  26384. *
  26385. * ```css
  26386. * //
  26387. * //a working example can be found at the bottom of this page
  26388. * //
  26389. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  26390. * /&#42; this is required as of 1.3x to properly
  26391. * apply all styling in a show/hide animation &#42;/
  26392. * transition: 0s linear all;
  26393. * }
  26394. *
  26395. * .my-element.ng-hide-add-active,
  26396. * .my-element.ng-hide-remove-active {
  26397. * /&#42; the transition is defined in the active class &#42;/
  26398. * transition: 1s linear all;
  26399. * }
  26400. *
  26401. * .my-element.ng-hide-add { ... }
  26402. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  26403. * .my-element.ng-hide-remove { ... }
  26404. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  26405. * ```
  26406. *
  26407. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display
  26408. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  26409. *
  26410. * @animations
  26411. * | Animation | Occurs |
  26412. * |----------------------------------|-------------------------------------|
  26413. * | {@link $animate#addClass addClass} `.ng-hide` | after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden |
  26414. * | {@link $animate#removeClass removeClass} `.ng-hide` | after the `ngShow` expression evaluates to a truthy value and just before contents are set to visible |
  26415. *
  26416. * @element ANY
  26417. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  26418. * then the element is shown or hidden respectively.
  26419. *
  26420. * @example
  26421. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  26422. <file name="index.html">
  26423. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
  26424. <div>
  26425. Show:
  26426. <div class="check-element animate-show" ng-show="checked">
  26427. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  26428. </div>
  26429. </div>
  26430. <div>
  26431. Hide:
  26432. <div class="check-element animate-show" ng-hide="checked">
  26433. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  26434. </div>
  26435. </div>
  26436. </file>
  26437. <file name="glyphicons.css">
  26438. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  26439. </file>
  26440. <file name="animations.css">
  26441. .animate-show {
  26442. line-height: 20px;
  26443. opacity: 1;
  26444. padding: 10px;
  26445. border: 1px solid black;
  26446. background: white;
  26447. }
  26448. .animate-show.ng-hide-add, .animate-show.ng-hide-remove {
  26449. transition: all linear 0.5s;
  26450. }
  26451. .animate-show.ng-hide {
  26452. line-height: 0;
  26453. opacity: 0;
  26454. padding: 0 10px;
  26455. }
  26456. .check-element {
  26457. padding: 10px;
  26458. border: 1px solid black;
  26459. background: white;
  26460. }
  26461. </file>
  26462. <file name="protractor.js" type="protractor">
  26463. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  26464. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  26465. it('should check ng-show / ng-hide', function() {
  26466. expect(thumbsUp.isDisplayed()).toBeFalsy();
  26467. expect(thumbsDown.isDisplayed()).toBeTruthy();
  26468. element(by.model('checked')).click();
  26469. expect(thumbsUp.isDisplayed()).toBeTruthy();
  26470. expect(thumbsDown.isDisplayed()).toBeFalsy();
  26471. });
  26472. </file>
  26473. </example>
  26474. */
  26475. var ngShowDirective = ['$animate', function($animate) {
  26476. return {
  26477. restrict: 'A',
  26478. multiElement: true,
  26479. link: function(scope, element, attr) {
  26480. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  26481. // we're adding a temporary, animation-specific class for ng-hide since this way
  26482. // we can control when the element is actually displayed on screen without having
  26483. // to have a global/greedy CSS selector that breaks when other animations are run.
  26484. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  26485. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  26486. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  26487. });
  26488. });
  26489. }
  26490. };
  26491. }];
  26492. /**
  26493. * @ngdoc directive
  26494. * @name ngHide
  26495. * @multiElement
  26496. *
  26497. * @description
  26498. * The `ngHide` directive shows or hides the given HTML element based on the expression
  26499. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  26500. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  26501. * in AngularJS and sets the display style to none (using an !important flag).
  26502. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  26503. *
  26504. * ```html
  26505. * <!-- when $scope.myValue is truthy (element is hidden) -->
  26506. * <div ng-hide="myValue" class="ng-hide"></div>
  26507. *
  26508. * <!-- when $scope.myValue is falsy (element is visible) -->
  26509. * <div ng-hide="myValue"></div>
  26510. * ```
  26511. *
  26512. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
  26513. * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
  26514. * from the element causing the element not to appear hidden.
  26515. *
  26516. * ## Why is !important used?
  26517. *
  26518. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  26519. * can be easily overridden by heavier selectors. For example, something as simple
  26520. * as changing the display style on a HTML list item would make hidden elements appear visible.
  26521. * This also becomes a bigger issue when dealing with CSS frameworks.
  26522. *
  26523. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  26524. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  26525. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  26526. *
  26527. * ### Overriding `.ng-hide`
  26528. *
  26529. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  26530. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  26531. * class in CSS:
  26532. *
  26533. * ```css
  26534. * .ng-hide {
  26535. * /&#42; this is just another form of hiding an element &#42;/
  26536. * display: block!important;
  26537. * position: absolute;
  26538. * top: -9999px;
  26539. * left: -9999px;
  26540. * }
  26541. * ```
  26542. *
  26543. * By default you don't need to override in CSS anything and the animations will work around the display style.
  26544. *
  26545. * ## A note about animations with `ngHide`
  26546. *
  26547. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  26548. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  26549. * CSS class is added and removed for you instead of your own CSS class.
  26550. *
  26551. * ```css
  26552. * //
  26553. * //a working example can be found at the bottom of this page
  26554. * //
  26555. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  26556. * transition: 0.5s linear all;
  26557. * }
  26558. *
  26559. * .my-element.ng-hide-add { ... }
  26560. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  26561. * .my-element.ng-hide-remove { ... }
  26562. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  26563. * ```
  26564. *
  26565. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display
  26566. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  26567. *
  26568. * @animations
  26569. * | Animation | Occurs |
  26570. * |----------------------------------|-------------------------------------|
  26571. * | {@link $animate#addClass addClass} `.ng-hide` | after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden |
  26572. * | {@link $animate#removeClass removeClass} `.ng-hide` | after the `ngHide` expression evaluates to a non truthy value and just before contents are set to visible |
  26573. *
  26574. *
  26575. * @element ANY
  26576. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  26577. * the element is shown or hidden respectively.
  26578. *
  26579. * @example
  26580. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  26581. <file name="index.html">
  26582. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
  26583. <div>
  26584. Show:
  26585. <div class="check-element animate-hide" ng-show="checked">
  26586. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  26587. </div>
  26588. </div>
  26589. <div>
  26590. Hide:
  26591. <div class="check-element animate-hide" ng-hide="checked">
  26592. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  26593. </div>
  26594. </div>
  26595. </file>
  26596. <file name="glyphicons.css">
  26597. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  26598. </file>
  26599. <file name="animations.css">
  26600. .animate-hide {
  26601. transition: all linear 0.5s;
  26602. line-height: 20px;
  26603. opacity: 1;
  26604. padding: 10px;
  26605. border: 1px solid black;
  26606. background: white;
  26607. }
  26608. .animate-hide.ng-hide {
  26609. line-height: 0;
  26610. opacity: 0;
  26611. padding: 0 10px;
  26612. }
  26613. .check-element {
  26614. padding: 10px;
  26615. border: 1px solid black;
  26616. background: white;
  26617. }
  26618. </file>
  26619. <file name="protractor.js" type="protractor">
  26620. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  26621. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  26622. it('should check ng-show / ng-hide', function() {
  26623. expect(thumbsUp.isDisplayed()).toBeFalsy();
  26624. expect(thumbsDown.isDisplayed()).toBeTruthy();
  26625. element(by.model('checked')).click();
  26626. expect(thumbsUp.isDisplayed()).toBeTruthy();
  26627. expect(thumbsDown.isDisplayed()).toBeFalsy();
  26628. });
  26629. </file>
  26630. </example>
  26631. */
  26632. var ngHideDirective = ['$animate', function($animate) {
  26633. return {
  26634. restrict: 'A',
  26635. multiElement: true,
  26636. link: function(scope, element, attr) {
  26637. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  26638. // The comment inside of the ngShowDirective explains why we add and
  26639. // remove a temporary class for the show/hide animation
  26640. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  26641. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  26642. });
  26643. });
  26644. }
  26645. };
  26646. }];
  26647. /**
  26648. * @ngdoc directive
  26649. * @name ngStyle
  26650. * @restrict AC
  26651. *
  26652. * @description
  26653. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  26654. *
  26655. * @element ANY
  26656. * @param {expression} ngStyle
  26657. *
  26658. * {@link guide/expression Expression} which evals to an
  26659. * object whose keys are CSS style names and values are corresponding values for those CSS
  26660. * keys.
  26661. *
  26662. * Since some CSS style names are not valid keys for an object, they must be quoted.
  26663. * See the 'background-color' style in the example below.
  26664. *
  26665. * @example
  26666. <example>
  26667. <file name="index.html">
  26668. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  26669. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  26670. <input type="button" value="clear" ng-click="myStyle={}">
  26671. <br/>
  26672. <span ng-style="myStyle">Sample Text</span>
  26673. <pre>myStyle={{myStyle}}</pre>
  26674. </file>
  26675. <file name="style.css">
  26676. span {
  26677. color: black;
  26678. }
  26679. </file>
  26680. <file name="protractor.js" type="protractor">
  26681. var colorSpan = element(by.css('span'));
  26682. it('should check ng-style', function() {
  26683. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  26684. element(by.css('input[value=\'set color\']')).click();
  26685. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  26686. element(by.css('input[value=clear]')).click();
  26687. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  26688. });
  26689. </file>
  26690. </example>
  26691. */
  26692. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  26693. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  26694. if (oldStyles && (newStyles !== oldStyles)) {
  26695. forEach(oldStyles, function(val, style) { element.css(style, '');});
  26696. }
  26697. if (newStyles) element.css(newStyles);
  26698. }, true);
  26699. });
  26700. /**
  26701. * @ngdoc directive
  26702. * @name ngSwitch
  26703. * @restrict EA
  26704. *
  26705. * @description
  26706. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  26707. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  26708. * as specified in the template.
  26709. *
  26710. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  26711. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  26712. * matches the value obtained from the evaluated expression. In other words, you define a container element
  26713. * (where you place the directive), place an expression on the **`on="..."` attribute**
  26714. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  26715. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  26716. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  26717. * attribute is displayed.
  26718. *
  26719. * <div class="alert alert-info">
  26720. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  26721. * as literal string values to match against.
  26722. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  26723. * value of the expression `$scope.someVal`.
  26724. * </div>
  26725. * @animations
  26726. * | Animation | Occurs |
  26727. * |----------------------------------|-------------------------------------|
  26728. * | {@link ng.$animate#enter enter} | after the ngSwitch contents change and the matched child element is placed inside the container |
  26729. * | {@link ng.$animate#leave leave} | after the ngSwitch contents change and just before the former contents are removed from the DOM |
  26730. *
  26731. * @usage
  26732. *
  26733. * ```
  26734. * <ANY ng-switch="expression">
  26735. * <ANY ng-switch-when="matchValue1">...</ANY>
  26736. * <ANY ng-switch-when="matchValue2">...</ANY>
  26737. * <ANY ng-switch-default>...</ANY>
  26738. * </ANY>
  26739. * ```
  26740. *
  26741. *
  26742. * @scope
  26743. * @priority 1200
  26744. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  26745. * On child elements add:
  26746. *
  26747. * * `ngSwitchWhen`: the case statement to match against. If match then this
  26748. * case will be displayed. If the same match appears multiple times, all the
  26749. * elements will be displayed.
  26750. * * `ngSwitchDefault`: the default case when no other case match. If there
  26751. * are multiple default cases, all of them will be displayed when no other
  26752. * case match.
  26753. *
  26754. *
  26755. * @example
  26756. <example module="switchExample" deps="angular-animate.js" animations="true">
  26757. <file name="index.html">
  26758. <div ng-controller="ExampleController">
  26759. <select ng-model="selection" ng-options="item for item in items">
  26760. </select>
  26761. <code>selection={{selection}}</code>
  26762. <hr/>
  26763. <div class="animate-switch-container"
  26764. ng-switch on="selection">
  26765. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  26766. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  26767. <div class="animate-switch" ng-switch-default>default</div>
  26768. </div>
  26769. </div>
  26770. </file>
  26771. <file name="script.js">
  26772. angular.module('switchExample', ['ngAnimate'])
  26773. .controller('ExampleController', ['$scope', function($scope) {
  26774. $scope.items = ['settings', 'home', 'other'];
  26775. $scope.selection = $scope.items[0];
  26776. }]);
  26777. </file>
  26778. <file name="animations.css">
  26779. .animate-switch-container {
  26780. position:relative;
  26781. background:white;
  26782. border:1px solid black;
  26783. height:40px;
  26784. overflow:hidden;
  26785. }
  26786. .animate-switch {
  26787. padding:10px;
  26788. }
  26789. .animate-switch.ng-animate {
  26790. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  26791. position:absolute;
  26792. top:0;
  26793. left:0;
  26794. right:0;
  26795. bottom:0;
  26796. }
  26797. .animate-switch.ng-leave.ng-leave-active,
  26798. .animate-switch.ng-enter {
  26799. top:-50px;
  26800. }
  26801. .animate-switch.ng-leave,
  26802. .animate-switch.ng-enter.ng-enter-active {
  26803. top:0;
  26804. }
  26805. </file>
  26806. <file name="protractor.js" type="protractor">
  26807. var switchElem = element(by.css('[ng-switch]'));
  26808. var select = element(by.model('selection'));
  26809. it('should start in settings', function() {
  26810. expect(switchElem.getText()).toMatch(/Settings Div/);
  26811. });
  26812. it('should change to home', function() {
  26813. select.all(by.css('option')).get(1).click();
  26814. expect(switchElem.getText()).toMatch(/Home Span/);
  26815. });
  26816. it('should select default', function() {
  26817. select.all(by.css('option')).get(2).click();
  26818. expect(switchElem.getText()).toMatch(/default/);
  26819. });
  26820. </file>
  26821. </example>
  26822. */
  26823. var ngSwitchDirective = ['$animate', '$compile', function($animate, $compile) {
  26824. return {
  26825. require: 'ngSwitch',
  26826. // asks for $scope to fool the BC controller module
  26827. controller: ['$scope', function ngSwitchController() {
  26828. this.cases = {};
  26829. }],
  26830. link: function(scope, element, attr, ngSwitchController) {
  26831. var watchExpr = attr.ngSwitch || attr.on,
  26832. selectedTranscludes = [],
  26833. selectedElements = [],
  26834. previousLeaveAnimations = [],
  26835. selectedScopes = [];
  26836. var spliceFactory = function(array, index) {
  26837. return function() { array.splice(index, 1); };
  26838. };
  26839. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  26840. var i, ii;
  26841. for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
  26842. $animate.cancel(previousLeaveAnimations[i]);
  26843. }
  26844. previousLeaveAnimations.length = 0;
  26845. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  26846. var selected = getBlockNodes(selectedElements[i].clone);
  26847. selectedScopes[i].$destroy();
  26848. var promise = previousLeaveAnimations[i] = $animate.leave(selected);
  26849. promise.then(spliceFactory(previousLeaveAnimations, i));
  26850. }
  26851. selectedElements.length = 0;
  26852. selectedScopes.length = 0;
  26853. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  26854. forEach(selectedTranscludes, function(selectedTransclude) {
  26855. selectedTransclude.transclude(function(caseElement, selectedScope) {
  26856. selectedScopes.push(selectedScope);
  26857. var anchor = selectedTransclude.element;
  26858. caseElement[caseElement.length++] = $compile.$$createComment('end ngSwitchWhen');
  26859. var block = { clone: caseElement };
  26860. selectedElements.push(block);
  26861. $animate.enter(caseElement, anchor.parent(), anchor);
  26862. });
  26863. });
  26864. }
  26865. });
  26866. }
  26867. };
  26868. }];
  26869. var ngSwitchWhenDirective = ngDirective({
  26870. transclude: 'element',
  26871. priority: 1200,
  26872. require: '^ngSwitch',
  26873. multiElement: true,
  26874. link: function(scope, element, attrs, ctrl, $transclude) {
  26875. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  26876. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  26877. }
  26878. });
  26879. var ngSwitchDefaultDirective = ngDirective({
  26880. transclude: 'element',
  26881. priority: 1200,
  26882. require: '^ngSwitch',
  26883. multiElement: true,
  26884. link: function(scope, element, attr, ctrl, $transclude) {
  26885. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  26886. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  26887. }
  26888. });
  26889. /**
  26890. * @ngdoc directive
  26891. * @name ngTransclude
  26892. * @restrict EAC
  26893. *
  26894. * @description
  26895. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  26896. *
  26897. * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name
  26898. * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.
  26899. *
  26900. * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing
  26901. * content of this element will be removed before the transcluded content is inserted.
  26902. * If the transcluded content is empty, the existing content is left intact. This lets you provide fallback content in the case
  26903. * that no transcluded content is provided.
  26904. *
  26905. * @element ANY
  26906. *
  26907. * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty
  26908. * or its value is the same as the name of the attribute then the default slot is used.
  26909. *
  26910. * @example
  26911. * ### Basic transclusion
  26912. * This example demonstrates basic transclusion of content into a component directive.
  26913. * <example name="simpleTranscludeExample" module="transcludeExample">
  26914. * <file name="index.html">
  26915. * <script>
  26916. * angular.module('transcludeExample', [])
  26917. * .directive('pane', function(){
  26918. * return {
  26919. * restrict: 'E',
  26920. * transclude: true,
  26921. * scope: { title:'@' },
  26922. * template: '<div style="border: 1px solid black;">' +
  26923. * '<div style="background-color: gray">{{title}}</div>' +
  26924. * '<ng-transclude></ng-transclude>' +
  26925. * '</div>'
  26926. * };
  26927. * })
  26928. * .controller('ExampleController', ['$scope', function($scope) {
  26929. * $scope.title = 'Lorem Ipsum';
  26930. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  26931. * }]);
  26932. * </script>
  26933. * <div ng-controller="ExampleController">
  26934. * <input ng-model="title" aria-label="title"> <br/>
  26935. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  26936. * <pane title="{{title}}">{{text}}</pane>
  26937. * </div>
  26938. * </file>
  26939. * <file name="protractor.js" type="protractor">
  26940. * it('should have transcluded', function() {
  26941. * var titleElement = element(by.model('title'));
  26942. * titleElement.clear();
  26943. * titleElement.sendKeys('TITLE');
  26944. * var textElement = element(by.model('text'));
  26945. * textElement.clear();
  26946. * textElement.sendKeys('TEXT');
  26947. * expect(element(by.binding('title')).getText()).toEqual('TITLE');
  26948. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  26949. * });
  26950. * </file>
  26951. * </example>
  26952. *
  26953. * @example
  26954. * ### Transclude fallback content
  26955. * This example shows how to use `NgTransclude` with fallback content, that
  26956. * is displayed if no transcluded content is provided.
  26957. *
  26958. * <example module="transcludeFallbackContentExample">
  26959. * <file name="index.html">
  26960. * <script>
  26961. * angular.module('transcludeFallbackContentExample', [])
  26962. * .directive('myButton', function(){
  26963. * return {
  26964. * restrict: 'E',
  26965. * transclude: true,
  26966. * scope: true,
  26967. * template: '<button style="cursor: pointer;">' +
  26968. * '<ng-transclude>' +
  26969. * '<b style="color: red;">Button1</b>' +
  26970. * '</ng-transclude>' +
  26971. * '</button>'
  26972. * };
  26973. * });
  26974. * </script>
  26975. * <!-- fallback button content -->
  26976. * <my-button id="fallback"></my-button>
  26977. * <!-- modified button content -->
  26978. * <my-button id="modified">
  26979. * <i style="color: green;">Button2</i>
  26980. * </my-button>
  26981. * </file>
  26982. * <file name="protractor.js" type="protractor">
  26983. * it('should have different transclude element content', function() {
  26984. * expect(element(by.id('fallback')).getText()).toBe('Button1');
  26985. * expect(element(by.id('modified')).getText()).toBe('Button2');
  26986. * });
  26987. * </file>
  26988. * </example>
  26989. *
  26990. * @example
  26991. * ### Multi-slot transclusion
  26992. * This example demonstrates using multi-slot transclusion in a component directive.
  26993. * <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample">
  26994. * <file name="index.html">
  26995. * <style>
  26996. * .title, .footer {
  26997. * background-color: gray
  26998. * }
  26999. * </style>
  27000. * <div ng-controller="ExampleController">
  27001. * <input ng-model="title" aria-label="title"> <br/>
  27002. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  27003. * <pane>
  27004. * <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
  27005. * <pane-body><p>{{text}}</p></pane-body>
  27006. * </pane>
  27007. * </div>
  27008. * </file>
  27009. * <file name="app.js">
  27010. * angular.module('multiSlotTranscludeExample', [])
  27011. * .directive('pane', function(){
  27012. * return {
  27013. * restrict: 'E',
  27014. * transclude: {
  27015. * 'title': '?paneTitle',
  27016. * 'body': 'paneBody',
  27017. * 'footer': '?paneFooter'
  27018. * },
  27019. * template: '<div style="border: 1px solid black;">' +
  27020. * '<div class="title" ng-transclude="title">Fallback Title</div>' +
  27021. * '<div ng-transclude="body"></div>' +
  27022. * '<div class="footer" ng-transclude="footer">Fallback Footer</div>' +
  27023. * '</div>'
  27024. * };
  27025. * })
  27026. * .controller('ExampleController', ['$scope', function($scope) {
  27027. * $scope.title = 'Lorem Ipsum';
  27028. * $scope.link = "https://google.com";
  27029. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  27030. * }]);
  27031. * </file>
  27032. * <file name="protractor.js" type="protractor">
  27033. * it('should have transcluded the title and the body', function() {
  27034. * var titleElement = element(by.model('title'));
  27035. * titleElement.clear();
  27036. * titleElement.sendKeys('TITLE');
  27037. * var textElement = element(by.model('text'));
  27038. * textElement.clear();
  27039. * textElement.sendKeys('TEXT');
  27040. * expect(element(by.css('.title')).getText()).toEqual('TITLE');
  27041. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  27042. * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer');
  27043. * });
  27044. * </file>
  27045. * </example>
  27046. */
  27047. var ngTranscludeMinErr = minErr('ngTransclude');
  27048. var ngTranscludeDirective = ngDirective({
  27049. restrict: 'EAC',
  27050. link: function($scope, $element, $attrs, controller, $transclude) {
  27051. if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) {
  27052. // If the attribute is of the form: `ng-transclude="ng-transclude"`
  27053. // then treat it like the default
  27054. $attrs.ngTransclude = '';
  27055. }
  27056. function ngTranscludeCloneAttachFn(clone) {
  27057. if (clone.length) {
  27058. $element.empty();
  27059. $element.append(clone);
  27060. }
  27061. }
  27062. if (!$transclude) {
  27063. throw ngTranscludeMinErr('orphan',
  27064. 'Illegal use of ngTransclude directive in the template! ' +
  27065. 'No parent directive that requires a transclusion found. ' +
  27066. 'Element: {0}',
  27067. startingTag($element));
  27068. }
  27069. // If there is no slot name defined or the slot name is not optional
  27070. // then transclude the slot
  27071. var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot;
  27072. $transclude(ngTranscludeCloneAttachFn, null, slotName);
  27073. }
  27074. });
  27075. /**
  27076. * @ngdoc directive
  27077. * @name script
  27078. * @restrict E
  27079. *
  27080. * @description
  27081. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  27082. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  27083. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  27084. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  27085. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  27086. *
  27087. * @param {string} type Must be set to `'text/ng-template'`.
  27088. * @param {string} id Cache name of the template.
  27089. *
  27090. * @example
  27091. <example>
  27092. <file name="index.html">
  27093. <script type="text/ng-template" id="/tpl.html">
  27094. Content of the template.
  27095. </script>
  27096. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  27097. <div id="tpl-content" ng-include src="currentTpl"></div>
  27098. </file>
  27099. <file name="protractor.js" type="protractor">
  27100. it('should load template defined inside script tag', function() {
  27101. element(by.css('#tpl-link')).click();
  27102. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  27103. });
  27104. </file>
  27105. </example>
  27106. */
  27107. var scriptDirective = ['$templateCache', function($templateCache) {
  27108. return {
  27109. restrict: 'E',
  27110. terminal: true,
  27111. compile: function(element, attr) {
  27112. if (attr.type == 'text/ng-template') {
  27113. var templateUrl = attr.id,
  27114. text = element[0].text;
  27115. $templateCache.put(templateUrl, text);
  27116. }
  27117. }
  27118. };
  27119. }];
  27120. var noopNgModelController = { $setViewValue: noop, $render: noop };
  27121. function chromeHack(optionElement) {
  27122. // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
  27123. // Adding an <option selected="selected"> element to a <select required="required"> should
  27124. // automatically select the new element
  27125. if (optionElement[0].hasAttribute('selected')) {
  27126. optionElement[0].selected = true;
  27127. }
  27128. }
  27129. /**
  27130. * @ngdoc type
  27131. * @name select.SelectController
  27132. * @description
  27133. * The controller for the `<select>` directive. This provides support for reading
  27134. * and writing the selected value(s) of the control and also coordinates dynamically
  27135. * added `<option>` elements, perhaps by an `ngRepeat` directive.
  27136. */
  27137. var SelectController =
  27138. ['$element', '$scope', function($element, $scope) {
  27139. var self = this,
  27140. optionsMap = new HashMap();
  27141. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  27142. self.ngModelCtrl = noopNgModelController;
  27143. // The "unknown" option is one that is prepended to the list if the viewValue
  27144. // does not match any of the options. When it is rendered the value of the unknown
  27145. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  27146. //
  27147. // We can't just jqLite('<option>') since jqLite is not smart enough
  27148. // to create it in <select> and IE barfs otherwise.
  27149. self.unknownOption = jqLite(document.createElement('option'));
  27150. self.renderUnknownOption = function(val) {
  27151. var unknownVal = '? ' + hashKey(val) + ' ?';
  27152. self.unknownOption.val(unknownVal);
  27153. $element.prepend(self.unknownOption);
  27154. $element.val(unknownVal);
  27155. };
  27156. $scope.$on('$destroy', function() {
  27157. // disable unknown option so that we don't do work when the whole select is being destroyed
  27158. self.renderUnknownOption = noop;
  27159. });
  27160. self.removeUnknownOption = function() {
  27161. if (self.unknownOption.parent()) self.unknownOption.remove();
  27162. };
  27163. // Read the value of the select control, the implementation of this changes depending
  27164. // upon whether the select can have multiple values and whether ngOptions is at work.
  27165. self.readValue = function readSingleValue() {
  27166. self.removeUnknownOption();
  27167. return $element.val();
  27168. };
  27169. // Write the value to the select control, the implementation of this changes depending
  27170. // upon whether the select can have multiple values and whether ngOptions is at work.
  27171. self.writeValue = function writeSingleValue(value) {
  27172. if (self.hasOption(value)) {
  27173. self.removeUnknownOption();
  27174. $element.val(value);
  27175. if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy
  27176. } else {
  27177. if (value == null && self.emptyOption) {
  27178. self.removeUnknownOption();
  27179. $element.val('');
  27180. } else {
  27181. self.renderUnknownOption(value);
  27182. }
  27183. }
  27184. };
  27185. // Tell the select control that an option, with the given value, has been added
  27186. self.addOption = function(value, element) {
  27187. // Skip comment nodes, as they only pollute the `optionsMap`
  27188. if (element[0].nodeType === NODE_TYPE_COMMENT) return;
  27189. assertNotHasOwnProperty(value, '"option value"');
  27190. if (value === '') {
  27191. self.emptyOption = element;
  27192. }
  27193. var count = optionsMap.get(value) || 0;
  27194. optionsMap.put(value, count + 1);
  27195. self.ngModelCtrl.$render();
  27196. chromeHack(element);
  27197. };
  27198. // Tell the select control that an option, with the given value, has been removed
  27199. self.removeOption = function(value) {
  27200. var count = optionsMap.get(value);
  27201. if (count) {
  27202. if (count === 1) {
  27203. optionsMap.remove(value);
  27204. if (value === '') {
  27205. self.emptyOption = undefined;
  27206. }
  27207. } else {
  27208. optionsMap.put(value, count - 1);
  27209. }
  27210. }
  27211. };
  27212. // Check whether the select control has an option matching the given value
  27213. self.hasOption = function(value) {
  27214. return !!optionsMap.get(value);
  27215. };
  27216. self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
  27217. if (interpolateValueFn) {
  27218. // The value attribute is interpolated
  27219. var oldVal;
  27220. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  27221. if (isDefined(oldVal)) {
  27222. self.removeOption(oldVal);
  27223. }
  27224. oldVal = newVal;
  27225. self.addOption(newVal, optionElement);
  27226. });
  27227. } else if (interpolateTextFn) {
  27228. // The text content is interpolated
  27229. optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
  27230. optionAttrs.$set('value', newVal);
  27231. if (oldVal !== newVal) {
  27232. self.removeOption(oldVal);
  27233. }
  27234. self.addOption(newVal, optionElement);
  27235. });
  27236. } else {
  27237. // The value attribute is static
  27238. self.addOption(optionAttrs.value, optionElement);
  27239. }
  27240. optionElement.on('$destroy', function() {
  27241. self.removeOption(optionAttrs.value);
  27242. self.ngModelCtrl.$render();
  27243. });
  27244. };
  27245. }];
  27246. /**
  27247. * @ngdoc directive
  27248. * @name select
  27249. * @restrict E
  27250. *
  27251. * @description
  27252. * HTML `SELECT` element with angular data-binding.
  27253. *
  27254. * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
  27255. * between the scope and the `<select>` control (including setting default values).
  27256. * It also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
  27257. * {@link ngOptions `ngOptions`} directives.
  27258. *
  27259. * When an item in the `<select>` menu is selected, the value of the selected option will be bound
  27260. * to the model identified by the `ngModel` directive. With static or repeated options, this is
  27261. * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
  27262. * If you want dynamic value attributes, you can use interpolation inside the value attribute.
  27263. *
  27264. * <div class="alert alert-warning">
  27265. * Note that the value of a `select` directive used without `ngOptions` is always a string.
  27266. * When the model needs to be bound to a non-string value, you must either explicitly convert it
  27267. * using a directive (see example below) or use `ngOptions` to specify the set of options.
  27268. * This is because an option element can only be bound to string values at present.
  27269. * </div>
  27270. *
  27271. * If the viewValue of `ngModel` does not match any of the options, then the control
  27272. * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
  27273. *
  27274. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  27275. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  27276. * option. See example below for demonstration.
  27277. *
  27278. * <div class="alert alert-info">
  27279. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  27280. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits, such as
  27281. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  27282. * comprehension expression, and additionally in reducing memory and increasing speed by not creating
  27283. * a new scope for each repeated instance.
  27284. * </div>
  27285. *
  27286. *
  27287. * @param {string} ngModel Assignable angular expression to data-bind to.
  27288. * @param {string=} name Property name of the form under which the control is published.
  27289. * @param {string=} multiple Allows multiple options to be selected. The selected values will be
  27290. * bound to the model as an array.
  27291. * @param {string=} required Sets `required` validation error key if the value is not entered.
  27292. * @param {string=} ngRequired Adds required attribute and required validation constraint to
  27293. * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
  27294. * when you want to data-bind to the required attribute.
  27295. * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
  27296. * interaction with the select element.
  27297. * @param {string=} ngOptions sets the options that the select is populated with and defines what is
  27298. * set on the model on selection. See {@link ngOptions `ngOptions`}.
  27299. *
  27300. * @example
  27301. * ### Simple `select` elements with static options
  27302. *
  27303. * <example name="static-select" module="staticSelect">
  27304. * <file name="index.html">
  27305. * <div ng-controller="ExampleController">
  27306. * <form name="myForm">
  27307. * <label for="singleSelect"> Single select: </label><br>
  27308. * <select name="singleSelect" ng-model="data.singleSelect">
  27309. * <option value="option-1">Option 1</option>
  27310. * <option value="option-2">Option 2</option>
  27311. * </select><br>
  27312. *
  27313. * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
  27314. * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
  27315. * <option value="">---Please select---</option> <!-- not selected / blank option -->
  27316. * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
  27317. * <option value="option-2">Option 2</option>
  27318. * </select><br>
  27319. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  27320. * <tt>singleSelect = {{data.singleSelect}}</tt>
  27321. *
  27322. * <hr>
  27323. * <label for="multipleSelect"> Multiple select: </label><br>
  27324. * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
  27325. * <option value="option-1">Option 1</option>
  27326. * <option value="option-2">Option 2</option>
  27327. * <option value="option-3">Option 3</option>
  27328. * </select><br>
  27329. * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
  27330. * </form>
  27331. * </div>
  27332. * </file>
  27333. * <file name="app.js">
  27334. * angular.module('staticSelect', [])
  27335. * .controller('ExampleController', ['$scope', function($scope) {
  27336. * $scope.data = {
  27337. * singleSelect: null,
  27338. * multipleSelect: [],
  27339. * option1: 'option-1',
  27340. * };
  27341. *
  27342. * $scope.forceUnknownOption = function() {
  27343. * $scope.data.singleSelect = 'nonsense';
  27344. * };
  27345. * }]);
  27346. * </file>
  27347. *</example>
  27348. *
  27349. * ### Using `ngRepeat` to generate `select` options
  27350. * <example name="ngrepeat-select" module="ngrepeatSelect">
  27351. * <file name="index.html">
  27352. * <div ng-controller="ExampleController">
  27353. * <form name="myForm">
  27354. * <label for="repeatSelect"> Repeat select: </label>
  27355. * <select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect">
  27356. * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
  27357. * </select>
  27358. * </form>
  27359. * <hr>
  27360. * <tt>repeatSelect = {{data.repeatSelect}}</tt><br/>
  27361. * </div>
  27362. * </file>
  27363. * <file name="app.js">
  27364. * angular.module('ngrepeatSelect', [])
  27365. * .controller('ExampleController', ['$scope', function($scope) {
  27366. * $scope.data = {
  27367. * repeatSelect: null,
  27368. * availableOptions: [
  27369. * {id: '1', name: 'Option A'},
  27370. * {id: '2', name: 'Option B'},
  27371. * {id: '3', name: 'Option C'}
  27372. * ],
  27373. * };
  27374. * }]);
  27375. * </file>
  27376. *</example>
  27377. *
  27378. *
  27379. * ### Using `select` with `ngOptions` and setting a default value
  27380. * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
  27381. *
  27382. * <example name="select-with-default-values" module="defaultValueSelect">
  27383. * <file name="index.html">
  27384. * <div ng-controller="ExampleController">
  27385. * <form name="myForm">
  27386. * <label for="mySelect">Make a choice:</label>
  27387. * <select name="mySelect" id="mySelect"
  27388. * ng-options="option.name for option in data.availableOptions track by option.id"
  27389. * ng-model="data.selectedOption"></select>
  27390. * </form>
  27391. * <hr>
  27392. * <tt>option = {{data.selectedOption}}</tt><br/>
  27393. * </div>
  27394. * </file>
  27395. * <file name="app.js">
  27396. * angular.module('defaultValueSelect', [])
  27397. * .controller('ExampleController', ['$scope', function($scope) {
  27398. * $scope.data = {
  27399. * availableOptions: [
  27400. * {id: '1', name: 'Option A'},
  27401. * {id: '2', name: 'Option B'},
  27402. * {id: '3', name: 'Option C'}
  27403. * ],
  27404. * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
  27405. * };
  27406. * }]);
  27407. * </file>
  27408. *</example>
  27409. *
  27410. *
  27411. * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
  27412. *
  27413. * <example name="select-with-non-string-options" module="nonStringSelect">
  27414. * <file name="index.html">
  27415. * <select ng-model="model.id" convert-to-number>
  27416. * <option value="0">Zero</option>
  27417. * <option value="1">One</option>
  27418. * <option value="2">Two</option>
  27419. * </select>
  27420. * {{ model }}
  27421. * </file>
  27422. * <file name="app.js">
  27423. * angular.module('nonStringSelect', [])
  27424. * .run(function($rootScope) {
  27425. * $rootScope.model = { id: 2 };
  27426. * })
  27427. * .directive('convertToNumber', function() {
  27428. * return {
  27429. * require: 'ngModel',
  27430. * link: function(scope, element, attrs, ngModel) {
  27431. * ngModel.$parsers.push(function(val) {
  27432. * return parseInt(val, 10);
  27433. * });
  27434. * ngModel.$formatters.push(function(val) {
  27435. * return '' + val;
  27436. * });
  27437. * }
  27438. * };
  27439. * });
  27440. * </file>
  27441. * <file name="protractor.js" type="protractor">
  27442. * it('should initialize to model', function() {
  27443. * var select = element(by.css('select'));
  27444. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  27445. * });
  27446. * </file>
  27447. * </example>
  27448. *
  27449. */
  27450. var selectDirective = function() {
  27451. return {
  27452. restrict: 'E',
  27453. require: ['select', '?ngModel'],
  27454. controller: SelectController,
  27455. priority: 1,
  27456. link: {
  27457. pre: selectPreLink,
  27458. post: selectPostLink
  27459. }
  27460. };
  27461. function selectPreLink(scope, element, attr, ctrls) {
  27462. // if ngModel is not defined, we don't need to do anything
  27463. var ngModelCtrl = ctrls[1];
  27464. if (!ngModelCtrl) return;
  27465. var selectCtrl = ctrls[0];
  27466. selectCtrl.ngModelCtrl = ngModelCtrl;
  27467. // When the selected item(s) changes we delegate getting the value of the select control
  27468. // to the `readValue` method, which can be changed if the select can have multiple
  27469. // selected values or if the options are being generated by `ngOptions`
  27470. element.on('change', function() {
  27471. scope.$apply(function() {
  27472. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  27473. });
  27474. });
  27475. // If the select allows multiple values then we need to modify how we read and write
  27476. // values from and to the control; also what it means for the value to be empty and
  27477. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  27478. // doesn't trigger rendering if only an item in the array changes.
  27479. if (attr.multiple) {
  27480. // Read value now needs to check each option to see if it is selected
  27481. selectCtrl.readValue = function readMultipleValue() {
  27482. var array = [];
  27483. forEach(element.find('option'), function(option) {
  27484. if (option.selected) {
  27485. array.push(option.value);
  27486. }
  27487. });
  27488. return array;
  27489. };
  27490. // Write value now needs to set the selected property of each matching option
  27491. selectCtrl.writeValue = function writeMultipleValue(value) {
  27492. var items = new HashMap(value);
  27493. forEach(element.find('option'), function(option) {
  27494. option.selected = isDefined(items.get(option.value));
  27495. });
  27496. };
  27497. // we have to do it on each watch since ngModel watches reference, but
  27498. // we need to work of an array, so we need to see if anything was inserted/removed
  27499. var lastView, lastViewRef = NaN;
  27500. scope.$watch(function selectMultipleWatch() {
  27501. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  27502. lastView = shallowCopy(ngModelCtrl.$viewValue);
  27503. ngModelCtrl.$render();
  27504. }
  27505. lastViewRef = ngModelCtrl.$viewValue;
  27506. });
  27507. // If we are a multiple select then value is now a collection
  27508. // so the meaning of $isEmpty changes
  27509. ngModelCtrl.$isEmpty = function(value) {
  27510. return !value || value.length === 0;
  27511. };
  27512. }
  27513. }
  27514. function selectPostLink(scope, element, attrs, ctrls) {
  27515. // if ngModel is not defined, we don't need to do anything
  27516. var ngModelCtrl = ctrls[1];
  27517. if (!ngModelCtrl) return;
  27518. var selectCtrl = ctrls[0];
  27519. // We delegate rendering to the `writeValue` method, which can be changed
  27520. // if the select can have multiple selected values or if the options are being
  27521. // generated by `ngOptions`.
  27522. // This must be done in the postLink fn to prevent $render to be called before
  27523. // all nodes have been linked correctly.
  27524. ngModelCtrl.$render = function() {
  27525. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  27526. };
  27527. }
  27528. };
  27529. // The option directive is purely designed to communicate the existence (or lack of)
  27530. // of dynamically created (and destroyed) option elements to their containing select
  27531. // directive via its controller.
  27532. var optionDirective = ['$interpolate', function($interpolate) {
  27533. return {
  27534. restrict: 'E',
  27535. priority: 100,
  27536. compile: function(element, attr) {
  27537. if (isDefined(attr.value)) {
  27538. // If the value attribute is defined, check if it contains an interpolation
  27539. var interpolateValueFn = $interpolate(attr.value, true);
  27540. } else {
  27541. // If the value attribute is not defined then we fall back to the
  27542. // text content of the option element, which may be interpolated
  27543. var interpolateTextFn = $interpolate(element.text(), true);
  27544. if (!interpolateTextFn) {
  27545. attr.$set('value', element.text());
  27546. }
  27547. }
  27548. return function(scope, element, attr) {
  27549. // This is an optimization over using ^^ since we don't want to have to search
  27550. // all the way to the root of the DOM for every single option element
  27551. var selectCtrlName = '$selectController',
  27552. parent = element.parent(),
  27553. selectCtrl = parent.data(selectCtrlName) ||
  27554. parent.parent().data(selectCtrlName); // in case we are in optgroup
  27555. if (selectCtrl) {
  27556. selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
  27557. }
  27558. };
  27559. }
  27560. };
  27561. }];
  27562. var styleDirective = valueFn({
  27563. restrict: 'E',
  27564. terminal: false
  27565. });
  27566. /**
  27567. * @ngdoc directive
  27568. * @name ngRequired
  27569. *
  27570. * @description
  27571. *
  27572. * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  27573. * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be
  27574. * applied to custom controls.
  27575. *
  27576. * The directive sets the `required` attribute on the element if the Angular expression inside
  27577. * `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we
  27578. * cannot use interpolation inside `required`. See the {@link guide/interpolation interpolation guide}
  27579. * for more info.
  27580. *
  27581. * The validator will set the `required` error key to true if the `required` attribute is set and
  27582. * calling {@link ngModel.NgModelController#$isEmpty `NgModelController.$isEmpty`} with the
  27583. * {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} returns `true`. For example, the
  27584. * `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing
  27585. * custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based.
  27586. *
  27587. * @example
  27588. * <example name="ngRequiredDirective" module="ngRequiredExample">
  27589. * <file name="index.html">
  27590. * <script>
  27591. * angular.module('ngRequiredExample', [])
  27592. * .controller('ExampleController', ['$scope', function($scope) {
  27593. * $scope.required = true;
  27594. * }]);
  27595. * </script>
  27596. * <div ng-controller="ExampleController">
  27597. * <form name="form">
  27598. * <label for="required">Toggle required: </label>
  27599. * <input type="checkbox" ng-model="required" id="required" />
  27600. * <br>
  27601. * <label for="input">This input must be filled if `required` is true: </label>
  27602. * <input type="text" ng-model="model" id="input" name="input" ng-required="required" /><br>
  27603. * <hr>
  27604. * required error set? = <code>{{form.input.$error.required}}</code><br>
  27605. * model = <code>{{model}}</code>
  27606. * </form>
  27607. * </div>
  27608. * </file>
  27609. * <file name="protractor.js" type="protractor">
  27610. var required = element(by.binding('form.input.$error.required'));
  27611. var model = element(by.binding('model'));
  27612. var input = element(by.id('input'));
  27613. it('should set the required error', function() {
  27614. expect(required.getText()).toContain('true');
  27615. input.sendKeys('123');
  27616. expect(required.getText()).not.toContain('true');
  27617. expect(model.getText()).toContain('123');
  27618. });
  27619. * </file>
  27620. * </example>
  27621. */
  27622. var requiredDirective = function() {
  27623. return {
  27624. restrict: 'A',
  27625. require: '?ngModel',
  27626. link: function(scope, elm, attr, ctrl) {
  27627. if (!ctrl) return;
  27628. attr.required = true; // force truthy in case we are on non input element
  27629. ctrl.$validators.required = function(modelValue, viewValue) {
  27630. return !attr.required || !ctrl.$isEmpty(viewValue);
  27631. };
  27632. attr.$observe('required', function() {
  27633. ctrl.$validate();
  27634. });
  27635. }
  27636. };
  27637. };
  27638. /**
  27639. * @ngdoc directive
  27640. * @name ngPattern
  27641. *
  27642. * @description
  27643. *
  27644. * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  27645. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  27646. *
  27647. * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  27648. * does not match a RegExp which is obtained by evaluating the Angular expression given in the
  27649. * `ngPattern` attribute value:
  27650. * * If the expression evaluates to a RegExp object, then this is used directly.
  27651. * * If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it
  27652. * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  27653. *
  27654. * <div class="alert alert-info">
  27655. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  27656. * start at the index of the last search's match, thus not taking the whole input value into
  27657. * account.
  27658. * </div>
  27659. *
  27660. * <div class="alert alert-info">
  27661. * **Note:** This directive is also added when the plain `pattern` attribute is used, with two
  27662. * differences:
  27663. * <ol>
  27664. * <li>
  27665. * `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is
  27666. * not available.
  27667. * </li>
  27668. * <li>
  27669. * The `ngPattern` attribute must be an expression, while the `pattern` value must be
  27670. * interpolated.
  27671. * </li>
  27672. * </ol>
  27673. * </div>
  27674. *
  27675. * @example
  27676. * <example name="ngPatternDirective" module="ngPatternExample">
  27677. * <file name="index.html">
  27678. * <script>
  27679. * angular.module('ngPatternExample', [])
  27680. * .controller('ExampleController', ['$scope', function($scope) {
  27681. * $scope.regex = '\\d+';
  27682. * }]);
  27683. * </script>
  27684. * <div ng-controller="ExampleController">
  27685. * <form name="form">
  27686. * <label for="regex">Set a pattern (regex string): </label>
  27687. * <input type="text" ng-model="regex" id="regex" />
  27688. * <br>
  27689. * <label for="input">This input is restricted by the current pattern: </label>
  27690. * <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
  27691. * <hr>
  27692. * input valid? = <code>{{form.input.$valid}}</code><br>
  27693. * model = <code>{{model}}</code>
  27694. * </form>
  27695. * </div>
  27696. * </file>
  27697. * <file name="protractor.js" type="protractor">
  27698. var model = element(by.binding('model'));
  27699. var input = element(by.id('input'));
  27700. it('should validate the input with the default pattern', function() {
  27701. input.sendKeys('aaa');
  27702. expect(model.getText()).not.toContain('aaa');
  27703. input.clear().then(function() {
  27704. input.sendKeys('123');
  27705. expect(model.getText()).toContain('123');
  27706. });
  27707. });
  27708. * </file>
  27709. * </example>
  27710. */
  27711. var patternDirective = function() {
  27712. return {
  27713. restrict: 'A',
  27714. require: '?ngModel',
  27715. link: function(scope, elm, attr, ctrl) {
  27716. if (!ctrl) return;
  27717. var regexp, patternExp = attr.ngPattern || attr.pattern;
  27718. attr.$observe('pattern', function(regex) {
  27719. if (isString(regex) && regex.length > 0) {
  27720. regex = new RegExp('^' + regex + '$');
  27721. }
  27722. if (regex && !regex.test) {
  27723. throw minErr('ngPattern')('noregexp',
  27724. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  27725. regex, startingTag(elm));
  27726. }
  27727. regexp = regex || undefined;
  27728. ctrl.$validate();
  27729. });
  27730. ctrl.$validators.pattern = function(modelValue, viewValue) {
  27731. // HTML5 pattern constraint validates the input value, so we validate the viewValue
  27732. return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
  27733. };
  27734. }
  27735. };
  27736. };
  27737. /**
  27738. * @ngdoc directive
  27739. * @name ngMaxlength
  27740. *
  27741. * @description
  27742. *
  27743. * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  27744. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  27745. *
  27746. * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  27747. * is longer than the integer obtained by evaluating the Angular expression given in the
  27748. * `ngMaxlength` attribute value.
  27749. *
  27750. * <div class="alert alert-info">
  27751. * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two
  27752. * differences:
  27753. * <ol>
  27754. * <li>
  27755. * `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint
  27756. * validation is not available.
  27757. * </li>
  27758. * <li>
  27759. * The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be
  27760. * interpolated.
  27761. * </li>
  27762. * </ol>
  27763. * </div>
  27764. *
  27765. * @example
  27766. * <example name="ngMaxlengthDirective" module="ngMaxlengthExample">
  27767. * <file name="index.html">
  27768. * <script>
  27769. * angular.module('ngMaxlengthExample', [])
  27770. * .controller('ExampleController', ['$scope', function($scope) {
  27771. * $scope.maxlength = 5;
  27772. * }]);
  27773. * </script>
  27774. * <div ng-controller="ExampleController">
  27775. * <form name="form">
  27776. * <label for="maxlength">Set a maxlength: </label>
  27777. * <input type="number" ng-model="maxlength" id="maxlength" />
  27778. * <br>
  27779. * <label for="input">This input is restricted by the current maxlength: </label>
  27780. * <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br>
  27781. * <hr>
  27782. * input valid? = <code>{{form.input.$valid}}</code><br>
  27783. * model = <code>{{model}}</code>
  27784. * </form>
  27785. * </div>
  27786. * </file>
  27787. * <file name="protractor.js" type="protractor">
  27788. var model = element(by.binding('model'));
  27789. var input = element(by.id('input'));
  27790. it('should validate the input with the default maxlength', function() {
  27791. input.sendKeys('abcdef');
  27792. expect(model.getText()).not.toContain('abcdef');
  27793. input.clear().then(function() {
  27794. input.sendKeys('abcde');
  27795. expect(model.getText()).toContain('abcde');
  27796. });
  27797. });
  27798. * </file>
  27799. * </example>
  27800. */
  27801. var maxlengthDirective = function() {
  27802. return {
  27803. restrict: 'A',
  27804. require: '?ngModel',
  27805. link: function(scope, elm, attr, ctrl) {
  27806. if (!ctrl) return;
  27807. var maxlength = -1;
  27808. attr.$observe('maxlength', function(value) {
  27809. var intVal = toInt(value);
  27810. maxlength = isNaN(intVal) ? -1 : intVal;
  27811. ctrl.$validate();
  27812. });
  27813. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  27814. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  27815. };
  27816. }
  27817. };
  27818. };
  27819. /**
  27820. * @ngdoc directive
  27821. * @name ngMinlength
  27822. *
  27823. * @description
  27824. *
  27825. * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  27826. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  27827. *
  27828. * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  27829. * is shorter than the integer obtained by evaluating the Angular expression given in the
  27830. * `ngMinlength` attribute value.
  27831. *
  27832. * <div class="alert alert-info">
  27833. * **Note:** This directive is also added when the plain `minlength` attribute is used, with two
  27834. * differences:
  27835. * <ol>
  27836. * <li>
  27837. * `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint
  27838. * validation is not available.
  27839. * </li>
  27840. * <li>
  27841. * The `ngMinlength` value must be an expression, while the `minlength` value must be
  27842. * interpolated.
  27843. * </li>
  27844. * </ol>
  27845. * </div>
  27846. *
  27847. * @example
  27848. * <example name="ngMinlengthDirective" module="ngMinlengthExample">
  27849. * <file name="index.html">
  27850. * <script>
  27851. * angular.module('ngMinlengthExample', [])
  27852. * .controller('ExampleController', ['$scope', function($scope) {
  27853. * $scope.minlength = 3;
  27854. * }]);
  27855. * </script>
  27856. * <div ng-controller="ExampleController">
  27857. * <form name="form">
  27858. * <label for="minlength">Set a minlength: </label>
  27859. * <input type="number" ng-model="minlength" id="minlength" />
  27860. * <br>
  27861. * <label for="input">This input is restricted by the current minlength: </label>
  27862. * <input type="text" ng-model="model" id="input" name="input" ng-minlength="minlength" /><br>
  27863. * <hr>
  27864. * input valid? = <code>{{form.input.$valid}}</code><br>
  27865. * model = <code>{{model}}</code>
  27866. * </form>
  27867. * </div>
  27868. * </file>
  27869. * <file name="protractor.js" type="protractor">
  27870. var model = element(by.binding('model'));
  27871. var input = element(by.id('input'));
  27872. it('should validate the input with the default minlength', function() {
  27873. input.sendKeys('ab');
  27874. expect(model.getText()).not.toContain('ab');
  27875. input.sendKeys('abc');
  27876. expect(model.getText()).toContain('abc');
  27877. });
  27878. * </file>
  27879. * </example>
  27880. */
  27881. var minlengthDirective = function() {
  27882. return {
  27883. restrict: 'A',
  27884. require: '?ngModel',
  27885. link: function(scope, elm, attr, ctrl) {
  27886. if (!ctrl) return;
  27887. var minlength = 0;
  27888. attr.$observe('minlength', function(value) {
  27889. minlength = toInt(value) || 0;
  27890. ctrl.$validate();
  27891. });
  27892. ctrl.$validators.minlength = function(modelValue, viewValue) {
  27893. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  27894. };
  27895. }
  27896. };
  27897. };
  27898. if (window.angular.bootstrap) {
  27899. //AngularJS is already loaded, so we can return here...
  27900. if (window.console) {
  27901. console.log('WARNING: Tried to load angular more than once.');
  27902. }
  27903. return;
  27904. }
  27905. //try to bind to jquery now so that one can write jqLite(document).ready()
  27906. //but we will rebind on bootstrap again.
  27907. bindJQuery();
  27908. publishExternalAPI(angular);
  27909. angular.module("ngLocale", [], ["$provide", function($provide) {
  27910. var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
  27911. function getDecimals(n) {
  27912. n = n + '';
  27913. var i = n.indexOf('.');
  27914. return (i == -1) ? 0 : n.length - i - 1;
  27915. }
  27916. function getVF(n, opt_precision) {
  27917. var v = opt_precision;
  27918. if (undefined === v) {
  27919. v = Math.min(getDecimals(n), 3);
  27920. }
  27921. var base = Math.pow(10, v);
  27922. var f = ((n * base) | 0) % base;
  27923. return {v: v, f: f};
  27924. }
  27925. $provide.value("$locale", {
  27926. "DATETIME_FORMATS": {
  27927. "AMPMS": [
  27928. "AM",
  27929. "PM"
  27930. ],
  27931. "DAY": [
  27932. "Sunday",
  27933. "Monday",
  27934. "Tuesday",
  27935. "Wednesday",
  27936. "Thursday",
  27937. "Friday",
  27938. "Saturday"
  27939. ],
  27940. "ERANAMES": [
  27941. "Before Christ",
  27942. "Anno Domini"
  27943. ],
  27944. "ERAS": [
  27945. "BC",
  27946. "AD"
  27947. ],
  27948. "FIRSTDAYOFWEEK": 6,
  27949. "MONTH": [
  27950. "January",
  27951. "February",
  27952. "March",
  27953. "April",
  27954. "May",
  27955. "June",
  27956. "July",
  27957. "August",
  27958. "September",
  27959. "October",
  27960. "November",
  27961. "December"
  27962. ],
  27963. "SHORTDAY": [
  27964. "Sun",
  27965. "Mon",
  27966. "Tue",
  27967. "Wed",
  27968. "Thu",
  27969. "Fri",
  27970. "Sat"
  27971. ],
  27972. "SHORTMONTH": [
  27973. "Jan",
  27974. "Feb",
  27975. "Mar",
  27976. "Apr",
  27977. "May",
  27978. "Jun",
  27979. "Jul",
  27980. "Aug",
  27981. "Sep",
  27982. "Oct",
  27983. "Nov",
  27984. "Dec"
  27985. ],
  27986. "STANDALONEMONTH": [
  27987. "January",
  27988. "February",
  27989. "March",
  27990. "April",
  27991. "May",
  27992. "June",
  27993. "July",
  27994. "August",
  27995. "September",
  27996. "October",
  27997. "November",
  27998. "December"
  27999. ],
  28000. "WEEKENDRANGE": [
  28001. 5,
  28002. 6
  28003. ],
  28004. "fullDate": "EEEE, MMMM d, y",
  28005. "longDate": "MMMM d, y",
  28006. "medium": "MMM d, y h:mm:ss a",
  28007. "mediumDate": "MMM d, y",
  28008. "mediumTime": "h:mm:ss a",
  28009. "short": "M/d/yy h:mm a",
  28010. "shortDate": "M/d/yy",
  28011. "shortTime": "h:mm a"
  28012. },
  28013. "NUMBER_FORMATS": {
  28014. "CURRENCY_SYM": "$",
  28015. "DECIMAL_SEP": ".",
  28016. "GROUP_SEP": ",",
  28017. "PATTERNS": [
  28018. {
  28019. "gSize": 3,
  28020. "lgSize": 3,
  28021. "maxFrac": 3,
  28022. "minFrac": 0,
  28023. "minInt": 1,
  28024. "negPre": "-",
  28025. "negSuf": "",
  28026. "posPre": "",
  28027. "posSuf": ""
  28028. },
  28029. {
  28030. "gSize": 3,
  28031. "lgSize": 3,
  28032. "maxFrac": 2,
  28033. "minFrac": 2,
  28034. "minInt": 1,
  28035. "negPre": "-\u00a4",
  28036. "negSuf": "",
  28037. "posPre": "\u00a4",
  28038. "posSuf": ""
  28039. }
  28040. ]
  28041. },
  28042. "id": "en-us",
  28043. "localeID": "en_US",
  28044. "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;}
  28045. });
  28046. }]);
  28047. jqLite(document).ready(function() {
  28048. angularInit(document, bootstrap);
  28049. });
  28050. })(window, document);
  28051. !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>');