angular.js 1.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133
  1. /**
  2. * @license AngularJS v1.4.0
  3. * (c) 2010-2015 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.4.0/' +
  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. /**
  175. * @ngdoc function
  176. * @name angular.lowercase
  177. * @module ng
  178. * @kind function
  179. *
  180. * @description Converts the specified string to lowercase.
  181. * @param {string} string String to be converted to lowercase.
  182. * @returns {string} Lowercased string.
  183. */
  184. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  185. var hasOwnProperty = Object.prototype.hasOwnProperty;
  186. /**
  187. * @ngdoc function
  188. * @name angular.uppercase
  189. * @module ng
  190. * @kind function
  191. *
  192. * @description Converts the specified string to uppercase.
  193. * @param {string} string String to be converted to uppercase.
  194. * @returns {string} Uppercased string.
  195. */
  196. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  197. var manualLowercase = function(s) {
  198. /* jshint bitwise: false */
  199. return isString(s)
  200. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  201. : s;
  202. };
  203. var manualUppercase = function(s) {
  204. /* jshint bitwise: false */
  205. return isString(s)
  206. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  207. : s;
  208. };
  209. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  210. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  211. // with correct but slower alternatives.
  212. if ('i' !== 'I'.toLowerCase()) {
  213. lowercase = manualLowercase;
  214. uppercase = manualUppercase;
  215. }
  216. var
  217. msie, // holds major version number for IE, or NaN if UA is not IE.
  218. jqLite, // delay binding since jQuery could be loaded after us.
  219. jQuery, // delay binding
  220. slice = [].slice,
  221. splice = [].splice,
  222. push = [].push,
  223. toString = Object.prototype.toString,
  224. getPrototypeOf = Object.getPrototypeOf,
  225. ngMinErr = minErr('ng'),
  226. /** @name angular */
  227. angular = window.angular || (window.angular = {}),
  228. angularModule,
  229. uid = 0;
  230. /**
  231. * documentMode is an IE-only property
  232. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  233. */
  234. msie = document.documentMode;
  235. /**
  236. * @private
  237. * @param {*} obj
  238. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  239. * String ...)
  240. */
  241. function isArrayLike(obj) {
  242. if (obj == null || isWindow(obj)) {
  243. return false;
  244. }
  245. // Support: iOS 8.2 (not reproducible in simulator)
  246. // "length" in obj used to prevent JIT error (gh-11508)
  247. var length = "length" in Object(obj) && obj.length;
  248. if (obj.nodeType === NODE_TYPE_ELEMENT && length) {
  249. return true;
  250. }
  251. return isString(obj) || isArray(obj) || length === 0 ||
  252. typeof length === 'number' && length > 0 && (length - 1) in obj;
  253. }
  254. /**
  255. * @ngdoc function
  256. * @name angular.forEach
  257. * @module ng
  258. * @kind function
  259. *
  260. * @description
  261. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  262. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  263. * is the value of an object property or an array element, `key` is the object property key or
  264. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  265. *
  266. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  267. * using the `hasOwnProperty` method.
  268. *
  269. * Unlike ES262's
  270. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  271. * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  272. * return the value provided.
  273. *
  274. ```js
  275. var values = {name: 'misko', gender: 'male'};
  276. var log = [];
  277. angular.forEach(values, function(value, key) {
  278. this.push(key + ': ' + value);
  279. }, log);
  280. expect(log).toEqual(['name: misko', 'gender: male']);
  281. ```
  282. *
  283. * @param {Object|Array} obj Object to iterate over.
  284. * @param {Function} iterator Iterator function.
  285. * @param {Object=} context Object to become context (`this`) for the iterator function.
  286. * @returns {Object|Array} Reference to `obj`.
  287. */
  288. function forEach(obj, iterator, context) {
  289. var key, length;
  290. if (obj) {
  291. if (isFunction(obj)) {
  292. for (key in obj) {
  293. // Need to check if hasOwnProperty exists,
  294. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  295. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  296. iterator.call(context, obj[key], key, obj);
  297. }
  298. }
  299. } else if (isArray(obj) || isArrayLike(obj)) {
  300. var isPrimitive = typeof obj !== 'object';
  301. for (key = 0, length = obj.length; key < length; key++) {
  302. if (isPrimitive || key in obj) {
  303. iterator.call(context, obj[key], key, obj);
  304. }
  305. }
  306. } else if (obj.forEach && obj.forEach !== forEach) {
  307. obj.forEach(iterator, context, obj);
  308. } else if (isBlankObject(obj)) {
  309. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  310. for (key in obj) {
  311. iterator.call(context, obj[key], key, obj);
  312. }
  313. } else if (typeof obj.hasOwnProperty === 'function') {
  314. // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
  315. for (key in obj) {
  316. if (obj.hasOwnProperty(key)) {
  317. iterator.call(context, obj[key], key, obj);
  318. }
  319. }
  320. } else {
  321. // Slow path for objects which do not have a method `hasOwnProperty`
  322. for (key in obj) {
  323. if (hasOwnProperty.call(obj, key)) {
  324. iterator.call(context, obj[key], key, obj);
  325. }
  326. }
  327. }
  328. }
  329. return obj;
  330. }
  331. function forEachSorted(obj, iterator, context) {
  332. var keys = Object.keys(obj).sort();
  333. for (var i = 0; i < keys.length; i++) {
  334. iterator.call(context, obj[keys[i]], keys[i]);
  335. }
  336. return keys;
  337. }
  338. /**
  339. * when using forEach the params are value, key, but it is often useful to have key, value.
  340. * @param {function(string, *)} iteratorFn
  341. * @returns {function(*, string)}
  342. */
  343. function reverseParams(iteratorFn) {
  344. return function(value, key) { iteratorFn(key, value); };
  345. }
  346. /**
  347. * A consistent way of creating unique IDs in angular.
  348. *
  349. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  350. * we hit number precision issues in JavaScript.
  351. *
  352. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  353. *
  354. * @returns {number} an unique alpha-numeric string
  355. */
  356. function nextUid() {
  357. return ++uid;
  358. }
  359. /**
  360. * Set or clear the hashkey for an object.
  361. * @param obj object
  362. * @param h the hashkey (!truthy to delete the hashkey)
  363. */
  364. function setHashKey(obj, h) {
  365. if (h) {
  366. obj.$$hashKey = h;
  367. } else {
  368. delete obj.$$hashKey;
  369. }
  370. }
  371. function baseExtend(dst, objs, deep) {
  372. var h = dst.$$hashKey;
  373. for (var i = 0, ii = objs.length; i < ii; ++i) {
  374. var obj = objs[i];
  375. if (!isObject(obj) && !isFunction(obj)) continue;
  376. var keys = Object.keys(obj);
  377. for (var j = 0, jj = keys.length; j < jj; j++) {
  378. var key = keys[j];
  379. var src = obj[key];
  380. if (deep && isObject(src)) {
  381. if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
  382. baseExtend(dst[key], [src], true);
  383. } else {
  384. dst[key] = src;
  385. }
  386. }
  387. }
  388. setHashKey(dst, h);
  389. return dst;
  390. }
  391. /**
  392. * @ngdoc function
  393. * @name angular.extend
  394. * @module ng
  395. * @kind function
  396. *
  397. * @description
  398. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  399. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  400. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  401. *
  402. * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
  403. * {@link angular.merge} for this.
  404. *
  405. * @param {Object} dst Destination object.
  406. * @param {...Object} src Source object(s).
  407. * @returns {Object} Reference to `dst`.
  408. */
  409. function extend(dst) {
  410. return baseExtend(dst, slice.call(arguments, 1), false);
  411. }
  412. /**
  413. * @ngdoc function
  414. * @name angular.merge
  415. * @module ng
  416. * @kind function
  417. *
  418. * @description
  419. * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  420. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  421. * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
  422. *
  423. * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
  424. * objects, performing a deep copy.
  425. *
  426. * @param {Object} dst Destination object.
  427. * @param {...Object} src Source object(s).
  428. * @returns {Object} Reference to `dst`.
  429. */
  430. function merge(dst) {
  431. return baseExtend(dst, slice.call(arguments, 1), true);
  432. }
  433. function toInt(str) {
  434. return parseInt(str, 10);
  435. }
  436. function inherit(parent, extra) {
  437. return extend(Object.create(parent), extra);
  438. }
  439. /**
  440. * @ngdoc function
  441. * @name angular.noop
  442. * @module ng
  443. * @kind function
  444. *
  445. * @description
  446. * A function that performs no operations. This function can be useful when writing code in the
  447. * functional style.
  448. ```js
  449. function foo(callback) {
  450. var result = calculateResult();
  451. (callback || angular.noop)(result);
  452. }
  453. ```
  454. */
  455. function noop() {}
  456. noop.$inject = [];
  457. /**
  458. * @ngdoc function
  459. * @name angular.identity
  460. * @module ng
  461. * @kind function
  462. *
  463. * @description
  464. * A function that returns its first argument. This function is useful when writing code in the
  465. * functional style.
  466. *
  467. ```js
  468. function transformer(transformationFn, value) {
  469. return (transformationFn || angular.identity)(value);
  470. };
  471. ```
  472. * @param {*} value to be returned.
  473. * @returns {*} the value passed in.
  474. */
  475. function identity($) {return $;}
  476. identity.$inject = [];
  477. function valueFn(value) {return function() {return value;};}
  478. /**
  479. * @ngdoc function
  480. * @name angular.isUndefined
  481. * @module ng
  482. * @kind function
  483. *
  484. * @description
  485. * Determines if a reference is undefined.
  486. *
  487. * @param {*} value Reference to check.
  488. * @returns {boolean} True if `value` is undefined.
  489. */
  490. function isUndefined(value) {return typeof value === 'undefined';}
  491. /**
  492. * @ngdoc function
  493. * @name angular.isDefined
  494. * @module ng
  495. * @kind function
  496. *
  497. * @description
  498. * Determines if a reference is defined.
  499. *
  500. * @param {*} value Reference to check.
  501. * @returns {boolean} True if `value` is defined.
  502. */
  503. function isDefined(value) {return typeof value !== 'undefined';}
  504. /**
  505. * @ngdoc function
  506. * @name angular.isObject
  507. * @module ng
  508. * @kind function
  509. *
  510. * @description
  511. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  512. * considered to be objects. Note that JavaScript arrays are objects.
  513. *
  514. * @param {*} value Reference to check.
  515. * @returns {boolean} True if `value` is an `Object` but not `null`.
  516. */
  517. function isObject(value) {
  518. // http://jsperf.com/isobject4
  519. return value !== null && typeof value === 'object';
  520. }
  521. /**
  522. * Determine if a value is an object with a null prototype
  523. *
  524. * @returns {boolean} True if `value` is an `Object` with a null prototype
  525. */
  526. function isBlankObject(value) {
  527. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  528. }
  529. /**
  530. * @ngdoc function
  531. * @name angular.isString
  532. * @module ng
  533. * @kind function
  534. *
  535. * @description
  536. * Determines if a reference is a `String`.
  537. *
  538. * @param {*} value Reference to check.
  539. * @returns {boolean} True if `value` is a `String`.
  540. */
  541. function isString(value) {return typeof value === 'string';}
  542. /**
  543. * @ngdoc function
  544. * @name angular.isNumber
  545. * @module ng
  546. * @kind function
  547. *
  548. * @description
  549. * Determines if a reference is a `Number`.
  550. *
  551. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  552. *
  553. * If you wish to exclude these then you can use the native
  554. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  555. * method.
  556. *
  557. * @param {*} value Reference to check.
  558. * @returns {boolean} True if `value` is a `Number`.
  559. */
  560. function isNumber(value) {return typeof value === 'number';}
  561. /**
  562. * @ngdoc function
  563. * @name angular.isDate
  564. * @module ng
  565. * @kind function
  566. *
  567. * @description
  568. * Determines if a value is a date.
  569. *
  570. * @param {*} value Reference to check.
  571. * @returns {boolean} True if `value` is a `Date`.
  572. */
  573. function isDate(value) {
  574. return toString.call(value) === '[object Date]';
  575. }
  576. /**
  577. * @ngdoc function
  578. * @name angular.isArray
  579. * @module ng
  580. * @kind function
  581. *
  582. * @description
  583. * Determines if a reference is an `Array`.
  584. *
  585. * @param {*} value Reference to check.
  586. * @returns {boolean} True if `value` is an `Array`.
  587. */
  588. var isArray = Array.isArray;
  589. /**
  590. * @ngdoc function
  591. * @name angular.isFunction
  592. * @module ng
  593. * @kind function
  594. *
  595. * @description
  596. * Determines if a reference is a `Function`.
  597. *
  598. * @param {*} value Reference to check.
  599. * @returns {boolean} True if `value` is a `Function`.
  600. */
  601. function isFunction(value) {return typeof value === 'function';}
  602. /**
  603. * Determines if a value is a regular expression object.
  604. *
  605. * @private
  606. * @param {*} value Reference to check.
  607. * @returns {boolean} True if `value` is a `RegExp`.
  608. */
  609. function isRegExp(value) {
  610. return toString.call(value) === '[object RegExp]';
  611. }
  612. /**
  613. * Checks if `obj` is a window object.
  614. *
  615. * @private
  616. * @param {*} obj Object to check
  617. * @returns {boolean} True if `obj` is a window obj.
  618. */
  619. function isWindow(obj) {
  620. return obj && obj.window === obj;
  621. }
  622. function isScope(obj) {
  623. return obj && obj.$evalAsync && obj.$watch;
  624. }
  625. function isFile(obj) {
  626. return toString.call(obj) === '[object File]';
  627. }
  628. function isFormData(obj) {
  629. return toString.call(obj) === '[object FormData]';
  630. }
  631. function isBlob(obj) {
  632. return toString.call(obj) === '[object Blob]';
  633. }
  634. function isBoolean(value) {
  635. return typeof value === 'boolean';
  636. }
  637. function isPromiseLike(obj) {
  638. return obj && isFunction(obj.then);
  639. }
  640. var TYPED_ARRAY_REGEXP = /^\[object (Uint8(Clamped)?)|(Uint16)|(Uint32)|(Int8)|(Int16)|(Int32)|(Float(32)|(64))Array\]$/;
  641. function isTypedArray(value) {
  642. return TYPED_ARRAY_REGEXP.test(toString.call(value));
  643. }
  644. var trim = function(value) {
  645. return isString(value) ? value.trim() : value;
  646. };
  647. // Copied from:
  648. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  649. // Prereq: s is a string.
  650. var escapeForRegexp = function(s) {
  651. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  652. replace(/\x08/g, '\\x08');
  653. };
  654. /**
  655. * @ngdoc function
  656. * @name angular.isElement
  657. * @module ng
  658. * @kind function
  659. *
  660. * @description
  661. * Determines if a reference is a DOM element (or wrapped jQuery element).
  662. *
  663. * @param {*} value Reference to check.
  664. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  665. */
  666. function isElement(node) {
  667. return !!(node &&
  668. (node.nodeName // we are a direct element
  669. || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
  670. }
  671. /**
  672. * @param str 'key1,key2,...'
  673. * @returns {object} in the form of {key1:true, key2:true, ...}
  674. */
  675. function makeMap(str) {
  676. var obj = {}, items = str.split(","), i;
  677. for (i = 0; i < items.length; i++) {
  678. obj[items[i]] = true;
  679. }
  680. return obj;
  681. }
  682. function nodeName_(element) {
  683. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  684. }
  685. function includes(array, obj) {
  686. return Array.prototype.indexOf.call(array, obj) != -1;
  687. }
  688. function arrayRemove(array, value) {
  689. var index = array.indexOf(value);
  690. if (index >= 0) {
  691. array.splice(index, 1);
  692. }
  693. return index;
  694. }
  695. /**
  696. * @ngdoc function
  697. * @name angular.copy
  698. * @module ng
  699. * @kind function
  700. *
  701. * @description
  702. * Creates a deep copy of `source`, which should be an object or an array.
  703. *
  704. * * If no destination is supplied, a copy of the object or array is created.
  705. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  706. * are deleted and then all elements/properties from the source are copied to it.
  707. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  708. * * If `source` is identical to 'destination' an exception will be thrown.
  709. *
  710. * @param {*} source The source that will be used to make a copy.
  711. * Can be any type, including primitives, `null`, and `undefined`.
  712. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  713. * provided, must be of the same type as `source`.
  714. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  715. *
  716. * @example
  717. <example module="copyExample">
  718. <file name="index.html">
  719. <div ng-controller="ExampleController">
  720. <form novalidate class="simple-form">
  721. Name: <input type="text" ng-model="user.name" /><br />
  722. E-mail: <input type="email" ng-model="user.email" /><br />
  723. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  724. <input type="radio" ng-model="user.gender" value="female" />female<br />
  725. <button ng-click="reset()">RESET</button>
  726. <button ng-click="update(user)">SAVE</button>
  727. </form>
  728. <pre>form = {{user | json}}</pre>
  729. <pre>master = {{master | json}}</pre>
  730. </div>
  731. <script>
  732. angular.module('copyExample', [])
  733. .controller('ExampleController', ['$scope', function($scope) {
  734. $scope.master= {};
  735. $scope.update = function(user) {
  736. // Example with 1 argument
  737. $scope.master= angular.copy(user);
  738. };
  739. $scope.reset = function() {
  740. // Example with 2 arguments
  741. angular.copy($scope.master, $scope.user);
  742. };
  743. $scope.reset();
  744. }]);
  745. </script>
  746. </file>
  747. </example>
  748. */
  749. function copy(source, destination, stackSource, stackDest) {
  750. if (isWindow(source) || isScope(source)) {
  751. throw ngMinErr('cpws',
  752. "Can't copy! Making copies of Window or Scope instances is not supported.");
  753. }
  754. if (isTypedArray(destination)) {
  755. throw ngMinErr('cpta',
  756. "Can't copy! TypedArray destination cannot be mutated.");
  757. }
  758. if (!destination) {
  759. destination = source;
  760. if (source) {
  761. if (isArray(source)) {
  762. destination = copy(source, [], stackSource, stackDest);
  763. } else if (isTypedArray(source)) {
  764. destination = new source.constructor(source);
  765. } else if (isDate(source)) {
  766. destination = new Date(source.getTime());
  767. } else if (isRegExp(source)) {
  768. destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  769. destination.lastIndex = source.lastIndex;
  770. } else if (isObject(source)) {
  771. var emptyObject = Object.create(getPrototypeOf(source));
  772. destination = copy(source, emptyObject, stackSource, stackDest);
  773. }
  774. }
  775. } else {
  776. if (source === destination) throw ngMinErr('cpi',
  777. "Can't copy! Source and destination are identical.");
  778. stackSource = stackSource || [];
  779. stackDest = stackDest || [];
  780. if (isObject(source)) {
  781. var index = stackSource.indexOf(source);
  782. if (index !== -1) return stackDest[index];
  783. stackSource.push(source);
  784. stackDest.push(destination);
  785. }
  786. var result, key;
  787. if (isArray(source)) {
  788. destination.length = 0;
  789. for (var i = 0; i < source.length; i++) {
  790. result = copy(source[i], null, stackSource, stackDest);
  791. if (isObject(source[i])) {
  792. stackSource.push(source[i]);
  793. stackDest.push(result);
  794. }
  795. destination.push(result);
  796. }
  797. } else {
  798. var h = destination.$$hashKey;
  799. if (isArray(destination)) {
  800. destination.length = 0;
  801. } else {
  802. forEach(destination, function(value, key) {
  803. delete destination[key];
  804. });
  805. }
  806. if (isBlankObject(source)) {
  807. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  808. for (key in source) {
  809. putValue(key, source[key], destination, stackSource, stackDest);
  810. }
  811. } else if (source && typeof source.hasOwnProperty === 'function') {
  812. // Slow path, which must rely on hasOwnProperty
  813. for (key in source) {
  814. if (source.hasOwnProperty(key)) {
  815. putValue(key, source[key], destination, stackSource, stackDest);
  816. }
  817. }
  818. } else {
  819. // Slowest path --- hasOwnProperty can't be called as a method
  820. for (key in source) {
  821. if (hasOwnProperty.call(source, key)) {
  822. putValue(key, source[key], destination, stackSource, stackDest);
  823. }
  824. }
  825. }
  826. setHashKey(destination,h);
  827. }
  828. }
  829. return destination;
  830. function putValue(key, val, destination, stackSource, stackDest) {
  831. // No context allocation, trivial outer scope, easily inlined
  832. var result = copy(val, null, stackSource, stackDest);
  833. if (isObject(val)) {
  834. stackSource.push(val);
  835. stackDest.push(result);
  836. }
  837. destination[key] = result;
  838. }
  839. }
  840. /**
  841. * Creates a shallow copy of an object, an array or a primitive.
  842. *
  843. * Assumes that there are no proto properties for objects.
  844. */
  845. function shallowCopy(src, dst) {
  846. if (isArray(src)) {
  847. dst = dst || [];
  848. for (var i = 0, ii = src.length; i < ii; i++) {
  849. dst[i] = src[i];
  850. }
  851. } else if (isObject(src)) {
  852. dst = dst || {};
  853. for (var key in src) {
  854. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  855. dst[key] = src[key];
  856. }
  857. }
  858. }
  859. return dst || src;
  860. }
  861. /**
  862. * @ngdoc function
  863. * @name angular.equals
  864. * @module ng
  865. * @kind function
  866. *
  867. * @description
  868. * Determines if two objects or two values are equivalent. Supports value types, regular
  869. * expressions, arrays and objects.
  870. *
  871. * Two objects or values are considered equivalent if at least one of the following is true:
  872. *
  873. * * Both objects or values pass `===` comparison.
  874. * * Both objects or values are of the same type and all of their properties are equal by
  875. * comparing them with `angular.equals`.
  876. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  877. * * Both values represent the same regular expression (In JavaScript,
  878. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  879. * representation matches).
  880. *
  881. * During a property comparison, properties of `function` type and properties with names
  882. * that begin with `$` are ignored.
  883. *
  884. * Scope and DOMWindow objects are being compared only by identify (`===`).
  885. *
  886. * @param {*} o1 Object or value to compare.
  887. * @param {*} o2 Object or value to compare.
  888. * @returns {boolean} True if arguments are equal.
  889. */
  890. function equals(o1, o2) {
  891. if (o1 === o2) return true;
  892. if (o1 === null || o2 === null) return false;
  893. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  894. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  895. if (t1 == t2) {
  896. if (t1 == 'object') {
  897. if (isArray(o1)) {
  898. if (!isArray(o2)) return false;
  899. if ((length = o1.length) == o2.length) {
  900. for (key = 0; key < length; key++) {
  901. if (!equals(o1[key], o2[key])) return false;
  902. }
  903. return true;
  904. }
  905. } else if (isDate(o1)) {
  906. if (!isDate(o2)) return false;
  907. return equals(o1.getTime(), o2.getTime());
  908. } else if (isRegExp(o1)) {
  909. return isRegExp(o2) ? o1.toString() == o2.toString() : false;
  910. } else {
  911. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  912. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  913. keySet = createMap();
  914. for (key in o1) {
  915. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  916. if (!equals(o1[key], o2[key])) return false;
  917. keySet[key] = true;
  918. }
  919. for (key in o2) {
  920. if (!(key in keySet) &&
  921. key.charAt(0) !== '$' &&
  922. o2[key] !== undefined &&
  923. !isFunction(o2[key])) return false;
  924. }
  925. return true;
  926. }
  927. }
  928. }
  929. return false;
  930. }
  931. var csp = function() {
  932. if (isDefined(csp.isActive_)) return csp.isActive_;
  933. var active = !!(document.querySelector('[ng-csp]') ||
  934. document.querySelector('[data-ng-csp]'));
  935. if (!active) {
  936. try {
  937. /* jshint -W031, -W054 */
  938. new Function('');
  939. /* jshint +W031, +W054 */
  940. } catch (e) {
  941. active = true;
  942. }
  943. }
  944. return (csp.isActive_ = active);
  945. };
  946. /**
  947. * @ngdoc directive
  948. * @module ng
  949. * @name ngJq
  950. *
  951. * @element ANY
  952. * @param {string=} ngJq the name of the library available under `window`
  953. * to be used for angular.element
  954. * @description
  955. * Use this directive to force the angular.element library. This should be
  956. * used to force either jqLite by leaving ng-jq blank or setting the name of
  957. * the jquery variable under window (eg. jQuery).
  958. *
  959. * Since angular looks for this directive when it is loaded (doesn't wait for the
  960. * DOMContentLoaded event), it must be placed on an element that comes before the script
  961. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  962. * others ignored.
  963. *
  964. * @example
  965. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  966. ```html
  967. <!doctype html>
  968. <html ng-app ng-jq>
  969. ...
  970. ...
  971. </html>
  972. ```
  973. * @example
  974. * This example shows how to use a jQuery based library of a different name.
  975. * The library name must be available at the top most 'window'.
  976. ```html
  977. <!doctype html>
  978. <html ng-app ng-jq="jQueryLib">
  979. ...
  980. ...
  981. </html>
  982. ```
  983. */
  984. var jq = function() {
  985. if (isDefined(jq.name_)) return jq.name_;
  986. var el;
  987. var i, ii = ngAttrPrefixes.length, prefix, name;
  988. for (i = 0; i < ii; ++i) {
  989. prefix = ngAttrPrefixes[i];
  990. if (el = document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]')) {
  991. name = el.getAttribute(prefix + 'jq');
  992. break;
  993. }
  994. }
  995. return (jq.name_ = name);
  996. };
  997. function concat(array1, array2, index) {
  998. return array1.concat(slice.call(array2, index));
  999. }
  1000. function sliceArgs(args, startIndex) {
  1001. return slice.call(args, startIndex || 0);
  1002. }
  1003. /* jshint -W101 */
  1004. /**
  1005. * @ngdoc function
  1006. * @name angular.bind
  1007. * @module ng
  1008. * @kind function
  1009. *
  1010. * @description
  1011. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  1012. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  1013. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  1014. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  1015. *
  1016. * @param {Object} self Context which `fn` should be evaluated in.
  1017. * @param {function()} fn Function to be bound.
  1018. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  1019. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  1020. */
  1021. /* jshint +W101 */
  1022. function bind(self, fn) {
  1023. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  1024. if (isFunction(fn) && !(fn instanceof RegExp)) {
  1025. return curryArgs.length
  1026. ? function() {
  1027. return arguments.length
  1028. ? fn.apply(self, concat(curryArgs, arguments, 0))
  1029. : fn.apply(self, curryArgs);
  1030. }
  1031. : function() {
  1032. return arguments.length
  1033. ? fn.apply(self, arguments)
  1034. : fn.call(self);
  1035. };
  1036. } else {
  1037. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  1038. return fn;
  1039. }
  1040. }
  1041. function toJsonReplacer(key, value) {
  1042. var val = value;
  1043. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  1044. val = undefined;
  1045. } else if (isWindow(value)) {
  1046. val = '$WINDOW';
  1047. } else if (value && document === value) {
  1048. val = '$DOCUMENT';
  1049. } else if (isScope(value)) {
  1050. val = '$SCOPE';
  1051. }
  1052. return val;
  1053. }
  1054. /**
  1055. * @ngdoc function
  1056. * @name angular.toJson
  1057. * @module ng
  1058. * @kind function
  1059. *
  1060. * @description
  1061. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  1062. * stripped since angular uses this notation internally.
  1063. *
  1064. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  1065. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  1066. * If set to an integer, the JSON output will contain that many spaces per indentation.
  1067. * @returns {string|undefined} JSON-ified string representing `obj`.
  1068. */
  1069. function toJson(obj, pretty) {
  1070. if (typeof obj === 'undefined') return undefined;
  1071. if (!isNumber(pretty)) {
  1072. pretty = pretty ? 2 : null;
  1073. }
  1074. return JSON.stringify(obj, toJsonReplacer, pretty);
  1075. }
  1076. /**
  1077. * @ngdoc function
  1078. * @name angular.fromJson
  1079. * @module ng
  1080. * @kind function
  1081. *
  1082. * @description
  1083. * Deserializes a JSON string.
  1084. *
  1085. * @param {string} json JSON string to deserialize.
  1086. * @returns {Object|Array|string|number} Deserialized JSON string.
  1087. */
  1088. function fromJson(json) {
  1089. return isString(json)
  1090. ? JSON.parse(json)
  1091. : json;
  1092. }
  1093. function timezoneToOffset(timezone, fallback) {
  1094. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  1095. return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  1096. }
  1097. function addDateMinutes(date, minutes) {
  1098. date = new Date(date.getTime());
  1099. date.setMinutes(date.getMinutes() + minutes);
  1100. return date;
  1101. }
  1102. function convertTimezoneToLocal(date, timezone, reverse) {
  1103. reverse = reverse ? -1 : 1;
  1104. var timezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
  1105. return addDateMinutes(date, reverse * (timezoneOffset - date.getTimezoneOffset()));
  1106. }
  1107. /**
  1108. * @returns {string} Returns the string representation of the element.
  1109. */
  1110. function startingTag(element) {
  1111. element = jqLite(element).clone();
  1112. try {
  1113. // turns out IE does not let you set .html() on elements which
  1114. // are not allowed to have children. So we just ignore it.
  1115. element.empty();
  1116. } catch (e) {}
  1117. var elemHtml = jqLite('<div>').append(element).html();
  1118. try {
  1119. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  1120. elemHtml.
  1121. match(/^(<[^>]+>)/)[1].
  1122. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
  1123. } catch (e) {
  1124. return lowercase(elemHtml);
  1125. }
  1126. }
  1127. /////////////////////////////////////////////////
  1128. /**
  1129. * Tries to decode the URI component without throwing an exception.
  1130. *
  1131. * @private
  1132. * @param str value potential URI component to check.
  1133. * @returns {boolean} True if `value` can be decoded
  1134. * with the decodeURIComponent function.
  1135. */
  1136. function tryDecodeURIComponent(value) {
  1137. try {
  1138. return decodeURIComponent(value);
  1139. } catch (e) {
  1140. // Ignore any invalid uri component
  1141. }
  1142. }
  1143. /**
  1144. * Parses an escaped url query string into key-value pairs.
  1145. * @returns {Object.<string,boolean|Array>}
  1146. */
  1147. function parseKeyValue(/**string*/keyValue) {
  1148. var obj = {}, key_value, key;
  1149. forEach((keyValue || "").split('&'), function(keyValue) {
  1150. if (keyValue) {
  1151. key_value = keyValue.replace(/\+/g,'%20').split('=');
  1152. key = tryDecodeURIComponent(key_value[0]);
  1153. if (isDefined(key)) {
  1154. var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
  1155. if (!hasOwnProperty.call(obj, key)) {
  1156. obj[key] = val;
  1157. } else if (isArray(obj[key])) {
  1158. obj[key].push(val);
  1159. } else {
  1160. obj[key] = [obj[key],val];
  1161. }
  1162. }
  1163. }
  1164. });
  1165. return obj;
  1166. }
  1167. function toKeyValue(obj) {
  1168. var parts = [];
  1169. forEach(obj, function(value, key) {
  1170. if (isArray(value)) {
  1171. forEach(value, function(arrayValue) {
  1172. parts.push(encodeUriQuery(key, true) +
  1173. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1174. });
  1175. } else {
  1176. parts.push(encodeUriQuery(key, true) +
  1177. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1178. }
  1179. });
  1180. return parts.length ? parts.join('&') : '';
  1181. }
  1182. /**
  1183. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1184. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1185. * segments:
  1186. * segment = *pchar
  1187. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1188. * pct-encoded = "%" HEXDIG HEXDIG
  1189. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1190. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1191. * / "*" / "+" / "," / ";" / "="
  1192. */
  1193. function encodeUriSegment(val) {
  1194. return encodeUriQuery(val, true).
  1195. replace(/%26/gi, '&').
  1196. replace(/%3D/gi, '=').
  1197. replace(/%2B/gi, '+');
  1198. }
  1199. /**
  1200. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1201. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1202. * encoded per http://tools.ietf.org/html/rfc3986:
  1203. * query = *( pchar / "/" / "?" )
  1204. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1205. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1206. * pct-encoded = "%" HEXDIG HEXDIG
  1207. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1208. * / "*" / "+" / "," / ";" / "="
  1209. */
  1210. function encodeUriQuery(val, pctEncodeSpaces) {
  1211. return encodeURIComponent(val).
  1212. replace(/%40/gi, '@').
  1213. replace(/%3A/gi, ':').
  1214. replace(/%24/g, '$').
  1215. replace(/%2C/gi, ',').
  1216. replace(/%3B/gi, ';').
  1217. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1218. }
  1219. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1220. function getNgAttribute(element, ngAttr) {
  1221. var attr, i, ii = ngAttrPrefixes.length;
  1222. for (i = 0; i < ii; ++i) {
  1223. attr = ngAttrPrefixes[i] + ngAttr;
  1224. if (isString(attr = element.getAttribute(attr))) {
  1225. return attr;
  1226. }
  1227. }
  1228. return null;
  1229. }
  1230. /**
  1231. * @ngdoc directive
  1232. * @name ngApp
  1233. * @module ng
  1234. *
  1235. * @element ANY
  1236. * @param {angular.Module} ngApp an optional application
  1237. * {@link angular.module module} name to load.
  1238. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1239. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1240. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1241. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1242. * tracking down the root of these bugs.
  1243. *
  1244. * @description
  1245. *
  1246. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1247. * designates the **root element** of the application and is typically placed near the root element
  1248. * of the page - e.g. on the `<body>` or `<html>` tags.
  1249. *
  1250. * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1251. * found in the document will be used to define the root element to auto-bootstrap as an
  1252. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1253. * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
  1254. *
  1255. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1256. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1257. * should contain the application code needed or have dependencies on other modules that will
  1258. * contain the code. See {@link angular.module} for more information.
  1259. *
  1260. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1261. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1262. * would not be resolved to `3`.
  1263. *
  1264. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1265. *
  1266. <example module="ngAppDemo">
  1267. <file name="index.html">
  1268. <div ng-controller="ngAppDemoController">
  1269. I can add: {{a}} + {{b}} = {{ a+b }}
  1270. </div>
  1271. </file>
  1272. <file name="script.js">
  1273. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1274. $scope.a = 1;
  1275. $scope.b = 2;
  1276. });
  1277. </file>
  1278. </example>
  1279. *
  1280. * Using `ngStrictDi`, you would see something like this:
  1281. *
  1282. <example ng-app-included="true">
  1283. <file name="index.html">
  1284. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1285. <div ng-controller="GoodController1">
  1286. I can add: {{a}} + {{b}} = {{ a+b }}
  1287. <p>This renders because the controller does not fail to
  1288. instantiate, by using explicit annotation style (see
  1289. script.js for details)
  1290. </p>
  1291. </div>
  1292. <div ng-controller="GoodController2">
  1293. Name: <input ng-model="name"><br />
  1294. Hello, {{name}}!
  1295. <p>This renders because the controller does not fail to
  1296. instantiate, by using explicit annotation style
  1297. (see script.js for details)
  1298. </p>
  1299. </div>
  1300. <div ng-controller="BadController">
  1301. I can add: {{a}} + {{b}} = {{ a+b }}
  1302. <p>The controller could not be instantiated, due to relying
  1303. on automatic function annotations (which are disabled in
  1304. strict mode). As such, the content of this section is not
  1305. interpolated, and there should be an error in your web console.
  1306. </p>
  1307. </div>
  1308. </div>
  1309. </file>
  1310. <file name="script.js">
  1311. angular.module('ngAppStrictDemo', [])
  1312. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1313. // rather than an explicit annotation
  1314. .controller('BadController', function($scope) {
  1315. $scope.a = 1;
  1316. $scope.b = 2;
  1317. })
  1318. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1319. // due to using explicit annotations using the array style and $inject property, respectively.
  1320. .controller('GoodController1', ['$scope', function($scope) {
  1321. $scope.a = 1;
  1322. $scope.b = 2;
  1323. }])
  1324. .controller('GoodController2', GoodController2);
  1325. function GoodController2($scope) {
  1326. $scope.name = "World";
  1327. }
  1328. GoodController2.$inject = ['$scope'];
  1329. </file>
  1330. <file name="style.css">
  1331. div[ng-controller] {
  1332. margin-bottom: 1em;
  1333. -webkit-border-radius: 4px;
  1334. border-radius: 4px;
  1335. border: 1px solid;
  1336. padding: .5em;
  1337. }
  1338. div[ng-controller^=Good] {
  1339. border-color: #d6e9c6;
  1340. background-color: #dff0d8;
  1341. color: #3c763d;
  1342. }
  1343. div[ng-controller^=Bad] {
  1344. border-color: #ebccd1;
  1345. background-color: #f2dede;
  1346. color: #a94442;
  1347. margin-bottom: 0;
  1348. }
  1349. </file>
  1350. </example>
  1351. */
  1352. function angularInit(element, bootstrap) {
  1353. var appElement,
  1354. module,
  1355. config = {};
  1356. // The element `element` has priority over any other element
  1357. forEach(ngAttrPrefixes, function(prefix) {
  1358. var name = prefix + 'app';
  1359. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1360. appElement = element;
  1361. module = element.getAttribute(name);
  1362. }
  1363. });
  1364. forEach(ngAttrPrefixes, function(prefix) {
  1365. var name = prefix + 'app';
  1366. var candidate;
  1367. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1368. appElement = candidate;
  1369. module = candidate.getAttribute(name);
  1370. }
  1371. });
  1372. if (appElement) {
  1373. config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
  1374. bootstrap(appElement, module ? [module] : [], config);
  1375. }
  1376. }
  1377. /**
  1378. * @ngdoc function
  1379. * @name angular.bootstrap
  1380. * @module ng
  1381. * @description
  1382. * Use this function to manually start up angular application.
  1383. *
  1384. * See: {@link guide/bootstrap Bootstrap}
  1385. *
  1386. * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1387. * They must use {@link ng.directive:ngApp ngApp}.
  1388. *
  1389. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1390. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1391. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1392. * multiple instances of Angular try to work on the DOM.
  1393. *
  1394. * ```html
  1395. * <!doctype html>
  1396. * <html>
  1397. * <body>
  1398. * <div ng-controller="WelcomeController">
  1399. * {{greeting}}
  1400. * </div>
  1401. *
  1402. * <script src="angular.js"></script>
  1403. * <script>
  1404. * var app = angular.module('demo', [])
  1405. * .controller('WelcomeController', function($scope) {
  1406. * $scope.greeting = 'Welcome!';
  1407. * });
  1408. * angular.bootstrap(document, ['demo']);
  1409. * </script>
  1410. * </body>
  1411. * </html>
  1412. * ```
  1413. *
  1414. * @param {DOMElement} element DOM element which is the root of angular application.
  1415. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1416. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1417. * function that will be invoked by the injector as a `config` block.
  1418. * See: {@link angular.module modules}
  1419. * @param {Object=} config an object for defining configuration options for the application. The
  1420. * following keys are supported:
  1421. *
  1422. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1423. * assist in finding bugs which break minified code. Defaults to `false`.
  1424. *
  1425. * @returns {auto.$injector} Returns the newly created injector for this app.
  1426. */
  1427. function bootstrap(element, modules, config) {
  1428. if (!isObject(config)) config = {};
  1429. var defaultConfig = {
  1430. strictDi: false
  1431. };
  1432. config = extend(defaultConfig, config);
  1433. var doBootstrap = function() {
  1434. element = jqLite(element);
  1435. if (element.injector()) {
  1436. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1437. //Encode angle brackets to prevent input from being sanitized to empty string #8683
  1438. throw ngMinErr(
  1439. 'btstrpd',
  1440. "App Already Bootstrapped with this Element '{0}'",
  1441. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1442. }
  1443. modules = modules || [];
  1444. modules.unshift(['$provide', function($provide) {
  1445. $provide.value('$rootElement', element);
  1446. }]);
  1447. if (config.debugInfoEnabled) {
  1448. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1449. modules.push(['$compileProvider', function($compileProvider) {
  1450. $compileProvider.debugInfoEnabled(true);
  1451. }]);
  1452. }
  1453. modules.unshift('ng');
  1454. var injector = createInjector(modules, config.strictDi);
  1455. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1456. function bootstrapApply(scope, element, compile, injector) {
  1457. scope.$apply(function() {
  1458. element.data('$injector', injector);
  1459. compile(element)(scope);
  1460. });
  1461. }]
  1462. );
  1463. return injector;
  1464. };
  1465. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1466. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1467. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1468. config.debugInfoEnabled = true;
  1469. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1470. }
  1471. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1472. return doBootstrap();
  1473. }
  1474. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1475. angular.resumeBootstrap = function(extraModules) {
  1476. forEach(extraModules, function(module) {
  1477. modules.push(module);
  1478. });
  1479. return doBootstrap();
  1480. };
  1481. if (isFunction(angular.resumeDeferredBootstrap)) {
  1482. angular.resumeDeferredBootstrap();
  1483. }
  1484. }
  1485. /**
  1486. * @ngdoc function
  1487. * @name angular.reloadWithDebugInfo
  1488. * @module ng
  1489. * @description
  1490. * Use this function to reload the current application with debug information turned on.
  1491. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1492. *
  1493. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1494. */
  1495. function reloadWithDebugInfo() {
  1496. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1497. window.location.reload();
  1498. }
  1499. /**
  1500. * @name angular.getTestability
  1501. * @module ng
  1502. * @description
  1503. * Get the testability service for the instance of Angular on the given
  1504. * element.
  1505. * @param {DOMElement} element DOM element which is the root of angular application.
  1506. */
  1507. function getTestability(rootElement) {
  1508. var injector = angular.element(rootElement).injector();
  1509. if (!injector) {
  1510. throw ngMinErr('test',
  1511. 'no injector found for element argument to getTestability');
  1512. }
  1513. return injector.get('$$testability');
  1514. }
  1515. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1516. function snake_case(name, separator) {
  1517. separator = separator || '_';
  1518. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1519. return (pos ? separator : '') + letter.toLowerCase();
  1520. });
  1521. }
  1522. var bindJQueryFired = false;
  1523. var skipDestroyOnNextJQueryCleanData;
  1524. function bindJQuery() {
  1525. var originalCleanData;
  1526. if (bindJQueryFired) {
  1527. return;
  1528. }
  1529. // bind to jQuery if present;
  1530. var jqName = jq();
  1531. jQuery = window.jQuery; // use default jQuery.
  1532. if (isDefined(jqName)) { // `ngJq` present
  1533. jQuery = jqName === null ? undefined : window[jqName]; // if empty; use jqLite. if not empty, use jQuery specified by `ngJq`.
  1534. }
  1535. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1536. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1537. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1538. // versions. It will not work for sure with jQuery <1.7, though.
  1539. if (jQuery && jQuery.fn.on) {
  1540. jqLite = jQuery;
  1541. extend(jQuery.fn, {
  1542. scope: JQLitePrototype.scope,
  1543. isolateScope: JQLitePrototype.isolateScope,
  1544. controller: JQLitePrototype.controller,
  1545. injector: JQLitePrototype.injector,
  1546. inheritedData: JQLitePrototype.inheritedData
  1547. });
  1548. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1549. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1550. // the $destroy event on all removed nodes.
  1551. originalCleanData = jQuery.cleanData;
  1552. jQuery.cleanData = function(elems) {
  1553. var events;
  1554. if (!skipDestroyOnNextJQueryCleanData) {
  1555. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1556. events = jQuery._data(elem, "events");
  1557. if (events && events.$destroy) {
  1558. jQuery(elem).triggerHandler('$destroy');
  1559. }
  1560. }
  1561. } else {
  1562. skipDestroyOnNextJQueryCleanData = false;
  1563. }
  1564. originalCleanData(elems);
  1565. };
  1566. } else {
  1567. jqLite = JQLite;
  1568. }
  1569. angular.element = jqLite;
  1570. // Prevent double-proxying.
  1571. bindJQueryFired = true;
  1572. }
  1573. /**
  1574. * throw error if the argument is falsy.
  1575. */
  1576. function assertArg(arg, name, reason) {
  1577. if (!arg) {
  1578. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1579. }
  1580. return arg;
  1581. }
  1582. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1583. if (acceptArrayAnnotation && isArray(arg)) {
  1584. arg = arg[arg.length - 1];
  1585. }
  1586. assertArg(isFunction(arg), name, 'not a function, got ' +
  1587. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1588. return arg;
  1589. }
  1590. /**
  1591. * throw error if the name given is hasOwnProperty
  1592. * @param {String} name the name to test
  1593. * @param {String} context the context in which the name is used, such as module or directive
  1594. */
  1595. function assertNotHasOwnProperty(name, context) {
  1596. if (name === 'hasOwnProperty') {
  1597. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1598. }
  1599. }
  1600. /**
  1601. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1602. * @param {Object} obj starting object
  1603. * @param {String} path path to traverse
  1604. * @param {boolean} [bindFnToScope=true]
  1605. * @returns {Object} value as accessible by path
  1606. */
  1607. //TODO(misko): this function needs to be removed
  1608. function getter(obj, path, bindFnToScope) {
  1609. if (!path) return obj;
  1610. var keys = path.split('.');
  1611. var key;
  1612. var lastInstance = obj;
  1613. var len = keys.length;
  1614. for (var i = 0; i < len; i++) {
  1615. key = keys[i];
  1616. if (obj) {
  1617. obj = (lastInstance = obj)[key];
  1618. }
  1619. }
  1620. if (!bindFnToScope && isFunction(obj)) {
  1621. return bind(lastInstance, obj);
  1622. }
  1623. return obj;
  1624. }
  1625. /**
  1626. * Return the DOM siblings between the first and last node in the given array.
  1627. * @param {Array} array like object
  1628. * @returns {jqLite} jqLite collection containing the nodes
  1629. */
  1630. function getBlockNodes(nodes) {
  1631. // TODO(perf): just check if all items in `nodes` are siblings and if they are return the original
  1632. // collection, otherwise update the original collection.
  1633. var node = nodes[0];
  1634. var endNode = nodes[nodes.length - 1];
  1635. var blockNodes = [node];
  1636. do {
  1637. node = node.nextSibling;
  1638. if (!node) break;
  1639. blockNodes.push(node);
  1640. } while (node !== endNode);
  1641. return jqLite(blockNodes);
  1642. }
  1643. /**
  1644. * Creates a new object without a prototype. This object is useful for lookup without having to
  1645. * guard against prototypically inherited properties via hasOwnProperty.
  1646. *
  1647. * Related micro-benchmarks:
  1648. * - http://jsperf.com/object-create2
  1649. * - http://jsperf.com/proto-map-lookup/2
  1650. * - http://jsperf.com/for-in-vs-object-keys2
  1651. *
  1652. * @returns {Object}
  1653. */
  1654. function createMap() {
  1655. return Object.create(null);
  1656. }
  1657. var NODE_TYPE_ELEMENT = 1;
  1658. var NODE_TYPE_ATTRIBUTE = 2;
  1659. var NODE_TYPE_TEXT = 3;
  1660. var NODE_TYPE_COMMENT = 8;
  1661. var NODE_TYPE_DOCUMENT = 9;
  1662. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1663. /**
  1664. * @ngdoc type
  1665. * @name angular.Module
  1666. * @module ng
  1667. * @description
  1668. *
  1669. * Interface for configuring angular {@link angular.module modules}.
  1670. */
  1671. function setupModuleLoader(window) {
  1672. var $injectorMinErr = minErr('$injector');
  1673. var ngMinErr = minErr('ng');
  1674. function ensure(obj, name, factory) {
  1675. return obj[name] || (obj[name] = factory());
  1676. }
  1677. var angular = ensure(window, 'angular', Object);
  1678. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1679. angular.$$minErr = angular.$$minErr || minErr;
  1680. return ensure(angular, 'module', function() {
  1681. /** @type {Object.<string, angular.Module>} */
  1682. var modules = {};
  1683. /**
  1684. * @ngdoc function
  1685. * @name angular.module
  1686. * @module ng
  1687. * @description
  1688. *
  1689. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1690. * modules.
  1691. * All modules (angular core or 3rd party) that should be available to an application must be
  1692. * registered using this mechanism.
  1693. *
  1694. * When passed two or more arguments, a new module is created. If passed only one argument, an
  1695. * existing module (the name passed as the first argument to `module`) is retrieved.
  1696. *
  1697. *
  1698. * # Module
  1699. *
  1700. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1701. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1702. *
  1703. * ```js
  1704. * // Create a new module
  1705. * var myModule = angular.module('myModule', []);
  1706. *
  1707. * // register a new service
  1708. * myModule.value('appName', 'MyCoolApp');
  1709. *
  1710. * // configure existing services inside initialization blocks.
  1711. * myModule.config(['$locationProvider', function($locationProvider) {
  1712. * // Configure existing providers
  1713. * $locationProvider.hashPrefix('!');
  1714. * }]);
  1715. * ```
  1716. *
  1717. * Then you can create an injector and load your modules like this:
  1718. *
  1719. * ```js
  1720. * var injector = angular.injector(['ng', 'myModule'])
  1721. * ```
  1722. *
  1723. * However it's more likely that you'll just use
  1724. * {@link ng.directive:ngApp ngApp} or
  1725. * {@link angular.bootstrap} to simplify this process for you.
  1726. *
  1727. * @param {!string} name The name of the module to create or retrieve.
  1728. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1729. * unspecified then the module is being retrieved for further configuration.
  1730. * @param {Function=} configFn Optional configuration function for the module. Same as
  1731. * {@link angular.Module#config Module#config()}.
  1732. * @returns {module} new module with the {@link angular.Module} api.
  1733. */
  1734. return function module(name, requires, configFn) {
  1735. var assertNotHasOwnProperty = function(name, context) {
  1736. if (name === 'hasOwnProperty') {
  1737. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1738. }
  1739. };
  1740. assertNotHasOwnProperty(name, 'module');
  1741. if (requires && modules.hasOwnProperty(name)) {
  1742. modules[name] = null;
  1743. }
  1744. return ensure(modules, name, function() {
  1745. if (!requires) {
  1746. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1747. "the module name or forgot to load it. If registering a module ensure that you " +
  1748. "specify the dependencies as the second argument.", name);
  1749. }
  1750. /** @type {!Array.<Array.<*>>} */
  1751. var invokeQueue = [];
  1752. /** @type {!Array.<Function>} */
  1753. var configBlocks = [];
  1754. /** @type {!Array.<Function>} */
  1755. var runBlocks = [];
  1756. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  1757. /** @type {angular.Module} */
  1758. var moduleInstance = {
  1759. // Private state
  1760. _invokeQueue: invokeQueue,
  1761. _configBlocks: configBlocks,
  1762. _runBlocks: runBlocks,
  1763. /**
  1764. * @ngdoc property
  1765. * @name angular.Module#requires
  1766. * @module ng
  1767. *
  1768. * @description
  1769. * Holds the list of modules which the injector will load before the current module is
  1770. * loaded.
  1771. */
  1772. requires: requires,
  1773. /**
  1774. * @ngdoc property
  1775. * @name angular.Module#name
  1776. * @module ng
  1777. *
  1778. * @description
  1779. * Name of the module.
  1780. */
  1781. name: name,
  1782. /**
  1783. * @ngdoc method
  1784. * @name angular.Module#provider
  1785. * @module ng
  1786. * @param {string} name service name
  1787. * @param {Function} providerType Construction function for creating new instance of the
  1788. * service.
  1789. * @description
  1790. * See {@link auto.$provide#provider $provide.provider()}.
  1791. */
  1792. provider: invokeLater('$provide', 'provider'),
  1793. /**
  1794. * @ngdoc method
  1795. * @name angular.Module#factory
  1796. * @module ng
  1797. * @param {string} name service name
  1798. * @param {Function} providerFunction Function for creating new instance of the service.
  1799. * @description
  1800. * See {@link auto.$provide#factory $provide.factory()}.
  1801. */
  1802. factory: invokeLater('$provide', 'factory'),
  1803. /**
  1804. * @ngdoc method
  1805. * @name angular.Module#service
  1806. * @module ng
  1807. * @param {string} name service name
  1808. * @param {Function} constructor A constructor function that will be instantiated.
  1809. * @description
  1810. * See {@link auto.$provide#service $provide.service()}.
  1811. */
  1812. service: invokeLater('$provide', 'service'),
  1813. /**
  1814. * @ngdoc method
  1815. * @name angular.Module#value
  1816. * @module ng
  1817. * @param {string} name service name
  1818. * @param {*} object Service instance object.
  1819. * @description
  1820. * See {@link auto.$provide#value $provide.value()}.
  1821. */
  1822. value: invokeLater('$provide', 'value'),
  1823. /**
  1824. * @ngdoc method
  1825. * @name angular.Module#constant
  1826. * @module ng
  1827. * @param {string} name constant name
  1828. * @param {*} object Constant value.
  1829. * @description
  1830. * Because the constant are fixed, they get applied before other provide methods.
  1831. * See {@link auto.$provide#constant $provide.constant()}.
  1832. */
  1833. constant: invokeLater('$provide', 'constant', 'unshift'),
  1834. /**
  1835. * @ngdoc method
  1836. * @name angular.Module#decorator
  1837. * @module ng
  1838. * @param {string} The name of the service to decorate.
  1839. * @param {Function} This function will be invoked when the service needs to be
  1840. * instantiated and should return the decorated service instance.
  1841. * @description
  1842. * See {@link auto.$provide#decorator $provide.decorator()}.
  1843. */
  1844. decorator: invokeLater('$provide', 'decorator'),
  1845. /**
  1846. * @ngdoc method
  1847. * @name angular.Module#animation
  1848. * @module ng
  1849. * @param {string} name animation name
  1850. * @param {Function} animationFactory Factory function for creating new instance of an
  1851. * animation.
  1852. * @description
  1853. *
  1854. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1855. *
  1856. *
  1857. * Defines an animation hook that can be later used with
  1858. * {@link $animate $animate} service and directives that use this service.
  1859. *
  1860. * ```js
  1861. * module.animation('.animation-name', function($inject1, $inject2) {
  1862. * return {
  1863. * eventName : function(element, done) {
  1864. * //code to run the animation
  1865. * //once complete, then run done()
  1866. * return function cancellationFunction(element) {
  1867. * //code to cancel the animation
  1868. * }
  1869. * }
  1870. * }
  1871. * })
  1872. * ```
  1873. *
  1874. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  1875. * {@link ngAnimate ngAnimate module} for more information.
  1876. */
  1877. animation: invokeLater('$animateProvider', 'register'),
  1878. /**
  1879. * @ngdoc method
  1880. * @name angular.Module#filter
  1881. * @module ng
  1882. * @param {string} name Filter name - this must be a valid angular expression identifier
  1883. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1884. * @description
  1885. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1886. *
  1887. * <div class="alert alert-warning">
  1888. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  1889. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  1890. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  1891. * (`myapp_subsection_filterx`).
  1892. * </div>
  1893. */
  1894. filter: invokeLater('$filterProvider', 'register'),
  1895. /**
  1896. * @ngdoc method
  1897. * @name angular.Module#controller
  1898. * @module ng
  1899. * @param {string|Object} name Controller name, or an object map of controllers where the
  1900. * keys are the names and the values are the constructors.
  1901. * @param {Function} constructor Controller constructor function.
  1902. * @description
  1903. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1904. */
  1905. controller: invokeLater('$controllerProvider', 'register'),
  1906. /**
  1907. * @ngdoc method
  1908. * @name angular.Module#directive
  1909. * @module ng
  1910. * @param {string|Object} name Directive name, or an object map of directives where the
  1911. * keys are the names and the values are the factories.
  1912. * @param {Function} directiveFactory Factory function for creating new instance of
  1913. * directives.
  1914. * @description
  1915. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  1916. */
  1917. directive: invokeLater('$compileProvider', 'directive'),
  1918. /**
  1919. * @ngdoc method
  1920. * @name angular.Module#config
  1921. * @module ng
  1922. * @param {Function} configFn Execute this function on module load. Useful for service
  1923. * configuration.
  1924. * @description
  1925. * Use this method to register work which needs to be performed on module loading.
  1926. * For more about how to configure services, see
  1927. * {@link providers#provider-recipe Provider Recipe}.
  1928. */
  1929. config: config,
  1930. /**
  1931. * @ngdoc method
  1932. * @name angular.Module#run
  1933. * @module ng
  1934. * @param {Function} initializationFn Execute this function after injector creation.
  1935. * Useful for application initialization.
  1936. * @description
  1937. * Use this method to register work which should be performed when the injector is done
  1938. * loading all modules.
  1939. */
  1940. run: function(block) {
  1941. runBlocks.push(block);
  1942. return this;
  1943. }
  1944. };
  1945. if (configFn) {
  1946. config(configFn);
  1947. }
  1948. return moduleInstance;
  1949. /**
  1950. * @param {string} provider
  1951. * @param {string} method
  1952. * @param {String=} insertMethod
  1953. * @returns {angular.Module}
  1954. */
  1955. function invokeLater(provider, method, insertMethod, queue) {
  1956. if (!queue) queue = invokeQueue;
  1957. return function() {
  1958. queue[insertMethod || 'push']([provider, method, arguments]);
  1959. return moduleInstance;
  1960. };
  1961. }
  1962. });
  1963. };
  1964. });
  1965. }
  1966. /* global: toDebugString: true */
  1967. function serializeObject(obj) {
  1968. var seen = [];
  1969. return JSON.stringify(obj, function(key, val) {
  1970. val = toJsonReplacer(key, val);
  1971. if (isObject(val)) {
  1972. if (seen.indexOf(val) >= 0) return '<<already seen>>';
  1973. seen.push(val);
  1974. }
  1975. return val;
  1976. });
  1977. }
  1978. function toDebugString(obj) {
  1979. if (typeof obj === 'function') {
  1980. return obj.toString().replace(/ \{[\s\S]*$/, '');
  1981. } else if (typeof obj === 'undefined') {
  1982. return 'undefined';
  1983. } else if (typeof obj !== 'string') {
  1984. return serializeObject(obj);
  1985. }
  1986. return obj;
  1987. }
  1988. /* global angularModule: true,
  1989. version: true,
  1990. $LocaleProvider,
  1991. $CompileProvider,
  1992. htmlAnchorDirective,
  1993. inputDirective,
  1994. inputDirective,
  1995. formDirective,
  1996. scriptDirective,
  1997. selectDirective,
  1998. styleDirective,
  1999. optionDirective,
  2000. ngBindDirective,
  2001. ngBindHtmlDirective,
  2002. ngBindTemplateDirective,
  2003. ngClassDirective,
  2004. ngClassEvenDirective,
  2005. ngClassOddDirective,
  2006. ngCspDirective,
  2007. ngCloakDirective,
  2008. ngControllerDirective,
  2009. ngFormDirective,
  2010. ngHideDirective,
  2011. ngIfDirective,
  2012. ngIncludeDirective,
  2013. ngIncludeFillContentDirective,
  2014. ngInitDirective,
  2015. ngNonBindableDirective,
  2016. ngPluralizeDirective,
  2017. ngRepeatDirective,
  2018. ngShowDirective,
  2019. ngStyleDirective,
  2020. ngSwitchDirective,
  2021. ngSwitchWhenDirective,
  2022. ngSwitchDefaultDirective,
  2023. ngOptionsDirective,
  2024. ngTranscludeDirective,
  2025. ngModelDirective,
  2026. ngListDirective,
  2027. ngChangeDirective,
  2028. patternDirective,
  2029. patternDirective,
  2030. requiredDirective,
  2031. requiredDirective,
  2032. minlengthDirective,
  2033. minlengthDirective,
  2034. maxlengthDirective,
  2035. maxlengthDirective,
  2036. ngValueDirective,
  2037. ngModelOptionsDirective,
  2038. ngAttributeAliasDirectives,
  2039. ngEventDirectives,
  2040. $AnchorScrollProvider,
  2041. $AnimateProvider,
  2042. $$CoreAnimateQueueProvider,
  2043. $$CoreAnimateRunnerProvider,
  2044. $BrowserProvider,
  2045. $CacheFactoryProvider,
  2046. $ControllerProvider,
  2047. $DocumentProvider,
  2048. $ExceptionHandlerProvider,
  2049. $FilterProvider,
  2050. $InterpolateProvider,
  2051. $IntervalProvider,
  2052. $$HashMapProvider,
  2053. $HttpProvider,
  2054. $HttpParamSerializerProvider,
  2055. $HttpParamSerializerJQLikeProvider,
  2056. $HttpBackendProvider,
  2057. $LocationProvider,
  2058. $LogProvider,
  2059. $ParseProvider,
  2060. $RootScopeProvider,
  2061. $QProvider,
  2062. $$QProvider,
  2063. $$SanitizeUriProvider,
  2064. $SceProvider,
  2065. $SceDelegateProvider,
  2066. $SnifferProvider,
  2067. $TemplateCacheProvider,
  2068. $TemplateRequestProvider,
  2069. $$TestabilityProvider,
  2070. $TimeoutProvider,
  2071. $$RAFProvider,
  2072. $$AsyncCallbackProvider,
  2073. $WindowProvider,
  2074. $$jqLiteProvider,
  2075. $$CookieReaderProvider
  2076. */
  2077. /**
  2078. * @ngdoc object
  2079. * @name angular.version
  2080. * @module ng
  2081. * @description
  2082. * An object that contains information about the current AngularJS version. This object has the
  2083. * following properties:
  2084. *
  2085. * - `full` – `{string}` – Full version string, such as "0.9.18".
  2086. * - `major` – `{number}` – Major version number, such as "0".
  2087. * - `minor` – `{number}` – Minor version number, such as "9".
  2088. * - `dot` – `{number}` – Dot version number, such as "18".
  2089. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  2090. */
  2091. var version = {
  2092. full: '1.4.0', // all of these placeholder strings will be replaced by grunt's
  2093. major: 1, // package task
  2094. minor: 4,
  2095. dot: 0,
  2096. codeName: 'jaracimrman-existence'
  2097. };
  2098. function publishExternalAPI(angular) {
  2099. extend(angular, {
  2100. 'bootstrap': bootstrap,
  2101. 'copy': copy,
  2102. 'extend': extend,
  2103. 'merge': merge,
  2104. 'equals': equals,
  2105. 'element': jqLite,
  2106. 'forEach': forEach,
  2107. 'injector': createInjector,
  2108. 'noop': noop,
  2109. 'bind': bind,
  2110. 'toJson': toJson,
  2111. 'fromJson': fromJson,
  2112. 'identity': identity,
  2113. 'isUndefined': isUndefined,
  2114. 'isDefined': isDefined,
  2115. 'isString': isString,
  2116. 'isFunction': isFunction,
  2117. 'isObject': isObject,
  2118. 'isNumber': isNumber,
  2119. 'isElement': isElement,
  2120. 'isArray': isArray,
  2121. 'version': version,
  2122. 'isDate': isDate,
  2123. 'lowercase': lowercase,
  2124. 'uppercase': uppercase,
  2125. 'callbacks': {counter: 0},
  2126. 'getTestability': getTestability,
  2127. '$$minErr': minErr,
  2128. '$$csp': csp,
  2129. 'reloadWithDebugInfo': reloadWithDebugInfo
  2130. });
  2131. angularModule = setupModuleLoader(window);
  2132. try {
  2133. angularModule('ngLocale');
  2134. } catch (e) {
  2135. angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
  2136. }
  2137. angularModule('ng', ['ngLocale'], ['$provide',
  2138. function ngModule($provide) {
  2139. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  2140. $provide.provider({
  2141. $$sanitizeUri: $$SanitizeUriProvider
  2142. });
  2143. $provide.provider('$compile', $CompileProvider).
  2144. directive({
  2145. a: htmlAnchorDirective,
  2146. input: inputDirective,
  2147. textarea: inputDirective,
  2148. form: formDirective,
  2149. script: scriptDirective,
  2150. select: selectDirective,
  2151. style: styleDirective,
  2152. option: optionDirective,
  2153. ngBind: ngBindDirective,
  2154. ngBindHtml: ngBindHtmlDirective,
  2155. ngBindTemplate: ngBindTemplateDirective,
  2156. ngClass: ngClassDirective,
  2157. ngClassEven: ngClassEvenDirective,
  2158. ngClassOdd: ngClassOddDirective,
  2159. ngCloak: ngCloakDirective,
  2160. ngController: ngControllerDirective,
  2161. ngForm: ngFormDirective,
  2162. ngHide: ngHideDirective,
  2163. ngIf: ngIfDirective,
  2164. ngInclude: ngIncludeDirective,
  2165. ngInit: ngInitDirective,
  2166. ngNonBindable: ngNonBindableDirective,
  2167. ngPluralize: ngPluralizeDirective,
  2168. ngRepeat: ngRepeatDirective,
  2169. ngShow: ngShowDirective,
  2170. ngStyle: ngStyleDirective,
  2171. ngSwitch: ngSwitchDirective,
  2172. ngSwitchWhen: ngSwitchWhenDirective,
  2173. ngSwitchDefault: ngSwitchDefaultDirective,
  2174. ngOptions: ngOptionsDirective,
  2175. ngTransclude: ngTranscludeDirective,
  2176. ngModel: ngModelDirective,
  2177. ngList: ngListDirective,
  2178. ngChange: ngChangeDirective,
  2179. pattern: patternDirective,
  2180. ngPattern: patternDirective,
  2181. required: requiredDirective,
  2182. ngRequired: requiredDirective,
  2183. minlength: minlengthDirective,
  2184. ngMinlength: minlengthDirective,
  2185. maxlength: maxlengthDirective,
  2186. ngMaxlength: maxlengthDirective,
  2187. ngValue: ngValueDirective,
  2188. ngModelOptions: ngModelOptionsDirective
  2189. }).
  2190. directive({
  2191. ngInclude: ngIncludeFillContentDirective
  2192. }).
  2193. directive(ngAttributeAliasDirectives).
  2194. directive(ngEventDirectives);
  2195. $provide.provider({
  2196. $anchorScroll: $AnchorScrollProvider,
  2197. $animate: $AnimateProvider,
  2198. $$animateQueue: $$CoreAnimateQueueProvider,
  2199. $$AnimateRunner: $$CoreAnimateRunnerProvider,
  2200. $browser: $BrowserProvider,
  2201. $cacheFactory: $CacheFactoryProvider,
  2202. $controller: $ControllerProvider,
  2203. $document: $DocumentProvider,
  2204. $exceptionHandler: $ExceptionHandlerProvider,
  2205. $filter: $FilterProvider,
  2206. $interpolate: $InterpolateProvider,
  2207. $interval: $IntervalProvider,
  2208. $http: $HttpProvider,
  2209. $httpParamSerializer: $HttpParamSerializerProvider,
  2210. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  2211. $httpBackend: $HttpBackendProvider,
  2212. $location: $LocationProvider,
  2213. $log: $LogProvider,
  2214. $parse: $ParseProvider,
  2215. $rootScope: $RootScopeProvider,
  2216. $q: $QProvider,
  2217. $$q: $$QProvider,
  2218. $sce: $SceProvider,
  2219. $sceDelegate: $SceDelegateProvider,
  2220. $sniffer: $SnifferProvider,
  2221. $templateCache: $TemplateCacheProvider,
  2222. $templateRequest: $TemplateRequestProvider,
  2223. $$testability: $$TestabilityProvider,
  2224. $timeout: $TimeoutProvider,
  2225. $window: $WindowProvider,
  2226. $$rAF: $$RAFProvider,
  2227. $$asyncCallback: $$AsyncCallbackProvider,
  2228. $$jqLite: $$jqLiteProvider,
  2229. $$HashMap: $$HashMapProvider,
  2230. $$cookieReader: $$CookieReaderProvider
  2231. });
  2232. }
  2233. ]);
  2234. }
  2235. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2236. * Any commits to this file should be reviewed with security in mind. *
  2237. * Changes to this file can potentially create security vulnerabilities. *
  2238. * An approval from 2 Core members with history of modifying *
  2239. * this file is required. *
  2240. * *
  2241. * Does the change somehow allow for arbitrary javascript to be executed? *
  2242. * Or allows for someone to change the prototype of built-in objects? *
  2243. * Or gives undesired access to variables likes document or window? *
  2244. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2245. /* global JQLitePrototype: true,
  2246. addEventListenerFn: true,
  2247. removeEventListenerFn: true,
  2248. BOOLEAN_ATTR: true,
  2249. ALIASED_ATTR: true,
  2250. */
  2251. //////////////////////////////////
  2252. //JQLite
  2253. //////////////////////////////////
  2254. /**
  2255. * @ngdoc function
  2256. * @name angular.element
  2257. * @module ng
  2258. * @kind function
  2259. *
  2260. * @description
  2261. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2262. *
  2263. * If jQuery is available, `angular.element` is an alias for the
  2264. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2265. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
  2266. *
  2267. * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
  2268. * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
  2269. * commonly needed functionality with the goal of having a very small footprint.</div>
  2270. *
  2271. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file.
  2272. *
  2273. * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
  2274. * jqLite; they are never raw DOM references.</div>
  2275. *
  2276. * ## Angular's jqLite
  2277. * jqLite provides only the following jQuery methods:
  2278. *
  2279. * - [`addClass()`](http://api.jquery.com/addClass/)
  2280. * - [`after()`](http://api.jquery.com/after/)
  2281. * - [`append()`](http://api.jquery.com/append/)
  2282. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2283. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  2284. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2285. * - [`clone()`](http://api.jquery.com/clone/)
  2286. * - [`contents()`](http://api.jquery.com/contents/)
  2287. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`. As a setter, does not convert numbers to strings or append 'px'.
  2288. * - [`data()`](http://api.jquery.com/data/)
  2289. * - [`detach()`](http://api.jquery.com/detach/)
  2290. * - [`empty()`](http://api.jquery.com/empty/)
  2291. * - [`eq()`](http://api.jquery.com/eq/)
  2292. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2293. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2294. * - [`html()`](http://api.jquery.com/html/)
  2295. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2296. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2297. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
  2298. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2299. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2300. * - [`prepend()`](http://api.jquery.com/prepend/)
  2301. * - [`prop()`](http://api.jquery.com/prop/)
  2302. * - [`ready()`](http://api.jquery.com/ready/)
  2303. * - [`remove()`](http://api.jquery.com/remove/)
  2304. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  2305. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  2306. * - [`removeData()`](http://api.jquery.com/removeData/)
  2307. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2308. * - [`text()`](http://api.jquery.com/text/)
  2309. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  2310. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  2311. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces
  2312. * - [`val()`](http://api.jquery.com/val/)
  2313. * - [`wrap()`](http://api.jquery.com/wrap/)
  2314. *
  2315. * ## jQuery/jqLite Extras
  2316. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2317. *
  2318. * ### Events
  2319. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2320. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2321. * element before it is removed.
  2322. *
  2323. * ### Methods
  2324. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2325. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2326. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2327. * `'ngModel'`).
  2328. * - `injector()` - retrieves the injector of the current element or its parent.
  2329. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2330. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2331. * be enabled.
  2332. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2333. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2334. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2335. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2336. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2337. * parent element is reached.
  2338. *
  2339. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2340. * @returns {Object} jQuery object.
  2341. */
  2342. JQLite.expando = 'ng339';
  2343. var jqCache = JQLite.cache = {},
  2344. jqId = 1,
  2345. addEventListenerFn = function(element, type, fn) {
  2346. element.addEventListener(type, fn, false);
  2347. },
  2348. removeEventListenerFn = function(element, type, fn) {
  2349. element.removeEventListener(type, fn, false);
  2350. };
  2351. /*
  2352. * !!! This is an undocumented "private" function !!!
  2353. */
  2354. JQLite._data = function(node) {
  2355. //jQuery always returns an object on cache miss
  2356. return this.cache[node[this.expando]] || {};
  2357. };
  2358. function jqNextId() { return ++jqId; }
  2359. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  2360. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  2361. var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
  2362. var jqLiteMinErr = minErr('jqLite');
  2363. /**
  2364. * Converts snake_case to camelCase.
  2365. * Also there is special case for Moz prefix starting with upper case letter.
  2366. * @param name Name to normalize
  2367. */
  2368. function camelCase(name) {
  2369. return name.
  2370. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2371. return offset ? letter.toUpperCase() : letter;
  2372. }).
  2373. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2374. }
  2375. var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
  2376. var HTML_REGEXP = /<|&#?\w+;/;
  2377. var TAG_NAME_REGEXP = /<([\w:]+)/;
  2378. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
  2379. var wrapMap = {
  2380. 'option': [1, '<select multiple="multiple">', '</select>'],
  2381. 'thead': [1, '<table>', '</table>'],
  2382. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2383. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2384. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2385. '_default': [0, "", ""]
  2386. };
  2387. wrapMap.optgroup = wrapMap.option;
  2388. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2389. wrapMap.th = wrapMap.td;
  2390. function jqLiteIsTextNode(html) {
  2391. return !HTML_REGEXP.test(html);
  2392. }
  2393. function jqLiteAcceptsData(node) {
  2394. // The window object can accept data but has no nodeType
  2395. // Otherwise we are only interested in elements (1) and documents (9)
  2396. var nodeType = node.nodeType;
  2397. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2398. }
  2399. function jqLiteBuildFragment(html, context) {
  2400. var tmp, tag, wrap,
  2401. fragment = context.createDocumentFragment(),
  2402. nodes = [], i;
  2403. if (jqLiteIsTextNode(html)) {
  2404. // Convert non-html into a text node
  2405. nodes.push(context.createTextNode(html));
  2406. } else {
  2407. // Convert html into DOM nodes
  2408. tmp = tmp || fragment.appendChild(context.createElement("div"));
  2409. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2410. wrap = wrapMap[tag] || wrapMap._default;
  2411. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2412. // Descend through wrappers to the right content
  2413. i = wrap[0];
  2414. while (i--) {
  2415. tmp = tmp.lastChild;
  2416. }
  2417. nodes = concat(nodes, tmp.childNodes);
  2418. tmp = fragment.firstChild;
  2419. tmp.textContent = "";
  2420. }
  2421. // Remove wrapper from fragment
  2422. fragment.textContent = "";
  2423. fragment.innerHTML = ""; // Clear inner HTML
  2424. forEach(nodes, function(node) {
  2425. fragment.appendChild(node);
  2426. });
  2427. return fragment;
  2428. }
  2429. function jqLiteParseHTML(html, context) {
  2430. context = context || document;
  2431. var parsed;
  2432. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2433. return [context.createElement(parsed[1])];
  2434. }
  2435. if ((parsed = jqLiteBuildFragment(html, context))) {
  2436. return parsed.childNodes;
  2437. }
  2438. return [];
  2439. }
  2440. /////////////////////////////////////////////
  2441. function JQLite(element) {
  2442. if (element instanceof JQLite) {
  2443. return element;
  2444. }
  2445. var argIsString;
  2446. if (isString(element)) {
  2447. element = trim(element);
  2448. argIsString = true;
  2449. }
  2450. if (!(this instanceof JQLite)) {
  2451. if (argIsString && element.charAt(0) != '<') {
  2452. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2453. }
  2454. return new JQLite(element);
  2455. }
  2456. if (argIsString) {
  2457. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2458. } else {
  2459. jqLiteAddNodes(this, element);
  2460. }
  2461. }
  2462. function jqLiteClone(element) {
  2463. return element.cloneNode(true);
  2464. }
  2465. function jqLiteDealoc(element, onlyDescendants) {
  2466. if (!onlyDescendants) jqLiteRemoveData(element);
  2467. if (element.querySelectorAll) {
  2468. var descendants = element.querySelectorAll('*');
  2469. for (var i = 0, l = descendants.length; i < l; i++) {
  2470. jqLiteRemoveData(descendants[i]);
  2471. }
  2472. }
  2473. }
  2474. function jqLiteOff(element, type, fn, unsupported) {
  2475. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2476. var expandoStore = jqLiteExpandoStore(element);
  2477. var events = expandoStore && expandoStore.events;
  2478. var handle = expandoStore && expandoStore.handle;
  2479. if (!handle) return; //no listeners registered
  2480. if (!type) {
  2481. for (type in events) {
  2482. if (type !== '$destroy') {
  2483. removeEventListenerFn(element, type, handle);
  2484. }
  2485. delete events[type];
  2486. }
  2487. } else {
  2488. forEach(type.split(' '), function(type) {
  2489. if (isDefined(fn)) {
  2490. var listenerFns = events[type];
  2491. arrayRemove(listenerFns || [], fn);
  2492. if (listenerFns && listenerFns.length > 0) {
  2493. return;
  2494. }
  2495. }
  2496. removeEventListenerFn(element, type, handle);
  2497. delete events[type];
  2498. });
  2499. }
  2500. }
  2501. function jqLiteRemoveData(element, name) {
  2502. var expandoId = element.ng339;
  2503. var expandoStore = expandoId && jqCache[expandoId];
  2504. if (expandoStore) {
  2505. if (name) {
  2506. delete expandoStore.data[name];
  2507. return;
  2508. }
  2509. if (expandoStore.handle) {
  2510. if (expandoStore.events.$destroy) {
  2511. expandoStore.handle({}, '$destroy');
  2512. }
  2513. jqLiteOff(element);
  2514. }
  2515. delete jqCache[expandoId];
  2516. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2517. }
  2518. }
  2519. function jqLiteExpandoStore(element, createIfNecessary) {
  2520. var expandoId = element.ng339,
  2521. expandoStore = expandoId && jqCache[expandoId];
  2522. if (createIfNecessary && !expandoStore) {
  2523. element.ng339 = expandoId = jqNextId();
  2524. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2525. }
  2526. return expandoStore;
  2527. }
  2528. function jqLiteData(element, key, value) {
  2529. if (jqLiteAcceptsData(element)) {
  2530. var isSimpleSetter = isDefined(value);
  2531. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2532. var massGetter = !key;
  2533. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2534. var data = expandoStore && expandoStore.data;
  2535. if (isSimpleSetter) { // data('key', value)
  2536. data[key] = value;
  2537. } else {
  2538. if (massGetter) { // data()
  2539. return data;
  2540. } else {
  2541. if (isSimpleGetter) { // data('key')
  2542. // don't force creation of expandoStore if it doesn't exist yet
  2543. return data && data[key];
  2544. } else { // mass-setter: data({key1: val1, key2: val2})
  2545. extend(data, key);
  2546. }
  2547. }
  2548. }
  2549. }
  2550. }
  2551. function jqLiteHasClass(element, selector) {
  2552. if (!element.getAttribute) return false;
  2553. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2554. indexOf(" " + selector + " ") > -1);
  2555. }
  2556. function jqLiteRemoveClass(element, cssClasses) {
  2557. if (cssClasses && element.setAttribute) {
  2558. forEach(cssClasses.split(' '), function(cssClass) {
  2559. element.setAttribute('class', trim(
  2560. (" " + (element.getAttribute('class') || '') + " ")
  2561. .replace(/[\n\t]/g, " ")
  2562. .replace(" " + trim(cssClass) + " ", " "))
  2563. );
  2564. });
  2565. }
  2566. }
  2567. function jqLiteAddClass(element, cssClasses) {
  2568. if (cssClasses && element.setAttribute) {
  2569. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2570. .replace(/[\n\t]/g, " ");
  2571. forEach(cssClasses.split(' '), function(cssClass) {
  2572. cssClass = trim(cssClass);
  2573. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2574. existingClasses += cssClass + ' ';
  2575. }
  2576. });
  2577. element.setAttribute('class', trim(existingClasses));
  2578. }
  2579. }
  2580. function jqLiteAddNodes(root, elements) {
  2581. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2582. if (elements) {
  2583. // if a Node (the most common case)
  2584. if (elements.nodeType) {
  2585. root[root.length++] = elements;
  2586. } else {
  2587. var length = elements.length;
  2588. // if an Array or NodeList and not a Window
  2589. if (typeof length === 'number' && elements.window !== elements) {
  2590. if (length) {
  2591. for (var i = 0; i < length; i++) {
  2592. root[root.length++] = elements[i];
  2593. }
  2594. }
  2595. } else {
  2596. root[root.length++] = elements;
  2597. }
  2598. }
  2599. }
  2600. }
  2601. function jqLiteController(element, name) {
  2602. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  2603. }
  2604. function jqLiteInheritedData(element, name, value) {
  2605. // if element is the document object work with the html element instead
  2606. // this makes $(document).scope() possible
  2607. if (element.nodeType == NODE_TYPE_DOCUMENT) {
  2608. element = element.documentElement;
  2609. }
  2610. var names = isArray(name) ? name : [name];
  2611. while (element) {
  2612. for (var i = 0, ii = names.length; i < ii; i++) {
  2613. if ((value = jqLite.data(element, names[i])) !== undefined) return value;
  2614. }
  2615. // If dealing with a document fragment node with a host element, and no parent, use the host
  2616. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2617. // to lookup parent controllers.
  2618. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  2619. }
  2620. }
  2621. function jqLiteEmpty(element) {
  2622. jqLiteDealoc(element, true);
  2623. while (element.firstChild) {
  2624. element.removeChild(element.firstChild);
  2625. }
  2626. }
  2627. function jqLiteRemove(element, keepData) {
  2628. if (!keepData) jqLiteDealoc(element);
  2629. var parent = element.parentNode;
  2630. if (parent) parent.removeChild(element);
  2631. }
  2632. function jqLiteDocumentLoaded(action, win) {
  2633. win = win || window;
  2634. if (win.document.readyState === 'complete') {
  2635. // Force the action to be run async for consistent behaviour
  2636. // from the action's point of view
  2637. // i.e. it will definitely not be in a $apply
  2638. win.setTimeout(action);
  2639. } else {
  2640. // No need to unbind this handler as load is only ever called once
  2641. jqLite(win).on('load', action);
  2642. }
  2643. }
  2644. //////////////////////////////////////////
  2645. // Functions which are declared directly.
  2646. //////////////////////////////////////////
  2647. var JQLitePrototype = JQLite.prototype = {
  2648. ready: function(fn) {
  2649. var fired = false;
  2650. function trigger() {
  2651. if (fired) return;
  2652. fired = true;
  2653. fn();
  2654. }
  2655. // check if document is already loaded
  2656. if (document.readyState === 'complete') {
  2657. setTimeout(trigger);
  2658. } else {
  2659. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2660. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2661. // jshint -W064
  2662. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2663. // jshint +W064
  2664. }
  2665. },
  2666. toString: function() {
  2667. var value = [];
  2668. forEach(this, function(e) { value.push('' + e);});
  2669. return '[' + value.join(', ') + ']';
  2670. },
  2671. eq: function(index) {
  2672. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2673. },
  2674. length: 0,
  2675. push: push,
  2676. sort: [].sort,
  2677. splice: [].splice
  2678. };
  2679. //////////////////////////////////////////
  2680. // Functions iterating getter/setters.
  2681. // these functions return self on setter and
  2682. // value on get.
  2683. //////////////////////////////////////////
  2684. var BOOLEAN_ATTR = {};
  2685. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2686. BOOLEAN_ATTR[lowercase(value)] = value;
  2687. });
  2688. var BOOLEAN_ELEMENTS = {};
  2689. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2690. BOOLEAN_ELEMENTS[value] = true;
  2691. });
  2692. var ALIASED_ATTR = {
  2693. 'ngMinlength': 'minlength',
  2694. 'ngMaxlength': 'maxlength',
  2695. 'ngMin': 'min',
  2696. 'ngMax': 'max',
  2697. 'ngPattern': 'pattern'
  2698. };
  2699. function getBooleanAttrName(element, name) {
  2700. // check dom last since we will most likely fail on name
  2701. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2702. // booleanAttr is here twice to minimize DOM access
  2703. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  2704. }
  2705. function getAliasedAttrName(element, name) {
  2706. var nodeName = element.nodeName;
  2707. return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name];
  2708. }
  2709. forEach({
  2710. data: jqLiteData,
  2711. removeData: jqLiteRemoveData
  2712. }, function(fn, name) {
  2713. JQLite[name] = fn;
  2714. });
  2715. forEach({
  2716. data: jqLiteData,
  2717. inheritedData: jqLiteInheritedData,
  2718. scope: function(element) {
  2719. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2720. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2721. },
  2722. isolateScope: function(element) {
  2723. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2724. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  2725. },
  2726. controller: jqLiteController,
  2727. injector: function(element) {
  2728. return jqLiteInheritedData(element, '$injector');
  2729. },
  2730. removeAttr: function(element, name) {
  2731. element.removeAttribute(name);
  2732. },
  2733. hasClass: jqLiteHasClass,
  2734. css: function(element, name, value) {
  2735. name = camelCase(name);
  2736. if (isDefined(value)) {
  2737. element.style[name] = value;
  2738. } else {
  2739. return element.style[name];
  2740. }
  2741. },
  2742. attr: function(element, name, value) {
  2743. var nodeType = element.nodeType;
  2744. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
  2745. return;
  2746. }
  2747. var lowercasedName = lowercase(name);
  2748. if (BOOLEAN_ATTR[lowercasedName]) {
  2749. if (isDefined(value)) {
  2750. if (!!value) {
  2751. element[name] = true;
  2752. element.setAttribute(name, lowercasedName);
  2753. } else {
  2754. element[name] = false;
  2755. element.removeAttribute(lowercasedName);
  2756. }
  2757. } else {
  2758. return (element[name] ||
  2759. (element.attributes.getNamedItem(name) || noop).specified)
  2760. ? lowercasedName
  2761. : undefined;
  2762. }
  2763. } else if (isDefined(value)) {
  2764. element.setAttribute(name, value);
  2765. } else if (element.getAttribute) {
  2766. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2767. // some elements (e.g. Document) don't have get attribute, so return undefined
  2768. var ret = element.getAttribute(name, 2);
  2769. // normalize non-existing attributes to undefined (as jQuery)
  2770. return ret === null ? undefined : ret;
  2771. }
  2772. },
  2773. prop: function(element, name, value) {
  2774. if (isDefined(value)) {
  2775. element[name] = value;
  2776. } else {
  2777. return element[name];
  2778. }
  2779. },
  2780. text: (function() {
  2781. getText.$dv = '';
  2782. return getText;
  2783. function getText(element, value) {
  2784. if (isUndefined(value)) {
  2785. var nodeType = element.nodeType;
  2786. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  2787. }
  2788. element.textContent = value;
  2789. }
  2790. })(),
  2791. val: function(element, value) {
  2792. if (isUndefined(value)) {
  2793. if (element.multiple && nodeName_(element) === 'select') {
  2794. var result = [];
  2795. forEach(element.options, function(option) {
  2796. if (option.selected) {
  2797. result.push(option.value || option.text);
  2798. }
  2799. });
  2800. return result.length === 0 ? null : result;
  2801. }
  2802. return element.value;
  2803. }
  2804. element.value = value;
  2805. },
  2806. html: function(element, value) {
  2807. if (isUndefined(value)) {
  2808. return element.innerHTML;
  2809. }
  2810. jqLiteDealoc(element, true);
  2811. element.innerHTML = value;
  2812. },
  2813. empty: jqLiteEmpty
  2814. }, function(fn, name) {
  2815. /**
  2816. * Properties: writes return selection, reads return first value
  2817. */
  2818. JQLite.prototype[name] = function(arg1, arg2) {
  2819. var i, key;
  2820. var nodeCount = this.length;
  2821. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  2822. // in a way that survives minification.
  2823. // jqLiteEmpty takes no arguments but is a setter.
  2824. if (fn !== jqLiteEmpty &&
  2825. (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
  2826. if (isObject(arg1)) {
  2827. // we are a write, but the object properties are the key/values
  2828. for (i = 0; i < nodeCount; i++) {
  2829. if (fn === jqLiteData) {
  2830. // data() takes the whole object in jQuery
  2831. fn(this[i], arg1);
  2832. } else {
  2833. for (key in arg1) {
  2834. fn(this[i], key, arg1[key]);
  2835. }
  2836. }
  2837. }
  2838. // return self for chaining
  2839. return this;
  2840. } else {
  2841. // we are a read, so read the first child.
  2842. // TODO: do we still need this?
  2843. var value = fn.$dv;
  2844. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  2845. var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;
  2846. for (var j = 0; j < jj; j++) {
  2847. var nodeValue = fn(this[j], arg1, arg2);
  2848. value = value ? value + nodeValue : nodeValue;
  2849. }
  2850. return value;
  2851. }
  2852. } else {
  2853. // we are a write, so apply to all children
  2854. for (i = 0; i < nodeCount; i++) {
  2855. fn(this[i], arg1, arg2);
  2856. }
  2857. // return self for chaining
  2858. return this;
  2859. }
  2860. };
  2861. });
  2862. function createEventHandler(element, events) {
  2863. var eventHandler = function(event, type) {
  2864. // jQuery specific api
  2865. event.isDefaultPrevented = function() {
  2866. return event.defaultPrevented;
  2867. };
  2868. var eventFns = events[type || event.type];
  2869. var eventFnsLength = eventFns ? eventFns.length : 0;
  2870. if (!eventFnsLength) return;
  2871. if (isUndefined(event.immediatePropagationStopped)) {
  2872. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  2873. event.stopImmediatePropagation = function() {
  2874. event.immediatePropagationStopped = true;
  2875. if (event.stopPropagation) {
  2876. event.stopPropagation();
  2877. }
  2878. if (originalStopImmediatePropagation) {
  2879. originalStopImmediatePropagation.call(event);
  2880. }
  2881. };
  2882. }
  2883. event.isImmediatePropagationStopped = function() {
  2884. return event.immediatePropagationStopped === true;
  2885. };
  2886. // Copy event handlers in case event handlers array is modified during execution.
  2887. if ((eventFnsLength > 1)) {
  2888. eventFns = shallowCopy(eventFns);
  2889. }
  2890. for (var i = 0; i < eventFnsLength; i++) {
  2891. if (!event.isImmediatePropagationStopped()) {
  2892. eventFns[i].call(element, event);
  2893. }
  2894. }
  2895. };
  2896. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  2897. // events on `element`
  2898. eventHandler.elem = element;
  2899. return eventHandler;
  2900. }
  2901. //////////////////////////////////////////
  2902. // Functions iterating traversal.
  2903. // These functions chain results into a single
  2904. // selector.
  2905. //////////////////////////////////////////
  2906. forEach({
  2907. removeData: jqLiteRemoveData,
  2908. on: function jqLiteOn(element, type, fn, unsupported) {
  2909. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  2910. // Do not add event handlers to non-elements because they will not be cleaned up.
  2911. if (!jqLiteAcceptsData(element)) {
  2912. return;
  2913. }
  2914. var expandoStore = jqLiteExpandoStore(element, true);
  2915. var events = expandoStore.events;
  2916. var handle = expandoStore.handle;
  2917. if (!handle) {
  2918. handle = expandoStore.handle = createEventHandler(element, events);
  2919. }
  2920. // http://jsperf.com/string-indexof-vs-split
  2921. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  2922. var i = types.length;
  2923. while (i--) {
  2924. type = types[i];
  2925. var eventFns = events[type];
  2926. if (!eventFns) {
  2927. events[type] = [];
  2928. if (type === 'mouseenter' || type === 'mouseleave') {
  2929. // Refer to jQuery's implementation of mouseenter & mouseleave
  2930. // Read about mouseenter and mouseleave:
  2931. // http://www.quirksmode.org/js/events_mouse.html#link8
  2932. jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) {
  2933. var target = this, related = event.relatedTarget;
  2934. // For mousenter/leave call the handler if related is outside the target.
  2935. // NB: No relatedTarget if the mouse left/entered the browser window
  2936. if (!related || (related !== target && !target.contains(related))) {
  2937. handle(event, type);
  2938. }
  2939. });
  2940. } else {
  2941. if (type !== '$destroy') {
  2942. addEventListenerFn(element, type, handle);
  2943. }
  2944. }
  2945. eventFns = events[type];
  2946. }
  2947. eventFns.push(fn);
  2948. }
  2949. },
  2950. off: jqLiteOff,
  2951. one: function(element, type, fn) {
  2952. element = jqLite(element);
  2953. //add the listener twice so that when it is called
  2954. //you can remove the original function and still be
  2955. //able to call element.off(ev, fn) normally
  2956. element.on(type, function onFn() {
  2957. element.off(type, fn);
  2958. element.off(type, onFn);
  2959. });
  2960. element.on(type, fn);
  2961. },
  2962. replaceWith: function(element, replaceNode) {
  2963. var index, parent = element.parentNode;
  2964. jqLiteDealoc(element);
  2965. forEach(new JQLite(replaceNode), function(node) {
  2966. if (index) {
  2967. parent.insertBefore(node, index.nextSibling);
  2968. } else {
  2969. parent.replaceChild(node, element);
  2970. }
  2971. index = node;
  2972. });
  2973. },
  2974. children: function(element) {
  2975. var children = [];
  2976. forEach(element.childNodes, function(element) {
  2977. if (element.nodeType === NODE_TYPE_ELEMENT) {
  2978. children.push(element);
  2979. }
  2980. });
  2981. return children;
  2982. },
  2983. contents: function(element) {
  2984. return element.contentDocument || element.childNodes || [];
  2985. },
  2986. append: function(element, node) {
  2987. var nodeType = element.nodeType;
  2988. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  2989. node = new JQLite(node);
  2990. for (var i = 0, ii = node.length; i < ii; i++) {
  2991. var child = node[i];
  2992. element.appendChild(child);
  2993. }
  2994. },
  2995. prepend: function(element, node) {
  2996. if (element.nodeType === NODE_TYPE_ELEMENT) {
  2997. var index = element.firstChild;
  2998. forEach(new JQLite(node), function(child) {
  2999. element.insertBefore(child, index);
  3000. });
  3001. }
  3002. },
  3003. wrap: function(element, wrapNode) {
  3004. wrapNode = jqLite(wrapNode).eq(0).clone()[0];
  3005. var parent = element.parentNode;
  3006. if (parent) {
  3007. parent.replaceChild(wrapNode, element);
  3008. }
  3009. wrapNode.appendChild(element);
  3010. },
  3011. remove: jqLiteRemove,
  3012. detach: function(element) {
  3013. jqLiteRemove(element, true);
  3014. },
  3015. after: function(element, newElement) {
  3016. var index = element, parent = element.parentNode;
  3017. newElement = new JQLite(newElement);
  3018. for (var i = 0, ii = newElement.length; i < ii; i++) {
  3019. var node = newElement[i];
  3020. parent.insertBefore(node, index.nextSibling);
  3021. index = node;
  3022. }
  3023. },
  3024. addClass: jqLiteAddClass,
  3025. removeClass: jqLiteRemoveClass,
  3026. toggleClass: function(element, selector, condition) {
  3027. if (selector) {
  3028. forEach(selector.split(' '), function(className) {
  3029. var classCondition = condition;
  3030. if (isUndefined(classCondition)) {
  3031. classCondition = !jqLiteHasClass(element, className);
  3032. }
  3033. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  3034. });
  3035. }
  3036. },
  3037. parent: function(element) {
  3038. var parent = element.parentNode;
  3039. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  3040. },
  3041. next: function(element) {
  3042. return element.nextElementSibling;
  3043. },
  3044. find: function(element, selector) {
  3045. if (element.getElementsByTagName) {
  3046. return element.getElementsByTagName(selector);
  3047. } else {
  3048. return [];
  3049. }
  3050. },
  3051. clone: jqLiteClone,
  3052. triggerHandler: function(element, event, extraParameters) {
  3053. var dummyEvent, eventFnsCopy, handlerArgs;
  3054. var eventName = event.type || event;
  3055. var expandoStore = jqLiteExpandoStore(element);
  3056. var events = expandoStore && expandoStore.events;
  3057. var eventFns = events && events[eventName];
  3058. if (eventFns) {
  3059. // Create a dummy event to pass to the handlers
  3060. dummyEvent = {
  3061. preventDefault: function() { this.defaultPrevented = true; },
  3062. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  3063. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  3064. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  3065. stopPropagation: noop,
  3066. type: eventName,
  3067. target: element
  3068. };
  3069. // If a custom event was provided then extend our dummy event with it
  3070. if (event.type) {
  3071. dummyEvent = extend(dummyEvent, event);
  3072. }
  3073. // Copy event handlers in case event handlers array is modified during execution.
  3074. eventFnsCopy = shallowCopy(eventFns);
  3075. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  3076. forEach(eventFnsCopy, function(fn) {
  3077. if (!dummyEvent.isImmediatePropagationStopped()) {
  3078. fn.apply(element, handlerArgs);
  3079. }
  3080. });
  3081. }
  3082. }
  3083. }, function(fn, name) {
  3084. /**
  3085. * chaining functions
  3086. */
  3087. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  3088. var value;
  3089. for (var i = 0, ii = this.length; i < ii; i++) {
  3090. if (isUndefined(value)) {
  3091. value = fn(this[i], arg1, arg2, arg3);
  3092. if (isDefined(value)) {
  3093. // any function which returns a value needs to be wrapped
  3094. value = jqLite(value);
  3095. }
  3096. } else {
  3097. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  3098. }
  3099. }
  3100. return isDefined(value) ? value : this;
  3101. };
  3102. // bind legacy bind/unbind to on/off
  3103. JQLite.prototype.bind = JQLite.prototype.on;
  3104. JQLite.prototype.unbind = JQLite.prototype.off;
  3105. });
  3106. // Provider for private $$jqLite service
  3107. function $$jqLiteProvider() {
  3108. this.$get = function $$jqLite() {
  3109. return extend(JQLite, {
  3110. hasClass: function(node, classes) {
  3111. if (node.attr) node = node[0];
  3112. return jqLiteHasClass(node, classes);
  3113. },
  3114. addClass: function(node, classes) {
  3115. if (node.attr) node = node[0];
  3116. return jqLiteAddClass(node, classes);
  3117. },
  3118. removeClass: function(node, classes) {
  3119. if (node.attr) node = node[0];
  3120. return jqLiteRemoveClass(node, classes);
  3121. }
  3122. });
  3123. };
  3124. }
  3125. /**
  3126. * Computes a hash of an 'obj'.
  3127. * Hash of a:
  3128. * string is string
  3129. * number is number as string
  3130. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  3131. * that is also assigned to the $$hashKey property of the object.
  3132. *
  3133. * @param obj
  3134. * @returns {string} hash string such that the same input will have the same hash string.
  3135. * The resulting string key is in 'type:hashKey' format.
  3136. */
  3137. function hashKey(obj, nextUidFn) {
  3138. var key = obj && obj.$$hashKey;
  3139. if (key) {
  3140. if (typeof key === 'function') {
  3141. key = obj.$$hashKey();
  3142. }
  3143. return key;
  3144. }
  3145. var objType = typeof obj;
  3146. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  3147. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  3148. } else {
  3149. key = objType + ':' + obj;
  3150. }
  3151. return key;
  3152. }
  3153. /**
  3154. * HashMap which can use objects as keys
  3155. */
  3156. function HashMap(array, isolatedUid) {
  3157. if (isolatedUid) {
  3158. var uid = 0;
  3159. this.nextUid = function() {
  3160. return ++uid;
  3161. };
  3162. }
  3163. forEach(array, this.put, this);
  3164. }
  3165. HashMap.prototype = {
  3166. /**
  3167. * Store key value pair
  3168. * @param key key to store can be any type
  3169. * @param value value to store can be any type
  3170. */
  3171. put: function(key, value) {
  3172. this[hashKey(key, this.nextUid)] = value;
  3173. },
  3174. /**
  3175. * @param key
  3176. * @returns {Object} the value for the key
  3177. */
  3178. get: function(key) {
  3179. return this[hashKey(key, this.nextUid)];
  3180. },
  3181. /**
  3182. * Remove the key/value pair
  3183. * @param key
  3184. */
  3185. remove: function(key) {
  3186. var value = this[key = hashKey(key, this.nextUid)];
  3187. delete this[key];
  3188. return value;
  3189. }
  3190. };
  3191. var $$HashMapProvider = [function() {
  3192. this.$get = [function() {
  3193. return HashMap;
  3194. }];
  3195. }];
  3196. /**
  3197. * @ngdoc function
  3198. * @module ng
  3199. * @name angular.injector
  3200. * @kind function
  3201. *
  3202. * @description
  3203. * Creates an injector object that can be used for retrieving services as well as for
  3204. * dependency injection (see {@link guide/di dependency injection}).
  3205. *
  3206. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3207. * {@link angular.module}. The `ng` module must be explicitly added.
  3208. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3209. * disallows argument name annotation inference.
  3210. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3211. *
  3212. * @example
  3213. * Typical usage
  3214. * ```js
  3215. * // create an injector
  3216. * var $injector = angular.injector(['ng']);
  3217. *
  3218. * // use the injector to kick off your application
  3219. * // use the type inference to auto inject arguments, or use implicit injection
  3220. * $injector.invoke(function($rootScope, $compile, $document) {
  3221. * $compile($document)($rootScope);
  3222. * $rootScope.$digest();
  3223. * });
  3224. * ```
  3225. *
  3226. * Sometimes you want to get access to the injector of a currently running Angular app
  3227. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  3228. * application has been bootstrapped. You can do this using the extra `injector()` added
  3229. * to JQuery/jqLite elements. See {@link angular.element}.
  3230. *
  3231. * *This is fairly rare but could be the case if a third party library is injecting the
  3232. * markup.*
  3233. *
  3234. * In the following example a new block of HTML containing a `ng-controller`
  3235. * directive is added to the end of the document body by JQuery. We then compile and link
  3236. * it into the current AngularJS scope.
  3237. *
  3238. * ```js
  3239. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3240. * $(document.body).append($div);
  3241. *
  3242. * angular.element(document).injector().invoke(function($compile) {
  3243. * var scope = angular.element($div).scope();
  3244. * $compile($div)(scope);
  3245. * });
  3246. * ```
  3247. */
  3248. /**
  3249. * @ngdoc module
  3250. * @name auto
  3251. * @description
  3252. *
  3253. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3254. */
  3255. var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
  3256. var FN_ARG_SPLIT = /,/;
  3257. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3258. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3259. var $injectorMinErr = minErr('$injector');
  3260. function anonFn(fn) {
  3261. // For anonymous functions, showing at the very least the function signature can help in
  3262. // debugging.
  3263. var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
  3264. args = fnText.match(FN_ARGS);
  3265. if (args) {
  3266. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3267. }
  3268. return 'fn';
  3269. }
  3270. function annotate(fn, strictDi, name) {
  3271. var $inject,
  3272. fnText,
  3273. argDecl,
  3274. last;
  3275. if (typeof fn === 'function') {
  3276. if (!($inject = fn.$inject)) {
  3277. $inject = [];
  3278. if (fn.length) {
  3279. if (strictDi) {
  3280. if (!isString(name) || !name) {
  3281. name = fn.name || anonFn(fn);
  3282. }
  3283. throw $injectorMinErr('strictdi',
  3284. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3285. }
  3286. fnText = fn.toString().replace(STRIP_COMMENTS, '');
  3287. argDecl = fnText.match(FN_ARGS);
  3288. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3289. arg.replace(FN_ARG, function(all, underscore, name) {
  3290. $inject.push(name);
  3291. });
  3292. });
  3293. }
  3294. fn.$inject = $inject;
  3295. }
  3296. } else if (isArray(fn)) {
  3297. last = fn.length - 1;
  3298. assertArgFn(fn[last], 'fn');
  3299. $inject = fn.slice(0, last);
  3300. } else {
  3301. assertArgFn(fn, 'fn', true);
  3302. }
  3303. return $inject;
  3304. }
  3305. ///////////////////////////////////////
  3306. /**
  3307. * @ngdoc service
  3308. * @name $injector
  3309. *
  3310. * @description
  3311. *
  3312. * `$injector` is used to retrieve object instances as defined by
  3313. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3314. * and load modules.
  3315. *
  3316. * The following always holds true:
  3317. *
  3318. * ```js
  3319. * var $injector = angular.injector();
  3320. * expect($injector.get('$injector')).toBe($injector);
  3321. * expect($injector.invoke(function($injector) {
  3322. * return $injector;
  3323. * })).toBe($injector);
  3324. * ```
  3325. *
  3326. * # Injection Function Annotation
  3327. *
  3328. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3329. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3330. *
  3331. * ```js
  3332. * // inferred (only works if code not minified/obfuscated)
  3333. * $injector.invoke(function(serviceA){});
  3334. *
  3335. * // annotated
  3336. * function explicit(serviceA) {};
  3337. * explicit.$inject = ['serviceA'];
  3338. * $injector.invoke(explicit);
  3339. *
  3340. * // inline
  3341. * $injector.invoke(['serviceA', function(serviceA){}]);
  3342. * ```
  3343. *
  3344. * ## Inference
  3345. *
  3346. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3347. * can then be parsed and the function arguments can be extracted. This method of discovering
  3348. * annotations is disallowed when the injector is in strict mode.
  3349. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3350. * argument names.
  3351. *
  3352. * ## `$inject` Annotation
  3353. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3354. *
  3355. * ## Inline
  3356. * As an array of injection names, where the last item in the array is the function to call.
  3357. */
  3358. /**
  3359. * @ngdoc method
  3360. * @name $injector#get
  3361. *
  3362. * @description
  3363. * Return an instance of the service.
  3364. *
  3365. * @param {string} name The name of the instance to retrieve.
  3366. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  3367. * @return {*} The instance.
  3368. */
  3369. /**
  3370. * @ngdoc method
  3371. * @name $injector#invoke
  3372. *
  3373. * @description
  3374. * Invoke the method and supply the method arguments from the `$injector`.
  3375. *
  3376. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  3377. * injected according to the {@link guide/di $inject Annotation} rules.
  3378. * @param {Object=} self The `this` for the invoked method.
  3379. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3380. * object first, before the `$injector` is consulted.
  3381. * @returns {*} the value returned by the invoked `fn` function.
  3382. */
  3383. /**
  3384. * @ngdoc method
  3385. * @name $injector#has
  3386. *
  3387. * @description
  3388. * Allows the user to query if the particular service exists.
  3389. *
  3390. * @param {string} name Name of the service to query.
  3391. * @returns {boolean} `true` if injector has given service.
  3392. */
  3393. /**
  3394. * @ngdoc method
  3395. * @name $injector#instantiate
  3396. * @description
  3397. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3398. * operator, and supplies all of the arguments to the constructor function as specified by the
  3399. * constructor annotation.
  3400. *
  3401. * @param {Function} Type Annotated constructor function.
  3402. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3403. * object first, before the `$injector` is consulted.
  3404. * @returns {Object} new instance of `Type`.
  3405. */
  3406. /**
  3407. * @ngdoc method
  3408. * @name $injector#annotate
  3409. *
  3410. * @description
  3411. * Returns an array of service names which the function is requesting for injection. This API is
  3412. * used by the injector to determine which services need to be injected into the function when the
  3413. * function is invoked. There are three ways in which the function can be annotated with the needed
  3414. * dependencies.
  3415. *
  3416. * # Argument names
  3417. *
  3418. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3419. * by converting the function into a string using `toString()` method and extracting the argument
  3420. * names.
  3421. * ```js
  3422. * // Given
  3423. * function MyController($scope, $route) {
  3424. * // ...
  3425. * }
  3426. *
  3427. * // Then
  3428. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3429. * ```
  3430. *
  3431. * You can disallow this method by using strict injection mode.
  3432. *
  3433. * This method does not work with code minification / obfuscation. For this reason the following
  3434. * annotation strategies are supported.
  3435. *
  3436. * # The `$inject` property
  3437. *
  3438. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3439. * represent names of services to be injected into the function.
  3440. * ```js
  3441. * // Given
  3442. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3443. * // ...
  3444. * }
  3445. * // Define function dependencies
  3446. * MyController['$inject'] = ['$scope', '$route'];
  3447. *
  3448. * // Then
  3449. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3450. * ```
  3451. *
  3452. * # The array notation
  3453. *
  3454. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3455. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3456. * a way that survives minification is a better choice:
  3457. *
  3458. * ```js
  3459. * // We wish to write this (not minification / obfuscation safe)
  3460. * injector.invoke(function($compile, $rootScope) {
  3461. * // ...
  3462. * });
  3463. *
  3464. * // We are forced to write break inlining
  3465. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3466. * // ...
  3467. * };
  3468. * tmpFn.$inject = ['$compile', '$rootScope'];
  3469. * injector.invoke(tmpFn);
  3470. *
  3471. * // To better support inline function the inline annotation is supported
  3472. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3473. * // ...
  3474. * }]);
  3475. *
  3476. * // Therefore
  3477. * expect(injector.annotate(
  3478. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3479. * ).toEqual(['$compile', '$rootScope']);
  3480. * ```
  3481. *
  3482. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3483. * be retrieved as described above.
  3484. *
  3485. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3486. *
  3487. * @returns {Array.<string>} The names of the services which the function requires.
  3488. */
  3489. /**
  3490. * @ngdoc service
  3491. * @name $provide
  3492. *
  3493. * @description
  3494. *
  3495. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3496. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3497. * {@link angular.Module}.
  3498. *
  3499. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3500. * factories** are functions which, in turn, are created by a **service provider**.
  3501. * The **service providers** are constructor functions. When instantiated they must contain a
  3502. * property called `$get`, which holds the **service factory** function.
  3503. *
  3504. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3505. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3506. * function to get the instance of the **service**.
  3507. *
  3508. * Often services have no configuration options and there is no need to add methods to the service
  3509. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3510. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3511. * services without specifying a provider.
  3512. *
  3513. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  3514. * {@link auto.$injector $injector}
  3515. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  3516. * providers and services.
  3517. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  3518. * services, not providers.
  3519. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  3520. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3521. * given factory function.
  3522. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  3523. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3524. * a new object using the given constructor function.
  3525. *
  3526. * See the individual methods for more information and examples.
  3527. */
  3528. /**
  3529. * @ngdoc method
  3530. * @name $provide#provider
  3531. * @description
  3532. *
  3533. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3534. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3535. * service.
  3536. *
  3537. * Service provider names start with the name of the service they provide followed by `Provider`.
  3538. * For example, the {@link ng.$log $log} service has a provider called
  3539. * {@link ng.$logProvider $logProvider}.
  3540. *
  3541. * Service provider objects can have additional methods which allow configuration of the provider
  3542. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3543. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3544. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3545. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3546. * console or not.
  3547. *
  3548. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3549. 'Provider'` key.
  3550. * @param {(Object|function())} provider If the provider is:
  3551. *
  3552. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3553. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3554. * - `Constructor`: a new instance of the provider will be created using
  3555. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3556. *
  3557. * @returns {Object} registered provider instance
  3558. * @example
  3559. *
  3560. * The following example shows how to create a simple event tracking service and register it using
  3561. * {@link auto.$provide#provider $provide.provider()}.
  3562. *
  3563. * ```js
  3564. * // Define the eventTracker provider
  3565. * function EventTrackerProvider() {
  3566. * var trackingUrl = '/track';
  3567. *
  3568. * // A provider method for configuring where the tracked events should been saved
  3569. * this.setTrackingUrl = function(url) {
  3570. * trackingUrl = url;
  3571. * };
  3572. *
  3573. * // The service factory function
  3574. * this.$get = ['$http', function($http) {
  3575. * var trackedEvents = {};
  3576. * return {
  3577. * // Call this to track an event
  3578. * event: function(event) {
  3579. * var count = trackedEvents[event] || 0;
  3580. * count += 1;
  3581. * trackedEvents[event] = count;
  3582. * return count;
  3583. * },
  3584. * // Call this to save the tracked events to the trackingUrl
  3585. * save: function() {
  3586. * $http.post(trackingUrl, trackedEvents);
  3587. * }
  3588. * };
  3589. * }];
  3590. * }
  3591. *
  3592. * describe('eventTracker', function() {
  3593. * var postSpy;
  3594. *
  3595. * beforeEach(module(function($provide) {
  3596. * // Register the eventTracker provider
  3597. * $provide.provider('eventTracker', EventTrackerProvider);
  3598. * }));
  3599. *
  3600. * beforeEach(module(function(eventTrackerProvider) {
  3601. * // Configure eventTracker provider
  3602. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3603. * }));
  3604. *
  3605. * it('tracks events', inject(function(eventTracker) {
  3606. * expect(eventTracker.event('login')).toEqual(1);
  3607. * expect(eventTracker.event('login')).toEqual(2);
  3608. * }));
  3609. *
  3610. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3611. * postSpy = spyOn($http, 'post');
  3612. * eventTracker.event('login');
  3613. * eventTracker.save();
  3614. * expect(postSpy).toHaveBeenCalled();
  3615. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3616. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3617. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3618. * }));
  3619. * });
  3620. * ```
  3621. */
  3622. /**
  3623. * @ngdoc method
  3624. * @name $provide#factory
  3625. * @description
  3626. *
  3627. * Register a **service factory**, which will be called to return the service instance.
  3628. * This is short for registering a service where its provider consists of only a `$get` property,
  3629. * which is the given service factory function.
  3630. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3631. * configure your service in a provider.
  3632. *
  3633. * @param {string} name The name of the instance.
  3634. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  3635. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  3636. * @returns {Object} registered provider instance
  3637. *
  3638. * @example
  3639. * Here is an example of registering a service
  3640. * ```js
  3641. * $provide.factory('ping', ['$http', function($http) {
  3642. * return function ping() {
  3643. * return $http.send('/ping');
  3644. * };
  3645. * }]);
  3646. * ```
  3647. * You would then inject and use this service like this:
  3648. * ```js
  3649. * someModule.controller('Ctrl', ['ping', function(ping) {
  3650. * ping();
  3651. * }]);
  3652. * ```
  3653. */
  3654. /**
  3655. * @ngdoc method
  3656. * @name $provide#service
  3657. * @description
  3658. *
  3659. * Register a **service constructor**, which will be invoked with `new` to create the service
  3660. * instance.
  3661. * This is short for registering a service where its provider's `$get` property is the service
  3662. * constructor function that will be used to instantiate the service instance.
  3663. *
  3664. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3665. * as a type/class.
  3666. *
  3667. * @param {string} name The name of the instance.
  3668. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  3669. * that will be instantiated.
  3670. * @returns {Object} registered provider instance
  3671. *
  3672. * @example
  3673. * Here is an example of registering a service using
  3674. * {@link auto.$provide#service $provide.service(class)}.
  3675. * ```js
  3676. * var Ping = function($http) {
  3677. * this.$http = $http;
  3678. * };
  3679. *
  3680. * Ping.$inject = ['$http'];
  3681. *
  3682. * Ping.prototype.send = function() {
  3683. * return this.$http.get('/ping');
  3684. * };
  3685. * $provide.service('ping', Ping);
  3686. * ```
  3687. * You would then inject and use this service like this:
  3688. * ```js
  3689. * someModule.controller('Ctrl', ['ping', function(ping) {
  3690. * ping.send();
  3691. * }]);
  3692. * ```
  3693. */
  3694. /**
  3695. * @ngdoc method
  3696. * @name $provide#value
  3697. * @description
  3698. *
  3699. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3700. * number, an array, an object or a function. This is short for registering a service where its
  3701. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3702. * service**.
  3703. *
  3704. * Value services are similar to constant services, except that they cannot be injected into a
  3705. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3706. * an Angular
  3707. * {@link auto.$provide#decorator decorator}.
  3708. *
  3709. * @param {string} name The name of the instance.
  3710. * @param {*} value The value.
  3711. * @returns {Object} registered provider instance
  3712. *
  3713. * @example
  3714. * Here are some examples of creating value services.
  3715. * ```js
  3716. * $provide.value('ADMIN_USER', 'admin');
  3717. *
  3718. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3719. *
  3720. * $provide.value('halfOf', function(value) {
  3721. * return value / 2;
  3722. * });
  3723. * ```
  3724. */
  3725. /**
  3726. * @ngdoc method
  3727. * @name $provide#constant
  3728. * @description
  3729. *
  3730. * Register a **constant service**, such as a string, a number, an array, an object or a function,
  3731. * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
  3732. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3733. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3734. *
  3735. * @param {string} name The name of the constant.
  3736. * @param {*} value The constant value.
  3737. * @returns {Object} registered instance
  3738. *
  3739. * @example
  3740. * Here a some examples of creating constants:
  3741. * ```js
  3742. * $provide.constant('SHARD_HEIGHT', 306);
  3743. *
  3744. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3745. *
  3746. * $provide.constant('double', function(value) {
  3747. * return value * 2;
  3748. * });
  3749. * ```
  3750. */
  3751. /**
  3752. * @ngdoc method
  3753. * @name $provide#decorator
  3754. * @description
  3755. *
  3756. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  3757. * intercepts the creation of a service, allowing it to override or modify the behaviour of the
  3758. * service. The object returned by the decorator may be the original service, or a new service
  3759. * object which replaces or wraps and delegates to the original service.
  3760. *
  3761. * @param {string} name The name of the service to decorate.
  3762. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  3763. * instantiated and should return the decorated service instance. The function is called using
  3764. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3765. * Local injection arguments:
  3766. *
  3767. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3768. * decorated or delegated to.
  3769. *
  3770. * @example
  3771. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3772. * calls to {@link ng.$log#error $log.warn()}.
  3773. * ```js
  3774. * $provide.decorator('$log', ['$delegate', function($delegate) {
  3775. * $delegate.warn = $delegate.error;
  3776. * return $delegate;
  3777. * }]);
  3778. * ```
  3779. */
  3780. function createInjector(modulesToLoad, strictDi) {
  3781. strictDi = (strictDi === true);
  3782. var INSTANTIATING = {},
  3783. providerSuffix = 'Provider',
  3784. path = [],
  3785. loadedModules = new HashMap([], true),
  3786. providerCache = {
  3787. $provide: {
  3788. provider: supportObject(provider),
  3789. factory: supportObject(factory),
  3790. service: supportObject(service),
  3791. value: supportObject(value),
  3792. constant: supportObject(constant),
  3793. decorator: decorator
  3794. }
  3795. },
  3796. providerInjector = (providerCache.$injector =
  3797. createInternalInjector(providerCache, function(serviceName, caller) {
  3798. if (angular.isString(caller)) {
  3799. path.push(caller);
  3800. }
  3801. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  3802. })),
  3803. instanceCache = {},
  3804. instanceInjector = (instanceCache.$injector =
  3805. createInternalInjector(instanceCache, function(serviceName, caller) {
  3806. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  3807. return instanceInjector.invoke(provider.$get, provider, undefined, serviceName);
  3808. }));
  3809. forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
  3810. return instanceInjector;
  3811. ////////////////////////////////////
  3812. // $provider
  3813. ////////////////////////////////////
  3814. function supportObject(delegate) {
  3815. return function(key, value) {
  3816. if (isObject(key)) {
  3817. forEach(key, reverseParams(delegate));
  3818. } else {
  3819. return delegate(key, value);
  3820. }
  3821. };
  3822. }
  3823. function provider(name, provider_) {
  3824. assertNotHasOwnProperty(name, 'service');
  3825. if (isFunction(provider_) || isArray(provider_)) {
  3826. provider_ = providerInjector.instantiate(provider_);
  3827. }
  3828. if (!provider_.$get) {
  3829. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  3830. }
  3831. return providerCache[name + providerSuffix] = provider_;
  3832. }
  3833. function enforceReturnValue(name, factory) {
  3834. return function enforcedReturnValue() {
  3835. var result = instanceInjector.invoke(factory, this);
  3836. if (isUndefined(result)) {
  3837. throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
  3838. }
  3839. return result;
  3840. };
  3841. }
  3842. function factory(name, factoryFn, enforce) {
  3843. return provider(name, {
  3844. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  3845. });
  3846. }
  3847. function service(name, constructor) {
  3848. return factory(name, ['$injector', function($injector) {
  3849. return $injector.instantiate(constructor);
  3850. }]);
  3851. }
  3852. function value(name, val) { return factory(name, valueFn(val), false); }
  3853. function constant(name, value) {
  3854. assertNotHasOwnProperty(name, 'constant');
  3855. providerCache[name] = value;
  3856. instanceCache[name] = value;
  3857. }
  3858. function decorator(serviceName, decorFn) {
  3859. var origProvider = providerInjector.get(serviceName + providerSuffix),
  3860. orig$get = origProvider.$get;
  3861. origProvider.$get = function() {
  3862. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  3863. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  3864. };
  3865. }
  3866. ////////////////////////////////////
  3867. // Module Loading
  3868. ////////////////////////////////////
  3869. function loadModules(modulesToLoad) {
  3870. var runBlocks = [], moduleFn;
  3871. forEach(modulesToLoad, function(module) {
  3872. if (loadedModules.get(module)) return;
  3873. loadedModules.put(module, true);
  3874. function runInvokeQueue(queue) {
  3875. var i, ii;
  3876. for (i = 0, ii = queue.length; i < ii; i++) {
  3877. var invokeArgs = queue[i],
  3878. provider = providerInjector.get(invokeArgs[0]);
  3879. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  3880. }
  3881. }
  3882. try {
  3883. if (isString(module)) {
  3884. moduleFn = angularModule(module);
  3885. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  3886. runInvokeQueue(moduleFn._invokeQueue);
  3887. runInvokeQueue(moduleFn._configBlocks);
  3888. } else if (isFunction(module)) {
  3889. runBlocks.push(providerInjector.invoke(module));
  3890. } else if (isArray(module)) {
  3891. runBlocks.push(providerInjector.invoke(module));
  3892. } else {
  3893. assertArgFn(module, 'module');
  3894. }
  3895. } catch (e) {
  3896. if (isArray(module)) {
  3897. module = module[module.length - 1];
  3898. }
  3899. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  3900. // Safari & FF's stack traces don't contain error.message content
  3901. // unlike those of Chrome and IE
  3902. // So if stack doesn't contain message, we create a new string that contains both.
  3903. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  3904. /* jshint -W022 */
  3905. e = e.message + '\n' + e.stack;
  3906. }
  3907. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  3908. module, e.stack || e.message || e);
  3909. }
  3910. });
  3911. return runBlocks;
  3912. }
  3913. ////////////////////////////////////
  3914. // internal Injector
  3915. ////////////////////////////////////
  3916. function createInternalInjector(cache, factory) {
  3917. function getService(serviceName, caller) {
  3918. if (cache.hasOwnProperty(serviceName)) {
  3919. if (cache[serviceName] === INSTANTIATING) {
  3920. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  3921. serviceName + ' <- ' + path.join(' <- '));
  3922. }
  3923. return cache[serviceName];
  3924. } else {
  3925. try {
  3926. path.unshift(serviceName);
  3927. cache[serviceName] = INSTANTIATING;
  3928. return cache[serviceName] = factory(serviceName, caller);
  3929. } catch (err) {
  3930. if (cache[serviceName] === INSTANTIATING) {
  3931. delete cache[serviceName];
  3932. }
  3933. throw err;
  3934. } finally {
  3935. path.shift();
  3936. }
  3937. }
  3938. }
  3939. function invoke(fn, self, locals, serviceName) {
  3940. if (typeof locals === 'string') {
  3941. serviceName = locals;
  3942. locals = null;
  3943. }
  3944. var args = [],
  3945. $inject = createInjector.$$annotate(fn, strictDi, serviceName),
  3946. length, i,
  3947. key;
  3948. for (i = 0, length = $inject.length; i < length; i++) {
  3949. key = $inject[i];
  3950. if (typeof key !== 'string') {
  3951. throw $injectorMinErr('itkn',
  3952. 'Incorrect injection token! Expected service name as string, got {0}', key);
  3953. }
  3954. args.push(
  3955. locals && locals.hasOwnProperty(key)
  3956. ? locals[key]
  3957. : getService(key, serviceName)
  3958. );
  3959. }
  3960. if (isArray(fn)) {
  3961. fn = fn[length];
  3962. }
  3963. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  3964. // #5388
  3965. return fn.apply(self, args);
  3966. }
  3967. function instantiate(Type, locals, serviceName) {
  3968. // Check if Type is annotated and use just the given function at n-1 as parameter
  3969. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  3970. // Object creation: http://jsperf.com/create-constructor/2
  3971. var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);
  3972. var returnedValue = invoke(Type, instance, locals, serviceName);
  3973. return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
  3974. }
  3975. return {
  3976. invoke: invoke,
  3977. instantiate: instantiate,
  3978. get: getService,
  3979. annotate: createInjector.$$annotate,
  3980. has: function(name) {
  3981. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  3982. }
  3983. };
  3984. }
  3985. }
  3986. createInjector.$$annotate = annotate;
  3987. /**
  3988. * @ngdoc provider
  3989. * @name $anchorScrollProvider
  3990. *
  3991. * @description
  3992. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  3993. * {@link ng.$location#hash $location.hash()} changes.
  3994. */
  3995. function $AnchorScrollProvider() {
  3996. var autoScrollingEnabled = true;
  3997. /**
  3998. * @ngdoc method
  3999. * @name $anchorScrollProvider#disableAutoScrolling
  4000. *
  4001. * @description
  4002. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  4003. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  4004. * Use this method to disable automatic scrolling.
  4005. *
  4006. * If automatic scrolling is disabled, one must explicitly call
  4007. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  4008. * current hash.
  4009. */
  4010. this.disableAutoScrolling = function() {
  4011. autoScrollingEnabled = false;
  4012. };
  4013. /**
  4014. * @ngdoc service
  4015. * @name $anchorScroll
  4016. * @kind function
  4017. * @requires $window
  4018. * @requires $location
  4019. * @requires $rootScope
  4020. *
  4021. * @description
  4022. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  4023. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  4024. * in the
  4025. * [HTML5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).
  4026. *
  4027. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  4028. * match any anchor whenever it changes. This can be disabled by calling
  4029. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  4030. *
  4031. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  4032. * vertical scroll-offset (either fixed or dynamic).
  4033. *
  4034. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  4035. * {@link ng.$location#hash $location.hash()} will be used.
  4036. *
  4037. * @property {(number|function|jqLite)} yOffset
  4038. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  4039. * positioned elements at the top of the page, such as navbars, headers etc.
  4040. *
  4041. * `yOffset` can be specified in various ways:
  4042. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  4043. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  4044. * a number representing the offset (in pixels).<br /><br />
  4045. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  4046. * the top of the page to the element's bottom will be used as offset.<br />
  4047. * **Note**: The element will be taken into account only as long as its `position` is set to
  4048. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  4049. * their height and/or positioning according to the viewport's size.
  4050. *
  4051. * <br />
  4052. * <div class="alert alert-warning">
  4053. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  4054. * not some child element.
  4055. * </div>
  4056. *
  4057. * @example
  4058. <example module="anchorScrollExample">
  4059. <file name="index.html">
  4060. <div id="scrollArea" ng-controller="ScrollController">
  4061. <a ng-click="gotoBottom()">Go to bottom</a>
  4062. <a id="bottom"></a> You're at the bottom!
  4063. </div>
  4064. </file>
  4065. <file name="script.js">
  4066. angular.module('anchorScrollExample', [])
  4067. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  4068. function ($scope, $location, $anchorScroll) {
  4069. $scope.gotoBottom = function() {
  4070. // set the location.hash to the id of
  4071. // the element you wish to scroll to.
  4072. $location.hash('bottom');
  4073. // call $anchorScroll()
  4074. $anchorScroll();
  4075. };
  4076. }]);
  4077. </file>
  4078. <file name="style.css">
  4079. #scrollArea {
  4080. height: 280px;
  4081. overflow: auto;
  4082. }
  4083. #bottom {
  4084. display: block;
  4085. margin-top: 2000px;
  4086. }
  4087. </file>
  4088. </example>
  4089. *
  4090. * <hr />
  4091. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  4092. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  4093. *
  4094. * @example
  4095. <example module="anchorScrollOffsetExample">
  4096. <file name="index.html">
  4097. <div class="fixed-header" ng-controller="headerCtrl">
  4098. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  4099. Go to anchor {{x}}
  4100. </a>
  4101. </div>
  4102. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  4103. Anchor {{x}} of 5
  4104. </div>
  4105. </file>
  4106. <file name="script.js">
  4107. angular.module('anchorScrollOffsetExample', [])
  4108. .run(['$anchorScroll', function($anchorScroll) {
  4109. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  4110. }])
  4111. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  4112. function ($anchorScroll, $location, $scope) {
  4113. $scope.gotoAnchor = function(x) {
  4114. var newHash = 'anchor' + x;
  4115. if ($location.hash() !== newHash) {
  4116. // set the $location.hash to `newHash` and
  4117. // $anchorScroll will automatically scroll to it
  4118. $location.hash('anchor' + x);
  4119. } else {
  4120. // call $anchorScroll() explicitly,
  4121. // since $location.hash hasn't changed
  4122. $anchorScroll();
  4123. }
  4124. };
  4125. }
  4126. ]);
  4127. </file>
  4128. <file name="style.css">
  4129. body {
  4130. padding-top: 50px;
  4131. }
  4132. .anchor {
  4133. border: 2px dashed DarkOrchid;
  4134. padding: 10px 10px 200px 10px;
  4135. }
  4136. .fixed-header {
  4137. background-color: rgba(0, 0, 0, 0.2);
  4138. height: 50px;
  4139. position: fixed;
  4140. top: 0; left: 0; right: 0;
  4141. }
  4142. .fixed-header > a {
  4143. display: inline-block;
  4144. margin: 5px 15px;
  4145. }
  4146. </file>
  4147. </example>
  4148. */
  4149. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  4150. var document = $window.document;
  4151. // Helper function to get first anchor from a NodeList
  4152. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  4153. // and working in all supported browsers.)
  4154. function getFirstAnchor(list) {
  4155. var result = null;
  4156. Array.prototype.some.call(list, function(element) {
  4157. if (nodeName_(element) === 'a') {
  4158. result = element;
  4159. return true;
  4160. }
  4161. });
  4162. return result;
  4163. }
  4164. function getYOffset() {
  4165. var offset = scroll.yOffset;
  4166. if (isFunction(offset)) {
  4167. offset = offset();
  4168. } else if (isElement(offset)) {
  4169. var elem = offset[0];
  4170. var style = $window.getComputedStyle(elem);
  4171. if (style.position !== 'fixed') {
  4172. offset = 0;
  4173. } else {
  4174. offset = elem.getBoundingClientRect().bottom;
  4175. }
  4176. } else if (!isNumber(offset)) {
  4177. offset = 0;
  4178. }
  4179. return offset;
  4180. }
  4181. function scrollTo(elem) {
  4182. if (elem) {
  4183. elem.scrollIntoView();
  4184. var offset = getYOffset();
  4185. if (offset) {
  4186. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  4187. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  4188. // top of the viewport.
  4189. //
  4190. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  4191. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  4192. // way down the page.
  4193. //
  4194. // This is often the case for elements near the bottom of the page.
  4195. //
  4196. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  4197. // the top of the element and the offset, which is enough to align the top of `elem` at the
  4198. // desired position.
  4199. var elemTop = elem.getBoundingClientRect().top;
  4200. $window.scrollBy(0, elemTop - offset);
  4201. }
  4202. } else {
  4203. $window.scrollTo(0, 0);
  4204. }
  4205. }
  4206. function scroll(hash) {
  4207. hash = isString(hash) ? hash : $location.hash();
  4208. var elm;
  4209. // empty hash, scroll to the top of the page
  4210. if (!hash) scrollTo(null);
  4211. // element with given id
  4212. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4213. // first anchor with given name :-D
  4214. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4215. // no element and hash == 'top', scroll to the top of the page
  4216. else if (hash === 'top') scrollTo(null);
  4217. }
  4218. // does not scroll when user clicks on anchor link that is currently on
  4219. // (no url change, no $location.hash() change), browser native does scroll
  4220. if (autoScrollingEnabled) {
  4221. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4222. function autoScrollWatchAction(newVal, oldVal) {
  4223. // skip the initial scroll if $location.hash is empty
  4224. if (newVal === oldVal && newVal === '') return;
  4225. jqLiteDocumentLoaded(function() {
  4226. $rootScope.$evalAsync(scroll);
  4227. });
  4228. });
  4229. }
  4230. return scroll;
  4231. }];
  4232. }
  4233. var $animateMinErr = minErr('$animate');
  4234. var ELEMENT_NODE = 1;
  4235. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  4236. function mergeClasses(a,b) {
  4237. if (!a && !b) return '';
  4238. if (!a) return b;
  4239. if (!b) return a;
  4240. if (isArray(a)) a = a.join(' ');
  4241. if (isArray(b)) b = b.join(' ');
  4242. return a + ' ' + b;
  4243. }
  4244. function extractElementNode(element) {
  4245. for (var i = 0; i < element.length; i++) {
  4246. var elm = element[i];
  4247. if (elm.nodeType === ELEMENT_NODE) {
  4248. return elm;
  4249. }
  4250. }
  4251. }
  4252. function splitClasses(classes) {
  4253. if (isString(classes)) {
  4254. classes = classes.split(' ');
  4255. }
  4256. // Use createMap() to prevent class assumptions involving property names in
  4257. // Object.prototype
  4258. var obj = createMap();
  4259. forEach(classes, function(klass) {
  4260. // sometimes the split leaves empty string values
  4261. // incase extra spaces were applied to the options
  4262. if (klass.length) {
  4263. obj[klass] = true;
  4264. }
  4265. });
  4266. return obj;
  4267. }
  4268. // if any other type of options value besides an Object value is
  4269. // passed into the $animate.method() animation then this helper code
  4270. // will be run which will ignore it. While this patch is not the
  4271. // greatest solution to this, a lot of existing plugins depend on
  4272. // $animate to either call the callback (< 1.2) or return a promise
  4273. // that can be changed. This helper function ensures that the options
  4274. // are wiped clean incase a callback function is provided.
  4275. function prepareAnimateOptions(options) {
  4276. return isObject(options)
  4277. ? options
  4278. : {};
  4279. }
  4280. var $$CoreAnimateRunnerProvider = function() {
  4281. this.$get = ['$q', '$$rAF', function($q, $$rAF) {
  4282. function AnimateRunner() {}
  4283. AnimateRunner.all = noop;
  4284. AnimateRunner.chain = noop;
  4285. AnimateRunner.prototype = {
  4286. end: noop,
  4287. cancel: noop,
  4288. resume: noop,
  4289. pause: noop,
  4290. complete: noop,
  4291. then: function(pass, fail) {
  4292. return $q(function(resolve) {
  4293. $$rAF(function() {
  4294. resolve();
  4295. });
  4296. }).then(pass, fail);
  4297. }
  4298. };
  4299. return AnimateRunner;
  4300. }];
  4301. };
  4302. // this is prefixed with Core since it conflicts with
  4303. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  4304. var $$CoreAnimateQueueProvider = function() {
  4305. var postDigestQueue = new HashMap();
  4306. var postDigestElements = [];
  4307. this.$get = ['$$AnimateRunner', '$rootScope',
  4308. function($$AnimateRunner, $rootScope) {
  4309. return {
  4310. enabled: noop,
  4311. on: noop,
  4312. off: noop,
  4313. pin: noop,
  4314. push: function(element, event, options, domOperation) {
  4315. domOperation && domOperation();
  4316. options = options || {};
  4317. options.from && element.css(options.from);
  4318. options.to && element.css(options.to);
  4319. if (options.addClass || options.removeClass) {
  4320. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  4321. }
  4322. return new $$AnimateRunner(); // jshint ignore:line
  4323. }
  4324. };
  4325. function addRemoveClassesPostDigest(element, add, remove) {
  4326. var data = postDigestQueue.get(element);
  4327. var classVal;
  4328. if (!data) {
  4329. postDigestQueue.put(element, data = {});
  4330. postDigestElements.push(element);
  4331. }
  4332. if (add) {
  4333. forEach(add.split(' '), function(className) {
  4334. if (className) {
  4335. data[className] = true;
  4336. }
  4337. });
  4338. }
  4339. if (remove) {
  4340. forEach(remove.split(' '), function(className) {
  4341. if (className) {
  4342. data[className] = false;
  4343. }
  4344. });
  4345. }
  4346. if (postDigestElements.length > 1) return;
  4347. $rootScope.$$postDigest(function() {
  4348. forEach(postDigestElements, function(element) {
  4349. var data = postDigestQueue.get(element);
  4350. if (data) {
  4351. var existing = splitClasses(element.attr('class'));
  4352. var toAdd = '';
  4353. var toRemove = '';
  4354. forEach(data, function(status, className) {
  4355. var hasClass = !!existing[className];
  4356. if (status !== hasClass) {
  4357. if (status) {
  4358. toAdd += (toAdd.length ? ' ' : '') + className;
  4359. } else {
  4360. toRemove += (toRemove.length ? ' ' : '') + className;
  4361. }
  4362. }
  4363. });
  4364. forEach(element, function(elm) {
  4365. toAdd && jqLiteAddClass(elm, toAdd);
  4366. toRemove && jqLiteRemoveClass(elm, toRemove);
  4367. });
  4368. postDigestQueue.remove(element);
  4369. }
  4370. });
  4371. postDigestElements.length = 0;
  4372. });
  4373. }
  4374. }];
  4375. };
  4376. /**
  4377. * @ngdoc provider
  4378. * @name $animateProvider
  4379. *
  4380. * @description
  4381. * Default implementation of $animate that doesn't perform any animations, instead just
  4382. * synchronously performs DOM updates and resolves the returned runner promise.
  4383. *
  4384. * In order to enable animations the `ngAnimate` module has to be loaded.
  4385. *
  4386. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  4387. */
  4388. var $AnimateProvider = ['$provide', function($provide) {
  4389. var provider = this;
  4390. this.$$registeredAnimations = Object.create(null);
  4391. /**
  4392. * @ngdoc method
  4393. * @name $animateProvider#register
  4394. *
  4395. * @description
  4396. * Registers a new injectable animation factory function. The factory function produces the
  4397. * animation object which contains callback functions for each event that is expected to be
  4398. * animated.
  4399. *
  4400. * * `eventFn`: `function(element, ... , doneFunction, options)`
  4401. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  4402. * on the type of animation additional arguments will be injected into the animation function. The
  4403. * list below explains the function signatures for the different animation methods:
  4404. *
  4405. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  4406. * - addClass: function(element, addedClasses, doneFunction, options)
  4407. * - removeClass: function(element, removedClasses, doneFunction, options)
  4408. * - enter, leave, move: function(element, doneFunction, options)
  4409. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  4410. *
  4411. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  4412. *
  4413. * ```js
  4414. * return {
  4415. * //enter, leave, move signature
  4416. * eventFn : function(element, done, options) {
  4417. * //code to run the animation
  4418. * //once complete, then run done()
  4419. * return function endFunction(wasCancelled) {
  4420. * //code to cancel the animation
  4421. * }
  4422. * }
  4423. * }
  4424. * ```
  4425. *
  4426. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  4427. * @param {Function} factory The factory function that will be executed to return the animation
  4428. * object.
  4429. */
  4430. this.register = function(name, factory) {
  4431. if (name && name.charAt(0) !== '.') {
  4432. throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name);
  4433. }
  4434. var key = name + '-animation';
  4435. provider.$$registeredAnimations[name.substr(1)] = key;
  4436. $provide.factory(key, factory);
  4437. };
  4438. /**
  4439. * @ngdoc method
  4440. * @name $animateProvider#classNameFilter
  4441. *
  4442. * @description
  4443. * Sets and/or returns the CSS class regular expression that is checked when performing
  4444. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4445. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  4446. * When setting the `classNameFilter` value, animations will only be performed on elements
  4447. * that successfully match the filter expression. This in turn can boost performance
  4448. * for low-powered devices as well as applications containing a lot of structural operations.
  4449. * @param {RegExp=} expression The className expression which will be checked against all animations
  4450. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4451. */
  4452. this.classNameFilter = function(expression) {
  4453. if (arguments.length === 1) {
  4454. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  4455. if (this.$$classNameFilter) {
  4456. var reservedRegex = new RegExp("(\\s+|\\/)" + NG_ANIMATE_CLASSNAME + "(\\s+|\\/)");
  4457. if (reservedRegex.test(this.$$classNameFilter.toString())) {
  4458. throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  4459. }
  4460. }
  4461. }
  4462. return this.$$classNameFilter;
  4463. };
  4464. this.$get = ['$$animateQueue', function($$animateQueue) {
  4465. function domInsert(element, parentElement, afterElement) {
  4466. // if for some reason the previous element was removed
  4467. // from the dom sometime before this code runs then let's
  4468. // just stick to using the parent element as the anchor
  4469. if (afterElement) {
  4470. var afterNode = extractElementNode(afterElement);
  4471. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  4472. afterElement = null;
  4473. }
  4474. }
  4475. afterElement ? afterElement.after(element) : parentElement.prepend(element);
  4476. }
  4477. /**
  4478. * @ngdoc service
  4479. * @name $animate
  4480. * @description The $animate service exposes a series of DOM utility methods that provide support
  4481. * for animation hooks. The default behavior is the application of DOM operations, however,
  4482. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  4483. * to ensure that animation runs with the triggered DOM operation.
  4484. *
  4485. * By default $animate doesn't trigger an animations. This is because the `ngAnimate` module isn't
  4486. * included and only when it is active then the animation hooks that `$animate` triggers will be
  4487. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  4488. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  4489. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  4490. *
  4491. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  4492. *
  4493. * To learn more about enabling animation support, click here to visit the
  4494. * {@link ngAnimate ngAnimate module page}.
  4495. */
  4496. return {
  4497. // we don't call it directly since non-existant arguments may
  4498. // be interpreted as null within the sub enabled function
  4499. /**
  4500. *
  4501. * @ngdoc method
  4502. * @name $animate#on
  4503. * @kind function
  4504. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  4505. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  4506. * is fired with the following params:
  4507. *
  4508. * ```js
  4509. * $animate.on('enter', container,
  4510. * function callback(element, phase) {
  4511. * // cool we detected an enter animation within the container
  4512. * }
  4513. * );
  4514. * ```
  4515. *
  4516. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  4517. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  4518. * as well as among its children
  4519. * @param {Function} callback the callback function that will be fired when the listener is triggered
  4520. *
  4521. * The arguments present in the callback function are:
  4522. * * `element` - The captured DOM element that the animation was fired on.
  4523. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  4524. */
  4525. on: $$animateQueue.on,
  4526. /**
  4527. *
  4528. * @ngdoc method
  4529. * @name $animate#off
  4530. * @kind function
  4531. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  4532. * can be used in three different ways depending on the arguments:
  4533. *
  4534. * ```js
  4535. * // remove all the animation event listeners listening for `enter`
  4536. * $animate.off('enter');
  4537. *
  4538. * // remove all the animation event listeners listening for `enter` on the given element and its children
  4539. * $animate.off('enter', container);
  4540. *
  4541. * // remove the event listener function provided by `listenerFn` that is set
  4542. * // to listen for `enter` on the given `element` as well as its children
  4543. * $animate.off('enter', container, callback);
  4544. * ```
  4545. *
  4546. * @param {string} event the animation event (e.g. enter, leave, move, addClass, removeClass, etc...)
  4547. * @param {DOMElement=} container the container element the event listener was placed on
  4548. * @param {Function=} callback the callback function that was registered as the listener
  4549. */
  4550. off: $$animateQueue.off,
  4551. /**
  4552. * @ngdoc method
  4553. * @name $animate#pin
  4554. * @kind function
  4555. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  4556. * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
  4557. * element despite being outside the realm of the application or within another application. Say for example if the application
  4558. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  4559. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  4560. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  4561. *
  4562. * Note that this feature is only active when the `ngAnimate` module is used.
  4563. *
  4564. * @param {DOMElement} element the external element that will be pinned
  4565. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  4566. */
  4567. pin: $$animateQueue.pin,
  4568. /**
  4569. *
  4570. * @ngdoc method
  4571. * @name $animate#enabled
  4572. * @kind function
  4573. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  4574. * function can be called in four ways:
  4575. *
  4576. * ```js
  4577. * // returns true or false
  4578. * $animate.enabled();
  4579. *
  4580. * // changes the enabled state for all animations
  4581. * $animate.enabled(false);
  4582. * $animate.enabled(true);
  4583. *
  4584. * // returns true or false if animations are enabled for an element
  4585. * $animate.enabled(element);
  4586. *
  4587. * // changes the enabled state for an element and its children
  4588. * $animate.enabled(element, true);
  4589. * $animate.enabled(element, false);
  4590. * ```
  4591. *
  4592. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  4593. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  4594. *
  4595. * @return {boolean} whether or not animations are enabled
  4596. */
  4597. enabled: $$animateQueue.enabled,
  4598. /**
  4599. * @ngdoc method
  4600. * @name $animate#cancel
  4601. * @kind function
  4602. * @description Cancels the provided animation.
  4603. *
  4604. * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
  4605. */
  4606. cancel: function(runner) {
  4607. runner.end && runner.end();
  4608. },
  4609. /**
  4610. *
  4611. * @ngdoc method
  4612. * @name $animate#enter
  4613. * @kind function
  4614. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  4615. * as the first child within the `parent` element and then triggers an animation.
  4616. * A promise is returned that will be resolved during the next digest once the animation
  4617. * has completed.
  4618. *
  4619. * @param {DOMElement} element the element which will be inserted into the DOM
  4620. * @param {DOMElement} parent the parent element which will append the element as
  4621. * a child (so long as the after element is not present)
  4622. * @param {DOMElement=} after the sibling element after which the element will be appended
  4623. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4624. *
  4625. * @return {Promise} the animation callback promise
  4626. */
  4627. enter: function(element, parent, after, options) {
  4628. parent = parent && jqLite(parent);
  4629. after = after && jqLite(after);
  4630. parent = parent || after.parent();
  4631. domInsert(element, parent, after);
  4632. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  4633. },
  4634. /**
  4635. *
  4636. * @ngdoc method
  4637. * @name $animate#move
  4638. * @kind function
  4639. * @description Inserts (moves) the element into its new position in the DOM either after
  4640. * the `after` element (if provided) or as the first child within the `parent` element
  4641. * and then triggers an animation. A promise is returned that will be resolved
  4642. * during the next digest once the animation has completed.
  4643. *
  4644. * @param {DOMElement} element the element which will be moved into the new DOM position
  4645. * @param {DOMElement} parent the parent element which will append the element as
  4646. * a child (so long as the after element is not present)
  4647. * @param {DOMElement=} after the sibling element after which the element will be appended
  4648. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4649. *
  4650. * @return {Promise} the animation callback promise
  4651. */
  4652. move: function(element, parent, after, options) {
  4653. parent = parent && jqLite(parent);
  4654. after = after && jqLite(after);
  4655. parent = parent || after.parent();
  4656. domInsert(element, parent, after);
  4657. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  4658. },
  4659. /**
  4660. * @ngdoc method
  4661. * @name $animate#leave
  4662. * @kind function
  4663. * @description Triggers an animation and then removes the element from the DOM.
  4664. * When the function is called a promise is returned that will be resolved during the next
  4665. * digest once the animation has completed.
  4666. *
  4667. * @param {DOMElement} element the element which will be removed from the DOM
  4668. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4669. *
  4670. * @return {Promise} the animation callback promise
  4671. */
  4672. leave: function(element, options) {
  4673. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  4674. element.remove();
  4675. });
  4676. },
  4677. /**
  4678. * @ngdoc method
  4679. * @name $animate#addClass
  4680. * @kind function
  4681. *
  4682. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  4683. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  4684. * animation if element already contains the CSS class or if the class is removed at a later step.
  4685. * Note that class-based animations are treated differently compared to structural animations
  4686. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4687. * depending if CSS or JavaScript animations are used.
  4688. *
  4689. * @param {DOMElement} element the element which the CSS classes will be applied to
  4690. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  4691. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4692. *
  4693. * @return {Promise} the animation callback promise
  4694. */
  4695. addClass: function(element, className, options) {
  4696. options = prepareAnimateOptions(options);
  4697. options.addClass = mergeClasses(options.addclass, className);
  4698. return $$animateQueue.push(element, 'addClass', options);
  4699. },
  4700. /**
  4701. * @ngdoc method
  4702. * @name $animate#removeClass
  4703. * @kind function
  4704. *
  4705. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  4706. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  4707. * animation if element does not contain the CSS class or if the class is added at a later step.
  4708. * Note that class-based animations are treated differently compared to structural animations
  4709. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4710. * depending if CSS or JavaScript animations are used.
  4711. *
  4712. * @param {DOMElement} element the element which the CSS classes will be applied to
  4713. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  4714. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4715. *
  4716. * @return {Promise} the animation callback promise
  4717. */
  4718. removeClass: function(element, className, options) {
  4719. options = prepareAnimateOptions(options);
  4720. options.removeClass = mergeClasses(options.removeClass, className);
  4721. return $$animateQueue.push(element, 'removeClass', options);
  4722. },
  4723. /**
  4724. * @ngdoc method
  4725. * @name $animate#setClass
  4726. * @kind function
  4727. *
  4728. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  4729. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  4730. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  4731. * passed. Note that class-based animations are treated differently compared to structural animations
  4732. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4733. * depending if CSS or JavaScript animations are used.
  4734. *
  4735. * @param {DOMElement} element the element which the CSS classes will be applied to
  4736. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  4737. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  4738. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4739. *
  4740. * @return {Promise} the animation callback promise
  4741. */
  4742. setClass: function(element, add, remove, options) {
  4743. options = prepareAnimateOptions(options);
  4744. options.addClass = mergeClasses(options.addClass, add);
  4745. options.removeClass = mergeClasses(options.removeClass, remove);
  4746. return $$animateQueue.push(element, 'setClass', options);
  4747. },
  4748. /**
  4749. * @ngdoc method
  4750. * @name $animate#animate
  4751. * @kind function
  4752. *
  4753. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  4754. * If any detected CSS transition, keyframe or JavaScript matches the provided className value then the animation will take
  4755. * on the provided styles. For example, if a transition animation is set for the given className then the provided from and
  4756. * to styles will be applied alongside the given transition. If a JavaScript animation is detected then the provided styles
  4757. * will be given in as function paramters into the `animate` method (or as apart of the `options` parameter).
  4758. *
  4759. * @param {DOMElement} element the element which the CSS styles will be applied to
  4760. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  4761. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  4762. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  4763. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  4764. * (Note that if no animation is detected then this value will not be appplied to the element.)
  4765. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4766. *
  4767. * @return {Promise} the animation callback promise
  4768. */
  4769. animate: function(element, from, to, className, options) {
  4770. options = prepareAnimateOptions(options);
  4771. options.from = options.from ? extend(options.from, from) : from;
  4772. options.to = options.to ? extend(options.to, to) : to;
  4773. className = className || 'ng-inline-animate';
  4774. options.tempClasses = mergeClasses(options.tempClasses, className);
  4775. return $$animateQueue.push(element, 'animate', options);
  4776. }
  4777. };
  4778. }];
  4779. }];
  4780. function $$AsyncCallbackProvider() {
  4781. this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) {
  4782. return $$rAF.supported
  4783. ? function(fn) { return $$rAF(fn); }
  4784. : function(fn) {
  4785. return $timeout(fn, 0, false);
  4786. };
  4787. }];
  4788. }
  4789. /* global stripHash: true */
  4790. /**
  4791. * ! This is a private undocumented service !
  4792. *
  4793. * @name $browser
  4794. * @requires $log
  4795. * @description
  4796. * This object has two goals:
  4797. *
  4798. * - hide all the global state in the browser caused by the window object
  4799. * - abstract away all the browser specific features and inconsistencies
  4800. *
  4801. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  4802. * service, which can be used for convenient testing of the application without the interaction with
  4803. * the real browser apis.
  4804. */
  4805. /**
  4806. * @param {object} window The global window object.
  4807. * @param {object} document jQuery wrapped document.
  4808. * @param {object} $log window.console or an object with the same interface.
  4809. * @param {object} $sniffer $sniffer service
  4810. */
  4811. function Browser(window, document, $log, $sniffer) {
  4812. var self = this,
  4813. rawDocument = document[0],
  4814. location = window.location,
  4815. history = window.history,
  4816. setTimeout = window.setTimeout,
  4817. clearTimeout = window.clearTimeout,
  4818. pendingDeferIds = {};
  4819. self.isMock = false;
  4820. var outstandingRequestCount = 0;
  4821. var outstandingRequestCallbacks = [];
  4822. // TODO(vojta): remove this temporary api
  4823. self.$$completeOutstandingRequest = completeOutstandingRequest;
  4824. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  4825. /**
  4826. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  4827. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  4828. */
  4829. function completeOutstandingRequest(fn) {
  4830. try {
  4831. fn.apply(null, sliceArgs(arguments, 1));
  4832. } finally {
  4833. outstandingRequestCount--;
  4834. if (outstandingRequestCount === 0) {
  4835. while (outstandingRequestCallbacks.length) {
  4836. try {
  4837. outstandingRequestCallbacks.pop()();
  4838. } catch (e) {
  4839. $log.error(e);
  4840. }
  4841. }
  4842. }
  4843. }
  4844. }
  4845. function getHash(url) {
  4846. var index = url.indexOf('#');
  4847. return index === -1 ? '' : url.substr(index + 1);
  4848. }
  4849. /**
  4850. * @private
  4851. * Note: this method is used only by scenario runner
  4852. * TODO(vojta): prefix this method with $$ ?
  4853. * @param {function()} callback Function that will be called when no outstanding request
  4854. */
  4855. self.notifyWhenNoOutstandingRequests = function(callback) {
  4856. if (outstandingRequestCount === 0) {
  4857. callback();
  4858. } else {
  4859. outstandingRequestCallbacks.push(callback);
  4860. }
  4861. };
  4862. //////////////////////////////////////////////////////////////
  4863. // URL API
  4864. //////////////////////////////////////////////////////////////
  4865. var cachedState, lastHistoryState,
  4866. lastBrowserUrl = location.href,
  4867. baseElement = document.find('base'),
  4868. reloadLocation = null;
  4869. cacheState();
  4870. lastHistoryState = cachedState;
  4871. /**
  4872. * @name $browser#url
  4873. *
  4874. * @description
  4875. * GETTER:
  4876. * Without any argument, this method just returns current value of location.href.
  4877. *
  4878. * SETTER:
  4879. * With at least one argument, this method sets url to new value.
  4880. * If html5 history api supported, pushState/replaceState is used, otherwise
  4881. * location.href/location.replace is used.
  4882. * Returns its own instance to allow chaining
  4883. *
  4884. * NOTE: this api is intended for use only by the $location service. Please use the
  4885. * {@link ng.$location $location service} to change url.
  4886. *
  4887. * @param {string} url New url (when used as setter)
  4888. * @param {boolean=} replace Should new url replace current history record?
  4889. * @param {object=} state object to use with pushState/replaceState
  4890. */
  4891. self.url = function(url, replace, state) {
  4892. // In modern browsers `history.state` is `null` by default; treating it separately
  4893. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  4894. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  4895. if (isUndefined(state)) {
  4896. state = null;
  4897. }
  4898. // Android Browser BFCache causes location, history reference to become stale.
  4899. if (location !== window.location) location = window.location;
  4900. if (history !== window.history) history = window.history;
  4901. // setter
  4902. if (url) {
  4903. var sameState = lastHistoryState === state;
  4904. // Don't change anything if previous and current URLs and states match. This also prevents
  4905. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  4906. // See https://github.com/angular/angular.js/commit/ffb2701
  4907. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  4908. return self;
  4909. }
  4910. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  4911. lastBrowserUrl = url;
  4912. lastHistoryState = state;
  4913. // Don't use history API if only the hash changed
  4914. // due to a bug in IE10/IE11 which leads
  4915. // to not firing a `hashchange` nor `popstate` event
  4916. // in some cases (see #9143).
  4917. if ($sniffer.history && (!sameBase || !sameState)) {
  4918. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  4919. cacheState();
  4920. // Do the assignment again so that those two variables are referentially identical.
  4921. lastHistoryState = cachedState;
  4922. } else {
  4923. if (!sameBase) {
  4924. reloadLocation = url;
  4925. }
  4926. if (replace) {
  4927. location.replace(url);
  4928. } else if (!sameBase) {
  4929. location.href = url;
  4930. } else {
  4931. location.hash = getHash(url);
  4932. }
  4933. }
  4934. return self;
  4935. // getter
  4936. } else {
  4937. // - reloadLocation is needed as browsers don't allow to read out
  4938. // the new location.href if a reload happened.
  4939. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  4940. return reloadLocation || location.href.replace(/%27/g,"'");
  4941. }
  4942. };
  4943. /**
  4944. * @name $browser#state
  4945. *
  4946. * @description
  4947. * This method is a getter.
  4948. *
  4949. * Return history.state or null if history.state is undefined.
  4950. *
  4951. * @returns {object} state
  4952. */
  4953. self.state = function() {
  4954. return cachedState;
  4955. };
  4956. var urlChangeListeners = [],
  4957. urlChangeInit = false;
  4958. function cacheStateAndFireUrlChange() {
  4959. cacheState();
  4960. fireUrlChange();
  4961. }
  4962. function getCurrentState() {
  4963. try {
  4964. return history.state;
  4965. } catch (e) {
  4966. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  4967. }
  4968. }
  4969. // This variable should be used *only* inside the cacheState function.
  4970. var lastCachedState = null;
  4971. function cacheState() {
  4972. // This should be the only place in $browser where `history.state` is read.
  4973. cachedState = getCurrentState();
  4974. cachedState = isUndefined(cachedState) ? null : cachedState;
  4975. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  4976. if (equals(cachedState, lastCachedState)) {
  4977. cachedState = lastCachedState;
  4978. }
  4979. lastCachedState = cachedState;
  4980. }
  4981. function fireUrlChange() {
  4982. if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
  4983. return;
  4984. }
  4985. lastBrowserUrl = self.url();
  4986. lastHistoryState = cachedState;
  4987. forEach(urlChangeListeners, function(listener) {
  4988. listener(self.url(), cachedState);
  4989. });
  4990. }
  4991. /**
  4992. * @name $browser#onUrlChange
  4993. *
  4994. * @description
  4995. * Register callback function that will be called, when url changes.
  4996. *
  4997. * It's only called when the url is changed from outside of angular:
  4998. * - user types different url into address bar
  4999. * - user clicks on history (forward/back) button
  5000. * - user clicks on a link
  5001. *
  5002. * It's not called when url is changed by $browser.url() method
  5003. *
  5004. * The listener gets called with new url as parameter.
  5005. *
  5006. * NOTE: this api is intended for use only by the $location service. Please use the
  5007. * {@link ng.$location $location service} to monitor url changes in angular apps.
  5008. *
  5009. * @param {function(string)} listener Listener function to be called when url changes.
  5010. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  5011. */
  5012. self.onUrlChange = function(callback) {
  5013. // TODO(vojta): refactor to use node's syntax for events
  5014. if (!urlChangeInit) {
  5015. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  5016. // don't fire popstate when user change the address bar and don't fire hashchange when url
  5017. // changed by push/replaceState
  5018. // html5 history api - popstate event
  5019. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  5020. // hashchange event
  5021. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  5022. urlChangeInit = true;
  5023. }
  5024. urlChangeListeners.push(callback);
  5025. return callback;
  5026. };
  5027. /**
  5028. * @private
  5029. * Remove popstate and hashchange handler from window.
  5030. *
  5031. * NOTE: this api is intended for use only by $rootScope.
  5032. */
  5033. self.$$applicationDestroyed = function() {
  5034. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  5035. };
  5036. /**
  5037. * Checks whether the url has changed outside of Angular.
  5038. * Needs to be exported to be able to check for changes that have been done in sync,
  5039. * as hashchange/popstate events fire in async.
  5040. */
  5041. self.$$checkUrlChange = fireUrlChange;
  5042. //////////////////////////////////////////////////////////////
  5043. // Misc API
  5044. //////////////////////////////////////////////////////////////
  5045. /**
  5046. * @name $browser#baseHref
  5047. *
  5048. * @description
  5049. * Returns current <base href>
  5050. * (always relative - without domain)
  5051. *
  5052. * @returns {string} The current base href
  5053. */
  5054. self.baseHref = function() {
  5055. var href = baseElement.attr('href');
  5056. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  5057. };
  5058. /**
  5059. * @name $browser#defer
  5060. * @param {function()} fn A function, who's execution should be deferred.
  5061. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  5062. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  5063. *
  5064. * @description
  5065. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  5066. *
  5067. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  5068. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  5069. * via `$browser.defer.flush()`.
  5070. *
  5071. */
  5072. self.defer = function(fn, delay) {
  5073. var timeoutId;
  5074. outstandingRequestCount++;
  5075. timeoutId = setTimeout(function() {
  5076. delete pendingDeferIds[timeoutId];
  5077. completeOutstandingRequest(fn);
  5078. }, delay || 0);
  5079. pendingDeferIds[timeoutId] = true;
  5080. return timeoutId;
  5081. };
  5082. /**
  5083. * @name $browser#defer.cancel
  5084. *
  5085. * @description
  5086. * Cancels a deferred task identified with `deferId`.
  5087. *
  5088. * @param {*} deferId Token returned by the `$browser.defer` function.
  5089. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  5090. * canceled.
  5091. */
  5092. self.defer.cancel = function(deferId) {
  5093. if (pendingDeferIds[deferId]) {
  5094. delete pendingDeferIds[deferId];
  5095. clearTimeout(deferId);
  5096. completeOutstandingRequest(noop);
  5097. return true;
  5098. }
  5099. return false;
  5100. };
  5101. }
  5102. function $BrowserProvider() {
  5103. this.$get = ['$window', '$log', '$sniffer', '$document',
  5104. function($window, $log, $sniffer, $document) {
  5105. return new Browser($window, $document, $log, $sniffer);
  5106. }];
  5107. }
  5108. /**
  5109. * @ngdoc service
  5110. * @name $cacheFactory
  5111. *
  5112. * @description
  5113. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  5114. * them.
  5115. *
  5116. * ```js
  5117. *
  5118. * var cache = $cacheFactory('cacheId');
  5119. * expect($cacheFactory.get('cacheId')).toBe(cache);
  5120. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  5121. *
  5122. * cache.put("key", "value");
  5123. * cache.put("another key", "another value");
  5124. *
  5125. * // We've specified no options on creation
  5126. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  5127. *
  5128. * ```
  5129. *
  5130. *
  5131. * @param {string} cacheId Name or id of the newly created cache.
  5132. * @param {object=} options Options object that specifies the cache behavior. Properties:
  5133. *
  5134. * - `{number=}` `capacity` — turns the cache into LRU cache.
  5135. *
  5136. * @returns {object} Newly created cache object with the following set of methods:
  5137. *
  5138. * - `{object}` `info()` — Returns id, size, and options of cache.
  5139. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  5140. * it.
  5141. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  5142. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  5143. * - `{void}` `removeAll()` — Removes all cached values.
  5144. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  5145. *
  5146. * @example
  5147. <example module="cacheExampleApp">
  5148. <file name="index.html">
  5149. <div ng-controller="CacheController">
  5150. <input ng-model="newCacheKey" placeholder="Key">
  5151. <input ng-model="newCacheValue" placeholder="Value">
  5152. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  5153. <p ng-if="keys.length">Cached Values</p>
  5154. <div ng-repeat="key in keys">
  5155. <span ng-bind="key"></span>
  5156. <span>: </span>
  5157. <b ng-bind="cache.get(key)"></b>
  5158. </div>
  5159. <p>Cache Info</p>
  5160. <div ng-repeat="(key, value) in cache.info()">
  5161. <span ng-bind="key"></span>
  5162. <span>: </span>
  5163. <b ng-bind="value"></b>
  5164. </div>
  5165. </div>
  5166. </file>
  5167. <file name="script.js">
  5168. angular.module('cacheExampleApp', []).
  5169. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  5170. $scope.keys = [];
  5171. $scope.cache = $cacheFactory('cacheId');
  5172. $scope.put = function(key, value) {
  5173. if ($scope.cache.get(key) === undefined) {
  5174. $scope.keys.push(key);
  5175. }
  5176. $scope.cache.put(key, value === undefined ? null : value);
  5177. };
  5178. }]);
  5179. </file>
  5180. <file name="style.css">
  5181. p {
  5182. margin: 10px 0 3px;
  5183. }
  5184. </file>
  5185. </example>
  5186. */
  5187. function $CacheFactoryProvider() {
  5188. this.$get = function() {
  5189. var caches = {};
  5190. function cacheFactory(cacheId, options) {
  5191. if (cacheId in caches) {
  5192. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  5193. }
  5194. var size = 0,
  5195. stats = extend({}, options, {id: cacheId}),
  5196. data = {},
  5197. capacity = (options && options.capacity) || Number.MAX_VALUE,
  5198. lruHash = {},
  5199. freshEnd = null,
  5200. staleEnd = null;
  5201. /**
  5202. * @ngdoc type
  5203. * @name $cacheFactory.Cache
  5204. *
  5205. * @description
  5206. * A cache object used to store and retrieve data, primarily used by
  5207. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  5208. * templates and other data.
  5209. *
  5210. * ```js
  5211. * angular.module('superCache')
  5212. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  5213. * return $cacheFactory('super-cache');
  5214. * }]);
  5215. * ```
  5216. *
  5217. * Example test:
  5218. *
  5219. * ```js
  5220. * it('should behave like a cache', inject(function(superCache) {
  5221. * superCache.put('key', 'value');
  5222. * superCache.put('another key', 'another value');
  5223. *
  5224. * expect(superCache.info()).toEqual({
  5225. * id: 'super-cache',
  5226. * size: 2
  5227. * });
  5228. *
  5229. * superCache.remove('another key');
  5230. * expect(superCache.get('another key')).toBeUndefined();
  5231. *
  5232. * superCache.removeAll();
  5233. * expect(superCache.info()).toEqual({
  5234. * id: 'super-cache',
  5235. * size: 0
  5236. * });
  5237. * }));
  5238. * ```
  5239. */
  5240. return caches[cacheId] = {
  5241. /**
  5242. * @ngdoc method
  5243. * @name $cacheFactory.Cache#put
  5244. * @kind function
  5245. *
  5246. * @description
  5247. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  5248. * retrieved later, and incrementing the size of the cache if the key was not already
  5249. * present in the cache. If behaving like an LRU cache, it will also remove stale
  5250. * entries from the set.
  5251. *
  5252. * It will not insert undefined values into the cache.
  5253. *
  5254. * @param {string} key the key under which the cached data is stored.
  5255. * @param {*} value the value to store alongside the key. If it is undefined, the key
  5256. * will not be stored.
  5257. * @returns {*} the value stored.
  5258. */
  5259. put: function(key, value) {
  5260. if (isUndefined(value)) return;
  5261. if (capacity < Number.MAX_VALUE) {
  5262. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  5263. refresh(lruEntry);
  5264. }
  5265. if (!(key in data)) size++;
  5266. data[key] = value;
  5267. if (size > capacity) {
  5268. this.remove(staleEnd.key);
  5269. }
  5270. return value;
  5271. },
  5272. /**
  5273. * @ngdoc method
  5274. * @name $cacheFactory.Cache#get
  5275. * @kind function
  5276. *
  5277. * @description
  5278. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  5279. *
  5280. * @param {string} key the key of the data to be retrieved
  5281. * @returns {*} the value stored.
  5282. */
  5283. get: function(key) {
  5284. if (capacity < Number.MAX_VALUE) {
  5285. var lruEntry = lruHash[key];
  5286. if (!lruEntry) return;
  5287. refresh(lruEntry);
  5288. }
  5289. return data[key];
  5290. },
  5291. /**
  5292. * @ngdoc method
  5293. * @name $cacheFactory.Cache#remove
  5294. * @kind function
  5295. *
  5296. * @description
  5297. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  5298. *
  5299. * @param {string} key the key of the entry to be removed
  5300. */
  5301. remove: function(key) {
  5302. if (capacity < Number.MAX_VALUE) {
  5303. var lruEntry = lruHash[key];
  5304. if (!lruEntry) return;
  5305. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  5306. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  5307. link(lruEntry.n,lruEntry.p);
  5308. delete lruHash[key];
  5309. }
  5310. delete data[key];
  5311. size--;
  5312. },
  5313. /**
  5314. * @ngdoc method
  5315. * @name $cacheFactory.Cache#removeAll
  5316. * @kind function
  5317. *
  5318. * @description
  5319. * Clears the cache object of any entries.
  5320. */
  5321. removeAll: function() {
  5322. data = {};
  5323. size = 0;
  5324. lruHash = {};
  5325. freshEnd = staleEnd = null;
  5326. },
  5327. /**
  5328. * @ngdoc method
  5329. * @name $cacheFactory.Cache#destroy
  5330. * @kind function
  5331. *
  5332. * @description
  5333. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  5334. * removing it from the {@link $cacheFactory $cacheFactory} set.
  5335. */
  5336. destroy: function() {
  5337. data = null;
  5338. stats = null;
  5339. lruHash = null;
  5340. delete caches[cacheId];
  5341. },
  5342. /**
  5343. * @ngdoc method
  5344. * @name $cacheFactory.Cache#info
  5345. * @kind function
  5346. *
  5347. * @description
  5348. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  5349. *
  5350. * @returns {object} an object with the following properties:
  5351. * <ul>
  5352. * <li>**id**: the id of the cache instance</li>
  5353. * <li>**size**: the number of entries kept in the cache instance</li>
  5354. * <li>**...**: any additional properties from the options object when creating the
  5355. * cache.</li>
  5356. * </ul>
  5357. */
  5358. info: function() {
  5359. return extend({}, stats, {size: size});
  5360. }
  5361. };
  5362. /**
  5363. * makes the `entry` the freshEnd of the LRU linked list
  5364. */
  5365. function refresh(entry) {
  5366. if (entry != freshEnd) {
  5367. if (!staleEnd) {
  5368. staleEnd = entry;
  5369. } else if (staleEnd == entry) {
  5370. staleEnd = entry.n;
  5371. }
  5372. link(entry.n, entry.p);
  5373. link(entry, freshEnd);
  5374. freshEnd = entry;
  5375. freshEnd.n = null;
  5376. }
  5377. }
  5378. /**
  5379. * bidirectionally links two entries of the LRU linked list
  5380. */
  5381. function link(nextEntry, prevEntry) {
  5382. if (nextEntry != prevEntry) {
  5383. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  5384. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  5385. }
  5386. }
  5387. }
  5388. /**
  5389. * @ngdoc method
  5390. * @name $cacheFactory#info
  5391. *
  5392. * @description
  5393. * Get information about all the caches that have been created
  5394. *
  5395. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  5396. */
  5397. cacheFactory.info = function() {
  5398. var info = {};
  5399. forEach(caches, function(cache, cacheId) {
  5400. info[cacheId] = cache.info();
  5401. });
  5402. return info;
  5403. };
  5404. /**
  5405. * @ngdoc method
  5406. * @name $cacheFactory#get
  5407. *
  5408. * @description
  5409. * Get access to a cache object by the `cacheId` used when it was created.
  5410. *
  5411. * @param {string} cacheId Name or id of a cache to access.
  5412. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  5413. */
  5414. cacheFactory.get = function(cacheId) {
  5415. return caches[cacheId];
  5416. };
  5417. return cacheFactory;
  5418. };
  5419. }
  5420. /**
  5421. * @ngdoc service
  5422. * @name $templateCache
  5423. *
  5424. * @description
  5425. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  5426. * can load templates directly into the cache in a `script` tag, or by consuming the
  5427. * `$templateCache` service directly.
  5428. *
  5429. * Adding via the `script` tag:
  5430. *
  5431. * ```html
  5432. * <script type="text/ng-template" id="templateId.html">
  5433. * <p>This is the content of the template</p>
  5434. * </script>
  5435. * ```
  5436. *
  5437. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  5438. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  5439. * element with ng-app attribute), otherwise the template will be ignored.
  5440. *
  5441. * Adding via the `$templateCache` service:
  5442. *
  5443. * ```js
  5444. * var myApp = angular.module('myApp', []);
  5445. * myApp.run(function($templateCache) {
  5446. * $templateCache.put('templateId.html', 'This is the content of the template');
  5447. * });
  5448. * ```
  5449. *
  5450. * To retrieve the template later, simply use it in your HTML:
  5451. * ```html
  5452. * <div ng-include=" 'templateId.html' "></div>
  5453. * ```
  5454. *
  5455. * or get it via Javascript:
  5456. * ```js
  5457. * $templateCache.get('templateId.html')
  5458. * ```
  5459. *
  5460. * See {@link ng.$cacheFactory $cacheFactory}.
  5461. *
  5462. */
  5463. function $TemplateCacheProvider() {
  5464. this.$get = ['$cacheFactory', function($cacheFactory) {
  5465. return $cacheFactory('templates');
  5466. }];
  5467. }
  5468. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  5469. * Any commits to this file should be reviewed with security in mind. *
  5470. * Changes to this file can potentially create security vulnerabilities. *
  5471. * An approval from 2 Core members with history of modifying *
  5472. * this file is required. *
  5473. * *
  5474. * Does the change somehow allow for arbitrary javascript to be executed? *
  5475. * Or allows for someone to change the prototype of built-in objects? *
  5476. * Or gives undesired access to variables likes document or window? *
  5477. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  5478. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  5479. *
  5480. * DOM-related variables:
  5481. *
  5482. * - "node" - DOM Node
  5483. * - "element" - DOM Element or Node
  5484. * - "$node" or "$element" - jqLite-wrapped node or element
  5485. *
  5486. *
  5487. * Compiler related stuff:
  5488. *
  5489. * - "linkFn" - linking fn of a single directive
  5490. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  5491. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  5492. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  5493. */
  5494. /**
  5495. * @ngdoc service
  5496. * @name $compile
  5497. * @kind function
  5498. *
  5499. * @description
  5500. * Compiles an HTML string or DOM into a template and produces a template function, which
  5501. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  5502. *
  5503. * The compilation is a process of walking the DOM tree and matching DOM elements to
  5504. * {@link ng.$compileProvider#directive directives}.
  5505. *
  5506. * <div class="alert alert-warning">
  5507. * **Note:** This document is an in-depth reference of all directive options.
  5508. * For a gentle introduction to directives with examples of common use cases,
  5509. * see the {@link guide/directive directive guide}.
  5510. * </div>
  5511. *
  5512. * ## Comprehensive Directive API
  5513. *
  5514. * There are many different options for a directive.
  5515. *
  5516. * The difference resides in the return value of the factory function.
  5517. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  5518. * or just the `postLink` function (all other properties will have the default values).
  5519. *
  5520. * <div class="alert alert-success">
  5521. * **Best Practice:** It's recommended to use the "directive definition object" form.
  5522. * </div>
  5523. *
  5524. * Here's an example directive declared with a Directive Definition Object:
  5525. *
  5526. * ```js
  5527. * var myModule = angular.module(...);
  5528. *
  5529. * myModule.directive('directiveName', function factory(injectables) {
  5530. * var directiveDefinitionObject = {
  5531. * priority: 0,
  5532. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  5533. * // or
  5534. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  5535. * transclude: false,
  5536. * restrict: 'A',
  5537. * templateNamespace: 'html',
  5538. * scope: false,
  5539. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  5540. * controllerAs: 'stringIdentifier',
  5541. * bindToController: false,
  5542. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  5543. * compile: function compile(tElement, tAttrs, transclude) {
  5544. * return {
  5545. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5546. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5547. * }
  5548. * // or
  5549. * // return function postLink( ... ) { ... }
  5550. * },
  5551. * // or
  5552. * // link: {
  5553. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5554. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5555. * // }
  5556. * // or
  5557. * // link: function postLink( ... ) { ... }
  5558. * };
  5559. * return directiveDefinitionObject;
  5560. * });
  5561. * ```
  5562. *
  5563. * <div class="alert alert-warning">
  5564. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  5565. * </div>
  5566. *
  5567. * Therefore the above can be simplified as:
  5568. *
  5569. * ```js
  5570. * var myModule = angular.module(...);
  5571. *
  5572. * myModule.directive('directiveName', function factory(injectables) {
  5573. * var directiveDefinitionObject = {
  5574. * link: function postLink(scope, iElement, iAttrs) { ... }
  5575. * };
  5576. * return directiveDefinitionObject;
  5577. * // or
  5578. * // return function postLink(scope, iElement, iAttrs) { ... }
  5579. * });
  5580. * ```
  5581. *
  5582. *
  5583. *
  5584. * ### Directive Definition Object
  5585. *
  5586. * The directive definition object provides instructions to the {@link ng.$compile
  5587. * compiler}. The attributes are:
  5588. *
  5589. * #### `multiElement`
  5590. * When this property is set to true, the HTML compiler will collect DOM nodes between
  5591. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  5592. * together as the directive elements. It is recommended that this feature be used on directives
  5593. * which are not strictly behavioural (such as {@link ngClick}), and which
  5594. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  5595. *
  5596. * #### `priority`
  5597. * When there are multiple directives defined on a single DOM element, sometimes it
  5598. * is necessary to specify the order in which the directives are applied. The `priority` is used
  5599. * to sort the directives before their `compile` functions get called. Priority is defined as a
  5600. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  5601. * are also run in priority order, but post-link functions are run in reverse order. The order
  5602. * of directives with the same priority is undefined. The default priority is `0`.
  5603. *
  5604. * #### `terminal`
  5605. * If set to true then the current `priority` will be the last set of directives
  5606. * which will execute (any directives at the current priority will still execute
  5607. * as the order of execution on same `priority` is undefined). Note that expressions
  5608. * and other directives used in the directive's template will also be excluded from execution.
  5609. *
  5610. * #### `scope`
  5611. * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
  5612. * same element request a new scope, only one new scope is created. The new scope rule does not
  5613. * apply for the root of the template since the root of the template always gets a new scope.
  5614. *
  5615. * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
  5616. * normal scope in that it does not prototypically inherit from the parent scope. This is useful
  5617. * when creating reusable components, which should not accidentally read or modify data in the
  5618. * parent scope.
  5619. *
  5620. * The 'isolate' scope takes an object hash which defines a set of local scope properties
  5621. * derived from the parent scope. These local properties are useful for aliasing values for
  5622. * templates. Locals definition is a hash of local scope property to its source:
  5623. *
  5624. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  5625. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  5626. * attribute name is assumed to be the same as the local name.
  5627. * Given `<widget my-attr="hello {{name}}">` and widget definition
  5628. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  5629. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  5630. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  5631. * component scope).
  5632. *
  5633. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  5634. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  5635. * name is specified then the attribute name is assumed to be the same as the local name.
  5636. * Given `<widget my-attr="parentModel">` and widget definition of
  5637. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  5638. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  5639. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  5640. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  5641. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If
  5642. * you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use
  5643. * `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).
  5644. *
  5645. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  5646. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  5647. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  5648. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  5649. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  5650. * pass data from the isolated scope via an expression to the parent scope, this can be
  5651. * done by passing a map of local variable names and values into the expression wrapper fn.
  5652. * For example, if the expression is `increment(amount)` then we can specify the amount value
  5653. * by calling the `localFn` as `localFn({amount: 22})`.
  5654. *
  5655. *
  5656. * #### `bindToController`
  5657. * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will
  5658. * allow a component to have its properties bound to the controller, rather than to scope. When the controller
  5659. * is instantiated, the initial values of the isolate scope bindings are already available.
  5660. *
  5661. * #### `controller`
  5662. * Controller constructor function. The controller is instantiated before the
  5663. * pre-linking phase and it is shared with other directives (see
  5664. * `require` attribute). This allows the directives to communicate with each other and augment
  5665. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  5666. *
  5667. * * `$scope` - Current scope associated with the element
  5668. * * `$element` - Current element
  5669. * * `$attrs` - Current attributes object for the element
  5670. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  5671. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5672. * * `scope`: optional argument to override the scope.
  5673. * * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.
  5674. * * `futureParentElement`:
  5675. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  5676. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  5677. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  5678. * and when the `cloneLinkinFn` is passed,
  5679. * as those elements need to created and cloned in a special way when they are defined outside their
  5680. * usual containers (e.g. like `<svg>`).
  5681. * * See also the `directive.templateNamespace` property.
  5682. *
  5683. *
  5684. * #### `require`
  5685. * Require another directive and inject its controller as the fourth argument to the linking function. The
  5686. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  5687. * injected argument will be an array in corresponding order. If no such directive can be
  5688. * found, or if the directive does not have a controller, then an error is raised (unless no link function
  5689. * is specified, in which case error checking is skipped). The name can be prefixed with:
  5690. *
  5691. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  5692. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  5693. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  5694. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  5695. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  5696. * `null` to the `link` fn if not found.
  5697. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  5698. * `null` to the `link` fn if not found.
  5699. *
  5700. *
  5701. * #### `controllerAs`
  5702. * Identifier name for a reference to the controller in the directive's scope.
  5703. * This allows the controller to be referenced from the directive template. The directive
  5704. * needs to define a scope for this configuration to be used. Useful in the case when
  5705. * directive is used as component.
  5706. *
  5707. *
  5708. * #### `restrict`
  5709. * String of subset of `EACM` which restricts the directive to a specific directive
  5710. * declaration style. If omitted, the defaults (elements and attributes) are used.
  5711. *
  5712. * * `E` - Element name (default): `<my-directive></my-directive>`
  5713. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  5714. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  5715. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  5716. *
  5717. *
  5718. * #### `templateNamespace`
  5719. * String representing the document type used by the markup in the template.
  5720. * AngularJS needs this information as those elements need to be created and cloned
  5721. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  5722. *
  5723. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  5724. * top-level elements such as `<svg>` or `<math>`.
  5725. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  5726. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  5727. *
  5728. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  5729. *
  5730. * #### `template`
  5731. * HTML markup that may:
  5732. * * Replace the contents of the directive's element (default).
  5733. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  5734. * * Wrap the contents of the directive's element (if `transclude` is true).
  5735. *
  5736. * Value may be:
  5737. *
  5738. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  5739. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  5740. * function api below) and returns a string value.
  5741. *
  5742. *
  5743. * #### `templateUrl`
  5744. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  5745. *
  5746. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  5747. * for later when the template has been resolved. In the meantime it will continue to compile and link
  5748. * sibling and parent elements as though this element had not contained any directives.
  5749. *
  5750. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  5751. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  5752. * case when only one deeply nested directive has `templateUrl`.
  5753. *
  5754. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  5755. *
  5756. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  5757. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  5758. * a string value representing the url. In either case, the template URL is passed through {@link
  5759. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  5760. *
  5761. *
  5762. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  5763. * specify what the template should replace. Defaults to `false`.
  5764. *
  5765. * * `true` - the template will replace the directive's element.
  5766. * * `false` - the template will replace the contents of the directive's element.
  5767. *
  5768. * The replacement process migrates all of the attributes / classes from the old element to the new
  5769. * one. See the {@link guide/directive#template-expanding-directive
  5770. * Directives Guide} for an example.
  5771. *
  5772. * There are very few scenarios where element replacement is required for the application function,
  5773. * the main one being reusable custom components that are used within SVG contexts
  5774. * (because SVG doesn't work with custom elements in the DOM tree).
  5775. *
  5776. * #### `transclude`
  5777. * Extract the contents of the element where the directive appears and make it available to the directive.
  5778. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  5779. * {@link $compile#transclusion Transclusion} section below.
  5780. *
  5781. * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
  5782. * directive's element or the entire element:
  5783. *
  5784. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  5785. * * `'element'` - transclude the whole of the directive's element including any directives on this
  5786. * element that defined at a lower priority than this directive. When used, the `template`
  5787. * property is ignored.
  5788. *
  5789. *
  5790. * #### `compile`
  5791. *
  5792. * ```js
  5793. * function compile(tElement, tAttrs, transclude) { ... }
  5794. * ```
  5795. *
  5796. * The compile function deals with transforming the template DOM. Since most directives do not do
  5797. * template transformation, it is not used often. The compile function takes the following arguments:
  5798. *
  5799. * * `tElement` - template element - The element where the directive has been declared. It is
  5800. * safe to do template transformation on the element and child elements only.
  5801. *
  5802. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  5803. * between all directive compile functions.
  5804. *
  5805. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  5806. *
  5807. * <div class="alert alert-warning">
  5808. * **Note:** The template instance and the link instance may be different objects if the template has
  5809. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  5810. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  5811. * should be done in a linking function rather than in a compile function.
  5812. * </div>
  5813. * <div class="alert alert-warning">
  5814. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  5815. * own templates or compile functions. Compiling these directives results in an infinite loop and a
  5816. * stack overflow errors.
  5817. *
  5818. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  5819. * a directive's template instead of relying on automatic template compilation via `template` or
  5820. * `templateUrl` declaration or manual compilation inside the compile function.
  5821. * </div>
  5822. *
  5823. * <div class="alert alert-danger">
  5824. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  5825. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  5826. * to the link function instead.
  5827. * </div>
  5828. * A compile function can have a return value which can be either a function or an object.
  5829. *
  5830. * * returning a (post-link) function - is equivalent to registering the linking function via the
  5831. * `link` property of the config object when the compile function is empty.
  5832. *
  5833. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  5834. * control when a linking function should be called during the linking phase. See info about
  5835. * pre-linking and post-linking functions below.
  5836. *
  5837. *
  5838. * #### `link`
  5839. * This property is used only if the `compile` property is not defined.
  5840. *
  5841. * ```js
  5842. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  5843. * ```
  5844. *
  5845. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  5846. * executed after the template has been cloned. This is where most of the directive logic will be
  5847. * put.
  5848. *
  5849. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  5850. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  5851. *
  5852. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  5853. * manipulate the children of the element only in `postLink` function since the children have
  5854. * already been linked.
  5855. *
  5856. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  5857. * between all directive linking functions.
  5858. *
  5859. * * `controller` - the directive's required controller instance(s) - Instances are shared
  5860. * among all directives, which allows the directives to use the controllers as a communication
  5861. * channel. The exact value depends on the directive's `require` property:
  5862. * * `string`: the controller instance
  5863. * * `array`: array of controller instances
  5864. * * no controller(s) required: `undefined`
  5865. *
  5866. * If a required controller cannot be found, and it is optional, the instance is `null`,
  5867. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  5868. *
  5869. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  5870. * This is the same as the `$transclude`
  5871. * parameter of directive controllers, see there for details.
  5872. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5873. *
  5874. * #### Pre-linking function
  5875. *
  5876. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  5877. * compiler linking function will fail to locate the correct elements for linking.
  5878. *
  5879. * #### Post-linking function
  5880. *
  5881. * Executed after the child elements are linked.
  5882. *
  5883. * Note that child elements that contain `templateUrl` directives will not have been compiled
  5884. * and linked since they are waiting for their template to load asynchronously and their own
  5885. * compilation and linking has been suspended until that occurs.
  5886. *
  5887. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  5888. * for their async templates to be resolved.
  5889. *
  5890. *
  5891. * ### Transclusion
  5892. *
  5893. * Transclusion is the process of extracting a collection of DOM element from one part of the DOM and
  5894. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  5895. * scope from where they were taken.
  5896. *
  5897. * Transclusion is used (often with {@link ngTransclude}) to insert the
  5898. * original contents of a directive's element into a specified place in the template of the directive.
  5899. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  5900. * content has access to the properties on the scope from which it was taken, even if the directive
  5901. * has isolated scope.
  5902. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  5903. *
  5904. * This makes it possible for the widget to have private state for its template, while the transcluded
  5905. * content has access to its originating scope.
  5906. *
  5907. * <div class="alert alert-warning">
  5908. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  5909. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  5910. * Testing Transclusion Directives}.
  5911. * </div>
  5912. *
  5913. * #### Transclusion Functions
  5914. *
  5915. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  5916. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  5917. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  5918. *
  5919. * <div class="alert alert-info">
  5920. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  5921. * ngTransclude will deal with it for us.
  5922. * </div>
  5923. *
  5924. * If you want to manually control the insertion and removal of the transcluded content in your directive
  5925. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  5926. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  5927. *
  5928. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  5929. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  5930. * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
  5931. *
  5932. * <div class="alert alert-info">
  5933. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
  5934. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  5935. * </div>
  5936. *
  5937. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  5938. * attach function**:
  5939. *
  5940. * ```js
  5941. * var transcludedContent, transclusionScope;
  5942. *
  5943. * $transclude(function(clone, scope) {
  5944. * element.append(clone);
  5945. * transcludedContent = clone;
  5946. * transclusionScope = scope;
  5947. * });
  5948. * ```
  5949. *
  5950. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  5951. * associated transclusion scope:
  5952. *
  5953. * ```js
  5954. * transcludedContent.remove();
  5955. * transclusionScope.$destroy();
  5956. * ```
  5957. *
  5958. * <div class="alert alert-info">
  5959. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  5960. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  5961. * then you are also responsible for calling `$destroy` on the transclusion scope.
  5962. * </div>
  5963. *
  5964. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  5965. * automatically destroy their transluded clones as necessary so you do not need to worry about this if
  5966. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  5967. *
  5968. *
  5969. * #### Transclusion Scopes
  5970. *
  5971. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  5972. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  5973. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  5974. * was taken.
  5975. *
  5976. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  5977. * like this:
  5978. *
  5979. * ```html
  5980. * <div ng-app>
  5981. * <div isolate>
  5982. * <div transclusion>
  5983. * </div>
  5984. * </div>
  5985. * </div>
  5986. * ```
  5987. *
  5988. * The `$parent` scope hierarchy will look like this:
  5989. *
  5990. * ```
  5991. * - $rootScope
  5992. * - isolate
  5993. * - transclusion
  5994. * ```
  5995. *
  5996. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  5997. *
  5998. * ```
  5999. * - $rootScope
  6000. * - transclusion
  6001. * - isolate
  6002. * ```
  6003. *
  6004. *
  6005. * ### Attributes
  6006. *
  6007. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  6008. * `link()` or `compile()` functions. It has a variety of uses.
  6009. *
  6010. * accessing *Normalized attribute names:*
  6011. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  6012. * the attributes object allows for normalized access to
  6013. * the attributes.
  6014. *
  6015. * * *Directive inter-communication:* All directives share the same instance of the attributes
  6016. * object which allows the directives to use the attributes object as inter directive
  6017. * communication.
  6018. *
  6019. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  6020. * allowing other directives to read the interpolated value.
  6021. *
  6022. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  6023. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  6024. * the only way to easily get the actual value because during the linking phase the interpolation
  6025. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  6026. *
  6027. * ```js
  6028. * function linkingFn(scope, elm, attrs, ctrl) {
  6029. * // get the attribute value
  6030. * console.log(attrs.ngModel);
  6031. *
  6032. * // change the attribute
  6033. * attrs.$set('ngModel', 'new value');
  6034. *
  6035. * // observe changes to interpolated attribute
  6036. * attrs.$observe('ngModel', function(value) {
  6037. * console.log('ngModel has changed value to ' + value);
  6038. * });
  6039. * }
  6040. * ```
  6041. *
  6042. * ## Example
  6043. *
  6044. * <div class="alert alert-warning">
  6045. * **Note**: Typically directives are registered with `module.directive`. The example below is
  6046. * to illustrate how `$compile` works.
  6047. * </div>
  6048. *
  6049. <example module="compileExample">
  6050. <file name="index.html">
  6051. <script>
  6052. angular.module('compileExample', [], function($compileProvider) {
  6053. // configure new 'compile' directive by passing a directive
  6054. // factory function. The factory function injects the '$compile'
  6055. $compileProvider.directive('compile', function($compile) {
  6056. // directive factory creates a link function
  6057. return function(scope, element, attrs) {
  6058. scope.$watch(
  6059. function(scope) {
  6060. // watch the 'compile' expression for changes
  6061. return scope.$eval(attrs.compile);
  6062. },
  6063. function(value) {
  6064. // when the 'compile' expression changes
  6065. // assign it into the current DOM
  6066. element.html(value);
  6067. // compile the new DOM and link it to the current
  6068. // scope.
  6069. // NOTE: we only compile .childNodes so that
  6070. // we don't get into infinite loop compiling ourselves
  6071. $compile(element.contents())(scope);
  6072. }
  6073. );
  6074. };
  6075. });
  6076. })
  6077. .controller('GreeterController', ['$scope', function($scope) {
  6078. $scope.name = 'Angular';
  6079. $scope.html = 'Hello {{name}}';
  6080. }]);
  6081. </script>
  6082. <div ng-controller="GreeterController">
  6083. <input ng-model="name"> <br/>
  6084. <textarea ng-model="html"></textarea> <br/>
  6085. <div compile="html"></div>
  6086. </div>
  6087. </file>
  6088. <file name="protractor.js" type="protractor">
  6089. it('should auto compile', function() {
  6090. var textarea = $('textarea');
  6091. var output = $('div[compile]');
  6092. // The initial state reads 'Hello Angular'.
  6093. expect(output.getText()).toBe('Hello Angular');
  6094. textarea.clear();
  6095. textarea.sendKeys('{{name}}!');
  6096. expect(output.getText()).toBe('Angular!');
  6097. });
  6098. </file>
  6099. </example>
  6100. *
  6101. *
  6102. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  6103. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  6104. *
  6105. * <div class="alert alert-danger">
  6106. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  6107. * e.g. will not use the right outer scope. Please pass the transclude function as a
  6108. * `parentBoundTranscludeFn` to the link function instead.
  6109. * </div>
  6110. *
  6111. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  6112. * root element(s), not their children)
  6113. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  6114. * (a DOM element/tree) to a scope. Where:
  6115. *
  6116. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  6117. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  6118. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  6119. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  6120. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  6121. *
  6122. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  6123. * * `scope` - is the current scope with which the linking function is working with.
  6124. *
  6125. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  6126. * keys may be used to control linking behavior:
  6127. *
  6128. * * `parentBoundTranscludeFn` - the transclude function made available to
  6129. * directives; if given, it will be passed through to the link functions of
  6130. * directives found in `element` during compilation.
  6131. * * `transcludeControllers` - an object hash with keys that map controller names
  6132. * to controller instances; if given, it will make the controllers
  6133. * available to directives.
  6134. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  6135. * the cloned elements; only needed for transcludes that are allowed to contain non html
  6136. * elements (e.g. SVG elements). See also the directive.controller property.
  6137. *
  6138. * Calling the linking function returns the element of the template. It is either the original
  6139. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  6140. *
  6141. * After linking the view is not updated until after a call to $digest which typically is done by
  6142. * Angular automatically.
  6143. *
  6144. * If you need access to the bound view, there are two ways to do it:
  6145. *
  6146. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  6147. * before you send them to the compiler and keep this reference around.
  6148. * ```js
  6149. * var element = $compile('<p>{{total}}</p>')(scope);
  6150. * ```
  6151. *
  6152. * - if on the other hand, you need the element to be cloned, the view reference from the original
  6153. * example would not point to the clone, but rather to the original template that was cloned. In
  6154. * this case, you can access the clone via the cloneAttachFn:
  6155. * ```js
  6156. * var templateElement = angular.element('<p>{{total}}</p>'),
  6157. * scope = ....;
  6158. *
  6159. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  6160. * //attach the clone to DOM document at the right place
  6161. * });
  6162. *
  6163. * //now we have reference to the cloned DOM via `clonedElement`
  6164. * ```
  6165. *
  6166. *
  6167. * For information on how the compiler works, see the
  6168. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  6169. */
  6170. var $compileMinErr = minErr('$compile');
  6171. /**
  6172. * @ngdoc provider
  6173. * @name $compileProvider
  6174. *
  6175. * @description
  6176. */
  6177. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  6178. function $CompileProvider($provide, $$sanitizeUriProvider) {
  6179. var hasDirectives = {},
  6180. Suffix = 'Directive',
  6181. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
  6182. CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
  6183. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  6184. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  6185. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  6186. // The assumption is that future DOM event attribute names will begin with
  6187. // 'on' and be composed of only English letters.
  6188. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  6189. function parseIsolateBindings(scope, directiveName, isController) {
  6190. var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;
  6191. var bindings = {};
  6192. forEach(scope, function(definition, scopeName) {
  6193. var match = definition.match(LOCAL_REGEXP);
  6194. if (!match) {
  6195. throw $compileMinErr('iscp',
  6196. "Invalid {3} for directive '{0}'." +
  6197. " Definition: {... {1}: '{2}' ...}",
  6198. directiveName, scopeName, definition,
  6199. (isController ? "controller bindings definition" :
  6200. "isolate scope definition"));
  6201. }
  6202. bindings[scopeName] = {
  6203. mode: match[1][0],
  6204. collection: match[2] === '*',
  6205. optional: match[3] === '?',
  6206. attrName: match[4] || scopeName
  6207. };
  6208. });
  6209. return bindings;
  6210. }
  6211. function parseDirectiveBindings(directive, directiveName) {
  6212. var bindings = {
  6213. isolateScope: null,
  6214. bindToController: null
  6215. };
  6216. if (isObject(directive.scope)) {
  6217. if (directive.bindToController === true) {
  6218. bindings.bindToController = parseIsolateBindings(directive.scope,
  6219. directiveName, true);
  6220. bindings.isolateScope = {};
  6221. } else {
  6222. bindings.isolateScope = parseIsolateBindings(directive.scope,
  6223. directiveName, false);
  6224. }
  6225. }
  6226. if (isObject(directive.bindToController)) {
  6227. bindings.bindToController =
  6228. parseIsolateBindings(directive.bindToController, directiveName, true);
  6229. }
  6230. if (isObject(bindings.bindToController)) {
  6231. var controller = directive.controller;
  6232. var controllerAs = directive.controllerAs;
  6233. if (!controller) {
  6234. // There is no controller, there may or may not be a controllerAs property
  6235. throw $compileMinErr('noctrl',
  6236. "Cannot bind to controller without directive '{0}'s controller.",
  6237. directiveName);
  6238. } else if (!identifierForController(controller, controllerAs)) {
  6239. // There is a controller, but no identifier or controllerAs property
  6240. throw $compileMinErr('noident',
  6241. "Cannot bind to controller without identifier for directive '{0}'.",
  6242. directiveName);
  6243. }
  6244. }
  6245. return bindings;
  6246. }
  6247. function assertValidDirectiveName(name) {
  6248. var letter = name.charAt(0);
  6249. if (!letter || letter !== lowercase(letter)) {
  6250. throw $compileMinErr('baddir', "Directive name '{0}' is invalid. The first character must be a lowercase letter", name);
  6251. }
  6252. if (name !== name.trim()) {
  6253. throw $compileMinErr('baddir',
  6254. "Directive name '{0}' is invalid. The name should not contain leading or trailing whitespaces",
  6255. name);
  6256. }
  6257. }
  6258. /**
  6259. * @ngdoc method
  6260. * @name $compileProvider#directive
  6261. * @kind function
  6262. *
  6263. * @description
  6264. * Register a new directive with the compiler.
  6265. *
  6266. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  6267. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  6268. * names and the values are the factories.
  6269. * @param {Function|Array} directiveFactory An injectable directive factory function. See
  6270. * {@link guide/directive} for more info.
  6271. * @returns {ng.$compileProvider} Self for chaining.
  6272. */
  6273. this.directive = function registerDirective(name, directiveFactory) {
  6274. assertNotHasOwnProperty(name, 'directive');
  6275. if (isString(name)) {
  6276. assertValidDirectiveName(name);
  6277. assertArg(directiveFactory, 'directiveFactory');
  6278. if (!hasDirectives.hasOwnProperty(name)) {
  6279. hasDirectives[name] = [];
  6280. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  6281. function($injector, $exceptionHandler) {
  6282. var directives = [];
  6283. forEach(hasDirectives[name], function(directiveFactory, index) {
  6284. try {
  6285. var directive = $injector.invoke(directiveFactory);
  6286. if (isFunction(directive)) {
  6287. directive = { compile: valueFn(directive) };
  6288. } else if (!directive.compile && directive.link) {
  6289. directive.compile = valueFn(directive.link);
  6290. }
  6291. directive.priority = directive.priority || 0;
  6292. directive.index = index;
  6293. directive.name = directive.name || name;
  6294. directive.require = directive.require || (directive.controller && directive.name);
  6295. directive.restrict = directive.restrict || 'EA';
  6296. var bindings = directive.$$bindings =
  6297. parseDirectiveBindings(directive, directive.name);
  6298. if (isObject(bindings.isolateScope)) {
  6299. directive.$$isolateBindings = bindings.isolateScope;
  6300. }
  6301. directives.push(directive);
  6302. } catch (e) {
  6303. $exceptionHandler(e);
  6304. }
  6305. });
  6306. return directives;
  6307. }]);
  6308. }
  6309. hasDirectives[name].push(directiveFactory);
  6310. } else {
  6311. forEach(name, reverseParams(registerDirective));
  6312. }
  6313. return this;
  6314. };
  6315. /**
  6316. * @ngdoc method
  6317. * @name $compileProvider#aHrefSanitizationWhitelist
  6318. * @kind function
  6319. *
  6320. * @description
  6321. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  6322. * urls during a[href] sanitization.
  6323. *
  6324. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  6325. *
  6326. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  6327. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  6328. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  6329. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  6330. *
  6331. * @param {RegExp=} regexp New regexp to whitelist urls with.
  6332. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  6333. * chaining otherwise.
  6334. */
  6335. this.aHrefSanitizationWhitelist = function(regexp) {
  6336. if (isDefined(regexp)) {
  6337. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  6338. return this;
  6339. } else {
  6340. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  6341. }
  6342. };
  6343. /**
  6344. * @ngdoc method
  6345. * @name $compileProvider#imgSrcSanitizationWhitelist
  6346. * @kind function
  6347. *
  6348. * @description
  6349. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  6350. * urls during img[src] sanitization.
  6351. *
  6352. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  6353. *
  6354. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  6355. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  6356. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  6357. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  6358. *
  6359. * @param {RegExp=} regexp New regexp to whitelist urls with.
  6360. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  6361. * chaining otherwise.
  6362. */
  6363. this.imgSrcSanitizationWhitelist = function(regexp) {
  6364. if (isDefined(regexp)) {
  6365. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  6366. return this;
  6367. } else {
  6368. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  6369. }
  6370. };
  6371. /**
  6372. * @ngdoc method
  6373. * @name $compileProvider#debugInfoEnabled
  6374. *
  6375. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  6376. * current debugInfoEnabled state
  6377. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  6378. *
  6379. * @kind function
  6380. *
  6381. * @description
  6382. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  6383. * binding information and a reference to the current scope on to DOM elements.
  6384. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  6385. * * `ng-binding` CSS class
  6386. * * `$binding` data property containing an array of the binding expressions
  6387. *
  6388. * You may want to disable this in production for a significant performance boost. See
  6389. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  6390. *
  6391. * The default value is true.
  6392. */
  6393. var debugInfoEnabled = true;
  6394. this.debugInfoEnabled = function(enabled) {
  6395. if (isDefined(enabled)) {
  6396. debugInfoEnabled = enabled;
  6397. return this;
  6398. }
  6399. return debugInfoEnabled;
  6400. };
  6401. this.$get = [
  6402. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  6403. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  6404. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  6405. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  6406. var Attributes = function(element, attributesToCopy) {
  6407. if (attributesToCopy) {
  6408. var keys = Object.keys(attributesToCopy);
  6409. var i, l, key;
  6410. for (i = 0, l = keys.length; i < l; i++) {
  6411. key = keys[i];
  6412. this[key] = attributesToCopy[key];
  6413. }
  6414. } else {
  6415. this.$attr = {};
  6416. }
  6417. this.$$element = element;
  6418. };
  6419. Attributes.prototype = {
  6420. /**
  6421. * @ngdoc method
  6422. * @name $compile.directive.Attributes#$normalize
  6423. * @kind function
  6424. *
  6425. * @description
  6426. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  6427. * `data-`) to its normalized, camelCase form.
  6428. *
  6429. * Also there is special case for Moz prefix starting with upper case letter.
  6430. *
  6431. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  6432. *
  6433. * @param {string} name Name to normalize
  6434. */
  6435. $normalize: directiveNormalize,
  6436. /**
  6437. * @ngdoc method
  6438. * @name $compile.directive.Attributes#$addClass
  6439. * @kind function
  6440. *
  6441. * @description
  6442. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  6443. * are enabled then an animation will be triggered for the class addition.
  6444. *
  6445. * @param {string} classVal The className value that will be added to the element
  6446. */
  6447. $addClass: function(classVal) {
  6448. if (classVal && classVal.length > 0) {
  6449. $animate.addClass(this.$$element, classVal);
  6450. }
  6451. },
  6452. /**
  6453. * @ngdoc method
  6454. * @name $compile.directive.Attributes#$removeClass
  6455. * @kind function
  6456. *
  6457. * @description
  6458. * Removes the CSS class value specified by the classVal parameter from the element. If
  6459. * animations are enabled then an animation will be triggered for the class removal.
  6460. *
  6461. * @param {string} classVal The className value that will be removed from the element
  6462. */
  6463. $removeClass: function(classVal) {
  6464. if (classVal && classVal.length > 0) {
  6465. $animate.removeClass(this.$$element, classVal);
  6466. }
  6467. },
  6468. /**
  6469. * @ngdoc method
  6470. * @name $compile.directive.Attributes#$updateClass
  6471. * @kind function
  6472. *
  6473. * @description
  6474. * Adds and removes the appropriate CSS class values to the element based on the difference
  6475. * between the new and old CSS class values (specified as newClasses and oldClasses).
  6476. *
  6477. * @param {string} newClasses The current CSS className value
  6478. * @param {string} oldClasses The former CSS className value
  6479. */
  6480. $updateClass: function(newClasses, oldClasses) {
  6481. var toAdd = tokenDifference(newClasses, oldClasses);
  6482. if (toAdd && toAdd.length) {
  6483. $animate.addClass(this.$$element, toAdd);
  6484. }
  6485. var toRemove = tokenDifference(oldClasses, newClasses);
  6486. if (toRemove && toRemove.length) {
  6487. $animate.removeClass(this.$$element, toRemove);
  6488. }
  6489. },
  6490. /**
  6491. * Set a normalized attribute on the element in a way such that all directives
  6492. * can share the attribute. This function properly handles boolean attributes.
  6493. * @param {string} key Normalized key. (ie ngAttribute)
  6494. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  6495. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  6496. * Defaults to true.
  6497. * @param {string=} attrName Optional none normalized name. Defaults to key.
  6498. */
  6499. $set: function(key, value, writeAttr, attrName) {
  6500. // TODO: decide whether or not to throw an error if "class"
  6501. //is set through this function since it may cause $updateClass to
  6502. //become unstable.
  6503. var node = this.$$element[0],
  6504. booleanKey = getBooleanAttrName(node, key),
  6505. aliasedKey = getAliasedAttrName(node, key),
  6506. observer = key,
  6507. nodeName;
  6508. if (booleanKey) {
  6509. this.$$element.prop(key, value);
  6510. attrName = booleanKey;
  6511. } else if (aliasedKey) {
  6512. this[aliasedKey] = value;
  6513. observer = aliasedKey;
  6514. }
  6515. this[key] = value;
  6516. // translate normalized key to actual key
  6517. if (attrName) {
  6518. this.$attr[key] = attrName;
  6519. } else {
  6520. attrName = this.$attr[key];
  6521. if (!attrName) {
  6522. this.$attr[key] = attrName = snake_case(key, '-');
  6523. }
  6524. }
  6525. nodeName = nodeName_(this.$$element);
  6526. if ((nodeName === 'a' && key === 'href') ||
  6527. (nodeName === 'img' && key === 'src')) {
  6528. // sanitize a[href] and img[src] values
  6529. this[key] = value = $$sanitizeUri(value, key === 'src');
  6530. } else if (nodeName === 'img' && key === 'srcset') {
  6531. // sanitize img[srcset] values
  6532. var result = "";
  6533. // first check if there are spaces because it's not the same pattern
  6534. var trimmedSrcset = trim(value);
  6535. // ( 999x ,| 999w ,| ,|, )
  6536. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  6537. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  6538. // split srcset into tuple of uri and descriptor except for the last item
  6539. var rawUris = trimmedSrcset.split(pattern);
  6540. // for each tuples
  6541. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  6542. for (var i = 0; i < nbrUrisWith2parts; i++) {
  6543. var innerIdx = i * 2;
  6544. // sanitize the uri
  6545. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  6546. // add the descriptor
  6547. result += (" " + trim(rawUris[innerIdx + 1]));
  6548. }
  6549. // split the last item into uri and descriptor
  6550. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  6551. // sanitize the last uri
  6552. result += $$sanitizeUri(trim(lastTuple[0]), true);
  6553. // and add the last descriptor if any
  6554. if (lastTuple.length === 2) {
  6555. result += (" " + trim(lastTuple[1]));
  6556. }
  6557. this[key] = value = result;
  6558. }
  6559. if (writeAttr !== false) {
  6560. if (value === null || value === undefined) {
  6561. this.$$element.removeAttr(attrName);
  6562. } else {
  6563. this.$$element.attr(attrName, value);
  6564. }
  6565. }
  6566. // fire observers
  6567. var $$observers = this.$$observers;
  6568. $$observers && forEach($$observers[observer], function(fn) {
  6569. try {
  6570. fn(value);
  6571. } catch (e) {
  6572. $exceptionHandler(e);
  6573. }
  6574. });
  6575. },
  6576. /**
  6577. * @ngdoc method
  6578. * @name $compile.directive.Attributes#$observe
  6579. * @kind function
  6580. *
  6581. * @description
  6582. * Observes an interpolated attribute.
  6583. *
  6584. * The observer function will be invoked once during the next `$digest` following
  6585. * compilation. The observer is then invoked whenever the interpolated value
  6586. * changes.
  6587. *
  6588. * @param {string} key Normalized key. (ie ngAttribute) .
  6589. * @param {function(interpolatedValue)} fn Function that will be called whenever
  6590. the interpolated value of the attribute changes.
  6591. * See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.
  6592. * @returns {function()} Returns a deregistration function for this observer.
  6593. */
  6594. $observe: function(key, fn) {
  6595. var attrs = this,
  6596. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  6597. listeners = ($$observers[key] || ($$observers[key] = []));
  6598. listeners.push(fn);
  6599. $rootScope.$evalAsync(function() {
  6600. if (!listeners.$$inter && attrs.hasOwnProperty(key)) {
  6601. // no one registered attribute interpolation function, so lets call it manually
  6602. fn(attrs[key]);
  6603. }
  6604. });
  6605. return function() {
  6606. arrayRemove(listeners, fn);
  6607. };
  6608. }
  6609. };
  6610. function safeAddClass($element, className) {
  6611. try {
  6612. $element.addClass(className);
  6613. } catch (e) {
  6614. // ignore, since it means that we are trying to set class on
  6615. // SVG element, where class name is read-only.
  6616. }
  6617. }
  6618. var startSymbol = $interpolate.startSymbol(),
  6619. endSymbol = $interpolate.endSymbol(),
  6620. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  6621. ? identity
  6622. : function denormalizeTemplate(template) {
  6623. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  6624. },
  6625. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  6626. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  6627. var bindings = $element.data('$binding') || [];
  6628. if (isArray(binding)) {
  6629. bindings = bindings.concat(binding);
  6630. } else {
  6631. bindings.push(binding);
  6632. }
  6633. $element.data('$binding', bindings);
  6634. } : noop;
  6635. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  6636. safeAddClass($element, 'ng-binding');
  6637. } : noop;
  6638. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  6639. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  6640. $element.data(dataName, scope);
  6641. } : noop;
  6642. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  6643. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  6644. } : noop;
  6645. return compile;
  6646. //================================
  6647. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  6648. previousCompileContext) {
  6649. if (!($compileNodes instanceof jqLite)) {
  6650. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  6651. // modify it.
  6652. $compileNodes = jqLite($compileNodes);
  6653. }
  6654. // We can not compile top level text elements since text nodes can be merged and we will
  6655. // not be able to attach scope data to them, so we will wrap them in <span>
  6656. forEach($compileNodes, function(node, index) {
  6657. if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  6658. $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
  6659. }
  6660. });
  6661. var compositeLinkFn =
  6662. compileNodes($compileNodes, transcludeFn, $compileNodes,
  6663. maxPriority, ignoreDirective, previousCompileContext);
  6664. compile.$$addScopeClass($compileNodes);
  6665. var namespace = null;
  6666. return function publicLinkFn(scope, cloneConnectFn, options) {
  6667. assertArg(scope, 'scope');
  6668. options = options || {};
  6669. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  6670. transcludeControllers = options.transcludeControllers,
  6671. futureParentElement = options.futureParentElement;
  6672. // When `parentBoundTranscludeFn` is passed, it is a
  6673. // `controllersBoundTransclude` function (it was previously passed
  6674. // as `transclude` to directive.link) so we must unwrap it to get
  6675. // its `boundTranscludeFn`
  6676. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  6677. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  6678. }
  6679. if (!namespace) {
  6680. namespace = detectNamespaceForChildElements(futureParentElement);
  6681. }
  6682. var $linkNode;
  6683. if (namespace !== 'html') {
  6684. // When using a directive with replace:true and templateUrl the $compileNodes
  6685. // (or a child element inside of them)
  6686. // might change, so we need to recreate the namespace adapted compileNodes
  6687. // for call to the link function.
  6688. // Note: This will already clone the nodes...
  6689. $linkNode = jqLite(
  6690. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  6691. );
  6692. } else if (cloneConnectFn) {
  6693. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  6694. // and sometimes changes the structure of the DOM.
  6695. $linkNode = JQLitePrototype.clone.call($compileNodes);
  6696. } else {
  6697. $linkNode = $compileNodes;
  6698. }
  6699. if (transcludeControllers) {
  6700. for (var controllerName in transcludeControllers) {
  6701. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  6702. }
  6703. }
  6704. compile.$$addScopeInfo($linkNode, scope);
  6705. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  6706. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  6707. return $linkNode;
  6708. };
  6709. }
  6710. function detectNamespaceForChildElements(parentElement) {
  6711. // TODO: Make this detect MathML as well...
  6712. var node = parentElement && parentElement[0];
  6713. if (!node) {
  6714. return 'html';
  6715. } else {
  6716. return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';
  6717. }
  6718. }
  6719. /**
  6720. * Compile function matches each node in nodeList against the directives. Once all directives
  6721. * for a particular node are collected their compile functions are executed. The compile
  6722. * functions return values - the linking functions - are combined into a composite linking
  6723. * function, which is the a linking function for the node.
  6724. *
  6725. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  6726. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  6727. * scope argument is auto-generated to the new child of the transcluded parent scope.
  6728. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  6729. * the rootElement must be set the jqLite collection of the compile root. This is
  6730. * needed so that the jqLite collection items can be replaced with widgets.
  6731. * @param {number=} maxPriority Max directive priority.
  6732. * @returns {Function} A composite linking function of all of the matched directives or null.
  6733. */
  6734. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  6735. previousCompileContext) {
  6736. var linkFns = [],
  6737. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  6738. for (var i = 0; i < nodeList.length; i++) {
  6739. attrs = new Attributes();
  6740. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  6741. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  6742. ignoreDirective);
  6743. nodeLinkFn = (directives.length)
  6744. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  6745. null, [], [], previousCompileContext)
  6746. : null;
  6747. if (nodeLinkFn && nodeLinkFn.scope) {
  6748. compile.$$addScopeClass(attrs.$$element);
  6749. }
  6750. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  6751. !(childNodes = nodeList[i].childNodes) ||
  6752. !childNodes.length)
  6753. ? null
  6754. : compileNodes(childNodes,
  6755. nodeLinkFn ? (
  6756. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  6757. && nodeLinkFn.transclude) : transcludeFn);
  6758. if (nodeLinkFn || childLinkFn) {
  6759. linkFns.push(i, nodeLinkFn, childLinkFn);
  6760. linkFnFound = true;
  6761. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  6762. }
  6763. //use the previous context only for the first element in the virtual group
  6764. previousCompileContext = null;
  6765. }
  6766. // return a linking function if we have found anything, null otherwise
  6767. return linkFnFound ? compositeLinkFn : null;
  6768. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  6769. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  6770. var stableNodeList;
  6771. if (nodeLinkFnFound) {
  6772. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  6773. // offsets don't get screwed up
  6774. var nodeListLength = nodeList.length;
  6775. stableNodeList = new Array(nodeListLength);
  6776. // create a sparse array by only copying the elements which have a linkFn
  6777. for (i = 0; i < linkFns.length; i+=3) {
  6778. idx = linkFns[i];
  6779. stableNodeList[idx] = nodeList[idx];
  6780. }
  6781. } else {
  6782. stableNodeList = nodeList;
  6783. }
  6784. for (i = 0, ii = linkFns.length; i < ii;) {
  6785. node = stableNodeList[linkFns[i++]];
  6786. nodeLinkFn = linkFns[i++];
  6787. childLinkFn = linkFns[i++];
  6788. if (nodeLinkFn) {
  6789. if (nodeLinkFn.scope) {
  6790. childScope = scope.$new();
  6791. compile.$$addScopeInfo(jqLite(node), childScope);
  6792. var destroyBindings = nodeLinkFn.$$destroyBindings;
  6793. if (destroyBindings) {
  6794. nodeLinkFn.$$destroyBindings = null;
  6795. childScope.$on('$destroyed', destroyBindings);
  6796. }
  6797. } else {
  6798. childScope = scope;
  6799. }
  6800. if (nodeLinkFn.transcludeOnThisElement) {
  6801. childBoundTranscludeFn = createBoundTranscludeFn(
  6802. scope, nodeLinkFn.transclude, parentBoundTranscludeFn,
  6803. nodeLinkFn.elementTranscludeOnThisElement);
  6804. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  6805. childBoundTranscludeFn = parentBoundTranscludeFn;
  6806. } else if (!parentBoundTranscludeFn && transcludeFn) {
  6807. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  6808. } else {
  6809. childBoundTranscludeFn = null;
  6810. }
  6811. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn,
  6812. nodeLinkFn);
  6813. } else if (childLinkFn) {
  6814. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  6815. }
  6816. }
  6817. }
  6818. }
  6819. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn, elementTransclusion) {
  6820. var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  6821. if (!transcludedScope) {
  6822. transcludedScope = scope.$new(false, containingScope);
  6823. transcludedScope.$$transcluded = true;
  6824. }
  6825. return transcludeFn(transcludedScope, cloneFn, {
  6826. parentBoundTranscludeFn: previousBoundTranscludeFn,
  6827. transcludeControllers: controllers,
  6828. futureParentElement: futureParentElement
  6829. });
  6830. };
  6831. return boundTranscludeFn;
  6832. }
  6833. /**
  6834. * Looks for directives on the given node and adds them to the directive collection which is
  6835. * sorted.
  6836. *
  6837. * @param node Node to search.
  6838. * @param directives An array to which the directives are added to. This array is sorted before
  6839. * the function returns.
  6840. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  6841. * @param {number=} maxPriority Max directive priority.
  6842. */
  6843. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  6844. var nodeType = node.nodeType,
  6845. attrsMap = attrs.$attr,
  6846. match,
  6847. className;
  6848. switch (nodeType) {
  6849. case NODE_TYPE_ELEMENT: /* Element */
  6850. // use the node name: <directive>
  6851. addDirective(directives,
  6852. directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
  6853. // iterate over the attributes
  6854. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  6855. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  6856. var attrStartName = false;
  6857. var attrEndName = false;
  6858. attr = nAttrs[j];
  6859. name = attr.name;
  6860. value = trim(attr.value);
  6861. // support ngAttr attribute binding
  6862. ngAttrName = directiveNormalize(name);
  6863. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  6864. name = name.replace(PREFIX_REGEXP, '')
  6865. .substr(8).replace(/_(.)/g, function(match, letter) {
  6866. return letter.toUpperCase();
  6867. });
  6868. }
  6869. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  6870. if (directiveIsMultiElement(directiveNName)) {
  6871. if (ngAttrName === directiveNName + 'Start') {
  6872. attrStartName = name;
  6873. attrEndName = name.substr(0, name.length - 5) + 'end';
  6874. name = name.substr(0, name.length - 6);
  6875. }
  6876. }
  6877. nName = directiveNormalize(name.toLowerCase());
  6878. attrsMap[nName] = name;
  6879. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  6880. attrs[nName] = value;
  6881. if (getBooleanAttrName(node, nName)) {
  6882. attrs[nName] = true; // presence means true
  6883. }
  6884. }
  6885. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  6886. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  6887. attrEndName);
  6888. }
  6889. // use class as directive
  6890. className = node.className;
  6891. if (isObject(className)) {
  6892. // Maybe SVGAnimatedString
  6893. className = className.animVal;
  6894. }
  6895. if (isString(className) && className !== '') {
  6896. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  6897. nName = directiveNormalize(match[2]);
  6898. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  6899. attrs[nName] = trim(match[3]);
  6900. }
  6901. className = className.substr(match.index + match[0].length);
  6902. }
  6903. }
  6904. break;
  6905. case NODE_TYPE_TEXT: /* Text Node */
  6906. addTextInterpolateDirective(directives, node.nodeValue);
  6907. break;
  6908. case NODE_TYPE_COMMENT: /* Comment */
  6909. try {
  6910. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  6911. if (match) {
  6912. nName = directiveNormalize(match[1]);
  6913. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  6914. attrs[nName] = trim(match[2]);
  6915. }
  6916. }
  6917. } catch (e) {
  6918. // turns out that under some circumstances IE9 throws errors when one attempts to read
  6919. // comment's node value.
  6920. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  6921. }
  6922. break;
  6923. }
  6924. directives.sort(byPriority);
  6925. return directives;
  6926. }
  6927. /**
  6928. * Given a node with an directive-start it collects all of the siblings until it finds
  6929. * directive-end.
  6930. * @param node
  6931. * @param attrStart
  6932. * @param attrEnd
  6933. * @returns {*}
  6934. */
  6935. function groupScan(node, attrStart, attrEnd) {
  6936. var nodes = [];
  6937. var depth = 0;
  6938. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  6939. do {
  6940. if (!node) {
  6941. throw $compileMinErr('uterdir',
  6942. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  6943. attrStart, attrEnd);
  6944. }
  6945. if (node.nodeType == NODE_TYPE_ELEMENT) {
  6946. if (node.hasAttribute(attrStart)) depth++;
  6947. if (node.hasAttribute(attrEnd)) depth--;
  6948. }
  6949. nodes.push(node);
  6950. node = node.nextSibling;
  6951. } while (depth > 0);
  6952. } else {
  6953. nodes.push(node);
  6954. }
  6955. return jqLite(nodes);
  6956. }
  6957. /**
  6958. * Wrapper for linking function which converts normal linking function into a grouped
  6959. * linking function.
  6960. * @param linkFn
  6961. * @param attrStart
  6962. * @param attrEnd
  6963. * @returns {Function}
  6964. */
  6965. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  6966. return function(scope, element, attrs, controllers, transcludeFn) {
  6967. element = groupScan(element[0], attrStart, attrEnd);
  6968. return linkFn(scope, element, attrs, controllers, transcludeFn);
  6969. };
  6970. }
  6971. /**
  6972. * Once the directives have been collected, their compile functions are executed. This method
  6973. * is responsible for inlining directive templates as well as terminating the application
  6974. * of the directives if the terminal directive has been reached.
  6975. *
  6976. * @param {Array} directives Array of collected directives to execute their compile function.
  6977. * this needs to be pre-sorted by priority order.
  6978. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  6979. * @param {Object} templateAttrs The shared attribute function
  6980. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  6981. * scope argument is auto-generated to the new
  6982. * child of the transcluded parent scope.
  6983. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  6984. * argument has the root jqLite array so that we can replace nodes
  6985. * on it.
  6986. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  6987. * compiling the transclusion.
  6988. * @param {Array.<Function>} preLinkFns
  6989. * @param {Array.<Function>} postLinkFns
  6990. * @param {Object} previousCompileContext Context used for previous compilation of the current
  6991. * node
  6992. * @returns {Function} linkFn
  6993. */
  6994. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  6995. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  6996. previousCompileContext) {
  6997. previousCompileContext = previousCompileContext || {};
  6998. var terminalPriority = -Number.MAX_VALUE,
  6999. newScopeDirective,
  7000. controllerDirectives = previousCompileContext.controllerDirectives,
  7001. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  7002. templateDirective = previousCompileContext.templateDirective,
  7003. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  7004. hasTranscludeDirective = false,
  7005. hasTemplate = false,
  7006. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  7007. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  7008. directive,
  7009. directiveName,
  7010. $template,
  7011. replaceDirective = originalReplaceDirective,
  7012. childTranscludeFn = transcludeFn,
  7013. linkFn,
  7014. directiveValue;
  7015. // executes all directives on the current element
  7016. for (var i = 0, ii = directives.length; i < ii; i++) {
  7017. directive = directives[i];
  7018. var attrStart = directive.$$start;
  7019. var attrEnd = directive.$$end;
  7020. // collect multiblock sections
  7021. if (attrStart) {
  7022. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  7023. }
  7024. $template = undefined;
  7025. if (terminalPriority > directive.priority) {
  7026. break; // prevent further processing of directives
  7027. }
  7028. if (directiveValue = directive.scope) {
  7029. // skip the check for directives with async templates, we'll check the derived sync
  7030. // directive when the template arrives
  7031. if (!directive.templateUrl) {
  7032. if (isObject(directiveValue)) {
  7033. // This directive is trying to add an isolated scope.
  7034. // Check that there is no scope of any kind already
  7035. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  7036. directive, $compileNode);
  7037. newIsolateScopeDirective = directive;
  7038. } else {
  7039. // This directive is trying to add a child scope.
  7040. // Check that there is no isolated scope already
  7041. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  7042. $compileNode);
  7043. }
  7044. }
  7045. newScopeDirective = newScopeDirective || directive;
  7046. }
  7047. directiveName = directive.name;
  7048. if (!directive.templateUrl && directive.controller) {
  7049. directiveValue = directive.controller;
  7050. controllerDirectives = controllerDirectives || createMap();
  7051. assertNoDuplicate("'" + directiveName + "' controller",
  7052. controllerDirectives[directiveName], directive, $compileNode);
  7053. controllerDirectives[directiveName] = directive;
  7054. }
  7055. if (directiveValue = directive.transclude) {
  7056. hasTranscludeDirective = true;
  7057. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  7058. // This option should only be used by directives that know how to safely handle element transclusion,
  7059. // where the transcluded nodes are added or replaced after linking.
  7060. if (!directive.$$tlb) {
  7061. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  7062. nonTlbTranscludeDirective = directive;
  7063. }
  7064. if (directiveValue == 'element') {
  7065. hasElementTranscludeDirective = true;
  7066. terminalPriority = directive.priority;
  7067. $template = $compileNode;
  7068. $compileNode = templateAttrs.$$element =
  7069. jqLite(document.createComment(' ' + directiveName + ': ' +
  7070. templateAttrs[directiveName] + ' '));
  7071. compileNode = $compileNode[0];
  7072. replaceWith(jqCollection, sliceArgs($template), compileNode);
  7073. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  7074. replaceDirective && replaceDirective.name, {
  7075. // Don't pass in:
  7076. // - controllerDirectives - otherwise we'll create duplicates controllers
  7077. // - newIsolateScopeDirective or templateDirective - combining templates with
  7078. // element transclusion doesn't make sense.
  7079. //
  7080. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  7081. // on the same element more than once.
  7082. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  7083. });
  7084. } else {
  7085. $template = jqLite(jqLiteClone(compileNode)).contents();
  7086. $compileNode.empty(); // clear contents
  7087. childTranscludeFn = compile($template, transcludeFn);
  7088. }
  7089. }
  7090. if (directive.template) {
  7091. hasTemplate = true;
  7092. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  7093. templateDirective = directive;
  7094. directiveValue = (isFunction(directive.template))
  7095. ? directive.template($compileNode, templateAttrs)
  7096. : directive.template;
  7097. directiveValue = denormalizeTemplate(directiveValue);
  7098. if (directive.replace) {
  7099. replaceDirective = directive;
  7100. if (jqLiteIsTextNode(directiveValue)) {
  7101. $template = [];
  7102. } else {
  7103. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  7104. }
  7105. compileNode = $template[0];
  7106. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7107. throw $compileMinErr('tplrt',
  7108. "Template for directive '{0}' must have exactly one root element. {1}",
  7109. directiveName, '');
  7110. }
  7111. replaceWith(jqCollection, $compileNode, compileNode);
  7112. var newTemplateAttrs = {$attr: {}};
  7113. // combine directives from the original node and from the template:
  7114. // - take the array of directives for this element
  7115. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  7116. // - collect directives from the template and sort them by priority
  7117. // - combine directives as: processed + template + unprocessed
  7118. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  7119. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  7120. if (newIsolateScopeDirective) {
  7121. markDirectivesAsIsolate(templateDirectives);
  7122. }
  7123. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  7124. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  7125. ii = directives.length;
  7126. } else {
  7127. $compileNode.html(directiveValue);
  7128. }
  7129. }
  7130. if (directive.templateUrl) {
  7131. hasTemplate = true;
  7132. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  7133. templateDirective = directive;
  7134. if (directive.replace) {
  7135. replaceDirective = directive;
  7136. }
  7137. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  7138. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  7139. controllerDirectives: controllerDirectives,
  7140. newIsolateScopeDirective: newIsolateScopeDirective,
  7141. templateDirective: templateDirective,
  7142. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  7143. });
  7144. ii = directives.length;
  7145. } else if (directive.compile) {
  7146. try {
  7147. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  7148. if (isFunction(linkFn)) {
  7149. addLinkFns(null, linkFn, attrStart, attrEnd);
  7150. } else if (linkFn) {
  7151. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  7152. }
  7153. } catch (e) {
  7154. $exceptionHandler(e, startingTag($compileNode));
  7155. }
  7156. }
  7157. if (directive.terminal) {
  7158. nodeLinkFn.terminal = true;
  7159. terminalPriority = Math.max(terminalPriority, directive.priority);
  7160. }
  7161. }
  7162. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  7163. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  7164. nodeLinkFn.elementTranscludeOnThisElement = hasElementTranscludeDirective;
  7165. nodeLinkFn.templateOnThisElement = hasTemplate;
  7166. nodeLinkFn.transclude = childTranscludeFn;
  7167. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  7168. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  7169. return nodeLinkFn;
  7170. ////////////////////
  7171. function addLinkFns(pre, post, attrStart, attrEnd) {
  7172. if (pre) {
  7173. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  7174. pre.require = directive.require;
  7175. pre.directiveName = directiveName;
  7176. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  7177. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  7178. }
  7179. preLinkFns.push(pre);
  7180. }
  7181. if (post) {
  7182. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  7183. post.require = directive.require;
  7184. post.directiveName = directiveName;
  7185. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  7186. post = cloneAndAnnotateFn(post, {isolateScope: true});
  7187. }
  7188. postLinkFns.push(post);
  7189. }
  7190. }
  7191. function getControllers(directiveName, require, $element, elementControllers) {
  7192. var value;
  7193. if (isString(require)) {
  7194. var match = require.match(REQUIRE_PREFIX_REGEXP);
  7195. var name = require.substring(match[0].length);
  7196. var inheritType = match[1] || match[3];
  7197. var optional = match[2] === '?';
  7198. //If only parents then start at the parent element
  7199. if (inheritType === '^^') {
  7200. $element = $element.parent();
  7201. //Otherwise attempt getting the controller from elementControllers in case
  7202. //the element is transcluded (and has no data) and to avoid .data if possible
  7203. } else {
  7204. value = elementControllers && elementControllers[name];
  7205. value = value && value.instance;
  7206. }
  7207. if (!value) {
  7208. var dataName = '$' + name + 'Controller';
  7209. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  7210. }
  7211. if (!value && !optional) {
  7212. throw $compileMinErr('ctreq',
  7213. "Controller '{0}', required by directive '{1}', can't be found!",
  7214. name, directiveName);
  7215. }
  7216. } else if (isArray(require)) {
  7217. value = [];
  7218. for (var i = 0, ii = require.length; i < ii; i++) {
  7219. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  7220. }
  7221. }
  7222. return value || null;
  7223. }
  7224. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
  7225. var elementControllers = createMap();
  7226. for (var controllerKey in controllerDirectives) {
  7227. var directive = controllerDirectives[controllerKey];
  7228. var locals = {
  7229. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  7230. $element: $element,
  7231. $attrs: attrs,
  7232. $transclude: transcludeFn
  7233. };
  7234. var controller = directive.controller;
  7235. if (controller == '@') {
  7236. controller = attrs[directive.name];
  7237. }
  7238. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  7239. // For directives with element transclusion the element is a comment,
  7240. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  7241. // clean up (http://bugs.jquery.com/ticket/8335).
  7242. // Instead, we save the controllers for the element in a local hash and attach to .data
  7243. // later, once we have the actual element.
  7244. elementControllers[directive.name] = controllerInstance;
  7245. if (!hasElementTranscludeDirective) {
  7246. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  7247. }
  7248. }
  7249. return elementControllers;
  7250. }
  7251. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn,
  7252. thisLinkFn) {
  7253. var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element,
  7254. attrs;
  7255. if (compileNode === linkNode) {
  7256. attrs = templateAttrs;
  7257. $element = templateAttrs.$$element;
  7258. } else {
  7259. $element = jqLite(linkNode);
  7260. attrs = new Attributes($element, templateAttrs);
  7261. }
  7262. if (newIsolateScopeDirective) {
  7263. isolateScope = scope.$new(true);
  7264. }
  7265. if (boundTranscludeFn) {
  7266. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  7267. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  7268. transcludeFn = controllersBoundTransclude;
  7269. transcludeFn.$$boundTransclude = boundTranscludeFn;
  7270. }
  7271. if (controllerDirectives) {
  7272. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope);
  7273. }
  7274. if (newIsolateScopeDirective) {
  7275. // Initialize isolate scope bindings for new isolate scope directive.
  7276. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  7277. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  7278. compile.$$addScopeClass($element, true);
  7279. isolateScope.$$isolateBindings =
  7280. newIsolateScopeDirective.$$isolateBindings;
  7281. initializeDirectiveBindings(scope, attrs, isolateScope,
  7282. isolateScope.$$isolateBindings,
  7283. newIsolateScopeDirective, isolateScope);
  7284. }
  7285. if (elementControllers) {
  7286. // Initialize bindToController bindings for new/isolate scopes
  7287. var scopeDirective = newIsolateScopeDirective || newScopeDirective;
  7288. var bindings;
  7289. var controllerForBindings;
  7290. if (scopeDirective && elementControllers[scopeDirective.name]) {
  7291. bindings = scopeDirective.$$bindings.bindToController;
  7292. controller = elementControllers[scopeDirective.name];
  7293. if (controller && controller.identifier && bindings) {
  7294. controllerForBindings = controller;
  7295. thisLinkFn.$$destroyBindings =
  7296. initializeDirectiveBindings(scope, attrs, controller.instance,
  7297. bindings, scopeDirective);
  7298. }
  7299. }
  7300. for (i in elementControllers) {
  7301. controller = elementControllers[i];
  7302. var controllerResult = controller();
  7303. if (controllerResult !== controller.instance) {
  7304. controller.instance = controllerResult;
  7305. $element.data('$' + directive.name + 'Controller', controllerResult);
  7306. if (controller === controllerForBindings) {
  7307. // Remove and re-install bindToController bindings
  7308. thisLinkFn.$$destroyBindings();
  7309. thisLinkFn.$$destroyBindings =
  7310. initializeDirectiveBindings(scope, attrs, controllerResult, bindings, scopeDirective);
  7311. }
  7312. }
  7313. }
  7314. }
  7315. // PRELINKING
  7316. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  7317. linkFn = preLinkFns[i];
  7318. invokeLinkFn(linkFn,
  7319. linkFn.isolateScope ? isolateScope : scope,
  7320. $element,
  7321. attrs,
  7322. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  7323. transcludeFn
  7324. );
  7325. }
  7326. // RECURSION
  7327. // We only pass the isolate scope, if the isolate directive has a template,
  7328. // otherwise the child elements do not belong to the isolate directive.
  7329. var scopeToChild = scope;
  7330. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  7331. scopeToChild = isolateScope;
  7332. }
  7333. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  7334. // POSTLINKING
  7335. for (i = postLinkFns.length - 1; i >= 0; i--) {
  7336. linkFn = postLinkFns[i];
  7337. invokeLinkFn(linkFn,
  7338. linkFn.isolateScope ? isolateScope : scope,
  7339. $element,
  7340. attrs,
  7341. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  7342. transcludeFn
  7343. );
  7344. }
  7345. // This is the function that is injected as `$transclude`.
  7346. // Note: all arguments are optional!
  7347. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {
  7348. var transcludeControllers;
  7349. // No scope passed in:
  7350. if (!isScope(scope)) {
  7351. futureParentElement = cloneAttachFn;
  7352. cloneAttachFn = scope;
  7353. scope = undefined;
  7354. }
  7355. if (hasElementTranscludeDirective) {
  7356. transcludeControllers = elementControllers;
  7357. }
  7358. if (!futureParentElement) {
  7359. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  7360. }
  7361. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  7362. }
  7363. }
  7364. }
  7365. function markDirectivesAsIsolate(directives) {
  7366. // mark all directives as needing isolate scope.
  7367. for (var j = 0, jj = directives.length; j < jj; j++) {
  7368. directives[j] = inherit(directives[j], {$$isolateScope: true});
  7369. }
  7370. }
  7371. /**
  7372. * looks up the directive and decorates it with exception handling and proper parameters. We
  7373. * call this the boundDirective.
  7374. *
  7375. * @param {string} name name of the directive to look up.
  7376. * @param {string} location The directive must be found in specific format.
  7377. * String containing any of theses characters:
  7378. *
  7379. * * `E`: element name
  7380. * * `A': attribute
  7381. * * `C`: class
  7382. * * `M`: comment
  7383. * @returns {boolean} true if directive was added.
  7384. */
  7385. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  7386. endAttrName) {
  7387. if (name === ignoreDirective) return null;
  7388. var match = null;
  7389. if (hasDirectives.hasOwnProperty(name)) {
  7390. for (var directive, directives = $injector.get(name + Suffix),
  7391. i = 0, ii = directives.length; i < ii; i++) {
  7392. try {
  7393. directive = directives[i];
  7394. if ((maxPriority === undefined || maxPriority > directive.priority) &&
  7395. directive.restrict.indexOf(location) != -1) {
  7396. if (startAttrName) {
  7397. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  7398. }
  7399. tDirectives.push(directive);
  7400. match = directive;
  7401. }
  7402. } catch (e) { $exceptionHandler(e); }
  7403. }
  7404. }
  7405. return match;
  7406. }
  7407. /**
  7408. * looks up the directive and returns true if it is a multi-element directive,
  7409. * and therefore requires DOM nodes between -start and -end markers to be grouped
  7410. * together.
  7411. *
  7412. * @param {string} name name of the directive to look up.
  7413. * @returns true if directive was registered as multi-element.
  7414. */
  7415. function directiveIsMultiElement(name) {
  7416. if (hasDirectives.hasOwnProperty(name)) {
  7417. for (var directive, directives = $injector.get(name + Suffix),
  7418. i = 0, ii = directives.length; i < ii; i++) {
  7419. directive = directives[i];
  7420. if (directive.multiElement) {
  7421. return true;
  7422. }
  7423. }
  7424. }
  7425. return false;
  7426. }
  7427. /**
  7428. * When the element is replaced with HTML template then the new attributes
  7429. * on the template need to be merged with the existing attributes in the DOM.
  7430. * The desired effect is to have both of the attributes present.
  7431. *
  7432. * @param {object} dst destination attributes (original DOM)
  7433. * @param {object} src source attributes (from the directive template)
  7434. */
  7435. function mergeTemplateAttributes(dst, src) {
  7436. var srcAttr = src.$attr,
  7437. dstAttr = dst.$attr,
  7438. $element = dst.$$element;
  7439. // reapply the old attributes to the new element
  7440. forEach(dst, function(value, key) {
  7441. if (key.charAt(0) != '$') {
  7442. if (src[key] && src[key] !== value) {
  7443. value += (key === 'style' ? ';' : ' ') + src[key];
  7444. }
  7445. dst.$set(key, value, true, srcAttr[key]);
  7446. }
  7447. });
  7448. // copy the new attributes on the old attrs object
  7449. forEach(src, function(value, key) {
  7450. if (key == 'class') {
  7451. safeAddClass($element, value);
  7452. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  7453. } else if (key == 'style') {
  7454. $element.attr('style', $element.attr('style') + ';' + value);
  7455. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  7456. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  7457. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  7458. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  7459. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  7460. dst[key] = value;
  7461. dstAttr[key] = srcAttr[key];
  7462. }
  7463. });
  7464. }
  7465. function compileTemplateUrl(directives, $compileNode, tAttrs,
  7466. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  7467. var linkQueue = [],
  7468. afterTemplateNodeLinkFn,
  7469. afterTemplateChildLinkFn,
  7470. beforeTemplateCompileNode = $compileNode[0],
  7471. origAsyncDirective = directives.shift(),
  7472. derivedSyncDirective = inherit(origAsyncDirective, {
  7473. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  7474. }),
  7475. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  7476. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  7477. : origAsyncDirective.templateUrl,
  7478. templateNamespace = origAsyncDirective.templateNamespace;
  7479. $compileNode.empty();
  7480. $templateRequest($sce.getTrustedResourceUrl(templateUrl))
  7481. .then(function(content) {
  7482. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  7483. content = denormalizeTemplate(content);
  7484. if (origAsyncDirective.replace) {
  7485. if (jqLiteIsTextNode(content)) {
  7486. $template = [];
  7487. } else {
  7488. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  7489. }
  7490. compileNode = $template[0];
  7491. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7492. throw $compileMinErr('tplrt',
  7493. "Template for directive '{0}' must have exactly one root element. {1}",
  7494. origAsyncDirective.name, templateUrl);
  7495. }
  7496. tempTemplateAttrs = {$attr: {}};
  7497. replaceWith($rootElement, $compileNode, compileNode);
  7498. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  7499. if (isObject(origAsyncDirective.scope)) {
  7500. markDirectivesAsIsolate(templateDirectives);
  7501. }
  7502. directives = templateDirectives.concat(directives);
  7503. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  7504. } else {
  7505. compileNode = beforeTemplateCompileNode;
  7506. $compileNode.html(content);
  7507. }
  7508. directives.unshift(derivedSyncDirective);
  7509. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  7510. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  7511. previousCompileContext);
  7512. forEach($rootElement, function(node, i) {
  7513. if (node == compileNode) {
  7514. $rootElement[i] = $compileNode[0];
  7515. }
  7516. });
  7517. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  7518. while (linkQueue.length) {
  7519. var scope = linkQueue.shift(),
  7520. beforeTemplateLinkNode = linkQueue.shift(),
  7521. linkRootElement = linkQueue.shift(),
  7522. boundTranscludeFn = linkQueue.shift(),
  7523. linkNode = $compileNode[0];
  7524. if (scope.$$destroyed) continue;
  7525. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  7526. var oldClasses = beforeTemplateLinkNode.className;
  7527. if (!(previousCompileContext.hasElementTranscludeDirective &&
  7528. origAsyncDirective.replace)) {
  7529. // it was cloned therefore we have to clone as well.
  7530. linkNode = jqLiteClone(compileNode);
  7531. }
  7532. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  7533. // Copy in CSS classes from original node
  7534. safeAddClass(jqLite(linkNode), oldClasses);
  7535. }
  7536. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7537. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7538. } else {
  7539. childBoundTranscludeFn = boundTranscludeFn;
  7540. }
  7541. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  7542. childBoundTranscludeFn, afterTemplateNodeLinkFn);
  7543. }
  7544. linkQueue = null;
  7545. });
  7546. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  7547. var childBoundTranscludeFn = boundTranscludeFn;
  7548. if (scope.$$destroyed) return;
  7549. if (linkQueue) {
  7550. linkQueue.push(scope,
  7551. node,
  7552. rootElement,
  7553. childBoundTranscludeFn);
  7554. } else {
  7555. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7556. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7557. }
  7558. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn,
  7559. afterTemplateNodeLinkFn);
  7560. }
  7561. };
  7562. }
  7563. /**
  7564. * Sorting function for bound directives.
  7565. */
  7566. function byPriority(a, b) {
  7567. var diff = b.priority - a.priority;
  7568. if (diff !== 0) return diff;
  7569. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  7570. return a.index - b.index;
  7571. }
  7572. function assertNoDuplicate(what, previousDirective, directive, element) {
  7573. if (previousDirective) {
  7574. throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
  7575. previousDirective.name, directive.name, what, startingTag(element));
  7576. }
  7577. }
  7578. function addTextInterpolateDirective(directives, text) {
  7579. var interpolateFn = $interpolate(text, true);
  7580. if (interpolateFn) {
  7581. directives.push({
  7582. priority: 0,
  7583. compile: function textInterpolateCompileFn(templateNode) {
  7584. var templateNodeParent = templateNode.parent(),
  7585. hasCompileParent = !!templateNodeParent.length;
  7586. // When transcluding a template that has bindings in the root
  7587. // we don't have a parent and thus need to add the class during linking fn.
  7588. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  7589. return function textInterpolateLinkFn(scope, node) {
  7590. var parent = node.parent();
  7591. if (!hasCompileParent) compile.$$addBindingClass(parent);
  7592. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  7593. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  7594. node[0].nodeValue = value;
  7595. });
  7596. };
  7597. }
  7598. });
  7599. }
  7600. }
  7601. function wrapTemplate(type, template) {
  7602. type = lowercase(type || 'html');
  7603. switch (type) {
  7604. case 'svg':
  7605. case 'math':
  7606. var wrapper = document.createElement('div');
  7607. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  7608. return wrapper.childNodes[0].childNodes;
  7609. default:
  7610. return template;
  7611. }
  7612. }
  7613. function getTrustedContext(node, attrNormalizedName) {
  7614. if (attrNormalizedName == "srcdoc") {
  7615. return $sce.HTML;
  7616. }
  7617. var tag = nodeName_(node);
  7618. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  7619. if (attrNormalizedName == "xlinkHref" ||
  7620. (tag == "form" && attrNormalizedName == "action") ||
  7621. (tag != "img" && (attrNormalizedName == "src" ||
  7622. attrNormalizedName == "ngSrc"))) {
  7623. return $sce.RESOURCE_URL;
  7624. }
  7625. }
  7626. function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  7627. var trustedContext = getTrustedContext(node, name);
  7628. allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
  7629. var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
  7630. // no interpolation found -> ignore
  7631. if (!interpolateFn) return;
  7632. if (name === "multiple" && nodeName_(node) === "select") {
  7633. throw $compileMinErr("selmulti",
  7634. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  7635. startingTag(node));
  7636. }
  7637. directives.push({
  7638. priority: 100,
  7639. compile: function() {
  7640. return {
  7641. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  7642. var $$observers = (attr.$$observers || (attr.$$observers = {}));
  7643. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  7644. throw $compileMinErr('nodomevents',
  7645. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  7646. "ng- versions (such as ng-click instead of onclick) instead.");
  7647. }
  7648. // If the attribute has changed since last $interpolate()ed
  7649. var newValue = attr[name];
  7650. if (newValue !== value) {
  7651. // we need to interpolate again since the attribute value has been updated
  7652. // (e.g. by another directive's compile function)
  7653. // ensure unset/empty values make interpolateFn falsy
  7654. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  7655. value = newValue;
  7656. }
  7657. // if attribute was updated so that there is no interpolation going on we don't want to
  7658. // register any observers
  7659. if (!interpolateFn) return;
  7660. // initialize attr object so that it's ready in case we need the value for isolate
  7661. // scope initialization, otherwise the value would not be available from isolate
  7662. // directive's linking fn during linking phase
  7663. attr[name] = interpolateFn(scope);
  7664. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  7665. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  7666. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  7667. //special case for class attribute addition + removal
  7668. //so that class changes can tap into the animation
  7669. //hooks provided by the $animate service. Be sure to
  7670. //skip animations when the first digest occurs (when
  7671. //both the new and the old values are the same) since
  7672. //the CSS classes are the non-interpolated values
  7673. if (name === 'class' && newValue != oldValue) {
  7674. attr.$updateClass(newValue, oldValue);
  7675. } else {
  7676. attr.$set(name, newValue);
  7677. }
  7678. });
  7679. }
  7680. };
  7681. }
  7682. });
  7683. }
  7684. /**
  7685. * This is a special jqLite.replaceWith, which can replace items which
  7686. * have no parents, provided that the containing jqLite collection is provided.
  7687. *
  7688. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  7689. * in the root of the tree.
  7690. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  7691. * the shell, but replace its DOM node reference.
  7692. * @param {Node} newNode The new DOM node.
  7693. */
  7694. function replaceWith($rootElement, elementsToRemove, newNode) {
  7695. var firstElementToRemove = elementsToRemove[0],
  7696. removeCount = elementsToRemove.length,
  7697. parent = firstElementToRemove.parentNode,
  7698. i, ii;
  7699. if ($rootElement) {
  7700. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  7701. if ($rootElement[i] == firstElementToRemove) {
  7702. $rootElement[i++] = newNode;
  7703. for (var j = i, j2 = j + removeCount - 1,
  7704. jj = $rootElement.length;
  7705. j < jj; j++, j2++) {
  7706. if (j2 < jj) {
  7707. $rootElement[j] = $rootElement[j2];
  7708. } else {
  7709. delete $rootElement[j];
  7710. }
  7711. }
  7712. $rootElement.length -= removeCount - 1;
  7713. // If the replaced element is also the jQuery .context then replace it
  7714. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  7715. // http://api.jquery.com/context/
  7716. if ($rootElement.context === firstElementToRemove) {
  7717. $rootElement.context = newNode;
  7718. }
  7719. break;
  7720. }
  7721. }
  7722. }
  7723. if (parent) {
  7724. parent.replaceChild(newNode, firstElementToRemove);
  7725. }
  7726. // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?
  7727. var fragment = document.createDocumentFragment();
  7728. fragment.appendChild(firstElementToRemove);
  7729. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  7730. // data here because there's no public interface in jQuery to do that and copying over
  7731. // event listeners (which is the main use of private data) wouldn't work anyway.
  7732. jqLite(newNode).data(jqLite(firstElementToRemove).data());
  7733. // Remove data of the replaced element. We cannot just call .remove()
  7734. // on the element it since that would deallocate scope that is needed
  7735. // for the new node. Instead, remove the data "manually".
  7736. if (!jQuery) {
  7737. delete jqLite.cache[firstElementToRemove[jqLite.expando]];
  7738. } else {
  7739. // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after
  7740. // the replaced element. The cleanData version monkey-patched by Angular would cause
  7741. // the scope to be trashed and we do need the very same scope to work with the new
  7742. // element. However, we cannot just cache the non-patched version and use it here as
  7743. // that would break if another library patches the method after Angular does (one
  7744. // example is jQuery UI). Instead, set a flag indicating scope destroying should be
  7745. // skipped this one time.
  7746. skipDestroyOnNextJQueryCleanData = true;
  7747. jQuery.cleanData([firstElementToRemove]);
  7748. }
  7749. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  7750. var element = elementsToRemove[k];
  7751. jqLite(element).remove(); // must do this way to clean up expando
  7752. fragment.appendChild(element);
  7753. delete elementsToRemove[k];
  7754. }
  7755. elementsToRemove[0] = newNode;
  7756. elementsToRemove.length = 1;
  7757. }
  7758. function cloneAndAnnotateFn(fn, annotation) {
  7759. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  7760. }
  7761. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  7762. try {
  7763. linkFn(scope, $element, attrs, controllers, transcludeFn);
  7764. } catch (e) {
  7765. $exceptionHandler(e, startingTag($element));
  7766. }
  7767. }
  7768. // Set up $watches for isolate scope and controller bindings. This process
  7769. // only occurs for isolate scopes and new scopes with controllerAs.
  7770. function initializeDirectiveBindings(scope, attrs, destination, bindings,
  7771. directive, newScope) {
  7772. var onNewScopeDestroyed;
  7773. forEach(bindings, function(definition, scopeName) {
  7774. var attrName = definition.attrName,
  7775. optional = definition.optional,
  7776. mode = definition.mode, // @, =, or &
  7777. lastValue,
  7778. parentGet, parentSet, compare;
  7779. switch (mode) {
  7780. case '@':
  7781. attrs.$observe(attrName, function(value) {
  7782. destination[scopeName] = value;
  7783. });
  7784. attrs.$$observers[attrName].$$scope = scope;
  7785. if (attrs[attrName]) {
  7786. // If the attribute has been provided then we trigger an interpolation to ensure
  7787. // the value is there for use in the link fn
  7788. destination[scopeName] = $interpolate(attrs[attrName])(scope);
  7789. }
  7790. break;
  7791. case '=':
  7792. if (optional && !attrs[attrName]) {
  7793. return;
  7794. }
  7795. parentGet = $parse(attrs[attrName]);
  7796. if (parentGet.literal) {
  7797. compare = equals;
  7798. } else {
  7799. compare = function(a, b) { return a === b || (a !== a && b !== b); };
  7800. }
  7801. parentSet = parentGet.assign || function() {
  7802. // reset the change, or we will throw this exception on every $digest
  7803. lastValue = destination[scopeName] = parentGet(scope);
  7804. throw $compileMinErr('nonassign',
  7805. "Expression '{0}' used with directive '{1}' is non-assignable!",
  7806. attrs[attrName], directive.name);
  7807. };
  7808. lastValue = destination[scopeName] = parentGet(scope);
  7809. var parentValueWatch = function parentValueWatch(parentValue) {
  7810. if (!compare(parentValue, destination[scopeName])) {
  7811. // we are out of sync and need to copy
  7812. if (!compare(parentValue, lastValue)) {
  7813. // parent changed and it has precedence
  7814. destination[scopeName] = parentValue;
  7815. } else {
  7816. // if the parent can be assigned then do so
  7817. parentSet(scope, parentValue = destination[scopeName]);
  7818. }
  7819. }
  7820. return lastValue = parentValue;
  7821. };
  7822. parentValueWatch.$stateful = true;
  7823. var unwatch;
  7824. if (definition.collection) {
  7825. unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  7826. } else {
  7827. unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  7828. }
  7829. onNewScopeDestroyed = (onNewScopeDestroyed || []);
  7830. onNewScopeDestroyed.push(unwatch);
  7831. break;
  7832. case '&':
  7833. // Don't assign Object.prototype method to scope
  7834. if (!attrs.hasOwnProperty(attrName) && optional) break;
  7835. parentGet = $parse(attrs[attrName]);
  7836. // Don't assign noop to destination if expression is not valid
  7837. if (parentGet === noop && optional) break;
  7838. destination[scopeName] = function(locals) {
  7839. return parentGet(scope, locals);
  7840. };
  7841. break;
  7842. }
  7843. });
  7844. var destroyBindings = onNewScopeDestroyed ? function destroyBindings() {
  7845. for (var i = 0, ii = onNewScopeDestroyed.length; i < ii; ++i) {
  7846. onNewScopeDestroyed[i]();
  7847. }
  7848. } : noop;
  7849. if (newScope && destroyBindings !== noop) {
  7850. newScope.$on('$destroy', destroyBindings);
  7851. return noop;
  7852. }
  7853. return destroyBindings;
  7854. }
  7855. }];
  7856. }
  7857. var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
  7858. /**
  7859. * Converts all accepted directives format into proper directive name.
  7860. * @param name Name to normalize
  7861. */
  7862. function directiveNormalize(name) {
  7863. return camelCase(name.replace(PREFIX_REGEXP, ''));
  7864. }
  7865. /**
  7866. * @ngdoc type
  7867. * @name $compile.directive.Attributes
  7868. *
  7869. * @description
  7870. * A shared object between directive compile / linking functions which contains normalized DOM
  7871. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  7872. * needed since all of these are treated as equivalent in Angular:
  7873. *
  7874. * ```
  7875. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  7876. * ```
  7877. */
  7878. /**
  7879. * @ngdoc property
  7880. * @name $compile.directive.Attributes#$attr
  7881. *
  7882. * @description
  7883. * A map of DOM element attribute names to the normalized name. This is
  7884. * needed to do reverse lookup from normalized name back to actual name.
  7885. */
  7886. /**
  7887. * @ngdoc method
  7888. * @name $compile.directive.Attributes#$set
  7889. * @kind function
  7890. *
  7891. * @description
  7892. * Set DOM element attribute value.
  7893. *
  7894. *
  7895. * @param {string} name Normalized element attribute name of the property to modify. The name is
  7896. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  7897. * property to the original name.
  7898. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  7899. */
  7900. /**
  7901. * Closure compiler type information
  7902. */
  7903. function nodesetLinkingFn(
  7904. /* angular.Scope */ scope,
  7905. /* NodeList */ nodeList,
  7906. /* Element */ rootElement,
  7907. /* function(Function) */ boundTranscludeFn
  7908. ) {}
  7909. function directiveLinkingFn(
  7910. /* nodesetLinkingFn */ nodesetLinkingFn,
  7911. /* angular.Scope */ scope,
  7912. /* Node */ node,
  7913. /* Element */ rootElement,
  7914. /* function(Function) */ boundTranscludeFn
  7915. ) {}
  7916. function tokenDifference(str1, str2) {
  7917. var values = '',
  7918. tokens1 = str1.split(/\s+/),
  7919. tokens2 = str2.split(/\s+/);
  7920. outer:
  7921. for (var i = 0; i < tokens1.length; i++) {
  7922. var token = tokens1[i];
  7923. for (var j = 0; j < tokens2.length; j++) {
  7924. if (token == tokens2[j]) continue outer;
  7925. }
  7926. values += (values.length > 0 ? ' ' : '') + token;
  7927. }
  7928. return values;
  7929. }
  7930. function removeComments(jqNodes) {
  7931. jqNodes = jqLite(jqNodes);
  7932. var i = jqNodes.length;
  7933. if (i <= 1) {
  7934. return jqNodes;
  7935. }
  7936. while (i--) {
  7937. var node = jqNodes[i];
  7938. if (node.nodeType === NODE_TYPE_COMMENT) {
  7939. splice.call(jqNodes, i, 1);
  7940. }
  7941. }
  7942. return jqNodes;
  7943. }
  7944. var $controllerMinErr = minErr('$controller');
  7945. var CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
  7946. function identifierForController(controller, ident) {
  7947. if (ident && isString(ident)) return ident;
  7948. if (isString(controller)) {
  7949. var match = CNTRL_REG.exec(controller);
  7950. if (match) return match[3];
  7951. }
  7952. }
  7953. /**
  7954. * @ngdoc provider
  7955. * @name $controllerProvider
  7956. * @description
  7957. * The {@link ng.$controller $controller service} is used by Angular to create new
  7958. * controllers.
  7959. *
  7960. * This provider allows controller registration via the
  7961. * {@link ng.$controllerProvider#register register} method.
  7962. */
  7963. function $ControllerProvider() {
  7964. var controllers = {},
  7965. globals = false;
  7966. /**
  7967. * @ngdoc method
  7968. * @name $controllerProvider#register
  7969. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  7970. * the names and the values are the constructors.
  7971. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  7972. * annotations in the array notation).
  7973. */
  7974. this.register = function(name, constructor) {
  7975. assertNotHasOwnProperty(name, 'controller');
  7976. if (isObject(name)) {
  7977. extend(controllers, name);
  7978. } else {
  7979. controllers[name] = constructor;
  7980. }
  7981. };
  7982. /**
  7983. * @ngdoc method
  7984. * @name $controllerProvider#allowGlobals
  7985. * @description If called, allows `$controller` to find controller constructors on `window`
  7986. */
  7987. this.allowGlobals = function() {
  7988. globals = true;
  7989. };
  7990. this.$get = ['$injector', '$window', function($injector, $window) {
  7991. /**
  7992. * @ngdoc service
  7993. * @name $controller
  7994. * @requires $injector
  7995. *
  7996. * @param {Function|string} constructor If called with a function then it's considered to be the
  7997. * controller constructor function. Otherwise it's considered to be a string which is used
  7998. * to retrieve the controller constructor using the following steps:
  7999. *
  8000. * * check if a controller with given name is registered via `$controllerProvider`
  8001. * * check if evaluating the string on the current scope returns a constructor
  8002. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  8003. * `window` object (not recommended)
  8004. *
  8005. * The string can use the `controller as property` syntax, where the controller instance is published
  8006. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  8007. * to work correctly.
  8008. *
  8009. * @param {Object} locals Injection locals for Controller.
  8010. * @return {Object} Instance of given controller.
  8011. *
  8012. * @description
  8013. * `$controller` service is responsible for instantiating controllers.
  8014. *
  8015. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  8016. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  8017. */
  8018. return function(expression, locals, later, ident) {
  8019. // PRIVATE API:
  8020. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  8021. // If true, $controller will allocate the object with the correct
  8022. // prototype chain, but will not invoke the controller until a returned
  8023. // callback is invoked.
  8024. // param `ident` --- An optional label which overrides the label parsed from the controller
  8025. // expression, if any.
  8026. var instance, match, constructor, identifier;
  8027. later = later === true;
  8028. if (ident && isString(ident)) {
  8029. identifier = ident;
  8030. }
  8031. if (isString(expression)) {
  8032. match = expression.match(CNTRL_REG);
  8033. if (!match) {
  8034. throw $controllerMinErr('ctrlfmt',
  8035. "Badly formed controller string '{0}'. " +
  8036. "Must match `__name__ as __id__` or `__name__`.", expression);
  8037. }
  8038. constructor = match[1],
  8039. identifier = identifier || match[3];
  8040. expression = controllers.hasOwnProperty(constructor)
  8041. ? controllers[constructor]
  8042. : getter(locals.$scope, constructor, true) ||
  8043. (globals ? getter($window, constructor, true) : undefined);
  8044. assertArgFn(expression, constructor, true);
  8045. }
  8046. if (later) {
  8047. // Instantiate controller later:
  8048. // This machinery is used to create an instance of the object before calling the
  8049. // controller's constructor itself.
  8050. //
  8051. // This allows properties to be added to the controller before the constructor is
  8052. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  8053. //
  8054. // This feature is not intended for use by applications, and is thus not documented
  8055. // publicly.
  8056. // Object creation: http://jsperf.com/create-constructor/2
  8057. var controllerPrototype = (isArray(expression) ?
  8058. expression[expression.length - 1] : expression).prototype;
  8059. instance = Object.create(controllerPrototype || null);
  8060. if (identifier) {
  8061. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8062. }
  8063. var instantiate;
  8064. return instantiate = extend(function() {
  8065. var result = $injector.invoke(expression, instance, locals, constructor);
  8066. if (result !== instance && (isObject(result) || isFunction(result))) {
  8067. instance = result;
  8068. if (identifier) {
  8069. // If result changed, re-assign controllerAs value to scope.
  8070. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8071. }
  8072. }
  8073. return instance;
  8074. }, {
  8075. instance: instance,
  8076. identifier: identifier
  8077. });
  8078. }
  8079. instance = $injector.instantiate(expression, locals, constructor);
  8080. if (identifier) {
  8081. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8082. }
  8083. return instance;
  8084. };
  8085. function addIdentifier(locals, identifier, instance, name) {
  8086. if (!(locals && isObject(locals.$scope))) {
  8087. throw minErr('$controller')('noscp',
  8088. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  8089. name, identifier);
  8090. }
  8091. locals.$scope[identifier] = instance;
  8092. }
  8093. }];
  8094. }
  8095. /**
  8096. * @ngdoc service
  8097. * @name $document
  8098. * @requires $window
  8099. *
  8100. * @description
  8101. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  8102. *
  8103. * @example
  8104. <example module="documentExample">
  8105. <file name="index.html">
  8106. <div ng-controller="ExampleController">
  8107. <p>$document title: <b ng-bind="title"></b></p>
  8108. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  8109. </div>
  8110. </file>
  8111. <file name="script.js">
  8112. angular.module('documentExample', [])
  8113. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  8114. $scope.title = $document[0].title;
  8115. $scope.windowTitle = angular.element(window.document)[0].title;
  8116. }]);
  8117. </file>
  8118. </example>
  8119. */
  8120. function $DocumentProvider() {
  8121. this.$get = ['$window', function(window) {
  8122. return jqLite(window.document);
  8123. }];
  8124. }
  8125. /**
  8126. * @ngdoc service
  8127. * @name $exceptionHandler
  8128. * @requires ng.$log
  8129. *
  8130. * @description
  8131. * Any uncaught exception in angular expressions is delegated to this service.
  8132. * The default implementation simply delegates to `$log.error` which logs it into
  8133. * the browser console.
  8134. *
  8135. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  8136. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  8137. *
  8138. * ## Example:
  8139. *
  8140. * ```js
  8141. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
  8142. * return function(exception, cause) {
  8143. * exception.message += ' (caused by "' + cause + '")';
  8144. * throw exception;
  8145. * };
  8146. * });
  8147. * ```
  8148. *
  8149. * This example will override the normal action of `$exceptionHandler`, to make angular
  8150. * exceptions fail hard when they happen, instead of just logging to the console.
  8151. *
  8152. * <hr />
  8153. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  8154. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  8155. * (unless executed during a digest).
  8156. *
  8157. * If you wish, you can manually delegate exceptions, e.g.
  8158. * `try { ... } catch(e) { $exceptionHandler(e); }`
  8159. *
  8160. * @param {Error} exception Exception associated with the error.
  8161. * @param {string=} cause optional information about the context in which
  8162. * the error was thrown.
  8163. *
  8164. */
  8165. function $ExceptionHandlerProvider() {
  8166. this.$get = ['$log', function($log) {
  8167. return function(exception, cause) {
  8168. $log.error.apply($log, arguments);
  8169. };
  8170. }];
  8171. }
  8172. var APPLICATION_JSON = 'application/json';
  8173. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  8174. var JSON_START = /^\[|^\{(?!\{)/;
  8175. var JSON_ENDS = {
  8176. '[': /]$/,
  8177. '{': /}$/
  8178. };
  8179. var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
  8180. function serializeValue(v) {
  8181. if (isObject(v)) {
  8182. return isDate(v) ? v.toISOString() : toJson(v);
  8183. }
  8184. return v;
  8185. }
  8186. function $HttpParamSerializerProvider() {
  8187. /**
  8188. * @ngdoc service
  8189. * @name $httpParamSerializer
  8190. * @description
  8191. *
  8192. * Default $http params serializer that converts objects to a part of a request URL
  8193. * according to the following rules:
  8194. * * `{'foo': 'bar'}` results in `foo=bar`
  8195. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  8196. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  8197. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
  8198. * */
  8199. this.$get = function() {
  8200. return function ngParamSerializer(params) {
  8201. if (!params) return '';
  8202. var parts = [];
  8203. forEachSorted(params, function(value, key) {
  8204. if (value === null || isUndefined(value)) return;
  8205. if (isArray(value)) {
  8206. forEach(value, function(v, k) {
  8207. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  8208. });
  8209. } else {
  8210. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  8211. }
  8212. });
  8213. return parts.join('&');
  8214. };
  8215. };
  8216. }
  8217. function $HttpParamSerializerJQLikeProvider() {
  8218. /**
  8219. * @ngdoc service
  8220. * @name $httpParamSerializerJQLike
  8221. * @description
  8222. *
  8223. * Alternative $http params serializer that follows jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  8224. * */
  8225. this.$get = function() {
  8226. return function jQueryLikeParamSerializer(params) {
  8227. if (!params) return '';
  8228. var parts = [];
  8229. serialize(params, '', true);
  8230. return parts.join('&');
  8231. function serialize(toSerialize, prefix, topLevel) {
  8232. if (toSerialize === null || isUndefined(toSerialize)) return;
  8233. if (isArray(toSerialize)) {
  8234. forEach(toSerialize, function(value) {
  8235. serialize(value, prefix + '[]');
  8236. });
  8237. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  8238. forEachSorted(toSerialize, function(value, key) {
  8239. serialize(value, prefix +
  8240. (topLevel ? '' : '[') +
  8241. key +
  8242. (topLevel ? '' : ']'));
  8243. });
  8244. } else {
  8245. parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
  8246. }
  8247. }
  8248. };
  8249. };
  8250. }
  8251. function defaultHttpResponseTransform(data, headers) {
  8252. if (isString(data)) {
  8253. // Strip json vulnerability protection prefix and trim whitespace
  8254. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  8255. if (tempData) {
  8256. var contentType = headers('Content-Type');
  8257. if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
  8258. data = fromJson(tempData);
  8259. }
  8260. }
  8261. }
  8262. return data;
  8263. }
  8264. function isJsonLike(str) {
  8265. var jsonStart = str.match(JSON_START);
  8266. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  8267. }
  8268. /**
  8269. * Parse headers into key value object
  8270. *
  8271. * @param {string} headers Raw headers as a string
  8272. * @returns {Object} Parsed headers as key value object
  8273. */
  8274. function parseHeaders(headers) {
  8275. var parsed = createMap(), i;
  8276. function fillInParsed(key, val) {
  8277. if (key) {
  8278. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  8279. }
  8280. }
  8281. if (isString(headers)) {
  8282. forEach(headers.split('\n'), function(line) {
  8283. i = line.indexOf(':');
  8284. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  8285. });
  8286. } else if (isObject(headers)) {
  8287. forEach(headers, function(headerVal, headerKey) {
  8288. fillInParsed(lowercase(headerKey), trim(headerVal));
  8289. });
  8290. }
  8291. return parsed;
  8292. }
  8293. /**
  8294. * Returns a function that provides access to parsed headers.
  8295. *
  8296. * Headers are lazy parsed when first requested.
  8297. * @see parseHeaders
  8298. *
  8299. * @param {(string|Object)} headers Headers to provide access to.
  8300. * @returns {function(string=)} Returns a getter function which if called with:
  8301. *
  8302. * - if called with single an argument returns a single header value or null
  8303. * - if called with no arguments returns an object containing all headers.
  8304. */
  8305. function headersGetter(headers) {
  8306. var headersObj;
  8307. return function(name) {
  8308. if (!headersObj) headersObj = parseHeaders(headers);
  8309. if (name) {
  8310. var value = headersObj[lowercase(name)];
  8311. if (value === void 0) {
  8312. value = null;
  8313. }
  8314. return value;
  8315. }
  8316. return headersObj;
  8317. };
  8318. }
  8319. /**
  8320. * Chain all given functions
  8321. *
  8322. * This function is used for both request and response transforming
  8323. *
  8324. * @param {*} data Data to transform.
  8325. * @param {function(string=)} headers HTTP headers getter fn.
  8326. * @param {number} status HTTP status code of the response.
  8327. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  8328. * @returns {*} Transformed data.
  8329. */
  8330. function transformData(data, headers, status, fns) {
  8331. if (isFunction(fns)) {
  8332. return fns(data, headers, status);
  8333. }
  8334. forEach(fns, function(fn) {
  8335. data = fn(data, headers, status);
  8336. });
  8337. return data;
  8338. }
  8339. function isSuccess(status) {
  8340. return 200 <= status && status < 300;
  8341. }
  8342. /**
  8343. * @ngdoc provider
  8344. * @name $httpProvider
  8345. * @description
  8346. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  8347. * */
  8348. function $HttpProvider() {
  8349. /**
  8350. * @ngdoc property
  8351. * @name $httpProvider#defaults
  8352. * @description
  8353. *
  8354. * Object containing default values for all {@link ng.$http $http} requests.
  8355. *
  8356. * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
  8357. * that will provide the cache for all requests who set their `cache` property to `true`.
  8358. * If you set the `default.cache = false` then only requests that specify their own custom
  8359. * cache object will be cached. See {@link $http#caching $http Caching} for more information.
  8360. *
  8361. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  8362. * Defaults value is `'XSRF-TOKEN'`.
  8363. *
  8364. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  8365. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  8366. *
  8367. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  8368. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  8369. * setting default headers.
  8370. * - **`defaults.headers.common`**
  8371. * - **`defaults.headers.post`**
  8372. * - **`defaults.headers.put`**
  8373. * - **`defaults.headers.patch`**
  8374. *
  8375. * - **`defaults.paramSerializer`** - {string|function(Object<string,string>):string} - A function used to prepare string representation
  8376. * of request parameters (specified as an object).
  8377. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  8378. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  8379. *
  8380. **/
  8381. var defaults = this.defaults = {
  8382. // transform incoming response data
  8383. transformResponse: [defaultHttpResponseTransform],
  8384. // transform outgoing request data
  8385. transformRequest: [function(d) {
  8386. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  8387. }],
  8388. // default headers
  8389. headers: {
  8390. common: {
  8391. 'Accept': 'application/json, text/plain, */*'
  8392. },
  8393. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  8394. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  8395. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  8396. },
  8397. xsrfCookieName: 'XSRF-TOKEN',
  8398. xsrfHeaderName: 'X-XSRF-TOKEN',
  8399. paramSerializer: '$httpParamSerializer'
  8400. };
  8401. var useApplyAsync = false;
  8402. /**
  8403. * @ngdoc method
  8404. * @name $httpProvider#useApplyAsync
  8405. * @description
  8406. *
  8407. * Configure $http service to combine processing of multiple http responses received at around
  8408. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  8409. * significant performance improvement for bigger applications that make many HTTP requests
  8410. * concurrently (common during application bootstrap).
  8411. *
  8412. * Defaults to false. If no value is specified, returns the current configured value.
  8413. *
  8414. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  8415. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  8416. * to load and share the same digest cycle.
  8417. *
  8418. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  8419. * otherwise, returns the current configured value.
  8420. **/
  8421. this.useApplyAsync = function(value) {
  8422. if (isDefined(value)) {
  8423. useApplyAsync = !!value;
  8424. return this;
  8425. }
  8426. return useApplyAsync;
  8427. };
  8428. /**
  8429. * @ngdoc property
  8430. * @name $httpProvider#interceptors
  8431. * @description
  8432. *
  8433. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  8434. * pre-processing of request or postprocessing of responses.
  8435. *
  8436. * These service factories are ordered by request, i.e. they are applied in the same order as the
  8437. * array, on request, but reverse order, on response.
  8438. *
  8439. * {@link ng.$http#interceptors Interceptors detailed info}
  8440. **/
  8441. var interceptorFactories = this.interceptors = [];
  8442. this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
  8443. function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
  8444. var defaultCache = $cacheFactory('$http');
  8445. /**
  8446. * Make sure that default param serializer is exposed as a function
  8447. */
  8448. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  8449. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  8450. /**
  8451. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  8452. * The reversal is needed so that we can build up the interception chain around the
  8453. * server request.
  8454. */
  8455. var reversedInterceptors = [];
  8456. forEach(interceptorFactories, function(interceptorFactory) {
  8457. reversedInterceptors.unshift(isString(interceptorFactory)
  8458. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  8459. });
  8460. /**
  8461. * @ngdoc service
  8462. * @kind function
  8463. * @name $http
  8464. * @requires ng.$httpBackend
  8465. * @requires $cacheFactory
  8466. * @requires $rootScope
  8467. * @requires $q
  8468. * @requires $injector
  8469. *
  8470. * @description
  8471. * The `$http` service is a core Angular service that facilitates communication with the remote
  8472. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  8473. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  8474. *
  8475. * For unit testing applications that use `$http` service, see
  8476. * {@link ngMock.$httpBackend $httpBackend mock}.
  8477. *
  8478. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  8479. * $resource} service.
  8480. *
  8481. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  8482. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  8483. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  8484. *
  8485. *
  8486. * ## General usage
  8487. * The `$http` service is a function which takes a single argument — a configuration object —
  8488. * that is used to generate an HTTP request and returns a {@link ng.$q promise}
  8489. * with two $http specific methods: `success` and `error`.
  8490. *
  8491. * ```js
  8492. * // Simple GET request example :
  8493. * $http.get('/someUrl').
  8494. * success(function(data, status, headers, config) {
  8495. * // this callback will be called asynchronously
  8496. * // when the response is available
  8497. * }).
  8498. * error(function(data, status, headers, config) {
  8499. * // called asynchronously if an error occurs
  8500. * // or server returns response with an error status.
  8501. * });
  8502. * ```
  8503. *
  8504. * ```js
  8505. * // Simple POST request example (passing data) :
  8506. * $http.post('/someUrl', {msg:'hello word!'}).
  8507. * success(function(data, status, headers, config) {
  8508. * // this callback will be called asynchronously
  8509. * // when the response is available
  8510. * }).
  8511. * error(function(data, status, headers, config) {
  8512. * // called asynchronously if an error occurs
  8513. * // or server returns response with an error status.
  8514. * });
  8515. * ```
  8516. *
  8517. *
  8518. * Since the returned value of calling the $http function is a `promise`, you can also use
  8519. * the `then` method to register callbacks, and these callbacks will receive a single argument –
  8520. * an object representing the response. See the API signature and type info below for more
  8521. * details.
  8522. *
  8523. * A response status code between 200 and 299 is considered a success status and
  8524. * will result in the success callback being called. Note that if the response is a redirect,
  8525. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  8526. * called for such responses.
  8527. *
  8528. * ## Writing Unit Tests that use $http
  8529. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  8530. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  8531. * request using trained responses.
  8532. *
  8533. * ```
  8534. * $httpBackend.expectGET(...);
  8535. * $http.get(...);
  8536. * $httpBackend.flush();
  8537. * ```
  8538. *
  8539. * ## Shortcut methods
  8540. *
  8541. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  8542. * request data must be passed in for POST/PUT requests.
  8543. *
  8544. * ```js
  8545. * $http.get('/someUrl').success(successCallback);
  8546. * $http.post('/someUrl', data).success(successCallback);
  8547. * ```
  8548. *
  8549. * Complete list of shortcut methods:
  8550. *
  8551. * - {@link ng.$http#get $http.get}
  8552. * - {@link ng.$http#head $http.head}
  8553. * - {@link ng.$http#post $http.post}
  8554. * - {@link ng.$http#put $http.put}
  8555. * - {@link ng.$http#delete $http.delete}
  8556. * - {@link ng.$http#jsonp $http.jsonp}
  8557. * - {@link ng.$http#patch $http.patch}
  8558. *
  8559. *
  8560. * ## Setting HTTP Headers
  8561. *
  8562. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  8563. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  8564. * object, which currently contains this default configuration:
  8565. *
  8566. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  8567. * - `Accept: application/json, text/plain, * / *`
  8568. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  8569. * - `Content-Type: application/json`
  8570. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  8571. * - `Content-Type: application/json`
  8572. *
  8573. * To add or overwrite these defaults, simply add or remove a property from these configuration
  8574. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  8575. * with the lowercased HTTP method name as the key, e.g.
  8576. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  8577. *
  8578. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  8579. * fashion. For example:
  8580. *
  8581. * ```
  8582. * module.run(function($http) {
  8583. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
  8584. * });
  8585. * ```
  8586. *
  8587. * In addition, you can supply a `headers` property in the config object passed when
  8588. * calling `$http(config)`, which overrides the defaults without changing them globally.
  8589. *
  8590. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  8591. * Use the `headers` property, setting the desired header to `undefined`. For example:
  8592. *
  8593. * ```js
  8594. * var req = {
  8595. * method: 'POST',
  8596. * url: 'http://example.com',
  8597. * headers: {
  8598. * 'Content-Type': undefined
  8599. * },
  8600. * data: { test: 'test' }
  8601. * }
  8602. *
  8603. * $http(req).success(function(){...}).error(function(){...});
  8604. * ```
  8605. *
  8606. * ## Transforming Requests and Responses
  8607. *
  8608. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  8609. * and `transformResponse`. These properties can be a single function that returns
  8610. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  8611. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  8612. *
  8613. * ### Default Transformations
  8614. *
  8615. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  8616. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  8617. * then these will be applied.
  8618. *
  8619. * You can augment or replace the default transformations by modifying these properties by adding to or
  8620. * replacing the array.
  8621. *
  8622. * Angular provides the following default transformations:
  8623. *
  8624. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  8625. *
  8626. * - If the `data` property of the request configuration object contains an object, serialize it
  8627. * into JSON format.
  8628. *
  8629. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  8630. *
  8631. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  8632. * - If JSON response is detected, deserialize it using a JSON parser.
  8633. *
  8634. *
  8635. * ### Overriding the Default Transformations Per Request
  8636. *
  8637. * If you wish override the request/response transformations only for a single request then provide
  8638. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  8639. * into `$http`.
  8640. *
  8641. * Note that if you provide these properties on the config object the default transformations will be
  8642. * overwritten. If you wish to augment the default transformations then you must include them in your
  8643. * local transformation array.
  8644. *
  8645. * The following code demonstrates adding a new response transformation to be run after the default response
  8646. * transformations have been run.
  8647. *
  8648. * ```js
  8649. * function appendTransform(defaults, transform) {
  8650. *
  8651. * // We can't guarantee that the default transformation is an array
  8652. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  8653. *
  8654. * // Append the new transformation to the defaults
  8655. * return defaults.concat(transform);
  8656. * }
  8657. *
  8658. * $http({
  8659. * url: '...',
  8660. * method: 'GET',
  8661. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  8662. * return doTransform(value);
  8663. * })
  8664. * });
  8665. * ```
  8666. *
  8667. *
  8668. * ## Caching
  8669. *
  8670. * To enable caching, set the request configuration `cache` property to `true` (to use default
  8671. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  8672. * When the cache is enabled, `$http` stores the response from the server in the specified
  8673. * cache. The next time the same request is made, the response is served from the cache without
  8674. * sending a request to the server.
  8675. *
  8676. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  8677. * the same way that real requests are.
  8678. *
  8679. * If there are multiple GET requests for the same URL that should be cached using the same
  8680. * cache, but the cache is not populated yet, only one request to the server will be made and
  8681. * the remaining requests will be fulfilled using the response from the first request.
  8682. *
  8683. * You can change the default cache to a new object (built with
  8684. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  8685. * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
  8686. * their `cache` property to `true` will now use this cache object.
  8687. *
  8688. * If you set the default cache to `false` then only requests that specify their own custom
  8689. * cache object will be cached.
  8690. *
  8691. * ## Interceptors
  8692. *
  8693. * Before you start creating interceptors, be sure to understand the
  8694. * {@link ng.$q $q and deferred/promise APIs}.
  8695. *
  8696. * For purposes of global error handling, authentication, or any kind of synchronous or
  8697. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  8698. * able to intercept requests before they are handed to the server and
  8699. * responses before they are handed over to the application code that
  8700. * initiated these requests. The interceptors leverage the {@link ng.$q
  8701. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  8702. *
  8703. * The interceptors are service factories that are registered with the `$httpProvider` by
  8704. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  8705. * injected with dependencies (if specified) and returns the interceptor.
  8706. *
  8707. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  8708. *
  8709. * * `request`: interceptors get called with a http `config` object. The function is free to
  8710. * modify the `config` object or create a new one. The function needs to return the `config`
  8711. * object directly, or a promise containing the `config` or a new `config` object.
  8712. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  8713. * resolved with a rejection.
  8714. * * `response`: interceptors get called with http `response` object. The function is free to
  8715. * modify the `response` object or create a new one. The function needs to return the `response`
  8716. * object directly, or as a promise containing the `response` or a new `response` object.
  8717. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  8718. * resolved with a rejection.
  8719. *
  8720. *
  8721. * ```js
  8722. * // register the interceptor as a service
  8723. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  8724. * return {
  8725. * // optional method
  8726. * 'request': function(config) {
  8727. * // do something on success
  8728. * return config;
  8729. * },
  8730. *
  8731. * // optional method
  8732. * 'requestError': function(rejection) {
  8733. * // do something on error
  8734. * if (canRecover(rejection)) {
  8735. * return responseOrNewPromise
  8736. * }
  8737. * return $q.reject(rejection);
  8738. * },
  8739. *
  8740. *
  8741. *
  8742. * // optional method
  8743. * 'response': function(response) {
  8744. * // do something on success
  8745. * return response;
  8746. * },
  8747. *
  8748. * // optional method
  8749. * 'responseError': function(rejection) {
  8750. * // do something on error
  8751. * if (canRecover(rejection)) {
  8752. * return responseOrNewPromise
  8753. * }
  8754. * return $q.reject(rejection);
  8755. * }
  8756. * };
  8757. * });
  8758. *
  8759. * $httpProvider.interceptors.push('myHttpInterceptor');
  8760. *
  8761. *
  8762. * // alternatively, register the interceptor via an anonymous factory
  8763. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  8764. * return {
  8765. * 'request': function(config) {
  8766. * // same as above
  8767. * },
  8768. *
  8769. * 'response': function(response) {
  8770. * // same as above
  8771. * }
  8772. * };
  8773. * });
  8774. * ```
  8775. *
  8776. * ## Security Considerations
  8777. *
  8778. * When designing web applications, consider security threats from:
  8779. *
  8780. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  8781. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  8782. *
  8783. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  8784. * pre-configured with strategies that address these issues, but for this to work backend server
  8785. * cooperation is required.
  8786. *
  8787. * ### JSON Vulnerability Protection
  8788. *
  8789. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  8790. * allows third party website to turn your JSON resource URL into
  8791. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  8792. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  8793. * Angular will automatically strip the prefix before processing it as JSON.
  8794. *
  8795. * For example if your server needs to return:
  8796. * ```js
  8797. * ['one','two']
  8798. * ```
  8799. *
  8800. * which is vulnerable to attack, your server can return:
  8801. * ```js
  8802. * )]}',
  8803. * ['one','two']
  8804. * ```
  8805. *
  8806. * Angular will strip the prefix, before processing the JSON.
  8807. *
  8808. *
  8809. * ### Cross Site Request Forgery (XSRF) Protection
  8810. *
  8811. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
  8812. * an unauthorized site can gain your user's private data. Angular provides a mechanism
  8813. * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
  8814. * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
  8815. * JavaScript that runs on your domain could read the cookie, your server can be assured that
  8816. * the XHR came from JavaScript running on your domain. The header will not be set for
  8817. * cross-domain requests.
  8818. *
  8819. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  8820. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  8821. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  8822. * that only JavaScript running on your domain could have sent the request. The token must be
  8823. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  8824. * making up its own tokens). We recommend that the token is a digest of your site's
  8825. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  8826. * for added security.
  8827. *
  8828. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  8829. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  8830. * or the per-request config object.
  8831. *
  8832. *
  8833. * @param {object} config Object describing the request to be made and how it should be
  8834. * processed. The object has following properties:
  8835. *
  8836. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  8837. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  8838. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned
  8839. * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be
  8840. * JSONified.
  8841. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  8842. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  8843. * HTTP headers to send to the server. If the return value of a function is null, the
  8844. * header will not be sent. Functions accept a config object as an argument.
  8845. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  8846. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  8847. * - **transformRequest** –
  8848. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  8849. * transform function or an array of such functions. The transform function takes the http
  8850. * request body and headers and returns its transformed (typically serialized) version.
  8851. * See {@link ng.$http#overriding-the-default-transformations-per-request
  8852. * Overriding the Default Transformations}
  8853. * - **transformResponse** –
  8854. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  8855. * transform function or an array of such functions. The transform function takes the http
  8856. * response body, headers and status and returns its transformed (typically deserialized) version.
  8857. * See {@link ng.$http#overriding-the-default-transformations-per-request
  8858. * Overriding the Default Transformations}
  8859. * - **paramSerializer** - {string|function(Object<string,string>):string} - A function used to prepare string representation
  8860. * of request parameters (specified as an object).
  8861. * Is specified as string, it is interpreted as function registered in with the {$injector}.
  8862. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  8863. * GET request, otherwise if a cache instance built with
  8864. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  8865. * caching.
  8866. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  8867. * that should abort the request when resolved.
  8868. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  8869. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  8870. * for more information.
  8871. * - **responseType** - `{string}` - see
  8872. * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
  8873. *
  8874. * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
  8875. * standard `then` method and two http specific methods: `success` and `error`. The `then`
  8876. * method takes two arguments a success and an error callback which will be called with a
  8877. * response object. The `success` and `error` methods take a single argument - a function that
  8878. * will be called when the request succeeds or fails respectively. The arguments passed into
  8879. * these functions are destructured representation of the response object passed into the
  8880. * `then` method. The response object has these properties:
  8881. *
  8882. * - **data** – `{string|Object}` – The response body transformed with the transform
  8883. * functions.
  8884. * - **status** – `{number}` – HTTP status code of the response.
  8885. * - **headers** – `{function([headerName])}` – Header getter function.
  8886. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  8887. * - **statusText** – `{string}` – HTTP status text of the response.
  8888. *
  8889. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  8890. * requests. This is primarily meant to be used for debugging purposes.
  8891. *
  8892. *
  8893. * @example
  8894. <example module="httpExample">
  8895. <file name="index.html">
  8896. <div ng-controller="FetchController">
  8897. <select ng-model="method" aria-label="Request method">
  8898. <option>GET</option>
  8899. <option>JSONP</option>
  8900. </select>
  8901. <input type="text" ng-model="url" size="80" aria-label="URL" />
  8902. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  8903. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  8904. <button id="samplejsonpbtn"
  8905. ng-click="updateModel('JSONP',
  8906. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  8907. Sample JSONP
  8908. </button>
  8909. <button id="invalidjsonpbtn"
  8910. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  8911. Invalid JSONP
  8912. </button>
  8913. <pre>http status code: {{status}}</pre>
  8914. <pre>http response data: {{data}}</pre>
  8915. </div>
  8916. </file>
  8917. <file name="script.js">
  8918. angular.module('httpExample', [])
  8919. .controller('FetchController', ['$scope', '$http', '$templateCache',
  8920. function($scope, $http, $templateCache) {
  8921. $scope.method = 'GET';
  8922. $scope.url = 'http-hello.html';
  8923. $scope.fetch = function() {
  8924. $scope.code = null;
  8925. $scope.response = null;
  8926. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  8927. success(function(data, status) {
  8928. $scope.status = status;
  8929. $scope.data = data;
  8930. }).
  8931. error(function(data, status) {
  8932. $scope.data = data || "Request failed";
  8933. $scope.status = status;
  8934. });
  8935. };
  8936. $scope.updateModel = function(method, url) {
  8937. $scope.method = method;
  8938. $scope.url = url;
  8939. };
  8940. }]);
  8941. </file>
  8942. <file name="http-hello.html">
  8943. Hello, $http!
  8944. </file>
  8945. <file name="protractor.js" type="protractor">
  8946. var status = element(by.binding('status'));
  8947. var data = element(by.binding('data'));
  8948. var fetchBtn = element(by.id('fetchbtn'));
  8949. var sampleGetBtn = element(by.id('samplegetbtn'));
  8950. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  8951. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  8952. it('should make an xhr GET request', function() {
  8953. sampleGetBtn.click();
  8954. fetchBtn.click();
  8955. expect(status.getText()).toMatch('200');
  8956. expect(data.getText()).toMatch(/Hello, \$http!/);
  8957. });
  8958. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  8959. // it('should make a JSONP request to angularjs.org', function() {
  8960. // sampleJsonpBtn.click();
  8961. // fetchBtn.click();
  8962. // expect(status.getText()).toMatch('200');
  8963. // expect(data.getText()).toMatch(/Super Hero!/);
  8964. // });
  8965. it('should make JSONP request to invalid URL and invoke the error handler',
  8966. function() {
  8967. invalidJsonpBtn.click();
  8968. fetchBtn.click();
  8969. expect(status.getText()).toMatch('0');
  8970. expect(data.getText()).toMatch('Request failed');
  8971. });
  8972. </file>
  8973. </example>
  8974. */
  8975. function $http(requestConfig) {
  8976. if (!angular.isObject(requestConfig)) {
  8977. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  8978. }
  8979. var config = extend({
  8980. method: 'get',
  8981. transformRequest: defaults.transformRequest,
  8982. transformResponse: defaults.transformResponse,
  8983. paramSerializer: defaults.paramSerializer
  8984. }, requestConfig);
  8985. config.headers = mergeHeaders(requestConfig);
  8986. config.method = uppercase(config.method);
  8987. config.paramSerializer = isString(config.paramSerializer) ?
  8988. $injector.get(config.paramSerializer) : config.paramSerializer;
  8989. var serverRequest = function(config) {
  8990. var headers = config.headers;
  8991. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  8992. // strip content-type if data is undefined
  8993. if (isUndefined(reqData)) {
  8994. forEach(headers, function(value, header) {
  8995. if (lowercase(header) === 'content-type') {
  8996. delete headers[header];
  8997. }
  8998. });
  8999. }
  9000. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  9001. config.withCredentials = defaults.withCredentials;
  9002. }
  9003. // send request
  9004. return sendReq(config, reqData).then(transformResponse, transformResponse);
  9005. };
  9006. var chain = [serverRequest, undefined];
  9007. var promise = $q.when(config);
  9008. // apply interceptors
  9009. forEach(reversedInterceptors, function(interceptor) {
  9010. if (interceptor.request || interceptor.requestError) {
  9011. chain.unshift(interceptor.request, interceptor.requestError);
  9012. }
  9013. if (interceptor.response || interceptor.responseError) {
  9014. chain.push(interceptor.response, interceptor.responseError);
  9015. }
  9016. });
  9017. while (chain.length) {
  9018. var thenFn = chain.shift();
  9019. var rejectFn = chain.shift();
  9020. promise = promise.then(thenFn, rejectFn);
  9021. }
  9022. promise.success = function(fn) {
  9023. assertArgFn(fn, 'fn');
  9024. promise.then(function(response) {
  9025. fn(response.data, response.status, response.headers, config);
  9026. });
  9027. return promise;
  9028. };
  9029. promise.error = function(fn) {
  9030. assertArgFn(fn, 'fn');
  9031. promise.then(null, function(response) {
  9032. fn(response.data, response.status, response.headers, config);
  9033. });
  9034. return promise;
  9035. };
  9036. return promise;
  9037. function transformResponse(response) {
  9038. // make a copy since the response must be cacheable
  9039. var resp = extend({}, response);
  9040. if (!response.data) {
  9041. resp.data = response.data;
  9042. } else {
  9043. resp.data = transformData(response.data, response.headers, response.status, config.transformResponse);
  9044. }
  9045. return (isSuccess(response.status))
  9046. ? resp
  9047. : $q.reject(resp);
  9048. }
  9049. function executeHeaderFns(headers, config) {
  9050. var headerContent, processedHeaders = {};
  9051. forEach(headers, function(headerFn, header) {
  9052. if (isFunction(headerFn)) {
  9053. headerContent = headerFn(config);
  9054. if (headerContent != null) {
  9055. processedHeaders[header] = headerContent;
  9056. }
  9057. } else {
  9058. processedHeaders[header] = headerFn;
  9059. }
  9060. });
  9061. return processedHeaders;
  9062. }
  9063. function mergeHeaders(config) {
  9064. var defHeaders = defaults.headers,
  9065. reqHeaders = extend({}, config.headers),
  9066. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  9067. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  9068. // using for-in instead of forEach to avoid unecessary iteration after header has been found
  9069. defaultHeadersIteration:
  9070. for (defHeaderName in defHeaders) {
  9071. lowercaseDefHeaderName = lowercase(defHeaderName);
  9072. for (reqHeaderName in reqHeaders) {
  9073. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  9074. continue defaultHeadersIteration;
  9075. }
  9076. }
  9077. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  9078. }
  9079. // execute if header value is a function for merged headers
  9080. return executeHeaderFns(reqHeaders, shallowCopy(config));
  9081. }
  9082. }
  9083. $http.pendingRequests = [];
  9084. /**
  9085. * @ngdoc method
  9086. * @name $http#get
  9087. *
  9088. * @description
  9089. * Shortcut method to perform `GET` request.
  9090. *
  9091. * @param {string} url Relative or absolute URL specifying the destination of the request
  9092. * @param {Object=} config Optional configuration object
  9093. * @returns {HttpPromise} Future object
  9094. */
  9095. /**
  9096. * @ngdoc method
  9097. * @name $http#delete
  9098. *
  9099. * @description
  9100. * Shortcut method to perform `DELETE` request.
  9101. *
  9102. * @param {string} url Relative or absolute URL specifying the destination of the request
  9103. * @param {Object=} config Optional configuration object
  9104. * @returns {HttpPromise} Future object
  9105. */
  9106. /**
  9107. * @ngdoc method
  9108. * @name $http#head
  9109. *
  9110. * @description
  9111. * Shortcut method to perform `HEAD` request.
  9112. *
  9113. * @param {string} url Relative or absolute URL specifying the destination of the request
  9114. * @param {Object=} config Optional configuration object
  9115. * @returns {HttpPromise} Future object
  9116. */
  9117. /**
  9118. * @ngdoc method
  9119. * @name $http#jsonp
  9120. *
  9121. * @description
  9122. * Shortcut method to perform `JSONP` request.
  9123. *
  9124. * @param {string} url Relative or absolute URL specifying the destination of the request.
  9125. * The name of the callback should be the string `JSON_CALLBACK`.
  9126. * @param {Object=} config Optional configuration object
  9127. * @returns {HttpPromise} Future object
  9128. */
  9129. createShortMethods('get', 'delete', 'head', 'jsonp');
  9130. /**
  9131. * @ngdoc method
  9132. * @name $http#post
  9133. *
  9134. * @description
  9135. * Shortcut method to perform `POST` request.
  9136. *
  9137. * @param {string} url Relative or absolute URL specifying the destination of the request
  9138. * @param {*} data Request content
  9139. * @param {Object=} config Optional configuration object
  9140. * @returns {HttpPromise} Future object
  9141. */
  9142. /**
  9143. * @ngdoc method
  9144. * @name $http#put
  9145. *
  9146. * @description
  9147. * Shortcut method to perform `PUT` request.
  9148. *
  9149. * @param {string} url Relative or absolute URL specifying the destination of the request
  9150. * @param {*} data Request content
  9151. * @param {Object=} config Optional configuration object
  9152. * @returns {HttpPromise} Future object
  9153. */
  9154. /**
  9155. * @ngdoc method
  9156. * @name $http#patch
  9157. *
  9158. * @description
  9159. * Shortcut method to perform `PATCH` request.
  9160. *
  9161. * @param {string} url Relative or absolute URL specifying the destination of the request
  9162. * @param {*} data Request content
  9163. * @param {Object=} config Optional configuration object
  9164. * @returns {HttpPromise} Future object
  9165. */
  9166. createShortMethodsWithData('post', 'put', 'patch');
  9167. /**
  9168. * @ngdoc property
  9169. * @name $http#defaults
  9170. *
  9171. * @description
  9172. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  9173. * default headers, withCredentials as well as request and response transformations.
  9174. *
  9175. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  9176. */
  9177. $http.defaults = defaults;
  9178. return $http;
  9179. function createShortMethods(names) {
  9180. forEach(arguments, function(name) {
  9181. $http[name] = function(url, config) {
  9182. return $http(extend({}, config || {}, {
  9183. method: name,
  9184. url: url
  9185. }));
  9186. };
  9187. });
  9188. }
  9189. function createShortMethodsWithData(name) {
  9190. forEach(arguments, function(name) {
  9191. $http[name] = function(url, data, config) {
  9192. return $http(extend({}, config || {}, {
  9193. method: name,
  9194. url: url,
  9195. data: data
  9196. }));
  9197. };
  9198. });
  9199. }
  9200. /**
  9201. * Makes the request.
  9202. *
  9203. * !!! ACCESSES CLOSURE VARS:
  9204. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  9205. */
  9206. function sendReq(config, reqData) {
  9207. var deferred = $q.defer(),
  9208. promise = deferred.promise,
  9209. cache,
  9210. cachedResp,
  9211. reqHeaders = config.headers,
  9212. url = buildUrl(config.url, config.paramSerializer(config.params));
  9213. $http.pendingRequests.push(config);
  9214. promise.then(removePendingReq, removePendingReq);
  9215. if ((config.cache || defaults.cache) && config.cache !== false &&
  9216. (config.method === 'GET' || config.method === 'JSONP')) {
  9217. cache = isObject(config.cache) ? config.cache
  9218. : isObject(defaults.cache) ? defaults.cache
  9219. : defaultCache;
  9220. }
  9221. if (cache) {
  9222. cachedResp = cache.get(url);
  9223. if (isDefined(cachedResp)) {
  9224. if (isPromiseLike(cachedResp)) {
  9225. // cached request has already been sent, but there is no response yet
  9226. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  9227. } else {
  9228. // serving from cache
  9229. if (isArray(cachedResp)) {
  9230. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  9231. } else {
  9232. resolvePromise(cachedResp, 200, {}, 'OK');
  9233. }
  9234. }
  9235. } else {
  9236. // put the promise for the non-transformed response into cache as a placeholder
  9237. cache.put(url, promise);
  9238. }
  9239. }
  9240. // if we won't have the response in cache, set the xsrf headers and
  9241. // send the request to the backend
  9242. if (isUndefined(cachedResp)) {
  9243. var xsrfValue = urlIsSameOrigin(config.url)
  9244. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  9245. : undefined;
  9246. if (xsrfValue) {
  9247. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  9248. }
  9249. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  9250. config.withCredentials, config.responseType);
  9251. }
  9252. return promise;
  9253. /**
  9254. * Callback registered to $httpBackend():
  9255. * - caches the response if desired
  9256. * - resolves the raw $http promise
  9257. * - calls $apply
  9258. */
  9259. function done(status, response, headersString, statusText) {
  9260. if (cache) {
  9261. if (isSuccess(status)) {
  9262. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  9263. } else {
  9264. // remove promise from the cache
  9265. cache.remove(url);
  9266. }
  9267. }
  9268. function resolveHttpPromise() {
  9269. resolvePromise(response, status, headersString, statusText);
  9270. }
  9271. if (useApplyAsync) {
  9272. $rootScope.$applyAsync(resolveHttpPromise);
  9273. } else {
  9274. resolveHttpPromise();
  9275. if (!$rootScope.$$phase) $rootScope.$apply();
  9276. }
  9277. }
  9278. /**
  9279. * Resolves the raw $http promise.
  9280. */
  9281. function resolvePromise(response, status, headers, statusText) {
  9282. // normalize internal statuses to 0
  9283. status = Math.max(status, 0);
  9284. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  9285. data: response,
  9286. status: status,
  9287. headers: headersGetter(headers),
  9288. config: config,
  9289. statusText: statusText
  9290. });
  9291. }
  9292. function resolvePromiseWithResult(result) {
  9293. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
  9294. }
  9295. function removePendingReq() {
  9296. var idx = $http.pendingRequests.indexOf(config);
  9297. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  9298. }
  9299. }
  9300. function buildUrl(url, serializedParams) {
  9301. if (serializedParams.length > 0) {
  9302. url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
  9303. }
  9304. return url;
  9305. }
  9306. }];
  9307. }
  9308. function createXhr() {
  9309. return new window.XMLHttpRequest();
  9310. }
  9311. /**
  9312. * @ngdoc service
  9313. * @name $httpBackend
  9314. * @requires $window
  9315. * @requires $document
  9316. *
  9317. * @description
  9318. * HTTP backend used by the {@link ng.$http service} that delegates to
  9319. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  9320. *
  9321. * You should never need to use this service directly, instead use the higher-level abstractions:
  9322. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  9323. *
  9324. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  9325. * $httpBackend} which can be trained with responses.
  9326. */
  9327. function $HttpBackendProvider() {
  9328. this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
  9329. return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
  9330. }];
  9331. }
  9332. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  9333. // TODO(vojta): fix the signature
  9334. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  9335. $browser.$$incOutstandingRequestCount();
  9336. url = url || $browser.url();
  9337. if (lowercase(method) == 'jsonp') {
  9338. var callbackId = '_' + (callbacks.counter++).toString(36);
  9339. callbacks[callbackId] = function(data) {
  9340. callbacks[callbackId].data = data;
  9341. callbacks[callbackId].called = true;
  9342. };
  9343. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  9344. callbackId, function(status, text) {
  9345. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  9346. callbacks[callbackId] = noop;
  9347. });
  9348. } else {
  9349. var xhr = createXhr();
  9350. xhr.open(method, url, true);
  9351. forEach(headers, function(value, key) {
  9352. if (isDefined(value)) {
  9353. xhr.setRequestHeader(key, value);
  9354. }
  9355. });
  9356. xhr.onload = function requestLoaded() {
  9357. var statusText = xhr.statusText || '';
  9358. // responseText is the old-school way of retrieving response (supported by IE8 & 9)
  9359. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  9360. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  9361. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  9362. var status = xhr.status === 1223 ? 204 : xhr.status;
  9363. // fix status code when it is 0 (0 status is undocumented).
  9364. // Occurs when accessing file resources or on Android 4.1 stock browser
  9365. // while retrieving files from application cache.
  9366. if (status === 0) {
  9367. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  9368. }
  9369. completeRequest(callback,
  9370. status,
  9371. response,
  9372. xhr.getAllResponseHeaders(),
  9373. statusText);
  9374. };
  9375. var requestError = function() {
  9376. // The response is always empty
  9377. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  9378. completeRequest(callback, -1, null, null, '');
  9379. };
  9380. xhr.onerror = requestError;
  9381. xhr.onabort = requestError;
  9382. if (withCredentials) {
  9383. xhr.withCredentials = true;
  9384. }
  9385. if (responseType) {
  9386. try {
  9387. xhr.responseType = responseType;
  9388. } catch (e) {
  9389. // WebKit added support for the json responseType value on 09/03/2013
  9390. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  9391. // known to throw when setting the value "json" as the response type. Other older
  9392. // browsers implementing the responseType
  9393. //
  9394. // The json response type can be ignored if not supported, because JSON payloads are
  9395. // parsed on the client-side regardless.
  9396. if (responseType !== 'json') {
  9397. throw e;
  9398. }
  9399. }
  9400. }
  9401. xhr.send(post);
  9402. }
  9403. if (timeout > 0) {
  9404. var timeoutId = $browserDefer(timeoutRequest, timeout);
  9405. } else if (isPromiseLike(timeout)) {
  9406. timeout.then(timeoutRequest);
  9407. }
  9408. function timeoutRequest() {
  9409. jsonpDone && jsonpDone();
  9410. xhr && xhr.abort();
  9411. }
  9412. function completeRequest(callback, status, response, headersString, statusText) {
  9413. // cancel timeout and subsequent timeout promise resolution
  9414. if (timeoutId !== undefined) {
  9415. $browserDefer.cancel(timeoutId);
  9416. }
  9417. jsonpDone = xhr = null;
  9418. callback(status, response, headersString, statusText);
  9419. $browser.$$completeOutstandingRequest(noop);
  9420. }
  9421. };
  9422. function jsonpReq(url, callbackId, done) {
  9423. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  9424. // - fetches local scripts via XHR and evals them
  9425. // - adds and immediately removes script elements from the document
  9426. var script = rawDocument.createElement('script'), callback = null;
  9427. script.type = "text/javascript";
  9428. script.src = url;
  9429. script.async = true;
  9430. callback = function(event) {
  9431. removeEventListenerFn(script, "load", callback);
  9432. removeEventListenerFn(script, "error", callback);
  9433. rawDocument.body.removeChild(script);
  9434. script = null;
  9435. var status = -1;
  9436. var text = "unknown";
  9437. if (event) {
  9438. if (event.type === "load" && !callbacks[callbackId].called) {
  9439. event = { type: "error" };
  9440. }
  9441. text = event.type;
  9442. status = event.type === "error" ? 404 : 200;
  9443. }
  9444. if (done) {
  9445. done(status, text);
  9446. }
  9447. };
  9448. addEventListenerFn(script, "load", callback);
  9449. addEventListenerFn(script, "error", callback);
  9450. rawDocument.body.appendChild(script);
  9451. return callback;
  9452. }
  9453. }
  9454. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  9455. $interpolateMinErr.throwNoconcat = function(text) {
  9456. throw $interpolateMinErr('noconcat',
  9457. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  9458. "interpolations that concatenate multiple expressions when a trusted value is " +
  9459. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  9460. };
  9461. $interpolateMinErr.interr = function(text, err) {
  9462. return $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
  9463. };
  9464. /**
  9465. * @ngdoc provider
  9466. * @name $interpolateProvider
  9467. *
  9468. * @description
  9469. *
  9470. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  9471. *
  9472. * @example
  9473. <example module="customInterpolationApp">
  9474. <file name="index.html">
  9475. <script>
  9476. var customInterpolationApp = angular.module('customInterpolationApp', []);
  9477. customInterpolationApp.config(function($interpolateProvider) {
  9478. $interpolateProvider.startSymbol('//');
  9479. $interpolateProvider.endSymbol('//');
  9480. });
  9481. customInterpolationApp.controller('DemoController', function() {
  9482. this.label = "This binding is brought you by // interpolation symbols.";
  9483. });
  9484. </script>
  9485. <div ng-app="App" ng-controller="DemoController as demo">
  9486. //demo.label//
  9487. </div>
  9488. </file>
  9489. <file name="protractor.js" type="protractor">
  9490. it('should interpolate binding with custom symbols', function() {
  9491. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  9492. });
  9493. </file>
  9494. </example>
  9495. */
  9496. function $InterpolateProvider() {
  9497. var startSymbol = '{{';
  9498. var endSymbol = '}}';
  9499. /**
  9500. * @ngdoc method
  9501. * @name $interpolateProvider#startSymbol
  9502. * @description
  9503. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  9504. *
  9505. * @param {string=} value new value to set the starting symbol to.
  9506. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  9507. */
  9508. this.startSymbol = function(value) {
  9509. if (value) {
  9510. startSymbol = value;
  9511. return this;
  9512. } else {
  9513. return startSymbol;
  9514. }
  9515. };
  9516. /**
  9517. * @ngdoc method
  9518. * @name $interpolateProvider#endSymbol
  9519. * @description
  9520. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  9521. *
  9522. * @param {string=} value new value to set the ending symbol to.
  9523. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  9524. */
  9525. this.endSymbol = function(value) {
  9526. if (value) {
  9527. endSymbol = value;
  9528. return this;
  9529. } else {
  9530. return endSymbol;
  9531. }
  9532. };
  9533. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  9534. var startSymbolLength = startSymbol.length,
  9535. endSymbolLength = endSymbol.length,
  9536. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  9537. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  9538. function escape(ch) {
  9539. return '\\\\\\' + ch;
  9540. }
  9541. function unescapeText(text) {
  9542. return text.replace(escapedStartRegexp, startSymbol).
  9543. replace(escapedEndRegexp, endSymbol);
  9544. }
  9545. function stringify(value) {
  9546. if (value == null) { // null || undefined
  9547. return '';
  9548. }
  9549. switch (typeof value) {
  9550. case 'string':
  9551. break;
  9552. case 'number':
  9553. value = '' + value;
  9554. break;
  9555. default:
  9556. value = toJson(value);
  9557. }
  9558. return value;
  9559. }
  9560. /**
  9561. * @ngdoc service
  9562. * @name $interpolate
  9563. * @kind function
  9564. *
  9565. * @requires $parse
  9566. * @requires $sce
  9567. *
  9568. * @description
  9569. *
  9570. * Compiles a string with markup into an interpolation function. This service is used by the
  9571. * HTML {@link ng.$compile $compile} service for data binding. See
  9572. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  9573. * interpolation markup.
  9574. *
  9575. *
  9576. * ```js
  9577. * var $interpolate = ...; // injected
  9578. * var exp = $interpolate('Hello {{name | uppercase}}!');
  9579. * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
  9580. * ```
  9581. *
  9582. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  9583. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  9584. * evaluate to a value other than `undefined`.
  9585. *
  9586. * ```js
  9587. * var $interpolate = ...; // injected
  9588. * var context = {greeting: 'Hello', name: undefined };
  9589. *
  9590. * // default "forgiving" mode
  9591. * var exp = $interpolate('{{greeting}} {{name}}!');
  9592. * expect(exp(context)).toEqual('Hello !');
  9593. *
  9594. * // "allOrNothing" mode
  9595. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  9596. * expect(exp(context)).toBeUndefined();
  9597. * context.name = 'Angular';
  9598. * expect(exp(context)).toEqual('Hello Angular!');
  9599. * ```
  9600. *
  9601. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  9602. *
  9603. * ####Escaped Interpolation
  9604. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  9605. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  9606. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  9607. * or binding.
  9608. *
  9609. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  9610. * degree, while also enabling code examples to work without relying on the
  9611. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  9612. *
  9613. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  9614. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  9615. * interpolation start/end markers with their escaped counterparts.**
  9616. *
  9617. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  9618. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  9619. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  9620. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  9621. * this is typically useful only when user-data is used in rendering a template from the server, or
  9622. * when otherwise untrusted data is used by a directive.
  9623. *
  9624. * <example>
  9625. * <file name="index.html">
  9626. * <div ng-init="username='A user'">
  9627. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  9628. * </p>
  9629. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  9630. * application, but fails to accomplish their task, because the server has correctly
  9631. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  9632. * characters.</p>
  9633. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  9634. * from the database by an administrator.</p>
  9635. * </div>
  9636. * </file>
  9637. * </example>
  9638. *
  9639. * @param {string} text The text with markup to interpolate.
  9640. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  9641. * embedded expression in order to return an interpolation function. Strings with no
  9642. * embedded expression will return null for the interpolation function.
  9643. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  9644. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  9645. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  9646. * provides Strict Contextual Escaping for details.
  9647. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  9648. * unless all embedded expressions evaluate to a value other than `undefined`.
  9649. * @returns {function(context)} an interpolation function which is used to compute the
  9650. * interpolated string. The function has these parameters:
  9651. *
  9652. * - `context`: evaluation context for all expressions embedded in the interpolated text
  9653. */
  9654. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  9655. allOrNothing = !!allOrNothing;
  9656. var startIndex,
  9657. endIndex,
  9658. index = 0,
  9659. expressions = [],
  9660. parseFns = [],
  9661. textLength = text.length,
  9662. exp,
  9663. concat = [],
  9664. expressionPositions = [];
  9665. while (index < textLength) {
  9666. if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  9667. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
  9668. if (index !== startIndex) {
  9669. concat.push(unescapeText(text.substring(index, startIndex)));
  9670. }
  9671. exp = text.substring(startIndex + startSymbolLength, endIndex);
  9672. expressions.push(exp);
  9673. parseFns.push($parse(exp, parseStringifyInterceptor));
  9674. index = endIndex + endSymbolLength;
  9675. expressionPositions.push(concat.length);
  9676. concat.push('');
  9677. } else {
  9678. // we did not find an interpolation, so we have to add the remainder to the separators array
  9679. if (index !== textLength) {
  9680. concat.push(unescapeText(text.substring(index)));
  9681. }
  9682. break;
  9683. }
  9684. }
  9685. // Concatenating expressions makes it hard to reason about whether some combination of
  9686. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  9687. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  9688. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  9689. // make it obvious that you bound the value to some user controlled value. This helps reduce
  9690. // the load when auditing for XSS issues.
  9691. if (trustedContext && concat.length > 1) {
  9692. $interpolateMinErr.throwNoconcat(text);
  9693. }
  9694. if (!mustHaveExpression || expressions.length) {
  9695. var compute = function(values) {
  9696. for (var i = 0, ii = expressions.length; i < ii; i++) {
  9697. if (allOrNothing && isUndefined(values[i])) return;
  9698. concat[expressionPositions[i]] = values[i];
  9699. }
  9700. return concat.join('');
  9701. };
  9702. var getValue = function(value) {
  9703. return trustedContext ?
  9704. $sce.getTrusted(trustedContext, value) :
  9705. $sce.valueOf(value);
  9706. };
  9707. return extend(function interpolationFn(context) {
  9708. var i = 0;
  9709. var ii = expressions.length;
  9710. var values = new Array(ii);
  9711. try {
  9712. for (; i < ii; i++) {
  9713. values[i] = parseFns[i](context);
  9714. }
  9715. return compute(values);
  9716. } catch (err) {
  9717. $exceptionHandler($interpolateMinErr.interr(text, err));
  9718. }
  9719. }, {
  9720. // all of these properties are undocumented for now
  9721. exp: text, //just for compatibility with regular watchers created via $watch
  9722. expressions: expressions,
  9723. $$watchDelegate: function(scope, listener) {
  9724. var lastValue;
  9725. return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
  9726. var currValue = compute(values);
  9727. if (isFunction(listener)) {
  9728. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  9729. }
  9730. lastValue = currValue;
  9731. });
  9732. }
  9733. });
  9734. }
  9735. function parseStringifyInterceptor(value) {
  9736. try {
  9737. value = getValue(value);
  9738. return allOrNothing && !isDefined(value) ? value : stringify(value);
  9739. } catch (err) {
  9740. $exceptionHandler($interpolateMinErr.interr(text, err));
  9741. }
  9742. }
  9743. }
  9744. /**
  9745. * @ngdoc method
  9746. * @name $interpolate#startSymbol
  9747. * @description
  9748. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  9749. *
  9750. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  9751. * the symbol.
  9752. *
  9753. * @returns {string} start symbol.
  9754. */
  9755. $interpolate.startSymbol = function() {
  9756. return startSymbol;
  9757. };
  9758. /**
  9759. * @ngdoc method
  9760. * @name $interpolate#endSymbol
  9761. * @description
  9762. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  9763. *
  9764. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  9765. * the symbol.
  9766. *
  9767. * @returns {string} end symbol.
  9768. */
  9769. $interpolate.endSymbol = function() {
  9770. return endSymbol;
  9771. };
  9772. return $interpolate;
  9773. }];
  9774. }
  9775. function $IntervalProvider() {
  9776. this.$get = ['$rootScope', '$window', '$q', '$$q',
  9777. function($rootScope, $window, $q, $$q) {
  9778. var intervals = {};
  9779. /**
  9780. * @ngdoc service
  9781. * @name $interval
  9782. *
  9783. * @description
  9784. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  9785. * milliseconds.
  9786. *
  9787. * The return value of registering an interval function is a promise. This promise will be
  9788. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  9789. * run indefinitely if `count` is not defined. The value of the notification will be the
  9790. * number of iterations that have run.
  9791. * To cancel an interval, call `$interval.cancel(promise)`.
  9792. *
  9793. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  9794. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  9795. * time.
  9796. *
  9797. * <div class="alert alert-warning">
  9798. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  9799. * with them. In particular they are not automatically destroyed when a controller's scope or a
  9800. * directive's element are destroyed.
  9801. * You should take this into consideration and make sure to always cancel the interval at the
  9802. * appropriate moment. See the example below for more details on how and when to do this.
  9803. * </div>
  9804. *
  9805. * @param {function()} fn A function that should be called repeatedly.
  9806. * @param {number} delay Number of milliseconds between each function call.
  9807. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  9808. * indefinitely.
  9809. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  9810. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  9811. * @param {...*=} Pass additional parameters to the executed function.
  9812. * @returns {promise} A promise which will be notified on each iteration.
  9813. *
  9814. * @example
  9815. * <example module="intervalExample">
  9816. * <file name="index.html">
  9817. * <script>
  9818. * angular.module('intervalExample', [])
  9819. * .controller('ExampleController', ['$scope', '$interval',
  9820. * function($scope, $interval) {
  9821. * $scope.format = 'M/d/yy h:mm:ss a';
  9822. * $scope.blood_1 = 100;
  9823. * $scope.blood_2 = 120;
  9824. *
  9825. * var stop;
  9826. * $scope.fight = function() {
  9827. * // Don't start a new fight if we are already fighting
  9828. * if ( angular.isDefined(stop) ) return;
  9829. *
  9830. * stop = $interval(function() {
  9831. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  9832. * $scope.blood_1 = $scope.blood_1 - 3;
  9833. * $scope.blood_2 = $scope.blood_2 - 4;
  9834. * } else {
  9835. * $scope.stopFight();
  9836. * }
  9837. * }, 100);
  9838. * };
  9839. *
  9840. * $scope.stopFight = function() {
  9841. * if (angular.isDefined(stop)) {
  9842. * $interval.cancel(stop);
  9843. * stop = undefined;
  9844. * }
  9845. * };
  9846. *
  9847. * $scope.resetFight = function() {
  9848. * $scope.blood_1 = 100;
  9849. * $scope.blood_2 = 120;
  9850. * };
  9851. *
  9852. * $scope.$on('$destroy', function() {
  9853. * // Make sure that the interval is destroyed too
  9854. * $scope.stopFight();
  9855. * });
  9856. * }])
  9857. * // Register the 'myCurrentTime' directive factory method.
  9858. * // We inject $interval and dateFilter service since the factory method is DI.
  9859. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  9860. * function($interval, dateFilter) {
  9861. * // return the directive link function. (compile function not needed)
  9862. * return function(scope, element, attrs) {
  9863. * var format, // date format
  9864. * stopTime; // so that we can cancel the time updates
  9865. *
  9866. * // used to update the UI
  9867. * function updateTime() {
  9868. * element.text(dateFilter(new Date(), format));
  9869. * }
  9870. *
  9871. * // watch the expression, and update the UI on change.
  9872. * scope.$watch(attrs.myCurrentTime, function(value) {
  9873. * format = value;
  9874. * updateTime();
  9875. * });
  9876. *
  9877. * stopTime = $interval(updateTime, 1000);
  9878. *
  9879. * // listen on DOM destroy (removal) event, and cancel the next UI update
  9880. * // to prevent updating time after the DOM element was removed.
  9881. * element.on('$destroy', function() {
  9882. * $interval.cancel(stopTime);
  9883. * });
  9884. * }
  9885. * }]);
  9886. * </script>
  9887. *
  9888. * <div>
  9889. * <div ng-controller="ExampleController">
  9890. * <label>Date format: <input ng-model="format"></label> <hr/>
  9891. * Current time is: <span my-current-time="format"></span>
  9892. * <hr/>
  9893. * Blood 1 : <font color='red'>{{blood_1}}</font>
  9894. * Blood 2 : <font color='red'>{{blood_2}}</font>
  9895. * <button type="button" data-ng-click="fight()">Fight</button>
  9896. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  9897. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  9898. * </div>
  9899. * </div>
  9900. *
  9901. * </file>
  9902. * </example>
  9903. */
  9904. function interval(fn, delay, count, invokeApply) {
  9905. var hasParams = arguments.length > 4,
  9906. args = hasParams ? sliceArgs(arguments, 4) : [],
  9907. setInterval = $window.setInterval,
  9908. clearInterval = $window.clearInterval,
  9909. iteration = 0,
  9910. skipApply = (isDefined(invokeApply) && !invokeApply),
  9911. deferred = (skipApply ? $$q : $q).defer(),
  9912. promise = deferred.promise;
  9913. count = isDefined(count) ? count : 0;
  9914. promise.then(null, null, (!hasParams) ? fn : function() {
  9915. fn.apply(null, args);
  9916. });
  9917. promise.$$intervalId = setInterval(function tick() {
  9918. deferred.notify(iteration++);
  9919. if (count > 0 && iteration >= count) {
  9920. deferred.resolve(iteration);
  9921. clearInterval(promise.$$intervalId);
  9922. delete intervals[promise.$$intervalId];
  9923. }
  9924. if (!skipApply) $rootScope.$apply();
  9925. }, delay);
  9926. intervals[promise.$$intervalId] = deferred;
  9927. return promise;
  9928. }
  9929. /**
  9930. * @ngdoc method
  9931. * @name $interval#cancel
  9932. *
  9933. * @description
  9934. * Cancels a task associated with the `promise`.
  9935. *
  9936. * @param {promise} promise returned by the `$interval` function.
  9937. * @returns {boolean} Returns `true` if the task was successfully canceled.
  9938. */
  9939. interval.cancel = function(promise) {
  9940. if (promise && promise.$$intervalId in intervals) {
  9941. intervals[promise.$$intervalId].reject('canceled');
  9942. $window.clearInterval(promise.$$intervalId);
  9943. delete intervals[promise.$$intervalId];
  9944. return true;
  9945. }
  9946. return false;
  9947. };
  9948. return interval;
  9949. }];
  9950. }
  9951. /**
  9952. * @ngdoc service
  9953. * @name $locale
  9954. *
  9955. * @description
  9956. * $locale service provides localization rules for various Angular components. As of right now the
  9957. * only public api is:
  9958. *
  9959. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  9960. */
  9961. function $LocaleProvider() {
  9962. this.$get = function() {
  9963. return {
  9964. id: 'en-us',
  9965. NUMBER_FORMATS: {
  9966. DECIMAL_SEP: '.',
  9967. GROUP_SEP: ',',
  9968. PATTERNS: [
  9969. { // Decimal Pattern
  9970. minInt: 1,
  9971. minFrac: 0,
  9972. maxFrac: 3,
  9973. posPre: '',
  9974. posSuf: '',
  9975. negPre: '-',
  9976. negSuf: '',
  9977. gSize: 3,
  9978. lgSize: 3
  9979. },{ //Currency Pattern
  9980. minInt: 1,
  9981. minFrac: 2,
  9982. maxFrac: 2,
  9983. posPre: '\u00A4',
  9984. posSuf: '',
  9985. negPre: '(\u00A4',
  9986. negSuf: ')',
  9987. gSize: 3,
  9988. lgSize: 3
  9989. }
  9990. ],
  9991. CURRENCY_SYM: '$'
  9992. },
  9993. DATETIME_FORMATS: {
  9994. MONTH:
  9995. 'January,February,March,April,May,June,July,August,September,October,November,December'
  9996. .split(','),
  9997. SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
  9998. DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
  9999. SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
  10000. AMPMS: ['AM','PM'],
  10001. medium: 'MMM d, y h:mm:ss a',
  10002. 'short': 'M/d/yy h:mm a',
  10003. fullDate: 'EEEE, MMMM d, y',
  10004. longDate: 'MMMM d, y',
  10005. mediumDate: 'MMM d, y',
  10006. shortDate: 'M/d/yy',
  10007. mediumTime: 'h:mm:ss a',
  10008. shortTime: 'h:mm a',
  10009. ERANAMES: [
  10010. "Before Christ",
  10011. "Anno Domini"
  10012. ],
  10013. ERAS: [
  10014. "BC",
  10015. "AD"
  10016. ]
  10017. },
  10018. pluralCat: function(num) {
  10019. if (num === 1) {
  10020. return 'one';
  10021. }
  10022. return 'other';
  10023. }
  10024. };
  10025. };
  10026. }
  10027. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  10028. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  10029. var $locationMinErr = minErr('$location');
  10030. /**
  10031. * Encode path using encodeUriSegment, ignoring forward slashes
  10032. *
  10033. * @param {string} path Path to encode
  10034. * @returns {string}
  10035. */
  10036. function encodePath(path) {
  10037. var segments = path.split('/'),
  10038. i = segments.length;
  10039. while (i--) {
  10040. segments[i] = encodeUriSegment(segments[i]);
  10041. }
  10042. return segments.join('/');
  10043. }
  10044. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  10045. var parsedUrl = urlResolve(absoluteUrl);
  10046. locationObj.$$protocol = parsedUrl.protocol;
  10047. locationObj.$$host = parsedUrl.hostname;
  10048. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  10049. }
  10050. function parseAppUrl(relativeUrl, locationObj) {
  10051. var prefixed = (relativeUrl.charAt(0) !== '/');
  10052. if (prefixed) {
  10053. relativeUrl = '/' + relativeUrl;
  10054. }
  10055. var match = urlResolve(relativeUrl);
  10056. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  10057. match.pathname.substring(1) : match.pathname);
  10058. locationObj.$$search = parseKeyValue(match.search);
  10059. locationObj.$$hash = decodeURIComponent(match.hash);
  10060. // make sure path starts with '/';
  10061. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  10062. locationObj.$$path = '/' + locationObj.$$path;
  10063. }
  10064. }
  10065. /**
  10066. *
  10067. * @param {string} begin
  10068. * @param {string} whole
  10069. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  10070. * expected string.
  10071. */
  10072. function beginsWith(begin, whole) {
  10073. if (whole.indexOf(begin) === 0) {
  10074. return whole.substr(begin.length);
  10075. }
  10076. }
  10077. function stripHash(url) {
  10078. var index = url.indexOf('#');
  10079. return index == -1 ? url : url.substr(0, index);
  10080. }
  10081. function trimEmptyHash(url) {
  10082. return url.replace(/(#.+)|#$/, '$1');
  10083. }
  10084. function stripFile(url) {
  10085. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  10086. }
  10087. /* return the server only (scheme://host:port) */
  10088. function serverBase(url) {
  10089. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  10090. }
  10091. /**
  10092. * LocationHtml5Url represents an url
  10093. * This object is exposed as $location service when HTML5 mode is enabled and supported
  10094. *
  10095. * @constructor
  10096. * @param {string} appBase application base URL
  10097. * @param {string} basePrefix url path prefix
  10098. */
  10099. function LocationHtml5Url(appBase, basePrefix) {
  10100. this.$$html5 = true;
  10101. basePrefix = basePrefix || '';
  10102. var appBaseNoFile = stripFile(appBase);
  10103. parseAbsoluteUrl(appBase, this);
  10104. /**
  10105. * Parse given html5 (regular) url string into properties
  10106. * @param {string} url HTML5 url
  10107. * @private
  10108. */
  10109. this.$$parse = function(url) {
  10110. var pathUrl = beginsWith(appBaseNoFile, url);
  10111. if (!isString(pathUrl)) {
  10112. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  10113. appBaseNoFile);
  10114. }
  10115. parseAppUrl(pathUrl, this);
  10116. if (!this.$$path) {
  10117. this.$$path = '/';
  10118. }
  10119. this.$$compose();
  10120. };
  10121. /**
  10122. * Compose url and update `absUrl` property
  10123. * @private
  10124. */
  10125. this.$$compose = function() {
  10126. var search = toKeyValue(this.$$search),
  10127. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10128. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10129. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  10130. };
  10131. this.$$parseLinkUrl = function(url, relHref) {
  10132. if (relHref && relHref[0] === '#') {
  10133. // special case for links to hash fragments:
  10134. // keep the old url and only replace the hash fragment
  10135. this.hash(relHref.slice(1));
  10136. return true;
  10137. }
  10138. var appUrl, prevAppUrl;
  10139. var rewrittenUrl;
  10140. if ((appUrl = beginsWith(appBase, url)) !== undefined) {
  10141. prevAppUrl = appUrl;
  10142. if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) {
  10143. rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  10144. } else {
  10145. rewrittenUrl = appBase + prevAppUrl;
  10146. }
  10147. } else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) {
  10148. rewrittenUrl = appBaseNoFile + appUrl;
  10149. } else if (appBaseNoFile == url + '/') {
  10150. rewrittenUrl = appBaseNoFile;
  10151. }
  10152. if (rewrittenUrl) {
  10153. this.$$parse(rewrittenUrl);
  10154. }
  10155. return !!rewrittenUrl;
  10156. };
  10157. }
  10158. /**
  10159. * LocationHashbangUrl represents url
  10160. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  10161. * It also serves as the base class for html5 mode fallback on legacy browsers.
  10162. *
  10163. * @constructor
  10164. * @param {string} appBase application base URL
  10165. * @param {string} hashPrefix hashbang prefix
  10166. */
  10167. function LocationHashbangUrl(appBase, hashPrefix) {
  10168. var appBaseNoFile = stripFile(appBase);
  10169. parseAbsoluteUrl(appBase, this);
  10170. /**
  10171. * Parse given hashbang url into properties
  10172. * @param {string} url Hashbang url
  10173. * @private
  10174. */
  10175. this.$$parse = function(url) {
  10176. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  10177. var withoutHashUrl;
  10178. if (withoutBaseUrl.charAt(0) === '#') {
  10179. // The rest of the url starts with a hash so we have
  10180. // got either a hashbang path or a plain hash fragment
  10181. withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
  10182. if (isUndefined(withoutHashUrl)) {
  10183. // There was no hashbang prefix so we just have a hash fragment
  10184. withoutHashUrl = withoutBaseUrl;
  10185. }
  10186. } else {
  10187. // There was no hashbang path nor hash fragment:
  10188. // If we are in HTML5 mode we use what is left as the path;
  10189. // Otherwise we ignore what is left
  10190. withoutHashUrl = this.$$html5 ? withoutBaseUrl : '';
  10191. }
  10192. parseAppUrl(withoutHashUrl, this);
  10193. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  10194. this.$$compose();
  10195. /*
  10196. * In Windows, on an anchor node on documents loaded from
  10197. * the filesystem, the browser will return a pathname
  10198. * prefixed with the drive name ('/C:/path') when a
  10199. * pathname without a drive is set:
  10200. * * a.setAttribute('href', '/foo')
  10201. * * a.pathname === '/C:/foo' //true
  10202. *
  10203. * Inside of Angular, we're always using pathnames that
  10204. * do not include drive names for routing.
  10205. */
  10206. function removeWindowsDriveName(path, url, base) {
  10207. /*
  10208. Matches paths for file protocol on windows,
  10209. such as /C:/foo/bar, and captures only /foo/bar.
  10210. */
  10211. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  10212. var firstPathSegmentMatch;
  10213. //Get the relative path from the input URL.
  10214. if (url.indexOf(base) === 0) {
  10215. url = url.replace(base, '');
  10216. }
  10217. // The input URL intentionally contains a first path segment that ends with a colon.
  10218. if (windowsFilePathExp.exec(url)) {
  10219. return path;
  10220. }
  10221. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  10222. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  10223. }
  10224. };
  10225. /**
  10226. * Compose hashbang url and update `absUrl` property
  10227. * @private
  10228. */
  10229. this.$$compose = function() {
  10230. var search = toKeyValue(this.$$search),
  10231. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10232. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10233. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  10234. };
  10235. this.$$parseLinkUrl = function(url, relHref) {
  10236. if (stripHash(appBase) == stripHash(url)) {
  10237. this.$$parse(url);
  10238. return true;
  10239. }
  10240. return false;
  10241. };
  10242. }
  10243. /**
  10244. * LocationHashbangUrl represents url
  10245. * This object is exposed as $location service when html5 history api is enabled but the browser
  10246. * does not support it.
  10247. *
  10248. * @constructor
  10249. * @param {string} appBase application base URL
  10250. * @param {string} hashPrefix hashbang prefix
  10251. */
  10252. function LocationHashbangInHtml5Url(appBase, hashPrefix) {
  10253. this.$$html5 = true;
  10254. LocationHashbangUrl.apply(this, arguments);
  10255. var appBaseNoFile = stripFile(appBase);
  10256. this.$$parseLinkUrl = function(url, relHref) {
  10257. if (relHref && relHref[0] === '#') {
  10258. // special case for links to hash fragments:
  10259. // keep the old url and only replace the hash fragment
  10260. this.hash(relHref.slice(1));
  10261. return true;
  10262. }
  10263. var rewrittenUrl;
  10264. var appUrl;
  10265. if (appBase == stripHash(url)) {
  10266. rewrittenUrl = url;
  10267. } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
  10268. rewrittenUrl = appBase + hashPrefix + appUrl;
  10269. } else if (appBaseNoFile === url + '/') {
  10270. rewrittenUrl = appBaseNoFile;
  10271. }
  10272. if (rewrittenUrl) {
  10273. this.$$parse(rewrittenUrl);
  10274. }
  10275. return !!rewrittenUrl;
  10276. };
  10277. this.$$compose = function() {
  10278. var search = toKeyValue(this.$$search),
  10279. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10280. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10281. // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#'
  10282. this.$$absUrl = appBase + hashPrefix + this.$$url;
  10283. };
  10284. }
  10285. var locationPrototype = {
  10286. /**
  10287. * Are we in html5 mode?
  10288. * @private
  10289. */
  10290. $$html5: false,
  10291. /**
  10292. * Has any change been replacing?
  10293. * @private
  10294. */
  10295. $$replace: false,
  10296. /**
  10297. * @ngdoc method
  10298. * @name $location#absUrl
  10299. *
  10300. * @description
  10301. * This method is getter only.
  10302. *
  10303. * Return full url representation with all segments encoded according to rules specified in
  10304. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  10305. *
  10306. *
  10307. * ```js
  10308. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10309. * var absUrl = $location.absUrl();
  10310. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  10311. * ```
  10312. *
  10313. * @return {string} full url
  10314. */
  10315. absUrl: locationGetter('$$absUrl'),
  10316. /**
  10317. * @ngdoc method
  10318. * @name $location#url
  10319. *
  10320. * @description
  10321. * This method is getter / setter.
  10322. *
  10323. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  10324. *
  10325. * Change path, search and hash, when called with parameter and return `$location`.
  10326. *
  10327. *
  10328. * ```js
  10329. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10330. * var url = $location.url();
  10331. * // => "/some/path?foo=bar&baz=xoxo"
  10332. * ```
  10333. *
  10334. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  10335. * @return {string} url
  10336. */
  10337. url: function(url) {
  10338. if (isUndefined(url)) {
  10339. return this.$$url;
  10340. }
  10341. var match = PATH_MATCH.exec(url);
  10342. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  10343. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  10344. this.hash(match[5] || '');
  10345. return this;
  10346. },
  10347. /**
  10348. * @ngdoc method
  10349. * @name $location#protocol
  10350. *
  10351. * @description
  10352. * This method is getter only.
  10353. *
  10354. * Return protocol of current url.
  10355. *
  10356. *
  10357. * ```js
  10358. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10359. * var protocol = $location.protocol();
  10360. * // => "http"
  10361. * ```
  10362. *
  10363. * @return {string} protocol of current url
  10364. */
  10365. protocol: locationGetter('$$protocol'),
  10366. /**
  10367. * @ngdoc method
  10368. * @name $location#host
  10369. *
  10370. * @description
  10371. * This method is getter only.
  10372. *
  10373. * Return host of current url.
  10374. *
  10375. * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  10376. *
  10377. *
  10378. * ```js
  10379. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10380. * var host = $location.host();
  10381. * // => "example.com"
  10382. *
  10383. * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  10384. * host = $location.host();
  10385. * // => "example.com"
  10386. * host = location.host;
  10387. * // => "example.com:8080"
  10388. * ```
  10389. *
  10390. * @return {string} host of current url.
  10391. */
  10392. host: locationGetter('$$host'),
  10393. /**
  10394. * @ngdoc method
  10395. * @name $location#port
  10396. *
  10397. * @description
  10398. * This method is getter only.
  10399. *
  10400. * Return port of current url.
  10401. *
  10402. *
  10403. * ```js
  10404. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10405. * var port = $location.port();
  10406. * // => 80
  10407. * ```
  10408. *
  10409. * @return {Number} port
  10410. */
  10411. port: locationGetter('$$port'),
  10412. /**
  10413. * @ngdoc method
  10414. * @name $location#path
  10415. *
  10416. * @description
  10417. * This method is getter / setter.
  10418. *
  10419. * Return path of current url when called without any parameter.
  10420. *
  10421. * Change path when called with parameter and return `$location`.
  10422. *
  10423. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  10424. * if it is missing.
  10425. *
  10426. *
  10427. * ```js
  10428. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10429. * var path = $location.path();
  10430. * // => "/some/path"
  10431. * ```
  10432. *
  10433. * @param {(string|number)=} path New path
  10434. * @return {string} path
  10435. */
  10436. path: locationGetterSetter('$$path', function(path) {
  10437. path = path !== null ? path.toString() : '';
  10438. return path.charAt(0) == '/' ? path : '/' + path;
  10439. }),
  10440. /**
  10441. * @ngdoc method
  10442. * @name $location#search
  10443. *
  10444. * @description
  10445. * This method is getter / setter.
  10446. *
  10447. * Return search part (as object) of current url when called without any parameter.
  10448. *
  10449. * Change search part when called with parameter and return `$location`.
  10450. *
  10451. *
  10452. * ```js
  10453. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10454. * var searchObject = $location.search();
  10455. * // => {foo: 'bar', baz: 'xoxo'}
  10456. *
  10457. * // set foo to 'yipee'
  10458. * $location.search('foo', 'yipee');
  10459. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  10460. * ```
  10461. *
  10462. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  10463. * hash object.
  10464. *
  10465. * When called with a single argument the method acts as a setter, setting the `search` component
  10466. * of `$location` to the specified value.
  10467. *
  10468. * If the argument is a hash object containing an array of values, these values will be encoded
  10469. * as duplicate search parameters in the url.
  10470. *
  10471. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  10472. * will override only a single search property.
  10473. *
  10474. * If `paramValue` is an array, it will override the property of the `search` component of
  10475. * `$location` specified via the first argument.
  10476. *
  10477. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  10478. *
  10479. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  10480. * value nor trailing equal sign.
  10481. *
  10482. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  10483. * one or more arguments returns `$location` object itself.
  10484. */
  10485. search: function(search, paramValue) {
  10486. switch (arguments.length) {
  10487. case 0:
  10488. return this.$$search;
  10489. case 1:
  10490. if (isString(search) || isNumber(search)) {
  10491. search = search.toString();
  10492. this.$$search = parseKeyValue(search);
  10493. } else if (isObject(search)) {
  10494. search = copy(search, {});
  10495. // remove object undefined or null properties
  10496. forEach(search, function(value, key) {
  10497. if (value == null) delete search[key];
  10498. });
  10499. this.$$search = search;
  10500. } else {
  10501. throw $locationMinErr('isrcharg',
  10502. 'The first argument of the `$location#search()` call must be a string or an object.');
  10503. }
  10504. break;
  10505. default:
  10506. if (isUndefined(paramValue) || paramValue === null) {
  10507. delete this.$$search[search];
  10508. } else {
  10509. this.$$search[search] = paramValue;
  10510. }
  10511. }
  10512. this.$$compose();
  10513. return this;
  10514. },
  10515. /**
  10516. * @ngdoc method
  10517. * @name $location#hash
  10518. *
  10519. * @description
  10520. * This method is getter / setter.
  10521. *
  10522. * Return hash fragment when called without any parameter.
  10523. *
  10524. * Change hash fragment when called with parameter and return `$location`.
  10525. *
  10526. *
  10527. * ```js
  10528. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  10529. * var hash = $location.hash();
  10530. * // => "hashValue"
  10531. * ```
  10532. *
  10533. * @param {(string|number)=} hash New hash fragment
  10534. * @return {string} hash
  10535. */
  10536. hash: locationGetterSetter('$$hash', function(hash) {
  10537. return hash !== null ? hash.toString() : '';
  10538. }),
  10539. /**
  10540. * @ngdoc method
  10541. * @name $location#replace
  10542. *
  10543. * @description
  10544. * If called, all changes to $location during current `$digest` will be replacing current history
  10545. * record, instead of adding new one.
  10546. */
  10547. replace: function() {
  10548. this.$$replace = true;
  10549. return this;
  10550. }
  10551. };
  10552. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  10553. Location.prototype = Object.create(locationPrototype);
  10554. /**
  10555. * @ngdoc method
  10556. * @name $location#state
  10557. *
  10558. * @description
  10559. * This method is getter / setter.
  10560. *
  10561. * Return the history state object when called without any parameter.
  10562. *
  10563. * Change the history state object when called with one parameter and return `$location`.
  10564. * The state object is later passed to `pushState` or `replaceState`.
  10565. *
  10566. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  10567. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  10568. * older browsers (like IE9 or Android < 4.0), don't use this method.
  10569. *
  10570. * @param {object=} state State object for pushState or replaceState
  10571. * @return {object} state
  10572. */
  10573. Location.prototype.state = function(state) {
  10574. if (!arguments.length) {
  10575. return this.$$state;
  10576. }
  10577. if (Location !== LocationHtml5Url || !this.$$html5) {
  10578. throw $locationMinErr('nostate', 'History API state support is available only ' +
  10579. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  10580. }
  10581. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  10582. // but we're changing the $$state reference to $browser.state() during the $digest
  10583. // so the modification window is narrow.
  10584. this.$$state = isUndefined(state) ? null : state;
  10585. return this;
  10586. };
  10587. });
  10588. function locationGetter(property) {
  10589. return function() {
  10590. return this[property];
  10591. };
  10592. }
  10593. function locationGetterSetter(property, preprocess) {
  10594. return function(value) {
  10595. if (isUndefined(value)) {
  10596. return this[property];
  10597. }
  10598. this[property] = preprocess(value);
  10599. this.$$compose();
  10600. return this;
  10601. };
  10602. }
  10603. /**
  10604. * @ngdoc service
  10605. * @name $location
  10606. *
  10607. * @requires $rootElement
  10608. *
  10609. * @description
  10610. * The $location service parses the URL in the browser address bar (based on the
  10611. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  10612. * available to your application. Changes to the URL in the address bar are reflected into
  10613. * $location service and changes to $location are reflected into the browser address bar.
  10614. *
  10615. * **The $location service:**
  10616. *
  10617. * - Exposes the current URL in the browser address bar, so you can
  10618. * - Watch and observe the URL.
  10619. * - Change the URL.
  10620. * - Synchronizes the URL with the browser when the user
  10621. * - Changes the address bar.
  10622. * - Clicks the back or forward button (or clicks a History link).
  10623. * - Clicks on a link.
  10624. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  10625. *
  10626. * For more information see {@link guide/$location Developer Guide: Using $location}
  10627. */
  10628. /**
  10629. * @ngdoc provider
  10630. * @name $locationProvider
  10631. * @description
  10632. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  10633. */
  10634. function $LocationProvider() {
  10635. var hashPrefix = '',
  10636. html5Mode = {
  10637. enabled: false,
  10638. requireBase: true,
  10639. rewriteLinks: true
  10640. };
  10641. /**
  10642. * @ngdoc method
  10643. * @name $locationProvider#hashPrefix
  10644. * @description
  10645. * @param {string=} prefix Prefix for hash part (containing path and search)
  10646. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  10647. */
  10648. this.hashPrefix = function(prefix) {
  10649. if (isDefined(prefix)) {
  10650. hashPrefix = prefix;
  10651. return this;
  10652. } else {
  10653. return hashPrefix;
  10654. }
  10655. };
  10656. /**
  10657. * @ngdoc method
  10658. * @name $locationProvider#html5Mode
  10659. * @description
  10660. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  10661. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  10662. * properties:
  10663. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  10664. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  10665. * support `pushState`.
  10666. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  10667. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  10668. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  10669. * See the {@link guide/$location $location guide for more information}
  10670. * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
  10671. * enables/disables url rewriting for relative links.
  10672. *
  10673. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  10674. */
  10675. this.html5Mode = function(mode) {
  10676. if (isBoolean(mode)) {
  10677. html5Mode.enabled = mode;
  10678. return this;
  10679. } else if (isObject(mode)) {
  10680. if (isBoolean(mode.enabled)) {
  10681. html5Mode.enabled = mode.enabled;
  10682. }
  10683. if (isBoolean(mode.requireBase)) {
  10684. html5Mode.requireBase = mode.requireBase;
  10685. }
  10686. if (isBoolean(mode.rewriteLinks)) {
  10687. html5Mode.rewriteLinks = mode.rewriteLinks;
  10688. }
  10689. return this;
  10690. } else {
  10691. return html5Mode;
  10692. }
  10693. };
  10694. /**
  10695. * @ngdoc event
  10696. * @name $location#$locationChangeStart
  10697. * @eventType broadcast on root scope
  10698. * @description
  10699. * Broadcasted before a URL will change.
  10700. *
  10701. * This change can be prevented by calling
  10702. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  10703. * details about event object. Upon successful change
  10704. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  10705. *
  10706. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10707. * the browser supports the HTML5 History API.
  10708. *
  10709. * @param {Object} angularEvent Synthetic event object.
  10710. * @param {string} newUrl New URL
  10711. * @param {string=} oldUrl URL that was before it was changed.
  10712. * @param {string=} newState New history state object
  10713. * @param {string=} oldState History state object that was before it was changed.
  10714. */
  10715. /**
  10716. * @ngdoc event
  10717. * @name $location#$locationChangeSuccess
  10718. * @eventType broadcast on root scope
  10719. * @description
  10720. * Broadcasted after a URL was changed.
  10721. *
  10722. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10723. * the browser supports the HTML5 History API.
  10724. *
  10725. * @param {Object} angularEvent Synthetic event object.
  10726. * @param {string} newUrl New URL
  10727. * @param {string=} oldUrl URL that was before it was changed.
  10728. * @param {string=} newState New history state object
  10729. * @param {string=} oldState History state object that was before it was changed.
  10730. */
  10731. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  10732. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  10733. var $location,
  10734. LocationMode,
  10735. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  10736. initialUrl = $browser.url(),
  10737. appBase;
  10738. if (html5Mode.enabled) {
  10739. if (!baseHref && html5Mode.requireBase) {
  10740. throw $locationMinErr('nobase',
  10741. "$location in HTML5 mode requires a <base> tag to be present!");
  10742. }
  10743. appBase = serverBase(initialUrl) + (baseHref || '/');
  10744. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  10745. } else {
  10746. appBase = stripHash(initialUrl);
  10747. LocationMode = LocationHashbangUrl;
  10748. }
  10749. $location = new LocationMode(appBase, '#' + hashPrefix);
  10750. $location.$$parseLinkUrl(initialUrl, initialUrl);
  10751. $location.$$state = $browser.state();
  10752. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  10753. function setBrowserUrlWithFallback(url, replace, state) {
  10754. var oldUrl = $location.url();
  10755. var oldState = $location.$$state;
  10756. try {
  10757. $browser.url(url, replace, state);
  10758. // Make sure $location.state() returns referentially identical (not just deeply equal)
  10759. // state object; this makes possible quick checking if the state changed in the digest
  10760. // loop. Checking deep equality would be too expensive.
  10761. $location.$$state = $browser.state();
  10762. } catch (e) {
  10763. // Restore old values if pushState fails
  10764. $location.url(oldUrl);
  10765. $location.$$state = oldState;
  10766. throw e;
  10767. }
  10768. }
  10769. $rootElement.on('click', function(event) {
  10770. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  10771. // currently we open nice url link and redirect then
  10772. if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
  10773. var elm = jqLite(event.target);
  10774. // traverse the DOM up to find first A tag
  10775. while (nodeName_(elm[0]) !== 'a') {
  10776. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  10777. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  10778. }
  10779. var absHref = elm.prop('href');
  10780. // get the actual href attribute - see
  10781. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  10782. var relHref = elm.attr('href') || elm.attr('xlink:href');
  10783. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  10784. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  10785. // an animation.
  10786. absHref = urlResolve(absHref.animVal).href;
  10787. }
  10788. // Ignore when url is started with javascript: or mailto:
  10789. if (IGNORE_URI_REGEXP.test(absHref)) return;
  10790. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  10791. if ($location.$$parseLinkUrl(absHref, relHref)) {
  10792. // We do a preventDefault for all urls that are part of the angular application,
  10793. // in html5mode and also without, so that we are able to abort navigation without
  10794. // getting double entries in the location history.
  10795. event.preventDefault();
  10796. // update location manually
  10797. if ($location.absUrl() != $browser.url()) {
  10798. $rootScope.$apply();
  10799. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  10800. $window.angular['ff-684208-preventDefault'] = true;
  10801. }
  10802. }
  10803. }
  10804. });
  10805. // rewrite hashbang url <> html5 url
  10806. if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
  10807. $browser.url($location.absUrl(), true);
  10808. }
  10809. var initializing = true;
  10810. // update $location when $browser url changes
  10811. $browser.onUrlChange(function(newUrl, newState) {
  10812. $rootScope.$evalAsync(function() {
  10813. var oldUrl = $location.absUrl();
  10814. var oldState = $location.$$state;
  10815. var defaultPrevented;
  10816. $location.$$parse(newUrl);
  10817. $location.$$state = newState;
  10818. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  10819. newState, oldState).defaultPrevented;
  10820. // if the location was changed by a `$locationChangeStart` handler then stop
  10821. // processing this location change
  10822. if ($location.absUrl() !== newUrl) return;
  10823. if (defaultPrevented) {
  10824. $location.$$parse(oldUrl);
  10825. $location.$$state = oldState;
  10826. setBrowserUrlWithFallback(oldUrl, false, oldState);
  10827. } else {
  10828. initializing = false;
  10829. afterLocationChange(oldUrl, oldState);
  10830. }
  10831. });
  10832. if (!$rootScope.$$phase) $rootScope.$digest();
  10833. });
  10834. // update browser
  10835. $rootScope.$watch(function $locationWatch() {
  10836. var oldUrl = trimEmptyHash($browser.url());
  10837. var newUrl = trimEmptyHash($location.absUrl());
  10838. var oldState = $browser.state();
  10839. var currentReplace = $location.$$replace;
  10840. var urlOrStateChanged = oldUrl !== newUrl ||
  10841. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  10842. if (initializing || urlOrStateChanged) {
  10843. initializing = false;
  10844. $rootScope.$evalAsync(function() {
  10845. var newUrl = $location.absUrl();
  10846. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  10847. $location.$$state, oldState).defaultPrevented;
  10848. // if the location was changed by a `$locationChangeStart` handler then stop
  10849. // processing this location change
  10850. if ($location.absUrl() !== newUrl) return;
  10851. if (defaultPrevented) {
  10852. $location.$$parse(oldUrl);
  10853. $location.$$state = oldState;
  10854. } else {
  10855. if (urlOrStateChanged) {
  10856. setBrowserUrlWithFallback(newUrl, currentReplace,
  10857. oldState === $location.$$state ? null : $location.$$state);
  10858. }
  10859. afterLocationChange(oldUrl, oldState);
  10860. }
  10861. });
  10862. }
  10863. $location.$$replace = false;
  10864. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  10865. // there is a change
  10866. });
  10867. return $location;
  10868. function afterLocationChange(oldUrl, oldState) {
  10869. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  10870. $location.$$state, oldState);
  10871. }
  10872. }];
  10873. }
  10874. /**
  10875. * @ngdoc service
  10876. * @name $log
  10877. * @requires $window
  10878. *
  10879. * @description
  10880. * Simple service for logging. Default implementation safely writes the message
  10881. * into the browser's console (if present).
  10882. *
  10883. * The main purpose of this service is to simplify debugging and troubleshooting.
  10884. *
  10885. * The default is to log `debug` messages. You can use
  10886. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  10887. *
  10888. * @example
  10889. <example module="logExample">
  10890. <file name="script.js">
  10891. angular.module('logExample', [])
  10892. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  10893. $scope.$log = $log;
  10894. $scope.message = 'Hello World!';
  10895. }]);
  10896. </file>
  10897. <file name="index.html">
  10898. <div ng-controller="LogController">
  10899. <p>Reload this page with open console, enter text and hit the log button...</p>
  10900. <label>Message:
  10901. <input type="text" ng-model="message" /></label>
  10902. <button ng-click="$log.log(message)">log</button>
  10903. <button ng-click="$log.warn(message)">warn</button>
  10904. <button ng-click="$log.info(message)">info</button>
  10905. <button ng-click="$log.error(message)">error</button>
  10906. <button ng-click="$log.debug(message)">debug</button>
  10907. </div>
  10908. </file>
  10909. </example>
  10910. */
  10911. /**
  10912. * @ngdoc provider
  10913. * @name $logProvider
  10914. * @description
  10915. * Use the `$logProvider` to configure how the application logs messages
  10916. */
  10917. function $LogProvider() {
  10918. var debug = true,
  10919. self = this;
  10920. /**
  10921. * @ngdoc method
  10922. * @name $logProvider#debugEnabled
  10923. * @description
  10924. * @param {boolean=} flag enable or disable debug level messages
  10925. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  10926. */
  10927. this.debugEnabled = function(flag) {
  10928. if (isDefined(flag)) {
  10929. debug = flag;
  10930. return this;
  10931. } else {
  10932. return debug;
  10933. }
  10934. };
  10935. this.$get = ['$window', function($window) {
  10936. return {
  10937. /**
  10938. * @ngdoc method
  10939. * @name $log#log
  10940. *
  10941. * @description
  10942. * Write a log message
  10943. */
  10944. log: consoleLog('log'),
  10945. /**
  10946. * @ngdoc method
  10947. * @name $log#info
  10948. *
  10949. * @description
  10950. * Write an information message
  10951. */
  10952. info: consoleLog('info'),
  10953. /**
  10954. * @ngdoc method
  10955. * @name $log#warn
  10956. *
  10957. * @description
  10958. * Write a warning message
  10959. */
  10960. warn: consoleLog('warn'),
  10961. /**
  10962. * @ngdoc method
  10963. * @name $log#error
  10964. *
  10965. * @description
  10966. * Write an error message
  10967. */
  10968. error: consoleLog('error'),
  10969. /**
  10970. * @ngdoc method
  10971. * @name $log#debug
  10972. *
  10973. * @description
  10974. * Write a debug message
  10975. */
  10976. debug: (function() {
  10977. var fn = consoleLog('debug');
  10978. return function() {
  10979. if (debug) {
  10980. fn.apply(self, arguments);
  10981. }
  10982. };
  10983. }())
  10984. };
  10985. function formatError(arg) {
  10986. if (arg instanceof Error) {
  10987. if (arg.stack) {
  10988. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  10989. ? 'Error: ' + arg.message + '\n' + arg.stack
  10990. : arg.stack;
  10991. } else if (arg.sourceURL) {
  10992. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  10993. }
  10994. }
  10995. return arg;
  10996. }
  10997. function consoleLog(type) {
  10998. var console = $window.console || {},
  10999. logFn = console[type] || console.log || noop,
  11000. hasApply = false;
  11001. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  11002. // The reason behind this is that console.log has type "object" in IE8...
  11003. try {
  11004. hasApply = !!logFn.apply;
  11005. } catch (e) {}
  11006. if (hasApply) {
  11007. return function() {
  11008. var args = [];
  11009. forEach(arguments, function(arg) {
  11010. args.push(formatError(arg));
  11011. });
  11012. return logFn.apply(console, args);
  11013. };
  11014. }
  11015. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  11016. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  11017. return function(arg1, arg2) {
  11018. logFn(arg1, arg2 == null ? '' : arg2);
  11019. };
  11020. }
  11021. }];
  11022. }
  11023. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  11024. * Any commits to this file should be reviewed with security in mind. *
  11025. * Changes to this file can potentially create security vulnerabilities. *
  11026. * An approval from 2 Core members with history of modifying *
  11027. * this file is required. *
  11028. * *
  11029. * Does the change somehow allow for arbitrary javascript to be executed? *
  11030. * Or allows for someone to change the prototype of built-in objects? *
  11031. * Or gives undesired access to variables likes document or window? *
  11032. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  11033. var $parseMinErr = minErr('$parse');
  11034. // Sandboxing Angular Expressions
  11035. // ------------------------------
  11036. // Angular expressions are generally considered safe because these expressions only have direct
  11037. // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
  11038. // obtaining a reference to native JS functions such as the Function constructor.
  11039. //
  11040. // As an example, consider the following Angular expression:
  11041. //
  11042. // {}.toString.constructor('alert("evil JS code")')
  11043. //
  11044. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  11045. // against the expression language, but not to prevent exploits that were enabled by exposing
  11046. // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
  11047. // practice and therefore we are not even trying to protect against interaction with an object
  11048. // explicitly exposed in this way.
  11049. //
  11050. // In general, it is not possible to access a Window object from an angular expression unless a
  11051. // window or some DOM object that has a reference to window is published onto a Scope.
  11052. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  11053. // native objects.
  11054. //
  11055. // See https://docs.angularjs.org/guide/security
  11056. function ensureSafeMemberName(name, fullExpression) {
  11057. if (name === "__defineGetter__" || name === "__defineSetter__"
  11058. || name === "__lookupGetter__" || name === "__lookupSetter__"
  11059. || name === "__proto__") {
  11060. throw $parseMinErr('isecfld',
  11061. 'Attempting to access a disallowed field in Angular expressions! '
  11062. + 'Expression: {0}', fullExpression);
  11063. }
  11064. return name;
  11065. }
  11066. function ensureSafeObject(obj, fullExpression) {
  11067. // nifty check if obj is Function that is fast and works across iframes and other contexts
  11068. if (obj) {
  11069. if (obj.constructor === obj) {
  11070. throw $parseMinErr('isecfn',
  11071. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  11072. fullExpression);
  11073. } else if (// isWindow(obj)
  11074. obj.window === obj) {
  11075. throw $parseMinErr('isecwindow',
  11076. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  11077. fullExpression);
  11078. } else if (// isElement(obj)
  11079. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  11080. throw $parseMinErr('isecdom',
  11081. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  11082. fullExpression);
  11083. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  11084. obj === Object) {
  11085. throw $parseMinErr('isecobj',
  11086. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  11087. fullExpression);
  11088. }
  11089. }
  11090. return obj;
  11091. }
  11092. var CALL = Function.prototype.call;
  11093. var APPLY = Function.prototype.apply;
  11094. var BIND = Function.prototype.bind;
  11095. function ensureSafeFunction(obj, fullExpression) {
  11096. if (obj) {
  11097. if (obj.constructor === obj) {
  11098. throw $parseMinErr('isecfn',
  11099. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  11100. fullExpression);
  11101. } else if (obj === CALL || obj === APPLY || obj === BIND) {
  11102. throw $parseMinErr('isecff',
  11103. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  11104. fullExpression);
  11105. }
  11106. }
  11107. }
  11108. var OPERATORS = createMap();
  11109. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  11110. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  11111. /////////////////////////////////////////
  11112. /**
  11113. * @constructor
  11114. */
  11115. var Lexer = function(options) {
  11116. this.options = options;
  11117. };
  11118. Lexer.prototype = {
  11119. constructor: Lexer,
  11120. lex: function(text) {
  11121. this.text = text;
  11122. this.index = 0;
  11123. this.tokens = [];
  11124. while (this.index < this.text.length) {
  11125. var ch = this.text.charAt(this.index);
  11126. if (ch === '"' || ch === "'") {
  11127. this.readString(ch);
  11128. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  11129. this.readNumber();
  11130. } else if (this.isIdent(ch)) {
  11131. this.readIdent();
  11132. } else if (this.is(ch, '(){}[].,;:?')) {
  11133. this.tokens.push({index: this.index, text: ch});
  11134. this.index++;
  11135. } else if (this.isWhitespace(ch)) {
  11136. this.index++;
  11137. } else {
  11138. var ch2 = ch + this.peek();
  11139. var ch3 = ch2 + this.peek(2);
  11140. var op1 = OPERATORS[ch];
  11141. var op2 = OPERATORS[ch2];
  11142. var op3 = OPERATORS[ch3];
  11143. if (op1 || op2 || op3) {
  11144. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  11145. this.tokens.push({index: this.index, text: token, operator: true});
  11146. this.index += token.length;
  11147. } else {
  11148. this.throwError('Unexpected next character ', this.index, this.index + 1);
  11149. }
  11150. }
  11151. }
  11152. return this.tokens;
  11153. },
  11154. is: function(ch, chars) {
  11155. return chars.indexOf(ch) !== -1;
  11156. },
  11157. peek: function(i) {
  11158. var num = i || 1;
  11159. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  11160. },
  11161. isNumber: function(ch) {
  11162. return ('0' <= ch && ch <= '9') && typeof ch === "string";
  11163. },
  11164. isWhitespace: function(ch) {
  11165. // IE treats non-breaking space as \u00A0
  11166. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  11167. ch === '\n' || ch === '\v' || ch === '\u00A0');
  11168. },
  11169. isIdent: function(ch) {
  11170. return ('a' <= ch && ch <= 'z' ||
  11171. 'A' <= ch && ch <= 'Z' ||
  11172. '_' === ch || ch === '$');
  11173. },
  11174. isExpOperator: function(ch) {
  11175. return (ch === '-' || ch === '+' || this.isNumber(ch));
  11176. },
  11177. throwError: function(error, start, end) {
  11178. end = end || this.index;
  11179. var colStr = (isDefined(start)
  11180. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  11181. : ' ' + end);
  11182. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  11183. error, colStr, this.text);
  11184. },
  11185. readNumber: function() {
  11186. var number = '';
  11187. var start = this.index;
  11188. while (this.index < this.text.length) {
  11189. var ch = lowercase(this.text.charAt(this.index));
  11190. if (ch == '.' || this.isNumber(ch)) {
  11191. number += ch;
  11192. } else {
  11193. var peekCh = this.peek();
  11194. if (ch == 'e' && this.isExpOperator(peekCh)) {
  11195. number += ch;
  11196. } else if (this.isExpOperator(ch) &&
  11197. peekCh && this.isNumber(peekCh) &&
  11198. number.charAt(number.length - 1) == 'e') {
  11199. number += ch;
  11200. } else if (this.isExpOperator(ch) &&
  11201. (!peekCh || !this.isNumber(peekCh)) &&
  11202. number.charAt(number.length - 1) == 'e') {
  11203. this.throwError('Invalid exponent');
  11204. } else {
  11205. break;
  11206. }
  11207. }
  11208. this.index++;
  11209. }
  11210. this.tokens.push({
  11211. index: start,
  11212. text: number,
  11213. constant: true,
  11214. value: Number(number)
  11215. });
  11216. },
  11217. readIdent: function() {
  11218. var start = this.index;
  11219. while (this.index < this.text.length) {
  11220. var ch = this.text.charAt(this.index);
  11221. if (!(this.isIdent(ch) || this.isNumber(ch))) {
  11222. break;
  11223. }
  11224. this.index++;
  11225. }
  11226. this.tokens.push({
  11227. index: start,
  11228. text: this.text.slice(start, this.index),
  11229. identifier: true
  11230. });
  11231. },
  11232. readString: function(quote) {
  11233. var start = this.index;
  11234. this.index++;
  11235. var string = '';
  11236. var rawString = quote;
  11237. var escape = false;
  11238. while (this.index < this.text.length) {
  11239. var ch = this.text.charAt(this.index);
  11240. rawString += ch;
  11241. if (escape) {
  11242. if (ch === 'u') {
  11243. var hex = this.text.substring(this.index + 1, this.index + 5);
  11244. if (!hex.match(/[\da-f]{4}/i)) {
  11245. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  11246. }
  11247. this.index += 4;
  11248. string += String.fromCharCode(parseInt(hex, 16));
  11249. } else {
  11250. var rep = ESCAPE[ch];
  11251. string = string + (rep || ch);
  11252. }
  11253. escape = false;
  11254. } else if (ch === '\\') {
  11255. escape = true;
  11256. } else if (ch === quote) {
  11257. this.index++;
  11258. this.tokens.push({
  11259. index: start,
  11260. text: rawString,
  11261. constant: true,
  11262. value: string
  11263. });
  11264. return;
  11265. } else {
  11266. string += ch;
  11267. }
  11268. this.index++;
  11269. }
  11270. this.throwError('Unterminated quote', start);
  11271. }
  11272. };
  11273. var AST = function(lexer, options) {
  11274. this.lexer = lexer;
  11275. this.options = options;
  11276. };
  11277. AST.Program = 'Program';
  11278. AST.ExpressionStatement = 'ExpressionStatement';
  11279. AST.AssignmentExpression = 'AssignmentExpression';
  11280. AST.ConditionalExpression = 'ConditionalExpression';
  11281. AST.LogicalExpression = 'LogicalExpression';
  11282. AST.BinaryExpression = 'BinaryExpression';
  11283. AST.UnaryExpression = 'UnaryExpression';
  11284. AST.CallExpression = 'CallExpression';
  11285. AST.MemberExpression = 'MemberExpression';
  11286. AST.Identifier = 'Identifier';
  11287. AST.Literal = 'Literal';
  11288. AST.ArrayExpression = 'ArrayExpression';
  11289. AST.Property = 'Property';
  11290. AST.ObjectExpression = 'ObjectExpression';
  11291. AST.ThisExpression = 'ThisExpression';
  11292. // Internal use only
  11293. AST.NGValueParameter = 'NGValueParameter';
  11294. AST.prototype = {
  11295. ast: function(text) {
  11296. this.text = text;
  11297. this.tokens = this.lexer.lex(text);
  11298. var value = this.program();
  11299. if (this.tokens.length !== 0) {
  11300. this.throwError('is an unexpected token', this.tokens[0]);
  11301. }
  11302. return value;
  11303. },
  11304. program: function() {
  11305. var body = [];
  11306. while (true) {
  11307. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  11308. body.push(this.expressionStatement());
  11309. if (!this.expect(';')) {
  11310. return { type: AST.Program, body: body};
  11311. }
  11312. }
  11313. },
  11314. expressionStatement: function() {
  11315. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  11316. },
  11317. filterChain: function() {
  11318. var left = this.expression();
  11319. var token;
  11320. while ((token = this.expect('|'))) {
  11321. left = this.filter(left);
  11322. }
  11323. return left;
  11324. },
  11325. expression: function() {
  11326. return this.assignment();
  11327. },
  11328. assignment: function() {
  11329. var result = this.ternary();
  11330. if (this.expect('=')) {
  11331. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  11332. }
  11333. return result;
  11334. },
  11335. ternary: function() {
  11336. var test = this.logicalOR();
  11337. var alternate;
  11338. var consequent;
  11339. if (this.expect('?')) {
  11340. alternate = this.expression();
  11341. if (this.consume(':')) {
  11342. consequent = this.expression();
  11343. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  11344. }
  11345. }
  11346. return test;
  11347. },
  11348. logicalOR: function() {
  11349. var left = this.logicalAND();
  11350. while (this.expect('||')) {
  11351. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  11352. }
  11353. return left;
  11354. },
  11355. logicalAND: function() {
  11356. var left = this.equality();
  11357. while (this.expect('&&')) {
  11358. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  11359. }
  11360. return left;
  11361. },
  11362. equality: function() {
  11363. var left = this.relational();
  11364. var token;
  11365. while ((token = this.expect('==','!=','===','!=='))) {
  11366. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  11367. }
  11368. return left;
  11369. },
  11370. relational: function() {
  11371. var left = this.additive();
  11372. var token;
  11373. while ((token = this.expect('<', '>', '<=', '>='))) {
  11374. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  11375. }
  11376. return left;
  11377. },
  11378. additive: function() {
  11379. var left = this.multiplicative();
  11380. var token;
  11381. while ((token = this.expect('+','-'))) {
  11382. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  11383. }
  11384. return left;
  11385. },
  11386. multiplicative: function() {
  11387. var left = this.unary();
  11388. var token;
  11389. while ((token = this.expect('*','/','%'))) {
  11390. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  11391. }
  11392. return left;
  11393. },
  11394. unary: function() {
  11395. var token;
  11396. if ((token = this.expect('+', '-', '!'))) {
  11397. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  11398. } else {
  11399. return this.primary();
  11400. }
  11401. },
  11402. primary: function() {
  11403. var primary;
  11404. if (this.expect('(')) {
  11405. primary = this.filterChain();
  11406. this.consume(')');
  11407. } else if (this.expect('[')) {
  11408. primary = this.arrayDeclaration();
  11409. } else if (this.expect('{')) {
  11410. primary = this.object();
  11411. } else if (this.constants.hasOwnProperty(this.peek().text)) {
  11412. primary = copy(this.constants[this.consume().text]);
  11413. } else if (this.peek().identifier) {
  11414. primary = this.identifier();
  11415. } else if (this.peek().constant) {
  11416. primary = this.constant();
  11417. } else {
  11418. this.throwError('not a primary expression', this.peek());
  11419. }
  11420. var next;
  11421. while ((next = this.expect('(', '[', '.'))) {
  11422. if (next.text === '(') {
  11423. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  11424. this.consume(')');
  11425. } else if (next.text === '[') {
  11426. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  11427. this.consume(']');
  11428. } else if (next.text === '.') {
  11429. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  11430. } else {
  11431. this.throwError('IMPOSSIBLE');
  11432. }
  11433. }
  11434. return primary;
  11435. },
  11436. filter: function(baseExpression) {
  11437. var args = [baseExpression];
  11438. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  11439. while (this.expect(':')) {
  11440. args.push(this.expression());
  11441. }
  11442. return result;
  11443. },
  11444. parseArguments: function() {
  11445. var args = [];
  11446. if (this.peekToken().text !== ')') {
  11447. do {
  11448. args.push(this.expression());
  11449. } while (this.expect(','));
  11450. }
  11451. return args;
  11452. },
  11453. identifier: function() {
  11454. var token = this.consume();
  11455. if (!token.identifier) {
  11456. this.throwError('is not a valid identifier', token);
  11457. }
  11458. return { type: AST.Identifier, name: token.text };
  11459. },
  11460. constant: function() {
  11461. // TODO check that it is a constant
  11462. return { type: AST.Literal, value: this.consume().value };
  11463. },
  11464. arrayDeclaration: function() {
  11465. var elements = [];
  11466. if (this.peekToken().text !== ']') {
  11467. do {
  11468. if (this.peek(']')) {
  11469. // Support trailing commas per ES5.1.
  11470. break;
  11471. }
  11472. elements.push(this.expression());
  11473. } while (this.expect(','));
  11474. }
  11475. this.consume(']');
  11476. return { type: AST.ArrayExpression, elements: elements };
  11477. },
  11478. object: function() {
  11479. var properties = [], property;
  11480. if (this.peekToken().text !== '}') {
  11481. do {
  11482. if (this.peek('}')) {
  11483. // Support trailing commas per ES5.1.
  11484. break;
  11485. }
  11486. property = {type: AST.Property, kind: 'init'};
  11487. if (this.peek().constant) {
  11488. property.key = this.constant();
  11489. } else if (this.peek().identifier) {
  11490. property.key = this.identifier();
  11491. } else {
  11492. this.throwError("invalid key", this.peek());
  11493. }
  11494. this.consume(':');
  11495. property.value = this.expression();
  11496. properties.push(property);
  11497. } while (this.expect(','));
  11498. }
  11499. this.consume('}');
  11500. return {type: AST.ObjectExpression, properties: properties };
  11501. },
  11502. throwError: function(msg, token) {
  11503. throw $parseMinErr('syntax',
  11504. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  11505. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  11506. },
  11507. consume: function(e1) {
  11508. if (this.tokens.length === 0) {
  11509. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  11510. }
  11511. var token = this.expect(e1);
  11512. if (!token) {
  11513. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  11514. }
  11515. return token;
  11516. },
  11517. peekToken: function() {
  11518. if (this.tokens.length === 0) {
  11519. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  11520. }
  11521. return this.tokens[0];
  11522. },
  11523. peek: function(e1, e2, e3, e4) {
  11524. return this.peekAhead(0, e1, e2, e3, e4);
  11525. },
  11526. peekAhead: function(i, e1, e2, e3, e4) {
  11527. if (this.tokens.length > i) {
  11528. var token = this.tokens[i];
  11529. var t = token.text;
  11530. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  11531. (!e1 && !e2 && !e3 && !e4)) {
  11532. return token;
  11533. }
  11534. }
  11535. return false;
  11536. },
  11537. expect: function(e1, e2, e3, e4) {
  11538. var token = this.peek(e1, e2, e3, e4);
  11539. if (token) {
  11540. this.tokens.shift();
  11541. return token;
  11542. }
  11543. return false;
  11544. },
  11545. /* `undefined` is not a constant, it is an identifier,
  11546. * but using it as an identifier is not supported
  11547. */
  11548. constants: {
  11549. 'true': { type: AST.Literal, value: true },
  11550. 'false': { type: AST.Literal, value: false },
  11551. 'null': { type: AST.Literal, value: null },
  11552. 'undefined': {type: AST.Literal, value: undefined },
  11553. 'this': {type: AST.ThisExpression }
  11554. }
  11555. };
  11556. function ifDefined(v, d) {
  11557. return typeof v !== 'undefined' ? v : d;
  11558. }
  11559. function plusFn(l, r) {
  11560. if (typeof l === 'undefined') return r;
  11561. if (typeof r === 'undefined') return l;
  11562. return l + r;
  11563. }
  11564. function isStateless($filter, filterName) {
  11565. var fn = $filter(filterName);
  11566. return !fn.$stateful;
  11567. }
  11568. function findConstantAndWatchExpressions(ast, $filter) {
  11569. var allConstants;
  11570. var argsToWatch;
  11571. switch (ast.type) {
  11572. case AST.Program:
  11573. allConstants = true;
  11574. forEach(ast.body, function(expr) {
  11575. findConstantAndWatchExpressions(expr.expression, $filter);
  11576. allConstants = allConstants && expr.expression.constant;
  11577. });
  11578. ast.constant = allConstants;
  11579. break;
  11580. case AST.Literal:
  11581. ast.constant = true;
  11582. ast.toWatch = [];
  11583. break;
  11584. case AST.UnaryExpression:
  11585. findConstantAndWatchExpressions(ast.argument, $filter);
  11586. ast.constant = ast.argument.constant;
  11587. ast.toWatch = ast.argument.toWatch;
  11588. break;
  11589. case AST.BinaryExpression:
  11590. findConstantAndWatchExpressions(ast.left, $filter);
  11591. findConstantAndWatchExpressions(ast.right, $filter);
  11592. ast.constant = ast.left.constant && ast.right.constant;
  11593. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  11594. break;
  11595. case AST.LogicalExpression:
  11596. findConstantAndWatchExpressions(ast.left, $filter);
  11597. findConstantAndWatchExpressions(ast.right, $filter);
  11598. ast.constant = ast.left.constant && ast.right.constant;
  11599. ast.toWatch = ast.constant ? [] : [ast];
  11600. break;
  11601. case AST.ConditionalExpression:
  11602. findConstantAndWatchExpressions(ast.test, $filter);
  11603. findConstantAndWatchExpressions(ast.alternate, $filter);
  11604. findConstantAndWatchExpressions(ast.consequent, $filter);
  11605. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  11606. ast.toWatch = ast.constant ? [] : [ast];
  11607. break;
  11608. case AST.Identifier:
  11609. ast.constant = false;
  11610. ast.toWatch = [ast];
  11611. break;
  11612. case AST.MemberExpression:
  11613. findConstantAndWatchExpressions(ast.object, $filter);
  11614. if (ast.computed) {
  11615. findConstantAndWatchExpressions(ast.property, $filter);
  11616. }
  11617. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  11618. ast.toWatch = [ast];
  11619. break;
  11620. case AST.CallExpression:
  11621. allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
  11622. argsToWatch = [];
  11623. forEach(ast.arguments, function(expr) {
  11624. findConstantAndWatchExpressions(expr, $filter);
  11625. allConstants = allConstants && expr.constant;
  11626. if (!expr.constant) {
  11627. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  11628. }
  11629. });
  11630. ast.constant = allConstants;
  11631. ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
  11632. break;
  11633. case AST.AssignmentExpression:
  11634. findConstantAndWatchExpressions(ast.left, $filter);
  11635. findConstantAndWatchExpressions(ast.right, $filter);
  11636. ast.constant = ast.left.constant && ast.right.constant;
  11637. ast.toWatch = [ast];
  11638. break;
  11639. case AST.ArrayExpression:
  11640. allConstants = true;
  11641. argsToWatch = [];
  11642. forEach(ast.elements, function(expr) {
  11643. findConstantAndWatchExpressions(expr, $filter);
  11644. allConstants = allConstants && expr.constant;
  11645. if (!expr.constant) {
  11646. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  11647. }
  11648. });
  11649. ast.constant = allConstants;
  11650. ast.toWatch = argsToWatch;
  11651. break;
  11652. case AST.ObjectExpression:
  11653. allConstants = true;
  11654. argsToWatch = [];
  11655. forEach(ast.properties, function(property) {
  11656. findConstantAndWatchExpressions(property.value, $filter);
  11657. allConstants = allConstants && property.value.constant;
  11658. if (!property.value.constant) {
  11659. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  11660. }
  11661. });
  11662. ast.constant = allConstants;
  11663. ast.toWatch = argsToWatch;
  11664. break;
  11665. case AST.ThisExpression:
  11666. ast.constant = false;
  11667. ast.toWatch = [];
  11668. break;
  11669. }
  11670. }
  11671. function getInputs(body) {
  11672. if (body.length != 1) return;
  11673. var lastExpression = body[0].expression;
  11674. var candidate = lastExpression.toWatch;
  11675. if (candidate.length !== 1) return candidate;
  11676. return candidate[0] !== lastExpression ? candidate : undefined;
  11677. }
  11678. function isAssignable(ast) {
  11679. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  11680. }
  11681. function assignableAST(ast) {
  11682. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  11683. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  11684. }
  11685. }
  11686. function isLiteral(ast) {
  11687. return ast.body.length === 0 ||
  11688. ast.body.length === 1 && (
  11689. ast.body[0].expression.type === AST.Literal ||
  11690. ast.body[0].expression.type === AST.ArrayExpression ||
  11691. ast.body[0].expression.type === AST.ObjectExpression);
  11692. }
  11693. function isConstant(ast) {
  11694. return ast.constant;
  11695. }
  11696. function ASTCompiler(astBuilder, $filter) {
  11697. this.astBuilder = astBuilder;
  11698. this.$filter = $filter;
  11699. }
  11700. ASTCompiler.prototype = {
  11701. compile: function(expression, expensiveChecks) {
  11702. var self = this;
  11703. var ast = this.astBuilder.ast(expression);
  11704. this.state = {
  11705. nextId: 0,
  11706. filters: {},
  11707. expensiveChecks: expensiveChecks,
  11708. fn: {vars: [], body: [], own: {}},
  11709. assign: {vars: [], body: [], own: {}},
  11710. inputs: []
  11711. };
  11712. findConstantAndWatchExpressions(ast, self.$filter);
  11713. var extra = '';
  11714. var assignable;
  11715. this.stage = 'assign';
  11716. if ((assignable = assignableAST(ast))) {
  11717. this.state.computing = 'assign';
  11718. var result = this.nextId();
  11719. this.recurse(assignable, result);
  11720. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  11721. }
  11722. var toWatch = getInputs(ast.body);
  11723. self.stage = 'inputs';
  11724. forEach(toWatch, function(watch, key) {
  11725. var fnKey = 'fn' + key;
  11726. self.state[fnKey] = {vars: [], body: [], own: {}};
  11727. self.state.computing = fnKey;
  11728. var intoId = self.nextId();
  11729. self.recurse(watch, intoId);
  11730. self.return_(intoId);
  11731. self.state.inputs.push(fnKey);
  11732. watch.watchId = key;
  11733. });
  11734. this.state.computing = 'fn';
  11735. this.stage = 'main';
  11736. this.recurse(ast);
  11737. var fnString =
  11738. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  11739. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  11740. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  11741. this.filterPrefix() +
  11742. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  11743. extra +
  11744. this.watchFns() +
  11745. 'return fn;';
  11746. /* jshint -W054 */
  11747. var fn = (new Function('$filter',
  11748. 'ensureSafeMemberName',
  11749. 'ensureSafeObject',
  11750. 'ensureSafeFunction',
  11751. 'ifDefined',
  11752. 'plus',
  11753. 'text',
  11754. fnString))(
  11755. this.$filter,
  11756. ensureSafeMemberName,
  11757. ensureSafeObject,
  11758. ensureSafeFunction,
  11759. ifDefined,
  11760. plusFn,
  11761. expression);
  11762. /* jshint +W054 */
  11763. this.state = this.stage = undefined;
  11764. fn.literal = isLiteral(ast);
  11765. fn.constant = isConstant(ast);
  11766. return fn;
  11767. },
  11768. USE: 'use',
  11769. STRICT: 'strict',
  11770. watchFns: function() {
  11771. var result = [];
  11772. var fns = this.state.inputs;
  11773. var self = this;
  11774. forEach(fns, function(name) {
  11775. result.push('var ' + name + '=' + self.generateFunction(name, 's'));
  11776. });
  11777. if (fns.length) {
  11778. result.push('fn.inputs=[' + fns.join(',') + '];');
  11779. }
  11780. return result.join('');
  11781. },
  11782. generateFunction: function(name, params) {
  11783. return 'function(' + params + '){' +
  11784. this.varsPrefix(name) +
  11785. this.body(name) +
  11786. '};';
  11787. },
  11788. filterPrefix: function() {
  11789. var parts = [];
  11790. var self = this;
  11791. forEach(this.state.filters, function(id, filter) {
  11792. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  11793. });
  11794. if (parts.length) return 'var ' + parts.join(',') + ';';
  11795. return '';
  11796. },
  11797. varsPrefix: function(section) {
  11798. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  11799. },
  11800. body: function(section) {
  11801. return this.state[section].body.join('');
  11802. },
  11803. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  11804. var left, right, self = this, args, expression;
  11805. recursionFn = recursionFn || noop;
  11806. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  11807. intoId = intoId || this.nextId();
  11808. this.if_('i',
  11809. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  11810. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  11811. );
  11812. return;
  11813. }
  11814. switch (ast.type) {
  11815. case AST.Program:
  11816. forEach(ast.body, function(expression, pos) {
  11817. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  11818. if (pos !== ast.body.length - 1) {
  11819. self.current().body.push(right, ';');
  11820. } else {
  11821. self.return_(right);
  11822. }
  11823. });
  11824. break;
  11825. case AST.Literal:
  11826. expression = this.escape(ast.value);
  11827. this.assign(intoId, expression);
  11828. recursionFn(expression);
  11829. break;
  11830. case AST.UnaryExpression:
  11831. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  11832. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  11833. this.assign(intoId, expression);
  11834. recursionFn(expression);
  11835. break;
  11836. case AST.BinaryExpression:
  11837. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  11838. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  11839. if (ast.operator === '+') {
  11840. expression = this.plus(left, right);
  11841. } else if (ast.operator === '-') {
  11842. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  11843. } else {
  11844. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  11845. }
  11846. this.assign(intoId, expression);
  11847. recursionFn(expression);
  11848. break;
  11849. case AST.LogicalExpression:
  11850. intoId = intoId || this.nextId();
  11851. self.recurse(ast.left, intoId);
  11852. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  11853. recursionFn(intoId);
  11854. break;
  11855. case AST.ConditionalExpression:
  11856. intoId = intoId || this.nextId();
  11857. self.recurse(ast.test, intoId);
  11858. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  11859. recursionFn(intoId);
  11860. break;
  11861. case AST.Identifier:
  11862. intoId = intoId || this.nextId();
  11863. if (nameId) {
  11864. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  11865. nameId.computed = false;
  11866. nameId.name = ast.name;
  11867. }
  11868. ensureSafeMemberName(ast.name);
  11869. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  11870. function() {
  11871. self.if_(self.stage === 'inputs' || 's', function() {
  11872. if (create && create !== 1) {
  11873. self.if_(
  11874. self.not(self.nonComputedMember('s', ast.name)),
  11875. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  11876. }
  11877. self.assign(intoId, self.nonComputedMember('s', ast.name));
  11878. });
  11879. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  11880. );
  11881. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
  11882. self.addEnsureSafeObject(intoId);
  11883. }
  11884. recursionFn(intoId);
  11885. break;
  11886. case AST.MemberExpression:
  11887. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  11888. intoId = intoId || this.nextId();
  11889. self.recurse(ast.object, left, undefined, function() {
  11890. self.if_(self.notNull(left), function() {
  11891. if (ast.computed) {
  11892. right = self.nextId();
  11893. self.recurse(ast.property, right);
  11894. self.addEnsureSafeMemberName(right);
  11895. if (create && create !== 1) {
  11896. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  11897. }
  11898. expression = self.ensureSafeObject(self.computedMember(left, right));
  11899. self.assign(intoId, expression);
  11900. if (nameId) {
  11901. nameId.computed = true;
  11902. nameId.name = right;
  11903. }
  11904. } else {
  11905. ensureSafeMemberName(ast.property.name);
  11906. if (create && create !== 1) {
  11907. self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  11908. }
  11909. expression = self.nonComputedMember(left, ast.property.name);
  11910. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
  11911. expression = self.ensureSafeObject(expression);
  11912. }
  11913. self.assign(intoId, expression);
  11914. if (nameId) {
  11915. nameId.computed = false;
  11916. nameId.name = ast.property.name;
  11917. }
  11918. }
  11919. recursionFn(intoId);
  11920. });
  11921. }, !!create);
  11922. break;
  11923. case AST.CallExpression:
  11924. intoId = intoId || this.nextId();
  11925. if (ast.filter) {
  11926. right = self.filter(ast.callee.name);
  11927. args = [];
  11928. forEach(ast.arguments, function(expr) {
  11929. var argument = self.nextId();
  11930. self.recurse(expr, argument);
  11931. args.push(argument);
  11932. });
  11933. expression = right + '(' + args.join(',') + ')';
  11934. self.assign(intoId, expression);
  11935. recursionFn(intoId);
  11936. } else {
  11937. right = self.nextId();
  11938. left = {};
  11939. args = [];
  11940. self.recurse(ast.callee, right, left, function() {
  11941. self.if_(self.notNull(right), function() {
  11942. self.addEnsureSafeFunction(right);
  11943. forEach(ast.arguments, function(expr) {
  11944. self.recurse(expr, self.nextId(), undefined, function(argument) {
  11945. args.push(self.ensureSafeObject(argument));
  11946. });
  11947. });
  11948. if (left.name) {
  11949. if (!self.state.expensiveChecks) {
  11950. self.addEnsureSafeObject(left.context);
  11951. }
  11952. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  11953. } else {
  11954. expression = right + '(' + args.join(',') + ')';
  11955. }
  11956. expression = self.ensureSafeObject(expression);
  11957. self.assign(intoId, expression);
  11958. recursionFn(intoId);
  11959. });
  11960. });
  11961. }
  11962. break;
  11963. case AST.AssignmentExpression:
  11964. right = this.nextId();
  11965. left = {};
  11966. if (!isAssignable(ast.left)) {
  11967. throw $parseMinErr('lval', 'Trying to assing a value to a non l-value');
  11968. }
  11969. this.recurse(ast.left, undefined, left, function() {
  11970. self.if_(self.notNull(left.context), function() {
  11971. self.recurse(ast.right, right);
  11972. self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
  11973. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  11974. self.assign(intoId, expression);
  11975. recursionFn(intoId || expression);
  11976. });
  11977. }, 1);
  11978. break;
  11979. case AST.ArrayExpression:
  11980. args = [];
  11981. forEach(ast.elements, function(expr) {
  11982. self.recurse(expr, self.nextId(), undefined, function(argument) {
  11983. args.push(argument);
  11984. });
  11985. });
  11986. expression = '[' + args.join(',') + ']';
  11987. this.assign(intoId, expression);
  11988. recursionFn(expression);
  11989. break;
  11990. case AST.ObjectExpression:
  11991. args = [];
  11992. forEach(ast.properties, function(property) {
  11993. self.recurse(property.value, self.nextId(), undefined, function(expr) {
  11994. args.push(self.escape(
  11995. property.key.type === AST.Identifier ? property.key.name :
  11996. ('' + property.key.value)) +
  11997. ':' + expr);
  11998. });
  11999. });
  12000. expression = '{' + args.join(',') + '}';
  12001. this.assign(intoId, expression);
  12002. recursionFn(expression);
  12003. break;
  12004. case AST.ThisExpression:
  12005. this.assign(intoId, 's');
  12006. recursionFn('s');
  12007. break;
  12008. case AST.NGValueParameter:
  12009. this.assign(intoId, 'v');
  12010. recursionFn('v');
  12011. break;
  12012. }
  12013. },
  12014. getHasOwnProperty: function(element, property) {
  12015. var key = element + '.' + property;
  12016. var own = this.current().own;
  12017. if (!own.hasOwnProperty(key)) {
  12018. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  12019. }
  12020. return own[key];
  12021. },
  12022. assign: function(id, value) {
  12023. if (!id) return;
  12024. this.current().body.push(id, '=', value, ';');
  12025. return id;
  12026. },
  12027. filter: function(filterName) {
  12028. if (!this.state.filters.hasOwnProperty(filterName)) {
  12029. this.state.filters[filterName] = this.nextId(true);
  12030. }
  12031. return this.state.filters[filterName];
  12032. },
  12033. ifDefined: function(id, defaultValue) {
  12034. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  12035. },
  12036. plus: function(left, right) {
  12037. return 'plus(' + left + ',' + right + ')';
  12038. },
  12039. return_: function(id) {
  12040. this.current().body.push('return ', id, ';');
  12041. },
  12042. if_: function(test, alternate, consequent) {
  12043. if (test === true) {
  12044. alternate();
  12045. } else {
  12046. var body = this.current().body;
  12047. body.push('if(', test, '){');
  12048. alternate();
  12049. body.push('}');
  12050. if (consequent) {
  12051. body.push('else{');
  12052. consequent();
  12053. body.push('}');
  12054. }
  12055. }
  12056. },
  12057. not: function(expression) {
  12058. return '!(' + expression + ')';
  12059. },
  12060. notNull: function(expression) {
  12061. return expression + '!=null';
  12062. },
  12063. nonComputedMember: function(left, right) {
  12064. return left + '.' + right;
  12065. },
  12066. computedMember: function(left, right) {
  12067. return left + '[' + right + ']';
  12068. },
  12069. member: function(left, right, computed) {
  12070. if (computed) return this.computedMember(left, right);
  12071. return this.nonComputedMember(left, right);
  12072. },
  12073. addEnsureSafeObject: function(item) {
  12074. this.current().body.push(this.ensureSafeObject(item), ';');
  12075. },
  12076. addEnsureSafeMemberName: function(item) {
  12077. this.current().body.push(this.ensureSafeMemberName(item), ';');
  12078. },
  12079. addEnsureSafeFunction: function(item) {
  12080. this.current().body.push(this.ensureSafeFunction(item), ';');
  12081. },
  12082. ensureSafeObject: function(item) {
  12083. return 'ensureSafeObject(' + item + ',text)';
  12084. },
  12085. ensureSafeMemberName: function(item) {
  12086. return 'ensureSafeMemberName(' + item + ',text)';
  12087. },
  12088. ensureSafeFunction: function(item) {
  12089. return 'ensureSafeFunction(' + item + ',text)';
  12090. },
  12091. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  12092. var self = this;
  12093. return function() {
  12094. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  12095. };
  12096. },
  12097. lazyAssign: function(id, value) {
  12098. var self = this;
  12099. return function() {
  12100. self.assign(id, value);
  12101. };
  12102. },
  12103. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  12104. stringEscapeFn: function(c) {
  12105. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  12106. },
  12107. escape: function(value) {
  12108. if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
  12109. if (isNumber(value)) return value.toString();
  12110. if (value === true) return 'true';
  12111. if (value === false) return 'false';
  12112. if (value === null) return 'null';
  12113. if (typeof value === 'undefined') return 'undefined';
  12114. throw $parseMinErr('esc', 'IMPOSSIBLE');
  12115. },
  12116. nextId: function(skip, init) {
  12117. var id = 'v' + (this.state.nextId++);
  12118. if (!skip) {
  12119. this.current().vars.push(id + (init ? '=' + init : ''));
  12120. }
  12121. return id;
  12122. },
  12123. current: function() {
  12124. return this.state[this.state.computing];
  12125. }
  12126. };
  12127. function ASTInterpreter(astBuilder, $filter) {
  12128. this.astBuilder = astBuilder;
  12129. this.$filter = $filter;
  12130. }
  12131. ASTInterpreter.prototype = {
  12132. compile: function(expression, expensiveChecks) {
  12133. var self = this;
  12134. var ast = this.astBuilder.ast(expression);
  12135. this.expression = expression;
  12136. this.expensiveChecks = expensiveChecks;
  12137. findConstantAndWatchExpressions(ast, self.$filter);
  12138. var assignable;
  12139. var assign;
  12140. if ((assignable = assignableAST(ast))) {
  12141. assign = this.recurse(assignable);
  12142. }
  12143. var toWatch = getInputs(ast.body);
  12144. var inputs;
  12145. if (toWatch) {
  12146. inputs = [];
  12147. forEach(toWatch, function(watch, key) {
  12148. var input = self.recurse(watch);
  12149. watch.input = input;
  12150. inputs.push(input);
  12151. watch.watchId = key;
  12152. });
  12153. }
  12154. var expressions = [];
  12155. forEach(ast.body, function(expression) {
  12156. expressions.push(self.recurse(expression.expression));
  12157. });
  12158. var fn = ast.body.length === 0 ? function() {} :
  12159. ast.body.length === 1 ? expressions[0] :
  12160. function(scope, locals) {
  12161. var lastValue;
  12162. forEach(expressions, function(exp) {
  12163. lastValue = exp(scope, locals);
  12164. });
  12165. return lastValue;
  12166. };
  12167. if (assign) {
  12168. fn.assign = function(scope, value, locals) {
  12169. return assign(scope, locals, value);
  12170. };
  12171. }
  12172. if (inputs) {
  12173. fn.inputs = inputs;
  12174. }
  12175. fn.literal = isLiteral(ast);
  12176. fn.constant = isConstant(ast);
  12177. return fn;
  12178. },
  12179. recurse: function(ast, context, create) {
  12180. var left, right, self = this, args, expression;
  12181. if (ast.input) {
  12182. return this.inputs(ast.input, ast.watchId);
  12183. }
  12184. switch (ast.type) {
  12185. case AST.Literal:
  12186. return this.value(ast.value, context);
  12187. case AST.UnaryExpression:
  12188. right = this.recurse(ast.argument);
  12189. return this['unary' + ast.operator](right, context);
  12190. case AST.BinaryExpression:
  12191. left = this.recurse(ast.left);
  12192. right = this.recurse(ast.right);
  12193. return this['binary' + ast.operator](left, right, context);
  12194. case AST.LogicalExpression:
  12195. left = this.recurse(ast.left);
  12196. right = this.recurse(ast.right);
  12197. return this['binary' + ast.operator](left, right, context);
  12198. case AST.ConditionalExpression:
  12199. return this['ternary?:'](
  12200. this.recurse(ast.test),
  12201. this.recurse(ast.alternate),
  12202. this.recurse(ast.consequent),
  12203. context
  12204. );
  12205. case AST.Identifier:
  12206. ensureSafeMemberName(ast.name, self.expression);
  12207. return self.identifier(ast.name,
  12208. self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
  12209. context, create, self.expression);
  12210. case AST.MemberExpression:
  12211. left = this.recurse(ast.object, false, !!create);
  12212. if (!ast.computed) {
  12213. ensureSafeMemberName(ast.property.name, self.expression);
  12214. right = ast.property.name;
  12215. }
  12216. if (ast.computed) right = this.recurse(ast.property);
  12217. return ast.computed ?
  12218. this.computedMember(left, right, context, create, self.expression) :
  12219. this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
  12220. case AST.CallExpression:
  12221. args = [];
  12222. forEach(ast.arguments, function(expr) {
  12223. args.push(self.recurse(expr));
  12224. });
  12225. if (ast.filter) right = this.$filter(ast.callee.name);
  12226. if (!ast.filter) right = this.recurse(ast.callee, true);
  12227. return ast.filter ?
  12228. function(scope, locals, assign, inputs) {
  12229. var values = [];
  12230. for (var i = 0; i < args.length; ++i) {
  12231. values.push(args[i](scope, locals, assign, inputs));
  12232. }
  12233. var value = right.apply(undefined, values, inputs);
  12234. return context ? {context: undefined, name: undefined, value: value} : value;
  12235. } :
  12236. function(scope, locals, assign, inputs) {
  12237. var rhs = right(scope, locals, assign, inputs);
  12238. var value;
  12239. if (rhs.value != null) {
  12240. ensureSafeObject(rhs.context, self.expression);
  12241. ensureSafeFunction(rhs.value, self.expression);
  12242. var values = [];
  12243. for (var i = 0; i < args.length; ++i) {
  12244. values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
  12245. }
  12246. value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
  12247. }
  12248. return context ? {value: value} : value;
  12249. };
  12250. case AST.AssignmentExpression:
  12251. left = this.recurse(ast.left, true, 1);
  12252. right = this.recurse(ast.right);
  12253. return function(scope, locals, assign, inputs) {
  12254. var lhs = left(scope, locals, assign, inputs);
  12255. var rhs = right(scope, locals, assign, inputs);
  12256. ensureSafeObject(lhs.value, self.expression);
  12257. lhs.context[lhs.name] = rhs;
  12258. return context ? {value: rhs} : rhs;
  12259. };
  12260. case AST.ArrayExpression:
  12261. args = [];
  12262. forEach(ast.elements, function(expr) {
  12263. args.push(self.recurse(expr));
  12264. });
  12265. return function(scope, locals, assign, inputs) {
  12266. var value = [];
  12267. for (var i = 0; i < args.length; ++i) {
  12268. value.push(args[i](scope, locals, assign, inputs));
  12269. }
  12270. return context ? {value: value} : value;
  12271. };
  12272. case AST.ObjectExpression:
  12273. args = [];
  12274. forEach(ast.properties, function(property) {
  12275. args.push({key: property.key.type === AST.Identifier ?
  12276. property.key.name :
  12277. ('' + property.key.value),
  12278. value: self.recurse(property.value)
  12279. });
  12280. });
  12281. return function(scope, locals, assign, inputs) {
  12282. var value = {};
  12283. for (var i = 0; i < args.length; ++i) {
  12284. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  12285. }
  12286. return context ? {value: value} : value;
  12287. };
  12288. case AST.ThisExpression:
  12289. return function(scope) {
  12290. return context ? {value: scope} : scope;
  12291. };
  12292. case AST.NGValueParameter:
  12293. return function(scope, locals, assign, inputs) {
  12294. return context ? {value: assign} : assign;
  12295. };
  12296. }
  12297. },
  12298. 'unary+': function(argument, context) {
  12299. return function(scope, locals, assign, inputs) {
  12300. var arg = argument(scope, locals, assign, inputs);
  12301. if (isDefined(arg)) {
  12302. arg = +arg;
  12303. } else {
  12304. arg = 0;
  12305. }
  12306. return context ? {value: arg} : arg;
  12307. };
  12308. },
  12309. 'unary-': function(argument, context) {
  12310. return function(scope, locals, assign, inputs) {
  12311. var arg = argument(scope, locals, assign, inputs);
  12312. if (isDefined(arg)) {
  12313. arg = -arg;
  12314. } else {
  12315. arg = 0;
  12316. }
  12317. return context ? {value: arg} : arg;
  12318. };
  12319. },
  12320. 'unary!': function(argument, context) {
  12321. return function(scope, locals, assign, inputs) {
  12322. var arg = !argument(scope, locals, assign, inputs);
  12323. return context ? {value: arg} : arg;
  12324. };
  12325. },
  12326. 'binary+': function(left, right, context) {
  12327. return function(scope, locals, assign, inputs) {
  12328. var lhs = left(scope, locals, assign, inputs);
  12329. var rhs = right(scope, locals, assign, inputs);
  12330. var arg = plusFn(lhs, rhs);
  12331. return context ? {value: arg} : arg;
  12332. };
  12333. },
  12334. 'binary-': function(left, right, context) {
  12335. return function(scope, locals, assign, inputs) {
  12336. var lhs = left(scope, locals, assign, inputs);
  12337. var rhs = right(scope, locals, assign, inputs);
  12338. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  12339. return context ? {value: arg} : arg;
  12340. };
  12341. },
  12342. 'binary*': function(left, right, context) {
  12343. return function(scope, locals, assign, inputs) {
  12344. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  12345. return context ? {value: arg} : arg;
  12346. };
  12347. },
  12348. 'binary/': function(left, right, context) {
  12349. return function(scope, locals, assign, inputs) {
  12350. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  12351. return context ? {value: arg} : arg;
  12352. };
  12353. },
  12354. 'binary%': function(left, right, context) {
  12355. return function(scope, locals, assign, inputs) {
  12356. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  12357. return context ? {value: arg} : arg;
  12358. };
  12359. },
  12360. 'binary===': function(left, right, context) {
  12361. return function(scope, locals, assign, inputs) {
  12362. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  12363. return context ? {value: arg} : arg;
  12364. };
  12365. },
  12366. 'binary!==': function(left, right, context) {
  12367. return function(scope, locals, assign, inputs) {
  12368. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  12369. return context ? {value: arg} : arg;
  12370. };
  12371. },
  12372. 'binary==': function(left, right, context) {
  12373. return function(scope, locals, assign, inputs) {
  12374. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  12375. return context ? {value: arg} : arg;
  12376. };
  12377. },
  12378. 'binary!=': function(left, right, context) {
  12379. return function(scope, locals, assign, inputs) {
  12380. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  12381. return context ? {value: arg} : arg;
  12382. };
  12383. },
  12384. 'binary<': function(left, right, context) {
  12385. return function(scope, locals, assign, inputs) {
  12386. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  12387. return context ? {value: arg} : arg;
  12388. };
  12389. },
  12390. 'binary>': function(left, right, context) {
  12391. return function(scope, locals, assign, inputs) {
  12392. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  12393. return context ? {value: arg} : arg;
  12394. };
  12395. },
  12396. 'binary<=': function(left, right, context) {
  12397. return function(scope, locals, assign, inputs) {
  12398. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  12399. return context ? {value: arg} : arg;
  12400. };
  12401. },
  12402. 'binary>=': function(left, right, context) {
  12403. return function(scope, locals, assign, inputs) {
  12404. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  12405. return context ? {value: arg} : arg;
  12406. };
  12407. },
  12408. 'binary&&': function(left, right, context) {
  12409. return function(scope, locals, assign, inputs) {
  12410. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  12411. return context ? {value: arg} : arg;
  12412. };
  12413. },
  12414. 'binary||': function(left, right, context) {
  12415. return function(scope, locals, assign, inputs) {
  12416. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  12417. return context ? {value: arg} : arg;
  12418. };
  12419. },
  12420. 'ternary?:': function(test, alternate, consequent, context) {
  12421. return function(scope, locals, assign, inputs) {
  12422. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  12423. return context ? {value: arg} : arg;
  12424. };
  12425. },
  12426. value: function(value, context) {
  12427. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  12428. },
  12429. identifier: function(name, expensiveChecks, context, create, expression) {
  12430. return function(scope, locals, assign, inputs) {
  12431. var base = locals && (name in locals) ? locals : scope;
  12432. if (create && create !== 1 && base && !(base[name])) {
  12433. base[name] = {};
  12434. }
  12435. var value = base ? base[name] : undefined;
  12436. if (expensiveChecks) {
  12437. ensureSafeObject(value, expression);
  12438. }
  12439. if (context) {
  12440. return {context: base, name: name, value: value};
  12441. } else {
  12442. return value;
  12443. }
  12444. };
  12445. },
  12446. computedMember: function(left, right, context, create, expression) {
  12447. return function(scope, locals, assign, inputs) {
  12448. var lhs = left(scope, locals, assign, inputs);
  12449. var rhs;
  12450. var value;
  12451. if (lhs != null) {
  12452. rhs = right(scope, locals, assign, inputs);
  12453. ensureSafeMemberName(rhs, expression);
  12454. if (create && create !== 1 && lhs && !(lhs[rhs])) {
  12455. lhs[rhs] = {};
  12456. }
  12457. value = lhs[rhs];
  12458. ensureSafeObject(value, expression);
  12459. }
  12460. if (context) {
  12461. return {context: lhs, name: rhs, value: value};
  12462. } else {
  12463. return value;
  12464. }
  12465. };
  12466. },
  12467. nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
  12468. return function(scope, locals, assign, inputs) {
  12469. var lhs = left(scope, locals, assign, inputs);
  12470. if (create && create !== 1 && lhs && !(lhs[right])) {
  12471. lhs[right] = {};
  12472. }
  12473. var value = lhs != null ? lhs[right] : undefined;
  12474. if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
  12475. ensureSafeObject(value, expression);
  12476. }
  12477. if (context) {
  12478. return {context: lhs, name: right, value: value};
  12479. } else {
  12480. return value;
  12481. }
  12482. };
  12483. },
  12484. inputs: function(input, watchId) {
  12485. return function(scope, value, locals, inputs) {
  12486. if (inputs) return inputs[watchId];
  12487. return input(scope, value, locals);
  12488. };
  12489. }
  12490. };
  12491. /**
  12492. * @constructor
  12493. */
  12494. var Parser = function(lexer, $filter, options) {
  12495. this.lexer = lexer;
  12496. this.$filter = $filter;
  12497. this.options = options;
  12498. this.ast = new AST(this.lexer);
  12499. this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
  12500. new ASTCompiler(this.ast, $filter);
  12501. };
  12502. Parser.prototype = {
  12503. constructor: Parser,
  12504. parse: function(text) {
  12505. return this.astCompiler.compile(text, this.options.expensiveChecks);
  12506. }
  12507. };
  12508. //////////////////////////////////////////////////
  12509. // Parser helper functions
  12510. //////////////////////////////////////////////////
  12511. function setter(obj, path, setValue, fullExp) {
  12512. ensureSafeObject(obj, fullExp);
  12513. var element = path.split('.'), key;
  12514. for (var i = 0; element.length > 1; i++) {
  12515. key = ensureSafeMemberName(element.shift(), fullExp);
  12516. var propertyObj = ensureSafeObject(obj[key], fullExp);
  12517. if (!propertyObj) {
  12518. propertyObj = {};
  12519. obj[key] = propertyObj;
  12520. }
  12521. obj = propertyObj;
  12522. }
  12523. key = ensureSafeMemberName(element.shift(), fullExp);
  12524. ensureSafeObject(obj[key], fullExp);
  12525. obj[key] = setValue;
  12526. return setValue;
  12527. }
  12528. var getterFnCacheDefault = createMap();
  12529. var getterFnCacheExpensive = createMap();
  12530. function isPossiblyDangerousMemberName(name) {
  12531. return name == 'constructor';
  12532. }
  12533. var objectValueOf = Object.prototype.valueOf;
  12534. function getValueOf(value) {
  12535. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  12536. }
  12537. ///////////////////////////////////
  12538. /**
  12539. * @ngdoc service
  12540. * @name $parse
  12541. * @kind function
  12542. *
  12543. * @description
  12544. *
  12545. * Converts Angular {@link guide/expression expression} into a function.
  12546. *
  12547. * ```js
  12548. * var getter = $parse('user.name');
  12549. * var setter = getter.assign;
  12550. * var context = {user:{name:'angular'}};
  12551. * var locals = {user:{name:'local'}};
  12552. *
  12553. * expect(getter(context)).toEqual('angular');
  12554. * setter(context, 'newValue');
  12555. * expect(context.user.name).toEqual('newValue');
  12556. * expect(getter(context, locals)).toEqual('local');
  12557. * ```
  12558. *
  12559. *
  12560. * @param {string} expression String expression to compile.
  12561. * @returns {function(context, locals)} a function which represents the compiled expression:
  12562. *
  12563. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12564. * are evaluated against (typically a scope object).
  12565. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12566. * `context`.
  12567. *
  12568. * The returned function also has the following properties:
  12569. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  12570. * literal.
  12571. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  12572. * constant literals.
  12573. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  12574. * set to a function to change its value on the given context.
  12575. *
  12576. */
  12577. /**
  12578. * @ngdoc provider
  12579. * @name $parseProvider
  12580. *
  12581. * @description
  12582. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  12583. * service.
  12584. */
  12585. function $ParseProvider() {
  12586. var cacheDefault = createMap();
  12587. var cacheExpensive = createMap();
  12588. this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
  12589. var $parseOptions = {
  12590. csp: $sniffer.csp,
  12591. expensiveChecks: false
  12592. },
  12593. $parseOptionsExpensive = {
  12594. csp: $sniffer.csp,
  12595. expensiveChecks: true
  12596. };
  12597. return function $parse(exp, interceptorFn, expensiveChecks) {
  12598. var parsedExpression, oneTime, cacheKey;
  12599. switch (typeof exp) {
  12600. case 'string':
  12601. exp = exp.trim();
  12602. cacheKey = exp;
  12603. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  12604. parsedExpression = cache[cacheKey];
  12605. if (!parsedExpression) {
  12606. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  12607. oneTime = true;
  12608. exp = exp.substring(2);
  12609. }
  12610. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  12611. var lexer = new Lexer(parseOptions);
  12612. var parser = new Parser(lexer, $filter, parseOptions);
  12613. parsedExpression = parser.parse(exp);
  12614. if (parsedExpression.constant) {
  12615. parsedExpression.$$watchDelegate = constantWatchDelegate;
  12616. } else if (oneTime) {
  12617. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  12618. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  12619. } else if (parsedExpression.inputs) {
  12620. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  12621. }
  12622. cache[cacheKey] = parsedExpression;
  12623. }
  12624. return addInterceptor(parsedExpression, interceptorFn);
  12625. case 'function':
  12626. return addInterceptor(exp, interceptorFn);
  12627. default:
  12628. return noop;
  12629. }
  12630. };
  12631. function expressionInputDirtyCheck(newValue, oldValueOfValue) {
  12632. if (newValue == null || oldValueOfValue == null) { // null/undefined
  12633. return newValue === oldValueOfValue;
  12634. }
  12635. if (typeof newValue === 'object') {
  12636. // attempt to convert the value to a primitive type
  12637. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  12638. // be cheaply dirty-checked
  12639. newValue = getValueOf(newValue);
  12640. if (typeof newValue === 'object') {
  12641. // objects/arrays are not supported - deep-watching them would be too expensive
  12642. return false;
  12643. }
  12644. // fall-through to the primitive equality check
  12645. }
  12646. //Primitive or NaN
  12647. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  12648. }
  12649. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  12650. var inputExpressions = parsedExpression.inputs;
  12651. var lastResult;
  12652. if (inputExpressions.length === 1) {
  12653. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  12654. inputExpressions = inputExpressions[0];
  12655. return scope.$watch(function expressionInputWatch(scope) {
  12656. var newInputValue = inputExpressions(scope);
  12657. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
  12658. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  12659. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  12660. }
  12661. return lastResult;
  12662. }, listener, objectEquality, prettyPrintExpression);
  12663. }
  12664. var oldInputValueOfValues = [];
  12665. var oldInputValues = [];
  12666. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  12667. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  12668. oldInputValues[i] = null;
  12669. }
  12670. return scope.$watch(function expressionInputsWatch(scope) {
  12671. var changed = false;
  12672. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  12673. var newInputValue = inputExpressions[i](scope);
  12674. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
  12675. oldInputValues[i] = newInputValue;
  12676. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  12677. }
  12678. }
  12679. if (changed) {
  12680. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  12681. }
  12682. return lastResult;
  12683. }, listener, objectEquality, prettyPrintExpression);
  12684. }
  12685. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  12686. var unwatch, lastValue;
  12687. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  12688. return parsedExpression(scope);
  12689. }, function oneTimeListener(value, old, scope) {
  12690. lastValue = value;
  12691. if (isFunction(listener)) {
  12692. listener.apply(this, arguments);
  12693. }
  12694. if (isDefined(value)) {
  12695. scope.$$postDigest(function() {
  12696. if (isDefined(lastValue)) {
  12697. unwatch();
  12698. }
  12699. });
  12700. }
  12701. }, objectEquality);
  12702. }
  12703. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  12704. var unwatch, lastValue;
  12705. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  12706. return parsedExpression(scope);
  12707. }, function oneTimeListener(value, old, scope) {
  12708. lastValue = value;
  12709. if (isFunction(listener)) {
  12710. listener.call(this, value, old, scope);
  12711. }
  12712. if (isAllDefined(value)) {
  12713. scope.$$postDigest(function() {
  12714. if (isAllDefined(lastValue)) unwatch();
  12715. });
  12716. }
  12717. }, objectEquality);
  12718. function isAllDefined(value) {
  12719. var allDefined = true;
  12720. forEach(value, function(val) {
  12721. if (!isDefined(val)) allDefined = false;
  12722. });
  12723. return allDefined;
  12724. }
  12725. }
  12726. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  12727. var unwatch;
  12728. return unwatch = scope.$watch(function constantWatch(scope) {
  12729. return parsedExpression(scope);
  12730. }, function constantListener(value, old, scope) {
  12731. if (isFunction(listener)) {
  12732. listener.apply(this, arguments);
  12733. }
  12734. unwatch();
  12735. }, objectEquality);
  12736. }
  12737. function addInterceptor(parsedExpression, interceptorFn) {
  12738. if (!interceptorFn) return parsedExpression;
  12739. var watchDelegate = parsedExpression.$$watchDelegate;
  12740. var regularWatch =
  12741. watchDelegate !== oneTimeLiteralWatchDelegate &&
  12742. watchDelegate !== oneTimeWatchDelegate;
  12743. var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
  12744. var value = parsedExpression(scope, locals, assign, inputs);
  12745. return interceptorFn(value, scope, locals);
  12746. } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
  12747. var value = parsedExpression(scope, locals, assign, inputs);
  12748. var result = interceptorFn(value, scope, locals);
  12749. // we only return the interceptor's result if the
  12750. // initial value is defined (for bind-once)
  12751. return isDefined(value) ? result : value;
  12752. };
  12753. // Propagate $$watchDelegates other then inputsWatchDelegate
  12754. if (parsedExpression.$$watchDelegate &&
  12755. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  12756. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  12757. } else if (!interceptorFn.$stateful) {
  12758. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  12759. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  12760. fn.$$watchDelegate = inputsWatchDelegate;
  12761. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  12762. }
  12763. return fn;
  12764. }
  12765. }];
  12766. }
  12767. /**
  12768. * @ngdoc service
  12769. * @name $q
  12770. * @requires $rootScope
  12771. *
  12772. * @description
  12773. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  12774. * when they are done processing.
  12775. *
  12776. * This is an implementation of promises/deferred objects inspired by
  12777. * [Kris Kowal's Q](https://github.com/kriskowal/q).
  12778. *
  12779. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  12780. * implementations, and the other which resembles ES6 promises to some degree.
  12781. *
  12782. * # $q constructor
  12783. *
  12784. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  12785. * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
  12786. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  12787. *
  12788. * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
  12789. * available yet.
  12790. *
  12791. * It can be used like so:
  12792. *
  12793. * ```js
  12794. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  12795. * // are available in the current lexical scope (they could have been injected or passed in).
  12796. *
  12797. * function asyncGreet(name) {
  12798. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  12799. * return $q(function(resolve, reject) {
  12800. * setTimeout(function() {
  12801. * if (okToGreet(name)) {
  12802. * resolve('Hello, ' + name + '!');
  12803. * } else {
  12804. * reject('Greeting ' + name + ' is not allowed.');
  12805. * }
  12806. * }, 1000);
  12807. * });
  12808. * }
  12809. *
  12810. * var promise = asyncGreet('Robin Hood');
  12811. * promise.then(function(greeting) {
  12812. * alert('Success: ' + greeting);
  12813. * }, function(reason) {
  12814. * alert('Failed: ' + reason);
  12815. * });
  12816. * ```
  12817. *
  12818. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  12819. *
  12820. * However, the more traditional CommonJS-style usage is still available, and documented below.
  12821. *
  12822. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  12823. * interface for interacting with an object that represents the result of an action that is
  12824. * performed asynchronously, and may or may not be finished at any given point in time.
  12825. *
  12826. * From the perspective of dealing with error handling, deferred and promise APIs are to
  12827. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  12828. *
  12829. * ```js
  12830. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  12831. * // are available in the current lexical scope (they could have been injected or passed in).
  12832. *
  12833. * function asyncGreet(name) {
  12834. * var deferred = $q.defer();
  12835. *
  12836. * setTimeout(function() {
  12837. * deferred.notify('About to greet ' + name + '.');
  12838. *
  12839. * if (okToGreet(name)) {
  12840. * deferred.resolve('Hello, ' + name + '!');
  12841. * } else {
  12842. * deferred.reject('Greeting ' + name + ' is not allowed.');
  12843. * }
  12844. * }, 1000);
  12845. *
  12846. * return deferred.promise;
  12847. * }
  12848. *
  12849. * var promise = asyncGreet('Robin Hood');
  12850. * promise.then(function(greeting) {
  12851. * alert('Success: ' + greeting);
  12852. * }, function(reason) {
  12853. * alert('Failed: ' + reason);
  12854. * }, function(update) {
  12855. * alert('Got notification: ' + update);
  12856. * });
  12857. * ```
  12858. *
  12859. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  12860. * comes in the way of guarantees that promise and deferred APIs make, see
  12861. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  12862. *
  12863. * Additionally the promise api allows for composition that is very hard to do with the
  12864. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  12865. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  12866. * section on serial or parallel joining of promises.
  12867. *
  12868. * # The Deferred API
  12869. *
  12870. * A new instance of deferred is constructed by calling `$q.defer()`.
  12871. *
  12872. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  12873. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  12874. * of the task.
  12875. *
  12876. * **Methods**
  12877. *
  12878. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  12879. * constructed via `$q.reject`, the promise will be rejected instead.
  12880. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  12881. * resolving it with a rejection constructed via `$q.reject`.
  12882. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  12883. * multiple times before the promise is either resolved or rejected.
  12884. *
  12885. * **Properties**
  12886. *
  12887. * - promise – `{Promise}` – promise object associated with this deferred.
  12888. *
  12889. *
  12890. * # The Promise API
  12891. *
  12892. * A new promise instance is created when a deferred instance is created and can be retrieved by
  12893. * calling `deferred.promise`.
  12894. *
  12895. * The purpose of the promise object is to allow for interested parties to get access to the result
  12896. * of the deferred task when it completes.
  12897. *
  12898. * **Methods**
  12899. *
  12900. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  12901. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  12902. * as soon as the result is available. The callbacks are called with a single argument: the result
  12903. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  12904. * provide a progress indication, before the promise is resolved or rejected.
  12905. *
  12906. * This method *returns a new promise* which is resolved or rejected via the return value of the
  12907. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  12908. * with the value which is resolved in that promise using
  12909. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  12910. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  12911. * resolved or rejected from the notifyCallback method.
  12912. *
  12913. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  12914. *
  12915. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  12916. * but to do so without modifying the final value. This is useful to release resources or do some
  12917. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  12918. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  12919. * more information.
  12920. *
  12921. * # Chaining promises
  12922. *
  12923. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  12924. * possible to create a chain of promises:
  12925. *
  12926. * ```js
  12927. * promiseB = promiseA.then(function(result) {
  12928. * return result + 1;
  12929. * });
  12930. *
  12931. * // promiseB will be resolved immediately after promiseA is resolved and its value
  12932. * // will be the result of promiseA incremented by 1
  12933. * ```
  12934. *
  12935. * It is possible to create chains of any length and since a promise can be resolved with another
  12936. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  12937. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  12938. * $http's response interceptors.
  12939. *
  12940. *
  12941. * # Differences between Kris Kowal's Q and $q
  12942. *
  12943. * There are two main differences:
  12944. *
  12945. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  12946. * mechanism in angular, which means faster propagation of resolution or rejection into your
  12947. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  12948. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  12949. * all the important functionality needed for common async tasks.
  12950. *
  12951. * # Testing
  12952. *
  12953. * ```js
  12954. * it('should simulate promise', inject(function($q, $rootScope) {
  12955. * var deferred = $q.defer();
  12956. * var promise = deferred.promise;
  12957. * var resolvedValue;
  12958. *
  12959. * promise.then(function(value) { resolvedValue = value; });
  12960. * expect(resolvedValue).toBeUndefined();
  12961. *
  12962. * // Simulate resolving of promise
  12963. * deferred.resolve(123);
  12964. * // Note that the 'then' function does not get called synchronously.
  12965. * // This is because we want the promise API to always be async, whether or not
  12966. * // it got called synchronously or asynchronously.
  12967. * expect(resolvedValue).toBeUndefined();
  12968. *
  12969. * // Propagate promise resolution to 'then' functions using $apply().
  12970. * $rootScope.$apply();
  12971. * expect(resolvedValue).toEqual(123);
  12972. * }));
  12973. * ```
  12974. *
  12975. * @param {function(function, function)} resolver Function which is responsible for resolving or
  12976. * rejecting the newly created promise. The first parameter is a function which resolves the
  12977. * promise, the second parameter is a function which rejects the promise.
  12978. *
  12979. * @returns {Promise} The newly created promise.
  12980. */
  12981. function $QProvider() {
  12982. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  12983. return qFactory(function(callback) {
  12984. $rootScope.$evalAsync(callback);
  12985. }, $exceptionHandler);
  12986. }];
  12987. }
  12988. function $$QProvider() {
  12989. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  12990. return qFactory(function(callback) {
  12991. $browser.defer(callback);
  12992. }, $exceptionHandler);
  12993. }];
  12994. }
  12995. /**
  12996. * Constructs a promise manager.
  12997. *
  12998. * @param {function(function)} nextTick Function for executing functions in the next turn.
  12999. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  13000. * debugging purposes.
  13001. * @returns {object} Promise manager.
  13002. */
  13003. function qFactory(nextTick, exceptionHandler) {
  13004. var $qMinErr = minErr('$q', TypeError);
  13005. function callOnce(self, resolveFn, rejectFn) {
  13006. var called = false;
  13007. function wrap(fn) {
  13008. return function(value) {
  13009. if (called) return;
  13010. called = true;
  13011. fn.call(self, value);
  13012. };
  13013. }
  13014. return [wrap(resolveFn), wrap(rejectFn)];
  13015. }
  13016. /**
  13017. * @ngdoc method
  13018. * @name ng.$q#defer
  13019. * @kind function
  13020. *
  13021. * @description
  13022. * Creates a `Deferred` object which represents a task which will finish in the future.
  13023. *
  13024. * @returns {Deferred} Returns a new instance of deferred.
  13025. */
  13026. var defer = function() {
  13027. return new Deferred();
  13028. };
  13029. function Promise() {
  13030. this.$$state = { status: 0 };
  13031. }
  13032. Promise.prototype = {
  13033. then: function(onFulfilled, onRejected, progressBack) {
  13034. var result = new Deferred();
  13035. this.$$state.pending = this.$$state.pending || [];
  13036. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  13037. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  13038. return result.promise;
  13039. },
  13040. "catch": function(callback) {
  13041. return this.then(null, callback);
  13042. },
  13043. "finally": function(callback, progressBack) {
  13044. return this.then(function(value) {
  13045. return handleCallback(value, true, callback);
  13046. }, function(error) {
  13047. return handleCallback(error, false, callback);
  13048. }, progressBack);
  13049. }
  13050. };
  13051. //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
  13052. function simpleBind(context, fn) {
  13053. return function(value) {
  13054. fn.call(context, value);
  13055. };
  13056. }
  13057. function processQueue(state) {
  13058. var fn, deferred, pending;
  13059. pending = state.pending;
  13060. state.processScheduled = false;
  13061. state.pending = undefined;
  13062. for (var i = 0, ii = pending.length; i < ii; ++i) {
  13063. deferred = pending[i][0];
  13064. fn = pending[i][state.status];
  13065. try {
  13066. if (isFunction(fn)) {
  13067. deferred.resolve(fn(state.value));
  13068. } else if (state.status === 1) {
  13069. deferred.resolve(state.value);
  13070. } else {
  13071. deferred.reject(state.value);
  13072. }
  13073. } catch (e) {
  13074. deferred.reject(e);
  13075. exceptionHandler(e);
  13076. }
  13077. }
  13078. }
  13079. function scheduleProcessQueue(state) {
  13080. if (state.processScheduled || !state.pending) return;
  13081. state.processScheduled = true;
  13082. nextTick(function() { processQueue(state); });
  13083. }
  13084. function Deferred() {
  13085. this.promise = new Promise();
  13086. //Necessary to support unbound execution :/
  13087. this.resolve = simpleBind(this, this.resolve);
  13088. this.reject = simpleBind(this, this.reject);
  13089. this.notify = simpleBind(this, this.notify);
  13090. }
  13091. Deferred.prototype = {
  13092. resolve: function(val) {
  13093. if (this.promise.$$state.status) return;
  13094. if (val === this.promise) {
  13095. this.$$reject($qMinErr(
  13096. 'qcycle',
  13097. "Expected promise to be resolved with value other than itself '{0}'",
  13098. val));
  13099. } else {
  13100. this.$$resolve(val);
  13101. }
  13102. },
  13103. $$resolve: function(val) {
  13104. var then, fns;
  13105. fns = callOnce(this, this.$$resolve, this.$$reject);
  13106. try {
  13107. if ((isObject(val) || isFunction(val))) then = val && val.then;
  13108. if (isFunction(then)) {
  13109. this.promise.$$state.status = -1;
  13110. then.call(val, fns[0], fns[1], this.notify);
  13111. } else {
  13112. this.promise.$$state.value = val;
  13113. this.promise.$$state.status = 1;
  13114. scheduleProcessQueue(this.promise.$$state);
  13115. }
  13116. } catch (e) {
  13117. fns[1](e);
  13118. exceptionHandler(e);
  13119. }
  13120. },
  13121. reject: function(reason) {
  13122. if (this.promise.$$state.status) return;
  13123. this.$$reject(reason);
  13124. },
  13125. $$reject: function(reason) {
  13126. this.promise.$$state.value = reason;
  13127. this.promise.$$state.status = 2;
  13128. scheduleProcessQueue(this.promise.$$state);
  13129. },
  13130. notify: function(progress) {
  13131. var callbacks = this.promise.$$state.pending;
  13132. if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
  13133. nextTick(function() {
  13134. var callback, result;
  13135. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  13136. result = callbacks[i][0];
  13137. callback = callbacks[i][3];
  13138. try {
  13139. result.notify(isFunction(callback) ? callback(progress) : progress);
  13140. } catch (e) {
  13141. exceptionHandler(e);
  13142. }
  13143. }
  13144. });
  13145. }
  13146. }
  13147. };
  13148. /**
  13149. * @ngdoc method
  13150. * @name $q#reject
  13151. * @kind function
  13152. *
  13153. * @description
  13154. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  13155. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  13156. * a promise chain, you don't need to worry about it.
  13157. *
  13158. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  13159. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  13160. * a promise error callback and you want to forward the error to the promise derived from the
  13161. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  13162. * `reject`.
  13163. *
  13164. * ```js
  13165. * promiseB = promiseA.then(function(result) {
  13166. * // success: do something and resolve promiseB
  13167. * // with the old or a new result
  13168. * return result;
  13169. * }, function(reason) {
  13170. * // error: handle the error if possible and
  13171. * // resolve promiseB with newPromiseOrValue,
  13172. * // otherwise forward the rejection to promiseB
  13173. * if (canHandle(reason)) {
  13174. * // handle the error and recover
  13175. * return newPromiseOrValue;
  13176. * }
  13177. * return $q.reject(reason);
  13178. * });
  13179. * ```
  13180. *
  13181. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  13182. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  13183. */
  13184. var reject = function(reason) {
  13185. var result = new Deferred();
  13186. result.reject(reason);
  13187. return result.promise;
  13188. };
  13189. var makePromise = function makePromise(value, resolved) {
  13190. var result = new Deferred();
  13191. if (resolved) {
  13192. result.resolve(value);
  13193. } else {
  13194. result.reject(value);
  13195. }
  13196. return result.promise;
  13197. };
  13198. var handleCallback = function handleCallback(value, isResolved, callback) {
  13199. var callbackOutput = null;
  13200. try {
  13201. if (isFunction(callback)) callbackOutput = callback();
  13202. } catch (e) {
  13203. return makePromise(e, false);
  13204. }
  13205. if (isPromiseLike(callbackOutput)) {
  13206. return callbackOutput.then(function() {
  13207. return makePromise(value, isResolved);
  13208. }, function(error) {
  13209. return makePromise(error, false);
  13210. });
  13211. } else {
  13212. return makePromise(value, isResolved);
  13213. }
  13214. };
  13215. /**
  13216. * @ngdoc method
  13217. * @name $q#when
  13218. * @kind function
  13219. *
  13220. * @description
  13221. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  13222. * This is useful when you are dealing with an object that might or might not be a promise, or if
  13223. * the promise comes from a source that can't be trusted.
  13224. *
  13225. * @param {*} value Value or a promise
  13226. * @returns {Promise} Returns a promise of the passed value or promise
  13227. */
  13228. var when = function(value, callback, errback, progressBack) {
  13229. var result = new Deferred();
  13230. result.resolve(value);
  13231. return result.promise.then(callback, errback, progressBack);
  13232. };
  13233. /**
  13234. * @ngdoc method
  13235. * @name $q#all
  13236. * @kind function
  13237. *
  13238. * @description
  13239. * Combines multiple promises into a single promise that is resolved when all of the input
  13240. * promises are resolved.
  13241. *
  13242. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  13243. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  13244. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  13245. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  13246. * with the same rejection value.
  13247. */
  13248. function all(promises) {
  13249. var deferred = new Deferred(),
  13250. counter = 0,
  13251. results = isArray(promises) ? [] : {};
  13252. forEach(promises, function(promise, key) {
  13253. counter++;
  13254. when(promise).then(function(value) {
  13255. if (results.hasOwnProperty(key)) return;
  13256. results[key] = value;
  13257. if (!(--counter)) deferred.resolve(results);
  13258. }, function(reason) {
  13259. if (results.hasOwnProperty(key)) return;
  13260. deferred.reject(reason);
  13261. });
  13262. });
  13263. if (counter === 0) {
  13264. deferred.resolve(results);
  13265. }
  13266. return deferred.promise;
  13267. }
  13268. var $Q = function Q(resolver) {
  13269. if (!isFunction(resolver)) {
  13270. throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
  13271. }
  13272. if (!(this instanceof Q)) {
  13273. // More useful when $Q is the Promise itself.
  13274. return new Q(resolver);
  13275. }
  13276. var deferred = new Deferred();
  13277. function resolveFn(value) {
  13278. deferred.resolve(value);
  13279. }
  13280. function rejectFn(reason) {
  13281. deferred.reject(reason);
  13282. }
  13283. resolver(resolveFn, rejectFn);
  13284. return deferred.promise;
  13285. };
  13286. $Q.defer = defer;
  13287. $Q.reject = reject;
  13288. $Q.when = when;
  13289. $Q.all = all;
  13290. return $Q;
  13291. }
  13292. function $$RAFProvider() { //rAF
  13293. this.$get = ['$window', '$timeout', function($window, $timeout) {
  13294. var requestAnimationFrame = $window.requestAnimationFrame ||
  13295. $window.webkitRequestAnimationFrame;
  13296. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  13297. $window.webkitCancelAnimationFrame ||
  13298. $window.webkitCancelRequestAnimationFrame;
  13299. var rafSupported = !!requestAnimationFrame;
  13300. var rafFn = rafSupported
  13301. ? function(fn) {
  13302. var id = requestAnimationFrame(fn);
  13303. return function() {
  13304. cancelAnimationFrame(id);
  13305. };
  13306. }
  13307. : function(fn) {
  13308. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  13309. return function() {
  13310. $timeout.cancel(timer);
  13311. };
  13312. };
  13313. queueFn.supported = rafSupported;
  13314. var cancelLastRAF;
  13315. var taskCount = 0;
  13316. var taskQueue = [];
  13317. return queueFn;
  13318. function flush() {
  13319. for (var i = 0; i < taskQueue.length; i++) {
  13320. var task = taskQueue[i];
  13321. if (task) {
  13322. taskQueue[i] = null;
  13323. task();
  13324. }
  13325. }
  13326. taskCount = taskQueue.length = 0;
  13327. }
  13328. function queueFn(asyncFn) {
  13329. var index = taskQueue.length;
  13330. taskCount++;
  13331. taskQueue.push(asyncFn);
  13332. if (index === 0) {
  13333. cancelLastRAF = rafFn(flush);
  13334. }
  13335. return function cancelQueueFn() {
  13336. if (index >= 0) {
  13337. taskQueue[index] = null;
  13338. index = null;
  13339. if (--taskCount === 0 && cancelLastRAF) {
  13340. cancelLastRAF();
  13341. cancelLastRAF = null;
  13342. taskQueue.length = 0;
  13343. }
  13344. }
  13345. };
  13346. }
  13347. }];
  13348. }
  13349. /**
  13350. * DESIGN NOTES
  13351. *
  13352. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  13353. *
  13354. * The typical use of scope is to watch the expressions, which most of the time return the same
  13355. * value as last time so we optimize the operation.
  13356. *
  13357. * Closures construction is expensive in terms of speed as well as memory:
  13358. * - No closures, instead use prototypical inheritance for API
  13359. * - Internal state needs to be stored on scope directly, which means that private state is
  13360. * exposed as $$____ properties
  13361. *
  13362. * Loop operations are optimized by using while(count--) { ... }
  13363. * - this means that in order to keep the same order of execution as addition we have to add
  13364. * items to the array at the beginning (unshift) instead of at the end (push)
  13365. *
  13366. * Child scopes are created and removed often
  13367. * - Using an array would be slow since inserts in middle are expensive so we use linked list
  13368. *
  13369. * There are few watches then a lot of observers. This is why you don't want the observer to be
  13370. * implemented in the same way as watch. Watch requires return of initialization function which
  13371. * are expensive to construct.
  13372. */
  13373. /**
  13374. * @ngdoc provider
  13375. * @name $rootScopeProvider
  13376. * @description
  13377. *
  13378. * Provider for the $rootScope service.
  13379. */
  13380. /**
  13381. * @ngdoc method
  13382. * @name $rootScopeProvider#digestTtl
  13383. * @description
  13384. *
  13385. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  13386. * assuming that the model is unstable.
  13387. *
  13388. * The current default is 10 iterations.
  13389. *
  13390. * In complex applications it's possible that the dependencies between `$watch`s will result in
  13391. * several digest iterations. However if an application needs more than the default 10 digest
  13392. * iterations for its model to stabilize then you should investigate what is causing the model to
  13393. * continuously change during the digest.
  13394. *
  13395. * Increasing the TTL could have performance implications, so you should not change it without
  13396. * proper justification.
  13397. *
  13398. * @param {number} limit The number of digest iterations.
  13399. */
  13400. /**
  13401. * @ngdoc service
  13402. * @name $rootScope
  13403. * @description
  13404. *
  13405. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  13406. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  13407. * between the model and the view, via a mechanism for watching the model for changes.
  13408. * They also provide an event emission/broadcast and subscription facility. See the
  13409. * {@link guide/scope developer guide on scopes}.
  13410. */
  13411. function $RootScopeProvider() {
  13412. var TTL = 10;
  13413. var $rootScopeMinErr = minErr('$rootScope');
  13414. var lastDirtyWatch = null;
  13415. var applyAsyncId = null;
  13416. this.digestTtl = function(value) {
  13417. if (arguments.length) {
  13418. TTL = value;
  13419. }
  13420. return TTL;
  13421. };
  13422. function createChildScopeClass(parent) {
  13423. function ChildScope() {
  13424. this.$$watchers = this.$$nextSibling =
  13425. this.$$childHead = this.$$childTail = null;
  13426. this.$$listeners = {};
  13427. this.$$listenerCount = {};
  13428. this.$$watchersCount = 0;
  13429. this.$id = nextUid();
  13430. this.$$ChildScope = null;
  13431. }
  13432. ChildScope.prototype = parent;
  13433. return ChildScope;
  13434. }
  13435. this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
  13436. function($injector, $exceptionHandler, $parse, $browser) {
  13437. function destroyChildScope($event) {
  13438. $event.currentScope.$$destroyed = true;
  13439. }
  13440. /**
  13441. * @ngdoc type
  13442. * @name $rootScope.Scope
  13443. *
  13444. * @description
  13445. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  13446. * {@link auto.$injector $injector}. Child scopes are created using the
  13447. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  13448. * compiled HTML template is executed.)
  13449. *
  13450. * Here is a simple scope snippet to show how you can interact with the scope.
  13451. * ```html
  13452. * <file src="./test/ng/rootScopeSpec.js" tag="docs1" />
  13453. * ```
  13454. *
  13455. * # Inheritance
  13456. * A scope can inherit from a parent scope, as in this example:
  13457. * ```js
  13458. var parent = $rootScope;
  13459. var child = parent.$new();
  13460. parent.salutation = "Hello";
  13461. expect(child.salutation).toEqual('Hello');
  13462. child.salutation = "Welcome";
  13463. expect(child.salutation).toEqual('Welcome');
  13464. expect(parent.salutation).toEqual('Hello');
  13465. * ```
  13466. *
  13467. * When interacting with `Scope` in tests, additional helper methods are available on the
  13468. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  13469. * details.
  13470. *
  13471. *
  13472. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  13473. * provided for the current scope. Defaults to {@link ng}.
  13474. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  13475. * append/override services provided by `providers`. This is handy
  13476. * when unit-testing and having the need to override a default
  13477. * service.
  13478. * @returns {Object} Newly created scope.
  13479. *
  13480. */
  13481. function Scope() {
  13482. this.$id = nextUid();
  13483. this.$$phase = this.$parent = this.$$watchers =
  13484. this.$$nextSibling = this.$$prevSibling =
  13485. this.$$childHead = this.$$childTail = null;
  13486. this.$root = this;
  13487. this.$$destroyed = false;
  13488. this.$$listeners = {};
  13489. this.$$listenerCount = {};
  13490. this.$$watchersCount = 0;
  13491. this.$$isolateBindings = null;
  13492. }
  13493. /**
  13494. * @ngdoc property
  13495. * @name $rootScope.Scope#$id
  13496. *
  13497. * @description
  13498. * Unique scope ID (monotonically increasing) useful for debugging.
  13499. */
  13500. /**
  13501. * @ngdoc property
  13502. * @name $rootScope.Scope#$parent
  13503. *
  13504. * @description
  13505. * Reference to the parent scope.
  13506. */
  13507. /**
  13508. * @ngdoc property
  13509. * @name $rootScope.Scope#$root
  13510. *
  13511. * @description
  13512. * Reference to the root scope.
  13513. */
  13514. Scope.prototype = {
  13515. constructor: Scope,
  13516. /**
  13517. * @ngdoc method
  13518. * @name $rootScope.Scope#$new
  13519. * @kind function
  13520. *
  13521. * @description
  13522. * Creates a new child {@link ng.$rootScope.Scope scope}.
  13523. *
  13524. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  13525. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  13526. *
  13527. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  13528. * desired for the scope and its child scopes to be permanently detached from the parent and
  13529. * thus stop participating in model change detection and listener notification by invoking.
  13530. *
  13531. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  13532. * parent scope. The scope is isolated, as it can not see parent scope properties.
  13533. * When creating widgets, it is useful for the widget to not accidentally read parent
  13534. * state.
  13535. *
  13536. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  13537. * of the newly created scope. Defaults to `this` scope if not provided.
  13538. * This is used when creating a transclude scope to correctly place it
  13539. * in the scope hierarchy while maintaining the correct prototypical
  13540. * inheritance.
  13541. *
  13542. * @returns {Object} The newly created child scope.
  13543. *
  13544. */
  13545. $new: function(isolate, parent) {
  13546. var child;
  13547. parent = parent || this;
  13548. if (isolate) {
  13549. child = new Scope();
  13550. child.$root = this.$root;
  13551. } else {
  13552. // Only create a child scope class if somebody asks for one,
  13553. // but cache it to allow the VM to optimize lookups.
  13554. if (!this.$$ChildScope) {
  13555. this.$$ChildScope = createChildScopeClass(this);
  13556. }
  13557. child = new this.$$ChildScope();
  13558. }
  13559. child.$parent = parent;
  13560. child.$$prevSibling = parent.$$childTail;
  13561. if (parent.$$childHead) {
  13562. parent.$$childTail.$$nextSibling = child;
  13563. parent.$$childTail = child;
  13564. } else {
  13565. parent.$$childHead = parent.$$childTail = child;
  13566. }
  13567. // When the new scope is not isolated or we inherit from `this`, and
  13568. // the parent scope is destroyed, the property `$$destroyed` is inherited
  13569. // prototypically. In all other cases, this property needs to be set
  13570. // when the parent scope is destroyed.
  13571. // The listener needs to be added after the parent is set
  13572. if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
  13573. return child;
  13574. },
  13575. /**
  13576. * @ngdoc method
  13577. * @name $rootScope.Scope#$watch
  13578. * @kind function
  13579. *
  13580. * @description
  13581. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  13582. *
  13583. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  13584. * $digest()} and should return the value that will be watched. (Since
  13585. * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
  13586. * `watchExpression` can execute multiple times per
  13587. * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
  13588. * - The `listener` is called only when the value from the current `watchExpression` and the
  13589. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  13590. * see below). Inequality is determined according to reference inequality,
  13591. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  13592. * via the `!==` Javascript operator, unless `objectEquality == true`
  13593. * (see next point)
  13594. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  13595. * according to the {@link angular.equals} function. To save the value of the object for
  13596. * later comparison, the {@link angular.copy} function is used. This therefore means that
  13597. * watching complex objects will have adverse memory and performance implications.
  13598. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  13599. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  13600. * iteration limit is 10 to prevent an infinite loop deadlock.
  13601. *
  13602. *
  13603. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  13604. * you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
  13605. * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a
  13606. * change is detected, be prepared for multiple calls to your listener.)
  13607. *
  13608. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  13609. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  13610. * watcher. In rare cases, this is undesirable because the listener is called when the result
  13611. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  13612. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  13613. * listener was called due to initialization.
  13614. *
  13615. *
  13616. *
  13617. * # Example
  13618. * ```js
  13619. // let's assume that scope was dependency injected as the $rootScope
  13620. var scope = $rootScope;
  13621. scope.name = 'misko';
  13622. scope.counter = 0;
  13623. expect(scope.counter).toEqual(0);
  13624. scope.$watch('name', function(newValue, oldValue) {
  13625. scope.counter = scope.counter + 1;
  13626. });
  13627. expect(scope.counter).toEqual(0);
  13628. scope.$digest();
  13629. // the listener is always called during the first $digest loop after it was registered
  13630. expect(scope.counter).toEqual(1);
  13631. scope.$digest();
  13632. // but now it will not be called unless the value changes
  13633. expect(scope.counter).toEqual(1);
  13634. scope.name = 'adam';
  13635. scope.$digest();
  13636. expect(scope.counter).toEqual(2);
  13637. // Using a function as a watchExpression
  13638. var food;
  13639. scope.foodCounter = 0;
  13640. expect(scope.foodCounter).toEqual(0);
  13641. scope.$watch(
  13642. // This function returns the value being watched. It is called for each turn of the $digest loop
  13643. function() { return food; },
  13644. // This is the change listener, called when the value returned from the above function changes
  13645. function(newValue, oldValue) {
  13646. if ( newValue !== oldValue ) {
  13647. // Only increment the counter if the value changed
  13648. scope.foodCounter = scope.foodCounter + 1;
  13649. }
  13650. }
  13651. );
  13652. // No digest has been run so the counter will be zero
  13653. expect(scope.foodCounter).toEqual(0);
  13654. // Run the digest but since food has not changed count will still be zero
  13655. scope.$digest();
  13656. expect(scope.foodCounter).toEqual(0);
  13657. // Update food and run digest. Now the counter will increment
  13658. food = 'cheeseburger';
  13659. scope.$digest();
  13660. expect(scope.foodCounter).toEqual(1);
  13661. * ```
  13662. *
  13663. *
  13664. *
  13665. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  13666. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  13667. * a call to the `listener`.
  13668. *
  13669. * - `string`: Evaluated as {@link guide/expression expression}
  13670. * - `function(scope)`: called with current `scope` as a parameter.
  13671. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  13672. * of `watchExpression` changes.
  13673. *
  13674. * - `newVal` contains the current value of the `watchExpression`
  13675. * - `oldVal` contains the previous value of the `watchExpression`
  13676. * - `scope` refers to the current scope
  13677. * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
  13678. * comparing for reference equality.
  13679. * @returns {function()} Returns a deregistration function for this listener.
  13680. */
  13681. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  13682. var get = $parse(watchExp);
  13683. if (get.$$watchDelegate) {
  13684. return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
  13685. }
  13686. var scope = this,
  13687. array = scope.$$watchers,
  13688. watcher = {
  13689. fn: listener,
  13690. last: initWatchVal,
  13691. get: get,
  13692. exp: prettyPrintExpression || watchExp,
  13693. eq: !!objectEquality
  13694. };
  13695. lastDirtyWatch = null;
  13696. if (!isFunction(listener)) {
  13697. watcher.fn = noop;
  13698. }
  13699. if (!array) {
  13700. array = scope.$$watchers = [];
  13701. }
  13702. // we use unshift since we use a while loop in $digest for speed.
  13703. // the while loop reads in reverse order.
  13704. array.unshift(watcher);
  13705. incrementWatchersCount(this, 1);
  13706. return function deregisterWatch() {
  13707. if (arrayRemove(array, watcher) >= 0) {
  13708. incrementWatchersCount(scope, -1);
  13709. }
  13710. lastDirtyWatch = null;
  13711. };
  13712. },
  13713. /**
  13714. * @ngdoc method
  13715. * @name $rootScope.Scope#$watchGroup
  13716. * @kind function
  13717. *
  13718. * @description
  13719. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  13720. * If any one expression in the collection changes the `listener` is executed.
  13721. *
  13722. * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
  13723. * call to $digest() to see if any items changes.
  13724. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  13725. *
  13726. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  13727. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  13728. *
  13729. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  13730. * expression in `watchExpressions` changes
  13731. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  13732. * those of `watchExpression`
  13733. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  13734. * those of `watchExpression`
  13735. * The `scope` refers to the current scope.
  13736. * @returns {function()} Returns a de-registration function for all listeners.
  13737. */
  13738. $watchGroup: function(watchExpressions, listener) {
  13739. var oldValues = new Array(watchExpressions.length);
  13740. var newValues = new Array(watchExpressions.length);
  13741. var deregisterFns = [];
  13742. var self = this;
  13743. var changeReactionScheduled = false;
  13744. var firstRun = true;
  13745. if (!watchExpressions.length) {
  13746. // No expressions means we call the listener ASAP
  13747. var shouldCall = true;
  13748. self.$evalAsync(function() {
  13749. if (shouldCall) listener(newValues, newValues, self);
  13750. });
  13751. return function deregisterWatchGroup() {
  13752. shouldCall = false;
  13753. };
  13754. }
  13755. if (watchExpressions.length === 1) {
  13756. // Special case size of one
  13757. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  13758. newValues[0] = value;
  13759. oldValues[0] = oldValue;
  13760. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  13761. });
  13762. }
  13763. forEach(watchExpressions, function(expr, i) {
  13764. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  13765. newValues[i] = value;
  13766. oldValues[i] = oldValue;
  13767. if (!changeReactionScheduled) {
  13768. changeReactionScheduled = true;
  13769. self.$evalAsync(watchGroupAction);
  13770. }
  13771. });
  13772. deregisterFns.push(unwatchFn);
  13773. });
  13774. function watchGroupAction() {
  13775. changeReactionScheduled = false;
  13776. if (firstRun) {
  13777. firstRun = false;
  13778. listener(newValues, newValues, self);
  13779. } else {
  13780. listener(newValues, oldValues, self);
  13781. }
  13782. }
  13783. return function deregisterWatchGroup() {
  13784. while (deregisterFns.length) {
  13785. deregisterFns.shift()();
  13786. }
  13787. };
  13788. },
  13789. /**
  13790. * @ngdoc method
  13791. * @name $rootScope.Scope#$watchCollection
  13792. * @kind function
  13793. *
  13794. * @description
  13795. * Shallow watches the properties of an object and fires whenever any of the properties change
  13796. * (for arrays, this implies watching the array items; for object maps, this implies watching
  13797. * the properties). If a change is detected, the `listener` callback is fired.
  13798. *
  13799. * - The `obj` collection is observed via standard $watch operation and is examined on every
  13800. * call to $digest() to see if any items have been added, removed, or moved.
  13801. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  13802. * adding, removing, and moving items belonging to an object or array.
  13803. *
  13804. *
  13805. * # Example
  13806. * ```js
  13807. $scope.names = ['igor', 'matias', 'misko', 'james'];
  13808. $scope.dataCount = 4;
  13809. $scope.$watchCollection('names', function(newNames, oldNames) {
  13810. $scope.dataCount = newNames.length;
  13811. });
  13812. expect($scope.dataCount).toEqual(4);
  13813. $scope.$digest();
  13814. //still at 4 ... no changes
  13815. expect($scope.dataCount).toEqual(4);
  13816. $scope.names.pop();
  13817. $scope.$digest();
  13818. //now there's been a change
  13819. expect($scope.dataCount).toEqual(3);
  13820. * ```
  13821. *
  13822. *
  13823. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  13824. * expression value should evaluate to an object or an array which is observed on each
  13825. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  13826. * collection will trigger a call to the `listener`.
  13827. *
  13828. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  13829. * when a change is detected.
  13830. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  13831. * - The `oldCollection` object is a copy of the former collection data.
  13832. * Due to performance considerations, the`oldCollection` value is computed only if the
  13833. * `listener` function declares two or more arguments.
  13834. * - The `scope` argument refers to the current scope.
  13835. *
  13836. * @returns {function()} Returns a de-registration function for this listener. When the
  13837. * de-registration function is executed, the internal watch operation is terminated.
  13838. */
  13839. $watchCollection: function(obj, listener) {
  13840. $watchCollectionInterceptor.$stateful = true;
  13841. var self = this;
  13842. // the current value, updated on each dirty-check run
  13843. var newValue;
  13844. // a shallow copy of the newValue from the last dirty-check run,
  13845. // updated to match newValue during dirty-check run
  13846. var oldValue;
  13847. // a shallow copy of the newValue from when the last change happened
  13848. var veryOldValue;
  13849. // only track veryOldValue if the listener is asking for it
  13850. var trackVeryOldValue = (listener.length > 1);
  13851. var changeDetected = 0;
  13852. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  13853. var internalArray = [];
  13854. var internalObject = {};
  13855. var initRun = true;
  13856. var oldLength = 0;
  13857. function $watchCollectionInterceptor(_value) {
  13858. newValue = _value;
  13859. var newLength, key, bothNaN, newItem, oldItem;
  13860. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  13861. if (isUndefined(newValue)) return;
  13862. if (!isObject(newValue)) { // if primitive
  13863. if (oldValue !== newValue) {
  13864. oldValue = newValue;
  13865. changeDetected++;
  13866. }
  13867. } else if (isArrayLike(newValue)) {
  13868. if (oldValue !== internalArray) {
  13869. // we are transitioning from something which was not an array into array.
  13870. oldValue = internalArray;
  13871. oldLength = oldValue.length = 0;
  13872. changeDetected++;
  13873. }
  13874. newLength = newValue.length;
  13875. if (oldLength !== newLength) {
  13876. // if lengths do not match we need to trigger change notification
  13877. changeDetected++;
  13878. oldValue.length = oldLength = newLength;
  13879. }
  13880. // copy the items to oldValue and look for changes.
  13881. for (var i = 0; i < newLength; i++) {
  13882. oldItem = oldValue[i];
  13883. newItem = newValue[i];
  13884. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  13885. if (!bothNaN && (oldItem !== newItem)) {
  13886. changeDetected++;
  13887. oldValue[i] = newItem;
  13888. }
  13889. }
  13890. } else {
  13891. if (oldValue !== internalObject) {
  13892. // we are transitioning from something which was not an object into object.
  13893. oldValue = internalObject = {};
  13894. oldLength = 0;
  13895. changeDetected++;
  13896. }
  13897. // copy the items to oldValue and look for changes.
  13898. newLength = 0;
  13899. for (key in newValue) {
  13900. if (newValue.hasOwnProperty(key)) {
  13901. newLength++;
  13902. newItem = newValue[key];
  13903. oldItem = oldValue[key];
  13904. if (key in oldValue) {
  13905. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  13906. if (!bothNaN && (oldItem !== newItem)) {
  13907. changeDetected++;
  13908. oldValue[key] = newItem;
  13909. }
  13910. } else {
  13911. oldLength++;
  13912. oldValue[key] = newItem;
  13913. changeDetected++;
  13914. }
  13915. }
  13916. }
  13917. if (oldLength > newLength) {
  13918. // we used to have more keys, need to find them and destroy them.
  13919. changeDetected++;
  13920. for (key in oldValue) {
  13921. if (!newValue.hasOwnProperty(key)) {
  13922. oldLength--;
  13923. delete oldValue[key];
  13924. }
  13925. }
  13926. }
  13927. }
  13928. return changeDetected;
  13929. }
  13930. function $watchCollectionAction() {
  13931. if (initRun) {
  13932. initRun = false;
  13933. listener(newValue, newValue, self);
  13934. } else {
  13935. listener(newValue, veryOldValue, self);
  13936. }
  13937. // make a copy for the next time a collection is changed
  13938. if (trackVeryOldValue) {
  13939. if (!isObject(newValue)) {
  13940. //primitive
  13941. veryOldValue = newValue;
  13942. } else if (isArrayLike(newValue)) {
  13943. veryOldValue = new Array(newValue.length);
  13944. for (var i = 0; i < newValue.length; i++) {
  13945. veryOldValue[i] = newValue[i];
  13946. }
  13947. } else { // if object
  13948. veryOldValue = {};
  13949. for (var key in newValue) {
  13950. if (hasOwnProperty.call(newValue, key)) {
  13951. veryOldValue[key] = newValue[key];
  13952. }
  13953. }
  13954. }
  13955. }
  13956. }
  13957. return this.$watch(changeDetector, $watchCollectionAction);
  13958. },
  13959. /**
  13960. * @ngdoc method
  13961. * @name $rootScope.Scope#$digest
  13962. * @kind function
  13963. *
  13964. * @description
  13965. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  13966. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  13967. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  13968. * until no more listeners are firing. This means that it is possible to get into an infinite
  13969. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  13970. * iterations exceeds 10.
  13971. *
  13972. * Usually, you don't call `$digest()` directly in
  13973. * {@link ng.directive:ngController controllers} or in
  13974. * {@link ng.$compileProvider#directive directives}.
  13975. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  13976. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  13977. *
  13978. * If you want to be notified whenever `$digest()` is called,
  13979. * you can register a `watchExpression` function with
  13980. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  13981. *
  13982. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  13983. *
  13984. * # Example
  13985. * ```js
  13986. var scope = ...;
  13987. scope.name = 'misko';
  13988. scope.counter = 0;
  13989. expect(scope.counter).toEqual(0);
  13990. scope.$watch('name', function(newValue, oldValue) {
  13991. scope.counter = scope.counter + 1;
  13992. });
  13993. expect(scope.counter).toEqual(0);
  13994. scope.$digest();
  13995. // the listener is always called during the first $digest loop after it was registered
  13996. expect(scope.counter).toEqual(1);
  13997. scope.$digest();
  13998. // but now it will not be called unless the value changes
  13999. expect(scope.counter).toEqual(1);
  14000. scope.name = 'adam';
  14001. scope.$digest();
  14002. expect(scope.counter).toEqual(2);
  14003. * ```
  14004. *
  14005. */
  14006. $digest: function() {
  14007. var watch, value, last,
  14008. watchers,
  14009. length,
  14010. dirty, ttl = TTL,
  14011. next, current, target = this,
  14012. watchLog = [],
  14013. logIdx, logMsg, asyncTask;
  14014. beginPhase('$digest');
  14015. // Check for changes to browser url that happened in sync before the call to $digest
  14016. $browser.$$checkUrlChange();
  14017. if (this === $rootScope && applyAsyncId !== null) {
  14018. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  14019. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  14020. $browser.defer.cancel(applyAsyncId);
  14021. flushApplyAsync();
  14022. }
  14023. lastDirtyWatch = null;
  14024. do { // "while dirty" loop
  14025. dirty = false;
  14026. current = target;
  14027. while (asyncQueue.length) {
  14028. try {
  14029. asyncTask = asyncQueue.shift();
  14030. asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
  14031. } catch (e) {
  14032. $exceptionHandler(e);
  14033. }
  14034. lastDirtyWatch = null;
  14035. }
  14036. traverseScopesLoop:
  14037. do { // "traverse the scopes" loop
  14038. if ((watchers = current.$$watchers)) {
  14039. // process our watches
  14040. length = watchers.length;
  14041. while (length--) {
  14042. try {
  14043. watch = watchers[length];
  14044. // Most common watches are on primitives, in which case we can short
  14045. // circuit it with === operator, only when === fails do we use .equals
  14046. if (watch) {
  14047. if ((value = watch.get(current)) !== (last = watch.last) &&
  14048. !(watch.eq
  14049. ? equals(value, last)
  14050. : (typeof value === 'number' && typeof last === 'number'
  14051. && isNaN(value) && isNaN(last)))) {
  14052. dirty = true;
  14053. lastDirtyWatch = watch;
  14054. watch.last = watch.eq ? copy(value, null) : value;
  14055. watch.fn(value, ((last === initWatchVal) ? value : last), current);
  14056. if (ttl < 5) {
  14057. logIdx = 4 - ttl;
  14058. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  14059. watchLog[logIdx].push({
  14060. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  14061. newVal: value,
  14062. oldVal: last
  14063. });
  14064. }
  14065. } else if (watch === lastDirtyWatch) {
  14066. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  14067. // have already been tested.
  14068. dirty = false;
  14069. break traverseScopesLoop;
  14070. }
  14071. }
  14072. } catch (e) {
  14073. $exceptionHandler(e);
  14074. }
  14075. }
  14076. }
  14077. // Insanity Warning: scope depth-first traversal
  14078. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  14079. // this piece should be kept in sync with the traversal in $broadcast
  14080. if (!(next = ((current.$$watchersCount && current.$$childHead) ||
  14081. (current !== target && current.$$nextSibling)))) {
  14082. while (current !== target && !(next = current.$$nextSibling)) {
  14083. current = current.$parent;
  14084. }
  14085. }
  14086. } while ((current = next));
  14087. // `break traverseScopesLoop;` takes us to here
  14088. if ((dirty || asyncQueue.length) && !(ttl--)) {
  14089. clearPhase();
  14090. throw $rootScopeMinErr('infdig',
  14091. '{0} $digest() iterations reached. Aborting!\n' +
  14092. 'Watchers fired in the last 5 iterations: {1}',
  14093. TTL, watchLog);
  14094. }
  14095. } while (dirty || asyncQueue.length);
  14096. clearPhase();
  14097. while (postDigestQueue.length) {
  14098. try {
  14099. postDigestQueue.shift()();
  14100. } catch (e) {
  14101. $exceptionHandler(e);
  14102. }
  14103. }
  14104. },
  14105. /**
  14106. * @ngdoc event
  14107. * @name $rootScope.Scope#$destroy
  14108. * @eventType broadcast on scope being destroyed
  14109. *
  14110. * @description
  14111. * Broadcasted when a scope and its children are being destroyed.
  14112. *
  14113. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  14114. * clean up DOM bindings before an element is removed from the DOM.
  14115. */
  14116. /**
  14117. * @ngdoc method
  14118. * @name $rootScope.Scope#$destroy
  14119. * @kind function
  14120. *
  14121. * @description
  14122. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  14123. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  14124. * propagate to the current scope and its children. Removal also implies that the current
  14125. * scope is eligible for garbage collection.
  14126. *
  14127. * The `$destroy()` is usually used by directives such as
  14128. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  14129. * unrolling of the loop.
  14130. *
  14131. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  14132. * Application code can register a `$destroy` event handler that will give it a chance to
  14133. * perform any necessary cleanup.
  14134. *
  14135. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  14136. * clean up DOM bindings before an element is removed from the DOM.
  14137. */
  14138. $destroy: function() {
  14139. // We can't destroy a scope that has been already destroyed.
  14140. if (this.$$destroyed) return;
  14141. var parent = this.$parent;
  14142. this.$broadcast('$destroy');
  14143. this.$$destroyed = true;
  14144. if (this === $rootScope) {
  14145. //Remove handlers attached to window when $rootScope is removed
  14146. $browser.$$applicationDestroyed();
  14147. }
  14148. incrementWatchersCount(this, -this.$$watchersCount);
  14149. for (var eventName in this.$$listenerCount) {
  14150. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  14151. }
  14152. // sever all the references to parent scopes (after this cleanup, the current scope should
  14153. // not be retained by any of our references and should be eligible for garbage collection)
  14154. if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  14155. if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  14156. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  14157. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  14158. // Disable listeners, watchers and apply/digest methods
  14159. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  14160. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  14161. this.$$listeners = {};
  14162. // All of the code below is bogus code that works around V8's memory leak via optimized code
  14163. // and inline caches.
  14164. //
  14165. // see:
  14166. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  14167. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  14168. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  14169. this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
  14170. this.$$childTail = this.$root = this.$$watchers = null;
  14171. },
  14172. /**
  14173. * @ngdoc method
  14174. * @name $rootScope.Scope#$eval
  14175. * @kind function
  14176. *
  14177. * @description
  14178. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  14179. * the expression are propagated (uncaught). This is useful when evaluating Angular
  14180. * expressions.
  14181. *
  14182. * # Example
  14183. * ```js
  14184. var scope = ng.$rootScope.Scope();
  14185. scope.a = 1;
  14186. scope.b = 2;
  14187. expect(scope.$eval('a+b')).toEqual(3);
  14188. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  14189. * ```
  14190. *
  14191. * @param {(string|function())=} expression An angular expression to be executed.
  14192. *
  14193. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14194. * - `function(scope)`: execute the function with the current `scope` parameter.
  14195. *
  14196. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  14197. * @returns {*} The result of evaluating the expression.
  14198. */
  14199. $eval: function(expr, locals) {
  14200. return $parse(expr)(this, locals);
  14201. },
  14202. /**
  14203. * @ngdoc method
  14204. * @name $rootScope.Scope#$evalAsync
  14205. * @kind function
  14206. *
  14207. * @description
  14208. * Executes the expression on the current scope at a later point in time.
  14209. *
  14210. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  14211. * that:
  14212. *
  14213. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  14214. * rendering).
  14215. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  14216. * `expression` execution.
  14217. *
  14218. * Any exceptions from the execution of the expression are forwarded to the
  14219. * {@link ng.$exceptionHandler $exceptionHandler} service.
  14220. *
  14221. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  14222. * will be scheduled. However, it is encouraged to always call code that changes the model
  14223. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  14224. *
  14225. * @param {(string|function())=} expression An angular expression to be executed.
  14226. *
  14227. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14228. * - `function(scope)`: execute the function with the current `scope` parameter.
  14229. *
  14230. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  14231. */
  14232. $evalAsync: function(expr, locals) {
  14233. // if we are outside of an $digest loop and this is the first time we are scheduling async
  14234. // task also schedule async auto-flush
  14235. if (!$rootScope.$$phase && !asyncQueue.length) {
  14236. $browser.defer(function() {
  14237. if (asyncQueue.length) {
  14238. $rootScope.$digest();
  14239. }
  14240. });
  14241. }
  14242. asyncQueue.push({scope: this, expression: expr, locals: locals});
  14243. },
  14244. $$postDigest: function(fn) {
  14245. postDigestQueue.push(fn);
  14246. },
  14247. /**
  14248. * @ngdoc method
  14249. * @name $rootScope.Scope#$apply
  14250. * @kind function
  14251. *
  14252. * @description
  14253. * `$apply()` is used to execute an expression in angular from outside of the angular
  14254. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  14255. * Because we are calling into the angular framework we need to perform proper scope life
  14256. * cycle of {@link ng.$exceptionHandler exception handling},
  14257. * {@link ng.$rootScope.Scope#$digest executing watches}.
  14258. *
  14259. * ## Life cycle
  14260. *
  14261. * # Pseudo-Code of `$apply()`
  14262. * ```js
  14263. function $apply(expr) {
  14264. try {
  14265. return $eval(expr);
  14266. } catch (e) {
  14267. $exceptionHandler(e);
  14268. } finally {
  14269. $root.$digest();
  14270. }
  14271. }
  14272. * ```
  14273. *
  14274. *
  14275. * Scope's `$apply()` method transitions through the following stages:
  14276. *
  14277. * 1. The {@link guide/expression expression} is executed using the
  14278. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  14279. * 2. Any exceptions from the execution of the expression are forwarded to the
  14280. * {@link ng.$exceptionHandler $exceptionHandler} service.
  14281. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  14282. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  14283. *
  14284. *
  14285. * @param {(string|function())=} exp An angular expression to be executed.
  14286. *
  14287. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14288. * - `function(scope)`: execute the function with current `scope` parameter.
  14289. *
  14290. * @returns {*} The result of evaluating the expression.
  14291. */
  14292. $apply: function(expr) {
  14293. try {
  14294. beginPhase('$apply');
  14295. return this.$eval(expr);
  14296. } catch (e) {
  14297. $exceptionHandler(e);
  14298. } finally {
  14299. clearPhase();
  14300. try {
  14301. $rootScope.$digest();
  14302. } catch (e) {
  14303. $exceptionHandler(e);
  14304. throw e;
  14305. }
  14306. }
  14307. },
  14308. /**
  14309. * @ngdoc method
  14310. * @name $rootScope.Scope#$applyAsync
  14311. * @kind function
  14312. *
  14313. * @description
  14314. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  14315. * varies across browsers, but is typically around ~10 milliseconds.
  14316. *
  14317. * This can be used to queue up multiple expressions which need to be evaluated in the same
  14318. * digest.
  14319. *
  14320. * @param {(string|function())=} exp An angular expression to be executed.
  14321. *
  14322. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14323. * - `function(scope)`: execute the function with current `scope` parameter.
  14324. */
  14325. $applyAsync: function(expr) {
  14326. var scope = this;
  14327. expr && applyAsyncQueue.push($applyAsyncExpression);
  14328. scheduleApplyAsync();
  14329. function $applyAsyncExpression() {
  14330. scope.$eval(expr);
  14331. }
  14332. },
  14333. /**
  14334. * @ngdoc method
  14335. * @name $rootScope.Scope#$on
  14336. * @kind function
  14337. *
  14338. * @description
  14339. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  14340. * discussion of event life cycle.
  14341. *
  14342. * The event listener function format is: `function(event, args...)`. The `event` object
  14343. * passed into the listener has the following attributes:
  14344. *
  14345. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  14346. * `$broadcast`-ed.
  14347. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  14348. * event propagates through the scope hierarchy, this property is set to null.
  14349. * - `name` - `{string}`: name of the event.
  14350. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  14351. * further event propagation (available only for events that were `$emit`-ed).
  14352. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  14353. * to true.
  14354. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  14355. *
  14356. * @param {string} name Event name to listen on.
  14357. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  14358. * @returns {function()} Returns a deregistration function for this listener.
  14359. */
  14360. $on: function(name, listener) {
  14361. var namedListeners = this.$$listeners[name];
  14362. if (!namedListeners) {
  14363. this.$$listeners[name] = namedListeners = [];
  14364. }
  14365. namedListeners.push(listener);
  14366. var current = this;
  14367. do {
  14368. if (!current.$$listenerCount[name]) {
  14369. current.$$listenerCount[name] = 0;
  14370. }
  14371. current.$$listenerCount[name]++;
  14372. } while ((current = current.$parent));
  14373. var self = this;
  14374. return function() {
  14375. var indexOfListener = namedListeners.indexOf(listener);
  14376. if (indexOfListener !== -1) {
  14377. namedListeners[indexOfListener] = null;
  14378. decrementListenerCount(self, 1, name);
  14379. }
  14380. };
  14381. },
  14382. /**
  14383. * @ngdoc method
  14384. * @name $rootScope.Scope#$emit
  14385. * @kind function
  14386. *
  14387. * @description
  14388. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  14389. * registered {@link ng.$rootScope.Scope#$on} listeners.
  14390. *
  14391. * The event life cycle starts at the scope on which `$emit` was called. All
  14392. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  14393. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  14394. * registered listeners along the way. The event will stop propagating if one of the listeners
  14395. * cancels it.
  14396. *
  14397. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  14398. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  14399. *
  14400. * @param {string} name Event name to emit.
  14401. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  14402. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  14403. */
  14404. $emit: function(name, args) {
  14405. var empty = [],
  14406. namedListeners,
  14407. scope = this,
  14408. stopPropagation = false,
  14409. event = {
  14410. name: name,
  14411. targetScope: scope,
  14412. stopPropagation: function() {stopPropagation = true;},
  14413. preventDefault: function() {
  14414. event.defaultPrevented = true;
  14415. },
  14416. defaultPrevented: false
  14417. },
  14418. listenerArgs = concat([event], arguments, 1),
  14419. i, length;
  14420. do {
  14421. namedListeners = scope.$$listeners[name] || empty;
  14422. event.currentScope = scope;
  14423. for (i = 0, length = namedListeners.length; i < length; i++) {
  14424. // if listeners were deregistered, defragment the array
  14425. if (!namedListeners[i]) {
  14426. namedListeners.splice(i, 1);
  14427. i--;
  14428. length--;
  14429. continue;
  14430. }
  14431. try {
  14432. //allow all listeners attached to the current scope to run
  14433. namedListeners[i].apply(null, listenerArgs);
  14434. } catch (e) {
  14435. $exceptionHandler(e);
  14436. }
  14437. }
  14438. //if any listener on the current scope stops propagation, prevent bubbling
  14439. if (stopPropagation) {
  14440. event.currentScope = null;
  14441. return event;
  14442. }
  14443. //traverse upwards
  14444. scope = scope.$parent;
  14445. } while (scope);
  14446. event.currentScope = null;
  14447. return event;
  14448. },
  14449. /**
  14450. * @ngdoc method
  14451. * @name $rootScope.Scope#$broadcast
  14452. * @kind function
  14453. *
  14454. * @description
  14455. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  14456. * registered {@link ng.$rootScope.Scope#$on} listeners.
  14457. *
  14458. * The event life cycle starts at the scope on which `$broadcast` was called. All
  14459. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  14460. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  14461. * scope and calls all registered listeners along the way. The event cannot be canceled.
  14462. *
  14463. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  14464. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  14465. *
  14466. * @param {string} name Event name to broadcast.
  14467. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  14468. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  14469. */
  14470. $broadcast: function(name, args) {
  14471. var target = this,
  14472. current = target,
  14473. next = target,
  14474. event = {
  14475. name: name,
  14476. targetScope: target,
  14477. preventDefault: function() {
  14478. event.defaultPrevented = true;
  14479. },
  14480. defaultPrevented: false
  14481. };
  14482. if (!target.$$listenerCount[name]) return event;
  14483. var listenerArgs = concat([event], arguments, 1),
  14484. listeners, i, length;
  14485. //down while you can, then up and next sibling or up and next sibling until back at root
  14486. while ((current = next)) {
  14487. event.currentScope = current;
  14488. listeners = current.$$listeners[name] || [];
  14489. for (i = 0, length = listeners.length; i < length; i++) {
  14490. // if listeners were deregistered, defragment the array
  14491. if (!listeners[i]) {
  14492. listeners.splice(i, 1);
  14493. i--;
  14494. length--;
  14495. continue;
  14496. }
  14497. try {
  14498. listeners[i].apply(null, listenerArgs);
  14499. } catch (e) {
  14500. $exceptionHandler(e);
  14501. }
  14502. }
  14503. // Insanity Warning: scope depth-first traversal
  14504. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  14505. // this piece should be kept in sync with the traversal in $digest
  14506. // (though it differs due to having the extra check for $$listenerCount)
  14507. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  14508. (current !== target && current.$$nextSibling)))) {
  14509. while (current !== target && !(next = current.$$nextSibling)) {
  14510. current = current.$parent;
  14511. }
  14512. }
  14513. }
  14514. event.currentScope = null;
  14515. return event;
  14516. }
  14517. };
  14518. var $rootScope = new Scope();
  14519. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  14520. var asyncQueue = $rootScope.$$asyncQueue = [];
  14521. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  14522. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  14523. return $rootScope;
  14524. function beginPhase(phase) {
  14525. if ($rootScope.$$phase) {
  14526. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  14527. }
  14528. $rootScope.$$phase = phase;
  14529. }
  14530. function clearPhase() {
  14531. $rootScope.$$phase = null;
  14532. }
  14533. function incrementWatchersCount(current, count) {
  14534. do {
  14535. current.$$watchersCount += count;
  14536. } while ((current = current.$parent));
  14537. }
  14538. function decrementListenerCount(current, count, name) {
  14539. do {
  14540. current.$$listenerCount[name] -= count;
  14541. if (current.$$listenerCount[name] === 0) {
  14542. delete current.$$listenerCount[name];
  14543. }
  14544. } while ((current = current.$parent));
  14545. }
  14546. /**
  14547. * function used as an initial value for watchers.
  14548. * because it's unique we can easily tell it apart from other values
  14549. */
  14550. function initWatchVal() {}
  14551. function flushApplyAsync() {
  14552. while (applyAsyncQueue.length) {
  14553. try {
  14554. applyAsyncQueue.shift()();
  14555. } catch (e) {
  14556. $exceptionHandler(e);
  14557. }
  14558. }
  14559. applyAsyncId = null;
  14560. }
  14561. function scheduleApplyAsync() {
  14562. if (applyAsyncId === null) {
  14563. applyAsyncId = $browser.defer(function() {
  14564. $rootScope.$apply(flushApplyAsync);
  14565. });
  14566. }
  14567. }
  14568. }];
  14569. }
  14570. /**
  14571. * @description
  14572. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  14573. */
  14574. function $$SanitizeUriProvider() {
  14575. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  14576. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  14577. /**
  14578. * @description
  14579. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  14580. * urls during a[href] sanitization.
  14581. *
  14582. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  14583. *
  14584. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  14585. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  14586. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  14587. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  14588. *
  14589. * @param {RegExp=} regexp New regexp to whitelist urls with.
  14590. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  14591. * chaining otherwise.
  14592. */
  14593. this.aHrefSanitizationWhitelist = function(regexp) {
  14594. if (isDefined(regexp)) {
  14595. aHrefSanitizationWhitelist = regexp;
  14596. return this;
  14597. }
  14598. return aHrefSanitizationWhitelist;
  14599. };
  14600. /**
  14601. * @description
  14602. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  14603. * urls during img[src] sanitization.
  14604. *
  14605. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  14606. *
  14607. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  14608. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  14609. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  14610. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  14611. *
  14612. * @param {RegExp=} regexp New regexp to whitelist urls with.
  14613. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  14614. * chaining otherwise.
  14615. */
  14616. this.imgSrcSanitizationWhitelist = function(regexp) {
  14617. if (isDefined(regexp)) {
  14618. imgSrcSanitizationWhitelist = regexp;
  14619. return this;
  14620. }
  14621. return imgSrcSanitizationWhitelist;
  14622. };
  14623. this.$get = function() {
  14624. return function sanitizeUri(uri, isImage) {
  14625. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  14626. var normalizedVal;
  14627. normalizedVal = urlResolve(uri).href;
  14628. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  14629. return 'unsafe:' + normalizedVal;
  14630. }
  14631. return uri;
  14632. };
  14633. };
  14634. }
  14635. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  14636. * Any commits to this file should be reviewed with security in mind. *
  14637. * Changes to this file can potentially create security vulnerabilities. *
  14638. * An approval from 2 Core members with history of modifying *
  14639. * this file is required. *
  14640. * *
  14641. * Does the change somehow allow for arbitrary javascript to be executed? *
  14642. * Or allows for someone to change the prototype of built-in objects? *
  14643. * Or gives undesired access to variables likes document or window? *
  14644. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  14645. var $sceMinErr = minErr('$sce');
  14646. var SCE_CONTEXTS = {
  14647. HTML: 'html',
  14648. CSS: 'css',
  14649. URL: 'url',
  14650. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  14651. // url. (e.g. ng-include, script src, templateUrl)
  14652. RESOURCE_URL: 'resourceUrl',
  14653. JS: 'js'
  14654. };
  14655. // Helper functions follow.
  14656. function adjustMatcher(matcher) {
  14657. if (matcher === 'self') {
  14658. return matcher;
  14659. } else if (isString(matcher)) {
  14660. // Strings match exactly except for 2 wildcards - '*' and '**'.
  14661. // '*' matches any character except those from the set ':/.?&'.
  14662. // '**' matches any character (like .* in a RegExp).
  14663. // More than 2 *'s raises an error as it's ill defined.
  14664. if (matcher.indexOf('***') > -1) {
  14665. throw $sceMinErr('iwcard',
  14666. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  14667. }
  14668. matcher = escapeForRegexp(matcher).
  14669. replace('\\*\\*', '.*').
  14670. replace('\\*', '[^:/.?&;]*');
  14671. return new RegExp('^' + matcher + '$');
  14672. } else if (isRegExp(matcher)) {
  14673. // The only other type of matcher allowed is a Regexp.
  14674. // Match entire URL / disallow partial matches.
  14675. // Flags are reset (i.e. no global, ignoreCase or multiline)
  14676. return new RegExp('^' + matcher.source + '$');
  14677. } else {
  14678. throw $sceMinErr('imatcher',
  14679. 'Matchers may only be "self", string patterns or RegExp objects');
  14680. }
  14681. }
  14682. function adjustMatchers(matchers) {
  14683. var adjustedMatchers = [];
  14684. if (isDefined(matchers)) {
  14685. forEach(matchers, function(matcher) {
  14686. adjustedMatchers.push(adjustMatcher(matcher));
  14687. });
  14688. }
  14689. return adjustedMatchers;
  14690. }
  14691. /**
  14692. * @ngdoc service
  14693. * @name $sceDelegate
  14694. * @kind function
  14695. *
  14696. * @description
  14697. *
  14698. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  14699. * Contextual Escaping (SCE)} services to AngularJS.
  14700. *
  14701. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  14702. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  14703. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  14704. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  14705. * work because `$sce` delegates to `$sceDelegate` for these operations.
  14706. *
  14707. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  14708. *
  14709. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  14710. * can override it completely to change the behavior of `$sce`, the common case would
  14711. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  14712. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  14713. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  14714. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  14715. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  14716. */
  14717. /**
  14718. * @ngdoc provider
  14719. * @name $sceDelegateProvider
  14720. * @description
  14721. *
  14722. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  14723. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  14724. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  14725. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  14726. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  14727. *
  14728. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  14729. * Strict Contextual Escaping (SCE)}.
  14730. *
  14731. * **Example**: Consider the following case. <a name="example"></a>
  14732. *
  14733. * - your app is hosted at url `http://myapp.example.com/`
  14734. * - but some of your templates are hosted on other domains you control such as
  14735. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  14736. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  14737. *
  14738. * Here is what a secure configuration for this scenario might look like:
  14739. *
  14740. * ```
  14741. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  14742. * $sceDelegateProvider.resourceUrlWhitelist([
  14743. * // Allow same origin resource loads.
  14744. * 'self',
  14745. * // Allow loading from our assets domain. Notice the difference between * and **.
  14746. * 'http://srv*.assets.example.com/**'
  14747. * ]);
  14748. *
  14749. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  14750. * $sceDelegateProvider.resourceUrlBlacklist([
  14751. * 'http://myapp.example.com/clickThru**'
  14752. * ]);
  14753. * });
  14754. * ```
  14755. */
  14756. function $SceDelegateProvider() {
  14757. this.SCE_CONTEXTS = SCE_CONTEXTS;
  14758. // Resource URLs can also be trusted by policy.
  14759. var resourceUrlWhitelist = ['self'],
  14760. resourceUrlBlacklist = [];
  14761. /**
  14762. * @ngdoc method
  14763. * @name $sceDelegateProvider#resourceUrlWhitelist
  14764. * @kind function
  14765. *
  14766. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  14767. * provided. This must be an array or null. A snapshot of this array is used so further
  14768. * changes to the array are ignored.
  14769. *
  14770. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  14771. * allowed in this array.
  14772. *
  14773. * Note: **an empty whitelist array will block all URLs**!
  14774. *
  14775. * @return {Array} the currently set whitelist array.
  14776. *
  14777. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  14778. * same origin resource requests.
  14779. *
  14780. * @description
  14781. * Sets/Gets the whitelist of trusted resource URLs.
  14782. */
  14783. this.resourceUrlWhitelist = function(value) {
  14784. if (arguments.length) {
  14785. resourceUrlWhitelist = adjustMatchers(value);
  14786. }
  14787. return resourceUrlWhitelist;
  14788. };
  14789. /**
  14790. * @ngdoc method
  14791. * @name $sceDelegateProvider#resourceUrlBlacklist
  14792. * @kind function
  14793. *
  14794. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  14795. * provided. This must be an array or null. A snapshot of this array is used so further
  14796. * changes to the array are ignored.
  14797. *
  14798. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  14799. * allowed in this array.
  14800. *
  14801. * The typical usage for the blacklist is to **block
  14802. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  14803. * these would otherwise be trusted but actually return content from the redirected domain.
  14804. *
  14805. * Finally, **the blacklist overrides the whitelist** and has the final say.
  14806. *
  14807. * @return {Array} the currently set blacklist array.
  14808. *
  14809. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  14810. * is no blacklist.)
  14811. *
  14812. * @description
  14813. * Sets/Gets the blacklist of trusted resource URLs.
  14814. */
  14815. this.resourceUrlBlacklist = function(value) {
  14816. if (arguments.length) {
  14817. resourceUrlBlacklist = adjustMatchers(value);
  14818. }
  14819. return resourceUrlBlacklist;
  14820. };
  14821. this.$get = ['$injector', function($injector) {
  14822. var htmlSanitizer = function htmlSanitizer(html) {
  14823. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  14824. };
  14825. if ($injector.has('$sanitize')) {
  14826. htmlSanitizer = $injector.get('$sanitize');
  14827. }
  14828. function matchUrl(matcher, parsedUrl) {
  14829. if (matcher === 'self') {
  14830. return urlIsSameOrigin(parsedUrl);
  14831. } else {
  14832. // definitely a regex. See adjustMatchers()
  14833. return !!matcher.exec(parsedUrl.href);
  14834. }
  14835. }
  14836. function isResourceUrlAllowedByPolicy(url) {
  14837. var parsedUrl = urlResolve(url.toString());
  14838. var i, n, allowed = false;
  14839. // Ensure that at least one item from the whitelist allows this url.
  14840. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  14841. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  14842. allowed = true;
  14843. break;
  14844. }
  14845. }
  14846. if (allowed) {
  14847. // Ensure that no item from the blacklist blocked this url.
  14848. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  14849. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  14850. allowed = false;
  14851. break;
  14852. }
  14853. }
  14854. }
  14855. return allowed;
  14856. }
  14857. function generateHolderType(Base) {
  14858. var holderType = function TrustedValueHolderType(trustedValue) {
  14859. this.$$unwrapTrustedValue = function() {
  14860. return trustedValue;
  14861. };
  14862. };
  14863. if (Base) {
  14864. holderType.prototype = new Base();
  14865. }
  14866. holderType.prototype.valueOf = function sceValueOf() {
  14867. return this.$$unwrapTrustedValue();
  14868. };
  14869. holderType.prototype.toString = function sceToString() {
  14870. return this.$$unwrapTrustedValue().toString();
  14871. };
  14872. return holderType;
  14873. }
  14874. var trustedValueHolderBase = generateHolderType(),
  14875. byType = {};
  14876. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  14877. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  14878. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  14879. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  14880. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  14881. /**
  14882. * @ngdoc method
  14883. * @name $sceDelegate#trustAs
  14884. *
  14885. * @description
  14886. * Returns an object that is trusted by angular for use in specified strict
  14887. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  14888. * attribute interpolation, any dom event binding attribute interpolation
  14889. * such as for onclick, etc.) that uses the provided value.
  14890. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  14891. *
  14892. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  14893. * resourceUrl, html, js and css.
  14894. * @param {*} value The value that that should be considered trusted/safe.
  14895. * @returns {*} A value that can be used to stand in for the provided `value` in places
  14896. * where Angular expects a $sce.trustAs() return value.
  14897. */
  14898. function trustAs(type, trustedValue) {
  14899. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  14900. if (!Constructor) {
  14901. throw $sceMinErr('icontext',
  14902. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  14903. type, trustedValue);
  14904. }
  14905. if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
  14906. return trustedValue;
  14907. }
  14908. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  14909. // mutable objects, we ensure here that the value passed in is actually a string.
  14910. if (typeof trustedValue !== 'string') {
  14911. throw $sceMinErr('itype',
  14912. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  14913. type);
  14914. }
  14915. return new Constructor(trustedValue);
  14916. }
  14917. /**
  14918. * @ngdoc method
  14919. * @name $sceDelegate#valueOf
  14920. *
  14921. * @description
  14922. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  14923. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  14924. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  14925. *
  14926. * If the passed parameter is not a value that had been returned by {@link
  14927. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  14928. *
  14929. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  14930. * call or anything else.
  14931. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  14932. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  14933. * `value` unchanged.
  14934. */
  14935. function valueOf(maybeTrusted) {
  14936. if (maybeTrusted instanceof trustedValueHolderBase) {
  14937. return maybeTrusted.$$unwrapTrustedValue();
  14938. } else {
  14939. return maybeTrusted;
  14940. }
  14941. }
  14942. /**
  14943. * @ngdoc method
  14944. * @name $sceDelegate#getTrusted
  14945. *
  14946. * @description
  14947. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  14948. * returns the originally supplied value if the queried context type is a supertype of the
  14949. * created type. If this condition isn't satisfied, throws an exception.
  14950. *
  14951. * @param {string} type The kind of context in which this value is to be used.
  14952. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  14953. * `$sceDelegate.trustAs`} call.
  14954. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  14955. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  14956. */
  14957. function getTrusted(type, maybeTrusted) {
  14958. if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
  14959. return maybeTrusted;
  14960. }
  14961. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  14962. if (constructor && maybeTrusted instanceof constructor) {
  14963. return maybeTrusted.$$unwrapTrustedValue();
  14964. }
  14965. // If we get here, then we may only take one of two actions.
  14966. // 1. sanitize the value for the requested type, or
  14967. // 2. throw an exception.
  14968. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  14969. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  14970. return maybeTrusted;
  14971. } else {
  14972. throw $sceMinErr('insecurl',
  14973. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  14974. maybeTrusted.toString());
  14975. }
  14976. } else if (type === SCE_CONTEXTS.HTML) {
  14977. return htmlSanitizer(maybeTrusted);
  14978. }
  14979. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  14980. }
  14981. return { trustAs: trustAs,
  14982. getTrusted: getTrusted,
  14983. valueOf: valueOf };
  14984. }];
  14985. }
  14986. /**
  14987. * @ngdoc provider
  14988. * @name $sceProvider
  14989. * @description
  14990. *
  14991. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  14992. * - enable/disable Strict Contextual Escaping (SCE) in a module
  14993. * - override the default implementation with a custom delegate
  14994. *
  14995. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  14996. */
  14997. /* jshint maxlen: false*/
  14998. /**
  14999. * @ngdoc service
  15000. * @name $sce
  15001. * @kind function
  15002. *
  15003. * @description
  15004. *
  15005. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  15006. *
  15007. * # Strict Contextual Escaping
  15008. *
  15009. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  15010. * contexts to result in a value that is marked as safe to use for that context. One example of
  15011. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  15012. * to these contexts as privileged or SCE contexts.
  15013. *
  15014. * As of version 1.2, Angular ships with SCE enabled by default.
  15015. *
  15016. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  15017. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  15018. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  15019. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  15020. * to the top of your HTML document.
  15021. *
  15022. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  15023. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  15024. *
  15025. * Here's an example of a binding in a privileged context:
  15026. *
  15027. * ```
  15028. * <input ng-model="userHtml" aria-label="User input">
  15029. * <div ng-bind-html="userHtml"></div>
  15030. * ```
  15031. *
  15032. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  15033. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  15034. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  15035. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  15036. * security vulnerabilities.)
  15037. *
  15038. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  15039. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  15040. *
  15041. * How would you ensure that every place that used these types of bindings was bound to a value that
  15042. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  15043. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  15044. * properties/fields and forgot to update the binding to the sanitized value?
  15045. *
  15046. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  15047. * determine that something explicitly says it's safe to use a value for binding in that
  15048. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  15049. * for those values that you can easily tell are safe - because they were received from your server,
  15050. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  15051. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  15052. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  15053. *
  15054. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  15055. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  15056. * obtain values that will be accepted by SCE / privileged contexts.
  15057. *
  15058. *
  15059. * ## How does it work?
  15060. *
  15061. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  15062. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  15063. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  15064. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  15065. *
  15066. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  15067. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  15068. * simplified):
  15069. *
  15070. * ```
  15071. * var ngBindHtmlDirective = ['$sce', function($sce) {
  15072. * return function(scope, element, attr) {
  15073. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  15074. * element.html(value || '');
  15075. * });
  15076. * };
  15077. * }];
  15078. * ```
  15079. *
  15080. * ## Impact on loading templates
  15081. *
  15082. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  15083. * `templateUrl`'s specified by {@link guide/directive directives}.
  15084. *
  15085. * By default, Angular only loads templates from the same domain and protocol as the application
  15086. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  15087. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  15088. * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  15089. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  15090. *
  15091. * *Please note*:
  15092. * The browser's
  15093. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  15094. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  15095. * policy apply in addition to this and may further restrict whether the template is successfully
  15096. * loaded. This means that without the right CORS policy, loading templates from a different domain
  15097. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  15098. * browsers.
  15099. *
  15100. * ## This feels like too much overhead
  15101. *
  15102. * It's important to remember that SCE only applies to interpolation expressions.
  15103. *
  15104. * If your expressions are constant literals, they're automatically trusted and you don't need to
  15105. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  15106. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  15107. *
  15108. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  15109. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  15110. *
  15111. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  15112. * templates in `ng-include` from your application's domain without having to even know about SCE.
  15113. * It blocks loading templates from other domains or loading templates over http from an https
  15114. * served document. You can change these by setting your own custom {@link
  15115. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  15116. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  15117. *
  15118. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  15119. * application that's secure and can be audited to verify that with much more ease than bolting
  15120. * security onto an application later.
  15121. *
  15122. * <a name="contexts"></a>
  15123. * ## What trusted context types are supported?
  15124. *
  15125. * | Context | Notes |
  15126. * |---------------------|----------------|
  15127. * | `$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. |
  15128. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  15129. * | `$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. |
  15130. * | `$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. |
  15131. * | `$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. |
  15132. *
  15133. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  15134. *
  15135. * Each element in these arrays must be one of the following:
  15136. *
  15137. * - **'self'**
  15138. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  15139. * domain** as the application document using the **same protocol**.
  15140. * - **String** (except the special value `'self'`)
  15141. * - The string is matched against the full *normalized / absolute URL* of the resource
  15142. * being tested (substring matches are not good enough.)
  15143. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  15144. * match themselves.
  15145. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  15146. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use
  15147. * in a whitelist.
  15148. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  15149. * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g.
  15150. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  15151. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  15152. * http://foo.example.com/templates/**).
  15153. * - **RegExp** (*see caveat below*)
  15154. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  15155. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  15156. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  15157. * have good test coverage.). For instance, the use of `.` in the regex is correct only in a
  15158. * small number of cases. A `.` character in the regex used when matching the scheme or a
  15159. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  15160. * is highly recommended to use the string patterns and only fall back to regular expressions
  15161. * if they as a last resort.
  15162. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  15163. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  15164. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  15165. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  15166. * - If you are generating your JavaScript from some other templating engine (not
  15167. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  15168. * remember to escape your regular expression (and be aware that you might need more than
  15169. * one level of escaping depending on your templating engine and the way you interpolated
  15170. * the value.) Do make use of your platform's escaping mechanism as it might be good
  15171. * enough before coding your own. e.g. Ruby has
  15172. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  15173. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  15174. * Javascript lacks a similar built in function for escaping. Take a look at Google
  15175. * Closure library's [goog.string.regExpEscape(s)](
  15176. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  15177. *
  15178. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  15179. *
  15180. * ## Show me an example using SCE.
  15181. *
  15182. * <example module="mySceApp" deps="angular-sanitize.js">
  15183. * <file name="index.html">
  15184. * <div ng-controller="AppController as myCtrl">
  15185. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  15186. * <b>User comments</b><br>
  15187. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  15188. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  15189. * exploit.
  15190. * <div class="well">
  15191. * <div ng-repeat="userComment in myCtrl.userComments">
  15192. * <b>{{userComment.name}}</b>:
  15193. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  15194. * <br>
  15195. * </div>
  15196. * </div>
  15197. * </div>
  15198. * </file>
  15199. *
  15200. * <file name="script.js">
  15201. * angular.module('mySceApp', ['ngSanitize'])
  15202. * .controller('AppController', ['$http', '$templateCache', '$sce',
  15203. * function($http, $templateCache, $sce) {
  15204. * var self = this;
  15205. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  15206. * self.userComments = userComments;
  15207. * });
  15208. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  15209. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  15210. * 'sanitization.&quot;">Hover over this text.</span>');
  15211. * }]);
  15212. * </file>
  15213. *
  15214. * <file name="test_data.json">
  15215. * [
  15216. * { "name": "Alice",
  15217. * "htmlComment":
  15218. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  15219. * },
  15220. * { "name": "Bob",
  15221. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  15222. * }
  15223. * ]
  15224. * </file>
  15225. *
  15226. * <file name="protractor.js" type="protractor">
  15227. * describe('SCE doc demo', function() {
  15228. * it('should sanitize untrusted values', function() {
  15229. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  15230. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  15231. * });
  15232. *
  15233. * it('should NOT sanitize explicitly trusted values', function() {
  15234. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  15235. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  15236. * 'sanitization.&quot;">Hover over this text.</span>');
  15237. * });
  15238. * });
  15239. * </file>
  15240. * </example>
  15241. *
  15242. *
  15243. *
  15244. * ## Can I disable SCE completely?
  15245. *
  15246. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  15247. * for little coding overhead. It will be much harder to take an SCE disabled application and
  15248. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  15249. * for cases where you have a lot of existing code that was written before SCE was introduced and
  15250. * you're migrating them a module at a time.
  15251. *
  15252. * That said, here's how you can completely disable SCE:
  15253. *
  15254. * ```
  15255. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  15256. * // Completely disable SCE. For demonstration purposes only!
  15257. * // Do not use in new projects.
  15258. * $sceProvider.enabled(false);
  15259. * });
  15260. * ```
  15261. *
  15262. */
  15263. /* jshint maxlen: 100 */
  15264. function $SceProvider() {
  15265. var enabled = true;
  15266. /**
  15267. * @ngdoc method
  15268. * @name $sceProvider#enabled
  15269. * @kind function
  15270. *
  15271. * @param {boolean=} value If provided, then enables/disables SCE.
  15272. * @return {boolean} true if SCE is enabled, false otherwise.
  15273. *
  15274. * @description
  15275. * Enables/disables SCE and returns the current value.
  15276. */
  15277. this.enabled = function(value) {
  15278. if (arguments.length) {
  15279. enabled = !!value;
  15280. }
  15281. return enabled;
  15282. };
  15283. /* Design notes on the default implementation for SCE.
  15284. *
  15285. * The API contract for the SCE delegate
  15286. * -------------------------------------
  15287. * The SCE delegate object must provide the following 3 methods:
  15288. *
  15289. * - trustAs(contextEnum, value)
  15290. * This method is used to tell the SCE service that the provided value is OK to use in the
  15291. * contexts specified by contextEnum. It must return an object that will be accepted by
  15292. * getTrusted() for a compatible contextEnum and return this value.
  15293. *
  15294. * - valueOf(value)
  15295. * For values that were not produced by trustAs(), return them as is. For values that were
  15296. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  15297. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  15298. * such a value.
  15299. *
  15300. * - getTrusted(contextEnum, value)
  15301. * This function should return the a value that is safe to use in the context specified by
  15302. * contextEnum or throw and exception otherwise.
  15303. *
  15304. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  15305. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  15306. * instance, an implementation could maintain a registry of all trusted objects by context. In
  15307. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  15308. * return the same object passed in if it was found in the registry under a compatible context or
  15309. * throw an exception otherwise. An implementation might only wrap values some of the time based
  15310. * on some criteria. getTrusted() might return a value and not throw an exception for special
  15311. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  15312. *
  15313. *
  15314. * A note on the inheritance model for SCE contexts
  15315. * ------------------------------------------------
  15316. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  15317. * is purely an implementation details.
  15318. *
  15319. * The contract is simply this:
  15320. *
  15321. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  15322. * will also succeed.
  15323. *
  15324. * Inheritance happens to capture this in a natural way. In some future, we
  15325. * may not use inheritance anymore. That is OK because no code outside of
  15326. * sce.js and sceSpecs.js would need to be aware of this detail.
  15327. */
  15328. this.$get = ['$parse', '$sceDelegate', function(
  15329. $parse, $sceDelegate) {
  15330. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  15331. // the "expression(javascript expression)" syntax which is insecure.
  15332. if (enabled && msie < 8) {
  15333. throw $sceMinErr('iequirks',
  15334. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  15335. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  15336. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  15337. }
  15338. var sce = shallowCopy(SCE_CONTEXTS);
  15339. /**
  15340. * @ngdoc method
  15341. * @name $sce#isEnabled
  15342. * @kind function
  15343. *
  15344. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  15345. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  15346. *
  15347. * @description
  15348. * Returns a boolean indicating if SCE is enabled.
  15349. */
  15350. sce.isEnabled = function() {
  15351. return enabled;
  15352. };
  15353. sce.trustAs = $sceDelegate.trustAs;
  15354. sce.getTrusted = $sceDelegate.getTrusted;
  15355. sce.valueOf = $sceDelegate.valueOf;
  15356. if (!enabled) {
  15357. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  15358. sce.valueOf = identity;
  15359. }
  15360. /**
  15361. * @ngdoc method
  15362. * @name $sce#parseAs
  15363. *
  15364. * @description
  15365. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  15366. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  15367. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  15368. * *result*)}
  15369. *
  15370. * @param {string} type The kind of SCE context in which this result will be used.
  15371. * @param {string} expression String expression to compile.
  15372. * @returns {function(context, locals)} a function which represents the compiled expression:
  15373. *
  15374. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15375. * are evaluated against (typically a scope object).
  15376. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15377. * `context`.
  15378. */
  15379. sce.parseAs = function sceParseAs(type, expr) {
  15380. var parsed = $parse(expr);
  15381. if (parsed.literal && parsed.constant) {
  15382. return parsed;
  15383. } else {
  15384. return $parse(expr, function(value) {
  15385. return sce.getTrusted(type, value);
  15386. });
  15387. }
  15388. };
  15389. /**
  15390. * @ngdoc method
  15391. * @name $sce#trustAs
  15392. *
  15393. * @description
  15394. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  15395. * returns an object that is trusted by angular for use in specified strict contextual
  15396. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  15397. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  15398. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  15399. * escaping.
  15400. *
  15401. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  15402. * resourceUrl, html, js and css.
  15403. * @param {*} value The value that that should be considered trusted/safe.
  15404. * @returns {*} A value that can be used to stand in for the provided `value` in places
  15405. * where Angular expects a $sce.trustAs() return value.
  15406. */
  15407. /**
  15408. * @ngdoc method
  15409. * @name $sce#trustAsHtml
  15410. *
  15411. * @description
  15412. * Shorthand method. `$sce.trustAsHtml(value)` →
  15413. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  15414. *
  15415. * @param {*} value The value to trustAs.
  15416. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  15417. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  15418. * only accept expressions that are either literal constants or are the
  15419. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15420. */
  15421. /**
  15422. * @ngdoc method
  15423. * @name $sce#trustAsUrl
  15424. *
  15425. * @description
  15426. * Shorthand method. `$sce.trustAsUrl(value)` →
  15427. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  15428. *
  15429. * @param {*} value The value to trustAs.
  15430. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  15431. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  15432. * only accept expressions that are either literal constants or are the
  15433. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15434. */
  15435. /**
  15436. * @ngdoc method
  15437. * @name $sce#trustAsResourceUrl
  15438. *
  15439. * @description
  15440. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  15441. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  15442. *
  15443. * @param {*} value The value to trustAs.
  15444. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  15445. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  15446. * only accept expressions that are either literal constants or are the return
  15447. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15448. */
  15449. /**
  15450. * @ngdoc method
  15451. * @name $sce#trustAsJs
  15452. *
  15453. * @description
  15454. * Shorthand method. `$sce.trustAsJs(value)` →
  15455. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  15456. *
  15457. * @param {*} value The value to trustAs.
  15458. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  15459. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  15460. * only accept expressions that are either literal constants or are the
  15461. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15462. */
  15463. /**
  15464. * @ngdoc method
  15465. * @name $sce#getTrusted
  15466. *
  15467. * @description
  15468. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  15469. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  15470. * originally supplied value if the queried context type is a supertype of the created type.
  15471. * If this condition isn't satisfied, throws an exception.
  15472. *
  15473. * @param {string} type The kind of context in which this value is to be used.
  15474. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  15475. * call.
  15476. * @returns {*} The value the was originally provided to
  15477. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  15478. * Otherwise, throws an exception.
  15479. */
  15480. /**
  15481. * @ngdoc method
  15482. * @name $sce#getTrustedHtml
  15483. *
  15484. * @description
  15485. * Shorthand method. `$sce.getTrustedHtml(value)` →
  15486. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  15487. *
  15488. * @param {*} value The value to pass to `$sce.getTrusted`.
  15489. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  15490. */
  15491. /**
  15492. * @ngdoc method
  15493. * @name $sce#getTrustedCss
  15494. *
  15495. * @description
  15496. * Shorthand method. `$sce.getTrustedCss(value)` →
  15497. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  15498. *
  15499. * @param {*} value The value to pass to `$sce.getTrusted`.
  15500. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  15501. */
  15502. /**
  15503. * @ngdoc method
  15504. * @name $sce#getTrustedUrl
  15505. *
  15506. * @description
  15507. * Shorthand method. `$sce.getTrustedUrl(value)` →
  15508. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  15509. *
  15510. * @param {*} value The value to pass to `$sce.getTrusted`.
  15511. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  15512. */
  15513. /**
  15514. * @ngdoc method
  15515. * @name $sce#getTrustedResourceUrl
  15516. *
  15517. * @description
  15518. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  15519. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  15520. *
  15521. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  15522. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  15523. */
  15524. /**
  15525. * @ngdoc method
  15526. * @name $sce#getTrustedJs
  15527. *
  15528. * @description
  15529. * Shorthand method. `$sce.getTrustedJs(value)` →
  15530. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  15531. *
  15532. * @param {*} value The value to pass to `$sce.getTrusted`.
  15533. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  15534. */
  15535. /**
  15536. * @ngdoc method
  15537. * @name $sce#parseAsHtml
  15538. *
  15539. * @description
  15540. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  15541. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  15542. *
  15543. * @param {string} expression String expression to compile.
  15544. * @returns {function(context, locals)} a function which represents the compiled expression:
  15545. *
  15546. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15547. * are evaluated against (typically a scope object).
  15548. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15549. * `context`.
  15550. */
  15551. /**
  15552. * @ngdoc method
  15553. * @name $sce#parseAsCss
  15554. *
  15555. * @description
  15556. * Shorthand method. `$sce.parseAsCss(value)` →
  15557. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  15558. *
  15559. * @param {string} expression String expression to compile.
  15560. * @returns {function(context, locals)} a function which represents the compiled expression:
  15561. *
  15562. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15563. * are evaluated against (typically a scope object).
  15564. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15565. * `context`.
  15566. */
  15567. /**
  15568. * @ngdoc method
  15569. * @name $sce#parseAsUrl
  15570. *
  15571. * @description
  15572. * Shorthand method. `$sce.parseAsUrl(value)` →
  15573. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  15574. *
  15575. * @param {string} expression String expression to compile.
  15576. * @returns {function(context, locals)} a function which represents the compiled expression:
  15577. *
  15578. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15579. * are evaluated against (typically a scope object).
  15580. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15581. * `context`.
  15582. */
  15583. /**
  15584. * @ngdoc method
  15585. * @name $sce#parseAsResourceUrl
  15586. *
  15587. * @description
  15588. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  15589. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  15590. *
  15591. * @param {string} expression String expression to compile.
  15592. * @returns {function(context, locals)} a function which represents the compiled expression:
  15593. *
  15594. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15595. * are evaluated against (typically a scope object).
  15596. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15597. * `context`.
  15598. */
  15599. /**
  15600. * @ngdoc method
  15601. * @name $sce#parseAsJs
  15602. *
  15603. * @description
  15604. * Shorthand method. `$sce.parseAsJs(value)` →
  15605. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  15606. *
  15607. * @param {string} expression String expression to compile.
  15608. * @returns {function(context, locals)} a function which represents the compiled expression:
  15609. *
  15610. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15611. * are evaluated against (typically a scope object).
  15612. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15613. * `context`.
  15614. */
  15615. // Shorthand delegations.
  15616. var parse = sce.parseAs,
  15617. getTrusted = sce.getTrusted,
  15618. trustAs = sce.trustAs;
  15619. forEach(SCE_CONTEXTS, function(enumValue, name) {
  15620. var lName = lowercase(name);
  15621. sce[camelCase("parse_as_" + lName)] = function(expr) {
  15622. return parse(enumValue, expr);
  15623. };
  15624. sce[camelCase("get_trusted_" + lName)] = function(value) {
  15625. return getTrusted(enumValue, value);
  15626. };
  15627. sce[camelCase("trust_as_" + lName)] = function(value) {
  15628. return trustAs(enumValue, value);
  15629. };
  15630. });
  15631. return sce;
  15632. }];
  15633. }
  15634. /**
  15635. * !!! This is an undocumented "private" service !!!
  15636. *
  15637. * @name $sniffer
  15638. * @requires $window
  15639. * @requires $document
  15640. *
  15641. * @property {boolean} history Does the browser support html5 history api ?
  15642. * @property {boolean} transitions Does the browser support CSS transition events ?
  15643. * @property {boolean} animations Does the browser support CSS animation events ?
  15644. *
  15645. * @description
  15646. * This is very simple implementation of testing browser's features.
  15647. */
  15648. function $SnifferProvider() {
  15649. this.$get = ['$window', '$document', function($window, $document) {
  15650. var eventSupport = {},
  15651. android =
  15652. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  15653. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  15654. document = $document[0] || {},
  15655. vendorPrefix,
  15656. vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
  15657. bodyStyle = document.body && document.body.style,
  15658. transitions = false,
  15659. animations = false,
  15660. match;
  15661. if (bodyStyle) {
  15662. for (var prop in bodyStyle) {
  15663. if (match = vendorRegex.exec(prop)) {
  15664. vendorPrefix = match[0];
  15665. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  15666. break;
  15667. }
  15668. }
  15669. if (!vendorPrefix) {
  15670. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  15671. }
  15672. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  15673. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  15674. if (android && (!transitions || !animations)) {
  15675. transitions = isString(bodyStyle.webkitTransition);
  15676. animations = isString(bodyStyle.webkitAnimation);
  15677. }
  15678. }
  15679. return {
  15680. // Android has history.pushState, but it does not update location correctly
  15681. // so let's not use the history API at all.
  15682. // http://code.google.com/p/android/issues/detail?id=17471
  15683. // https://github.com/angular/angular.js/issues/904
  15684. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  15685. // so let's not use the history API also
  15686. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  15687. // jshint -W018
  15688. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  15689. // jshint +W018
  15690. hasEvent: function(event) {
  15691. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  15692. // it. In particular the event is not fired when backspace or delete key are pressed or
  15693. // when cut operation is performed.
  15694. // IE10+ implements 'input' event but it erroneously fires under various situations,
  15695. // e.g. when placeholder changes, or a form is focused.
  15696. if (event === 'input' && msie <= 11) return false;
  15697. if (isUndefined(eventSupport[event])) {
  15698. var divElm = document.createElement('div');
  15699. eventSupport[event] = 'on' + event in divElm;
  15700. }
  15701. return eventSupport[event];
  15702. },
  15703. csp: csp(),
  15704. vendorPrefix: vendorPrefix,
  15705. transitions: transitions,
  15706. animations: animations,
  15707. android: android
  15708. };
  15709. }];
  15710. }
  15711. var $compileMinErr = minErr('$compile');
  15712. /**
  15713. * @ngdoc service
  15714. * @name $templateRequest
  15715. *
  15716. * @description
  15717. * The `$templateRequest` service downloads the provided template using `$http` and, upon success,
  15718. * stores the contents inside of `$templateCache`. If the HTTP request fails or the response data
  15719. * of the HTTP request is empty, a `$compile` error will be thrown (the exception can be thwarted
  15720. * by setting the 2nd parameter of the function to true).
  15721. *
  15722. * @param {string} tpl The HTTP request template URL
  15723. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  15724. *
  15725. * @return {Promise} a promise for the HTTP response data of the given URL.
  15726. *
  15727. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  15728. */
  15729. function $TemplateRequestProvider() {
  15730. this.$get = ['$templateCache', '$http', '$q', function($templateCache, $http, $q) {
  15731. function handleRequestFn(tpl, ignoreRequestError) {
  15732. handleRequestFn.totalPendingRequests++;
  15733. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  15734. if (isArray(transformResponse)) {
  15735. transformResponse = transformResponse.filter(function(transformer) {
  15736. return transformer !== defaultHttpResponseTransform;
  15737. });
  15738. } else if (transformResponse === defaultHttpResponseTransform) {
  15739. transformResponse = null;
  15740. }
  15741. var httpOptions = {
  15742. cache: $templateCache,
  15743. transformResponse: transformResponse
  15744. };
  15745. return $http.get(tpl, httpOptions)
  15746. ['finally'](function() {
  15747. handleRequestFn.totalPendingRequests--;
  15748. })
  15749. .then(function(response) {
  15750. $templateCache.put(tpl, response.data);
  15751. return response.data;
  15752. }, handleError);
  15753. function handleError(resp) {
  15754. if (!ignoreRequestError) {
  15755. throw $compileMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
  15756. tpl, resp.status, resp.statusText);
  15757. }
  15758. return $q.reject(resp);
  15759. }
  15760. }
  15761. handleRequestFn.totalPendingRequests = 0;
  15762. return handleRequestFn;
  15763. }];
  15764. }
  15765. function $$TestabilityProvider() {
  15766. this.$get = ['$rootScope', '$browser', '$location',
  15767. function($rootScope, $browser, $location) {
  15768. /**
  15769. * @name $testability
  15770. *
  15771. * @description
  15772. * The private $$testability service provides a collection of methods for use when debugging
  15773. * or by automated test and debugging tools.
  15774. */
  15775. var testability = {};
  15776. /**
  15777. * @name $$testability#findBindings
  15778. *
  15779. * @description
  15780. * Returns an array of elements that are bound (via ng-bind or {{}})
  15781. * to expressions matching the input.
  15782. *
  15783. * @param {Element} element The element root to search from.
  15784. * @param {string} expression The binding expression to match.
  15785. * @param {boolean} opt_exactMatch If true, only returns exact matches
  15786. * for the expression. Filters and whitespace are ignored.
  15787. */
  15788. testability.findBindings = function(element, expression, opt_exactMatch) {
  15789. var bindings = element.getElementsByClassName('ng-binding');
  15790. var matches = [];
  15791. forEach(bindings, function(binding) {
  15792. var dataBinding = angular.element(binding).data('$binding');
  15793. if (dataBinding) {
  15794. forEach(dataBinding, function(bindingName) {
  15795. if (opt_exactMatch) {
  15796. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  15797. if (matcher.test(bindingName)) {
  15798. matches.push(binding);
  15799. }
  15800. } else {
  15801. if (bindingName.indexOf(expression) != -1) {
  15802. matches.push(binding);
  15803. }
  15804. }
  15805. });
  15806. }
  15807. });
  15808. return matches;
  15809. };
  15810. /**
  15811. * @name $$testability#findModels
  15812. *
  15813. * @description
  15814. * Returns an array of elements that are two-way found via ng-model to
  15815. * expressions matching the input.
  15816. *
  15817. * @param {Element} element The element root to search from.
  15818. * @param {string} expression The model expression to match.
  15819. * @param {boolean} opt_exactMatch If true, only returns exact matches
  15820. * for the expression.
  15821. */
  15822. testability.findModels = function(element, expression, opt_exactMatch) {
  15823. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  15824. for (var p = 0; p < prefixes.length; ++p) {
  15825. var attributeEquals = opt_exactMatch ? '=' : '*=';
  15826. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  15827. var elements = element.querySelectorAll(selector);
  15828. if (elements.length) {
  15829. return elements;
  15830. }
  15831. }
  15832. };
  15833. /**
  15834. * @name $$testability#getLocation
  15835. *
  15836. * @description
  15837. * Shortcut for getting the location in a browser agnostic way. Returns
  15838. * the path, search, and hash. (e.g. /path?a=b#hash)
  15839. */
  15840. testability.getLocation = function() {
  15841. return $location.url();
  15842. };
  15843. /**
  15844. * @name $$testability#setLocation
  15845. *
  15846. * @description
  15847. * Shortcut for navigating to a location without doing a full page reload.
  15848. *
  15849. * @param {string} url The location url (path, search and hash,
  15850. * e.g. /path?a=b#hash) to go to.
  15851. */
  15852. testability.setLocation = function(url) {
  15853. if (url !== $location.url()) {
  15854. $location.url(url);
  15855. $rootScope.$digest();
  15856. }
  15857. };
  15858. /**
  15859. * @name $$testability#whenStable
  15860. *
  15861. * @description
  15862. * Calls the callback when $timeout and $http requests are completed.
  15863. *
  15864. * @param {function} callback
  15865. */
  15866. testability.whenStable = function(callback) {
  15867. $browser.notifyWhenNoOutstandingRequests(callback);
  15868. };
  15869. return testability;
  15870. }];
  15871. }
  15872. function $TimeoutProvider() {
  15873. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  15874. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  15875. var deferreds = {};
  15876. /**
  15877. * @ngdoc service
  15878. * @name $timeout
  15879. *
  15880. * @description
  15881. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  15882. * block and delegates any exceptions to
  15883. * {@link ng.$exceptionHandler $exceptionHandler} service.
  15884. *
  15885. * The return value of calling `$timeout` is a promise, which will be resolved when
  15886. * the delay has passed and the timeout function, if provided, is executed.
  15887. *
  15888. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  15889. *
  15890. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  15891. * synchronously flush the queue of deferred functions.
  15892. *
  15893. * If you only want a promise that will be resolved after some specified delay
  15894. * then you can call `$timeout` without the `fn` function.
  15895. *
  15896. * @param {function()=} fn A function, whose execution should be delayed.
  15897. * @param {number=} [delay=0] Delay in milliseconds.
  15898. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  15899. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  15900. * @param {...*=} Pass additional parameters to the executed function.
  15901. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
  15902. * promise will be resolved with is the return value of the `fn` function.
  15903. *
  15904. */
  15905. function timeout(fn, delay, invokeApply) {
  15906. if (!isFunction(fn)) {
  15907. invokeApply = delay;
  15908. delay = fn;
  15909. fn = noop;
  15910. }
  15911. var args = sliceArgs(arguments, 3),
  15912. skipApply = (isDefined(invokeApply) && !invokeApply),
  15913. deferred = (skipApply ? $$q : $q).defer(),
  15914. promise = deferred.promise,
  15915. timeoutId;
  15916. timeoutId = $browser.defer(function() {
  15917. try {
  15918. deferred.resolve(fn.apply(null, args));
  15919. } catch (e) {
  15920. deferred.reject(e);
  15921. $exceptionHandler(e);
  15922. }
  15923. finally {
  15924. delete deferreds[promise.$$timeoutId];
  15925. }
  15926. if (!skipApply) $rootScope.$apply();
  15927. }, delay);
  15928. promise.$$timeoutId = timeoutId;
  15929. deferreds[timeoutId] = deferred;
  15930. return promise;
  15931. }
  15932. /**
  15933. * @ngdoc method
  15934. * @name $timeout#cancel
  15935. *
  15936. * @description
  15937. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  15938. * resolved with a rejection.
  15939. *
  15940. * @param {Promise=} promise Promise returned by the `$timeout` function.
  15941. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  15942. * canceled.
  15943. */
  15944. timeout.cancel = function(promise) {
  15945. if (promise && promise.$$timeoutId in deferreds) {
  15946. deferreds[promise.$$timeoutId].reject('canceled');
  15947. delete deferreds[promise.$$timeoutId];
  15948. return $browser.defer.cancel(promise.$$timeoutId);
  15949. }
  15950. return false;
  15951. };
  15952. return timeout;
  15953. }];
  15954. }
  15955. // NOTE: The usage of window and document instead of $window and $document here is
  15956. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  15957. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  15958. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  15959. // doesn't know about mocked locations and resolves URLs to the real document - which is
  15960. // exactly the behavior needed here. There is little value is mocking these out for this
  15961. // service.
  15962. var urlParsingNode = document.createElement("a");
  15963. var originUrl = urlResolve(window.location.href);
  15964. /**
  15965. *
  15966. * Implementation Notes for non-IE browsers
  15967. * ----------------------------------------
  15968. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  15969. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  15970. * URL will be resolved into an absolute URL in the context of the application document.
  15971. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  15972. * properties are all populated to reflect the normalized URL. This approach has wide
  15973. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  15974. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  15975. *
  15976. * Implementation Notes for IE
  15977. * ---------------------------
  15978. * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other
  15979. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  15980. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  15981. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  15982. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  15983. * properties such as protocol, hostname, port, etc.
  15984. *
  15985. * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one
  15986. * uses the inner HTML approach to assign the URL as part of an HTML snippet -
  15987. * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL.
  15988. * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception.
  15989. * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that
  15990. * method and IE < 8 is unsupported.
  15991. *
  15992. * References:
  15993. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  15994. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  15995. * http://url.spec.whatwg.org/#urlutils
  15996. * https://github.com/angular/angular.js/pull/2902
  15997. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  15998. *
  15999. * @kind function
  16000. * @param {string} url The URL to be parsed.
  16001. * @description Normalizes and parses a URL.
  16002. * @returns {object} Returns the normalized URL as a dictionary.
  16003. *
  16004. * | member name | Description |
  16005. * |---------------|----------------|
  16006. * | href | A normalized version of the provided URL if it was not an absolute URL |
  16007. * | protocol | The protocol including the trailing colon |
  16008. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  16009. * | search | The search params, minus the question mark |
  16010. * | hash | The hash string, minus the hash symbol
  16011. * | hostname | The hostname
  16012. * | port | The port, without ":"
  16013. * | pathname | The pathname, beginning with "/"
  16014. *
  16015. */
  16016. function urlResolve(url) {
  16017. var href = url;
  16018. if (msie) {
  16019. // Normalize before parse. Refer Implementation Notes on why this is
  16020. // done in two steps on IE.
  16021. urlParsingNode.setAttribute("href", href);
  16022. href = urlParsingNode.href;
  16023. }
  16024. urlParsingNode.setAttribute('href', href);
  16025. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  16026. return {
  16027. href: urlParsingNode.href,
  16028. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  16029. host: urlParsingNode.host,
  16030. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  16031. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  16032. hostname: urlParsingNode.hostname,
  16033. port: urlParsingNode.port,
  16034. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  16035. ? urlParsingNode.pathname
  16036. : '/' + urlParsingNode.pathname
  16037. };
  16038. }
  16039. /**
  16040. * Parse a request URL and determine whether this is a same-origin request as the application document.
  16041. *
  16042. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  16043. * or a parsed URL object.
  16044. * @returns {boolean} Whether the request is for the same origin as the application document.
  16045. */
  16046. function urlIsSameOrigin(requestUrl) {
  16047. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  16048. return (parsed.protocol === originUrl.protocol &&
  16049. parsed.host === originUrl.host);
  16050. }
  16051. /**
  16052. * @ngdoc service
  16053. * @name $window
  16054. *
  16055. * @description
  16056. * A reference to the browser's `window` object. While `window`
  16057. * is globally available in JavaScript, it causes testability problems, because
  16058. * it is a global variable. In angular we always refer to it through the
  16059. * `$window` service, so it may be overridden, removed or mocked for testing.
  16060. *
  16061. * Expressions, like the one defined for the `ngClick` directive in the example
  16062. * below, are evaluated with respect to the current scope. Therefore, there is
  16063. * no risk of inadvertently coding in a dependency on a global value in such an
  16064. * expression.
  16065. *
  16066. * @example
  16067. <example module="windowExample">
  16068. <file name="index.html">
  16069. <script>
  16070. angular.module('windowExample', [])
  16071. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  16072. $scope.greeting = 'Hello, World!';
  16073. $scope.doGreeting = function(greeting) {
  16074. $window.alert(greeting);
  16075. };
  16076. }]);
  16077. </script>
  16078. <div ng-controller="ExampleController">
  16079. <input type="text" ng-model="greeting" aria-label="greeting" />
  16080. <button ng-click="doGreeting(greeting)">ALERT</button>
  16081. </div>
  16082. </file>
  16083. <file name="protractor.js" type="protractor">
  16084. it('should display the greeting in the input box', function() {
  16085. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  16086. // If we click the button it will block the test runner
  16087. // element(':button').click();
  16088. });
  16089. </file>
  16090. </example>
  16091. */
  16092. function $WindowProvider() {
  16093. this.$get = valueFn(window);
  16094. }
  16095. /**
  16096. * @name $$cookieReader
  16097. * @requires $document
  16098. *
  16099. * @description
  16100. * This is a private service for reading cookies used by $http and ngCookies
  16101. *
  16102. * @return {Object} a key/value map of the current cookies
  16103. */
  16104. function $$CookieReader($document) {
  16105. var rawDocument = $document[0] || {};
  16106. var lastCookies = {};
  16107. var lastCookieString = '';
  16108. function safeDecodeURIComponent(str) {
  16109. try {
  16110. return decodeURIComponent(str);
  16111. } catch (e) {
  16112. return str;
  16113. }
  16114. }
  16115. return function() {
  16116. var cookieArray, cookie, i, index, name;
  16117. var currentCookieString = rawDocument.cookie || '';
  16118. if (currentCookieString !== lastCookieString) {
  16119. lastCookieString = currentCookieString;
  16120. cookieArray = lastCookieString.split('; ');
  16121. lastCookies = {};
  16122. for (i = 0; i < cookieArray.length; i++) {
  16123. cookie = cookieArray[i];
  16124. index = cookie.indexOf('=');
  16125. if (index > 0) { //ignore nameless cookies
  16126. name = safeDecodeURIComponent(cookie.substring(0, index));
  16127. // the first value that is seen for a cookie is the most
  16128. // specific one. values for the same cookie name that
  16129. // follow are for less specific paths.
  16130. if (lastCookies[name] === undefined) {
  16131. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  16132. }
  16133. }
  16134. }
  16135. }
  16136. return lastCookies;
  16137. };
  16138. }
  16139. $$CookieReader.$inject = ['$document'];
  16140. function $$CookieReaderProvider() {
  16141. this.$get = $$CookieReader;
  16142. }
  16143. /* global currencyFilter: true,
  16144. dateFilter: true,
  16145. filterFilter: true,
  16146. jsonFilter: true,
  16147. limitToFilter: true,
  16148. lowercaseFilter: true,
  16149. numberFilter: true,
  16150. orderByFilter: true,
  16151. uppercaseFilter: true,
  16152. */
  16153. /**
  16154. * @ngdoc provider
  16155. * @name $filterProvider
  16156. * @description
  16157. *
  16158. * Filters are just functions which transform input to an output. However filters need to be
  16159. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  16160. * annotated with dependencies and is responsible for creating a filter function.
  16161. *
  16162. * <div class="alert alert-warning">
  16163. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  16164. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  16165. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  16166. * (`myapp_subsection_filterx`).
  16167. * </div>
  16168. *
  16169. * ```js
  16170. * // Filter registration
  16171. * function MyModule($provide, $filterProvider) {
  16172. * // create a service to demonstrate injection (not always needed)
  16173. * $provide.value('greet', function(name){
  16174. * return 'Hello ' + name + '!';
  16175. * });
  16176. *
  16177. * // register a filter factory which uses the
  16178. * // greet service to demonstrate DI.
  16179. * $filterProvider.register('greet', function(greet){
  16180. * // return the filter function which uses the greet service
  16181. * // to generate salutation
  16182. * return function(text) {
  16183. * // filters need to be forgiving so check input validity
  16184. * return text && greet(text) || text;
  16185. * };
  16186. * });
  16187. * }
  16188. * ```
  16189. *
  16190. * The filter function is registered with the `$injector` under the filter name suffix with
  16191. * `Filter`.
  16192. *
  16193. * ```js
  16194. * it('should be the same instance', inject(
  16195. * function($filterProvider) {
  16196. * $filterProvider.register('reverse', function(){
  16197. * return ...;
  16198. * });
  16199. * },
  16200. * function($filter, reverseFilter) {
  16201. * expect($filter('reverse')).toBe(reverseFilter);
  16202. * });
  16203. * ```
  16204. *
  16205. *
  16206. * For more information about how angular filters work, and how to create your own filters, see
  16207. * {@link guide/filter Filters} in the Angular Developer Guide.
  16208. */
  16209. /**
  16210. * @ngdoc service
  16211. * @name $filter
  16212. * @kind function
  16213. * @description
  16214. * Filters are used for formatting data displayed to the user.
  16215. *
  16216. * The general syntax in templates is as follows:
  16217. *
  16218. * {{ expression [| filter_name[:parameter_value] ... ] }}
  16219. *
  16220. * @param {String} name Name of the filter function to retrieve
  16221. * @return {Function} the filter function
  16222. * @example
  16223. <example name="$filter" module="filterExample">
  16224. <file name="index.html">
  16225. <div ng-controller="MainCtrl">
  16226. <h3>{{ originalText }}</h3>
  16227. <h3>{{ filteredText }}</h3>
  16228. </div>
  16229. </file>
  16230. <file name="script.js">
  16231. angular.module('filterExample', [])
  16232. .controller('MainCtrl', function($scope, $filter) {
  16233. $scope.originalText = 'hello';
  16234. $scope.filteredText = $filter('uppercase')($scope.originalText);
  16235. });
  16236. </file>
  16237. </example>
  16238. */
  16239. $FilterProvider.$inject = ['$provide'];
  16240. function $FilterProvider($provide) {
  16241. var suffix = 'Filter';
  16242. /**
  16243. * @ngdoc method
  16244. * @name $filterProvider#register
  16245. * @param {string|Object} name Name of the filter function, or an object map of filters where
  16246. * the keys are the filter names and the values are the filter factories.
  16247. *
  16248. * <div class="alert alert-warning">
  16249. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  16250. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  16251. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  16252. * (`myapp_subsection_filterx`).
  16253. * </div>
  16254. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  16255. * of the registered filter instances.
  16256. */
  16257. function register(name, factory) {
  16258. if (isObject(name)) {
  16259. var filters = {};
  16260. forEach(name, function(filter, key) {
  16261. filters[key] = register(key, filter);
  16262. });
  16263. return filters;
  16264. } else {
  16265. return $provide.factory(name + suffix, factory);
  16266. }
  16267. }
  16268. this.register = register;
  16269. this.$get = ['$injector', function($injector) {
  16270. return function(name) {
  16271. return $injector.get(name + suffix);
  16272. };
  16273. }];
  16274. ////////////////////////////////////////
  16275. /* global
  16276. currencyFilter: false,
  16277. dateFilter: false,
  16278. filterFilter: false,
  16279. jsonFilter: false,
  16280. limitToFilter: false,
  16281. lowercaseFilter: false,
  16282. numberFilter: false,
  16283. orderByFilter: false,
  16284. uppercaseFilter: false,
  16285. */
  16286. register('currency', currencyFilter);
  16287. register('date', dateFilter);
  16288. register('filter', filterFilter);
  16289. register('json', jsonFilter);
  16290. register('limitTo', limitToFilter);
  16291. register('lowercase', lowercaseFilter);
  16292. register('number', numberFilter);
  16293. register('orderBy', orderByFilter);
  16294. register('uppercase', uppercaseFilter);
  16295. }
  16296. /**
  16297. * @ngdoc filter
  16298. * @name filter
  16299. * @kind function
  16300. *
  16301. * @description
  16302. * Selects a subset of items from `array` and returns it as a new array.
  16303. *
  16304. * @param {Array} array The source array.
  16305. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  16306. * `array`.
  16307. *
  16308. * Can be one of:
  16309. *
  16310. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  16311. * objects with string properties in `array` that match this string will be returned. This also
  16312. * applies to nested object properties.
  16313. * The predicate can be negated by prefixing the string with `!`.
  16314. *
  16315. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  16316. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  16317. * which have property `name` containing "M" and property `phone` containing "1". A special
  16318. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  16319. * property of the object or its nested object properties. That's equivalent to the simple
  16320. * substring match with a `string` as described above. The predicate can be negated by prefixing
  16321. * the string with `!`.
  16322. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  16323. * not containing "M".
  16324. *
  16325. * Note that a named property will match properties on the same level only, while the special
  16326. * `$` property will match properties on the same level or deeper. E.g. an array item like
  16327. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  16328. * **will** be matched by `{$: 'John'}`.
  16329. *
  16330. * - `function(value, index)`: A predicate function can be used to write arbitrary filters. The
  16331. * function is called for each element of `array`. The final result is an array of those
  16332. * elements that the predicate returned true for.
  16333. *
  16334. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  16335. * determining if the expected value (from the filter expression) and actual value (from
  16336. * the object in the array) should be considered a match.
  16337. *
  16338. * Can be one of:
  16339. *
  16340. * - `function(actual, expected)`:
  16341. * The function will be given the object value and the predicate value to compare and
  16342. * should return true if both values should be considered equal.
  16343. *
  16344. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  16345. * This is essentially strict comparison of expected and actual.
  16346. *
  16347. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  16348. * insensitive way.
  16349. *
  16350. * Primitive values are converted to strings. Objects are not compared against primitives,
  16351. * unless they have a custom `toString` method (e.g. `Date` objects).
  16352. *
  16353. * @example
  16354. <example>
  16355. <file name="index.html">
  16356. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  16357. {name:'Mary', phone:'800-BIG-MARY'},
  16358. {name:'Mike', phone:'555-4321'},
  16359. {name:'Adam', phone:'555-5678'},
  16360. {name:'Julie', phone:'555-8765'},
  16361. {name:'Juliette', phone:'555-5678'}]"></div>
  16362. <label>Search: <input ng-model="searchText"></label>
  16363. <table id="searchTextResults">
  16364. <tr><th>Name</th><th>Phone</th></tr>
  16365. <tr ng-repeat="friend in friends | filter:searchText">
  16366. <td>{{friend.name}}</td>
  16367. <td>{{friend.phone}}</td>
  16368. </tr>
  16369. </table>
  16370. <hr>
  16371. <label>Any: <input ng-model="search.$"></label> <br>
  16372. <label>Name only <input ng-model="search.name"></label><br>
  16373. <label>Phone only <input ng-model="search.phone"></label><br>
  16374. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  16375. <table id="searchObjResults">
  16376. <tr><th>Name</th><th>Phone</th></tr>
  16377. <tr ng-repeat="friendObj in friends | filter:search:strict">
  16378. <td>{{friendObj.name}}</td>
  16379. <td>{{friendObj.phone}}</td>
  16380. </tr>
  16381. </table>
  16382. </file>
  16383. <file name="protractor.js" type="protractor">
  16384. var expectFriendNames = function(expectedNames, key) {
  16385. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  16386. arr.forEach(function(wd, i) {
  16387. expect(wd.getText()).toMatch(expectedNames[i]);
  16388. });
  16389. });
  16390. };
  16391. it('should search across all fields when filtering with a string', function() {
  16392. var searchText = element(by.model('searchText'));
  16393. searchText.clear();
  16394. searchText.sendKeys('m');
  16395. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  16396. searchText.clear();
  16397. searchText.sendKeys('76');
  16398. expectFriendNames(['John', 'Julie'], 'friend');
  16399. });
  16400. it('should search in specific fields when filtering with a predicate object', function() {
  16401. var searchAny = element(by.model('search.$'));
  16402. searchAny.clear();
  16403. searchAny.sendKeys('i');
  16404. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  16405. });
  16406. it('should use a equal comparison when comparator is true', function() {
  16407. var searchName = element(by.model('search.name'));
  16408. var strict = element(by.model('strict'));
  16409. searchName.clear();
  16410. searchName.sendKeys('Julie');
  16411. strict.click();
  16412. expectFriendNames(['Julie'], 'friendObj');
  16413. });
  16414. </file>
  16415. </example>
  16416. */
  16417. function filterFilter() {
  16418. return function(array, expression, comparator) {
  16419. if (!isArrayLike(array)) {
  16420. if (array == null) {
  16421. return array;
  16422. } else {
  16423. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  16424. }
  16425. }
  16426. var expressionType = getTypeForFilter(expression);
  16427. var predicateFn;
  16428. var matchAgainstAnyProp;
  16429. switch (expressionType) {
  16430. case 'function':
  16431. predicateFn = expression;
  16432. break;
  16433. case 'boolean':
  16434. case 'null':
  16435. case 'number':
  16436. case 'string':
  16437. matchAgainstAnyProp = true;
  16438. //jshint -W086
  16439. case 'object':
  16440. //jshint +W086
  16441. predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
  16442. break;
  16443. default:
  16444. return array;
  16445. }
  16446. return Array.prototype.filter.call(array, predicateFn);
  16447. };
  16448. }
  16449. function hasCustomToString(obj) {
  16450. return isFunction(obj.toString) && obj.toString !== Object.prototype.toString;
  16451. }
  16452. // Helper functions for `filterFilter`
  16453. function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
  16454. var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
  16455. var predicateFn;
  16456. if (comparator === true) {
  16457. comparator = equals;
  16458. } else if (!isFunction(comparator)) {
  16459. comparator = function(actual, expected) {
  16460. if (isUndefined(actual)) {
  16461. // No substring matching against `undefined`
  16462. return false;
  16463. }
  16464. if ((actual === null) || (expected === null)) {
  16465. // No substring matching against `null`; only match against `null`
  16466. return actual === expected;
  16467. }
  16468. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  16469. // Should not compare primitives against objects, unless they have custom `toString` method
  16470. return false;
  16471. }
  16472. actual = lowercase('' + actual);
  16473. expected = lowercase('' + expected);
  16474. return actual.indexOf(expected) !== -1;
  16475. };
  16476. }
  16477. predicateFn = function(item) {
  16478. if (shouldMatchPrimitives && !isObject(item)) {
  16479. return deepCompare(item, expression.$, comparator, false);
  16480. }
  16481. return deepCompare(item, expression, comparator, matchAgainstAnyProp);
  16482. };
  16483. return predicateFn;
  16484. }
  16485. function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
  16486. var actualType = getTypeForFilter(actual);
  16487. var expectedType = getTypeForFilter(expected);
  16488. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  16489. return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
  16490. } else if (isArray(actual)) {
  16491. // In case `actual` is an array, consider it a match
  16492. // if ANY of it's items matches `expected`
  16493. return actual.some(function(item) {
  16494. return deepCompare(item, expected, comparator, matchAgainstAnyProp);
  16495. });
  16496. }
  16497. switch (actualType) {
  16498. case 'object':
  16499. var key;
  16500. if (matchAgainstAnyProp) {
  16501. for (key in actual) {
  16502. if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
  16503. return true;
  16504. }
  16505. }
  16506. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
  16507. } else if (expectedType === 'object') {
  16508. for (key in expected) {
  16509. var expectedVal = expected[key];
  16510. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  16511. continue;
  16512. }
  16513. var matchAnyProperty = key === '$';
  16514. var actualVal = matchAnyProperty ? actual : actual[key];
  16515. if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
  16516. return false;
  16517. }
  16518. }
  16519. return true;
  16520. } else {
  16521. return comparator(actual, expected);
  16522. }
  16523. break;
  16524. case 'function':
  16525. return false;
  16526. default:
  16527. return comparator(actual, expected);
  16528. }
  16529. }
  16530. // Used for easily differentiating between `null` and actual `object`
  16531. function getTypeForFilter(val) {
  16532. return (val === null) ? 'null' : typeof val;
  16533. }
  16534. /**
  16535. * @ngdoc filter
  16536. * @name currency
  16537. * @kind function
  16538. *
  16539. * @description
  16540. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  16541. * symbol for current locale is used.
  16542. *
  16543. * @param {number} amount Input to filter.
  16544. * @param {string=} symbol Currency symbol or identifier to be displayed.
  16545. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  16546. * @returns {string} Formatted number.
  16547. *
  16548. *
  16549. * @example
  16550. <example module="currencyExample">
  16551. <file name="index.html">
  16552. <script>
  16553. angular.module('currencyExample', [])
  16554. .controller('ExampleController', ['$scope', function($scope) {
  16555. $scope.amount = 1234.56;
  16556. }]);
  16557. </script>
  16558. <div ng-controller="ExampleController">
  16559. <input type="number" ng-model="amount" aria-label="amount"> <br>
  16560. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  16561. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
  16562. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  16563. </div>
  16564. </file>
  16565. <file name="protractor.js" type="protractor">
  16566. it('should init with 1234.56', function() {
  16567. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  16568. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  16569. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  16570. });
  16571. it('should update', function() {
  16572. if (browser.params.browser == 'safari') {
  16573. // Safari does not understand the minus key. See
  16574. // https://github.com/angular/protractor/issues/481
  16575. return;
  16576. }
  16577. element(by.model('amount')).clear();
  16578. element(by.model('amount')).sendKeys('-1234');
  16579. expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)');
  16580. expect(element(by.id('currency-custom')).getText()).toBe('(USD$1,234.00)');
  16581. expect(element(by.id('currency-no-fractions')).getText()).toBe('(USD$1,234)');
  16582. });
  16583. </file>
  16584. </example>
  16585. */
  16586. currencyFilter.$inject = ['$locale'];
  16587. function currencyFilter($locale) {
  16588. var formats = $locale.NUMBER_FORMATS;
  16589. return function(amount, currencySymbol, fractionSize) {
  16590. if (isUndefined(currencySymbol)) {
  16591. currencySymbol = formats.CURRENCY_SYM;
  16592. }
  16593. if (isUndefined(fractionSize)) {
  16594. fractionSize = formats.PATTERNS[1].maxFrac;
  16595. }
  16596. // if null or undefined pass it through
  16597. return (amount == null)
  16598. ? amount
  16599. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  16600. replace(/\u00A4/g, currencySymbol);
  16601. };
  16602. }
  16603. /**
  16604. * @ngdoc filter
  16605. * @name number
  16606. * @kind function
  16607. *
  16608. * @description
  16609. * Formats a number as text.
  16610. *
  16611. * If the input is not a number an empty string is returned.
  16612. *
  16613. * If the input is an infinite (Infinity/-Infinity) the Infinity symbol '∞' is returned.
  16614. *
  16615. * @param {number|string} number Number to format.
  16616. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  16617. * If this is not provided then the fraction size is computed from the current locale's number
  16618. * formatting pattern. In the case of the default locale, it will be 3.
  16619. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
  16620. *
  16621. * @example
  16622. <example module="numberFilterExample">
  16623. <file name="index.html">
  16624. <script>
  16625. angular.module('numberFilterExample', [])
  16626. .controller('ExampleController', ['$scope', function($scope) {
  16627. $scope.val = 1234.56789;
  16628. }]);
  16629. </script>
  16630. <div ng-controller="ExampleController">
  16631. <label>Enter number: <input ng-model='val'></label><br>
  16632. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  16633. No fractions: <span>{{val | number:0}}</span><br>
  16634. Negative number: <span>{{-val | number:4}}</span>
  16635. </div>
  16636. </file>
  16637. <file name="protractor.js" type="protractor">
  16638. it('should format numbers', function() {
  16639. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  16640. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  16641. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  16642. });
  16643. it('should update', function() {
  16644. element(by.model('val')).clear();
  16645. element(by.model('val')).sendKeys('3374.333');
  16646. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  16647. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  16648. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  16649. });
  16650. </file>
  16651. </example>
  16652. */
  16653. numberFilter.$inject = ['$locale'];
  16654. function numberFilter($locale) {
  16655. var formats = $locale.NUMBER_FORMATS;
  16656. return function(number, fractionSize) {
  16657. // if null or undefined pass it through
  16658. return (number == null)
  16659. ? number
  16660. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  16661. fractionSize);
  16662. };
  16663. }
  16664. var DECIMAL_SEP = '.';
  16665. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  16666. if (isObject(number)) return '';
  16667. var isNegative = number < 0;
  16668. number = Math.abs(number);
  16669. var isInfinity = number === Infinity;
  16670. if (!isInfinity && !isFinite(number)) return '';
  16671. var numStr = number + '',
  16672. formatedText = '',
  16673. hasExponent = false,
  16674. parts = [];
  16675. if (isInfinity) formatedText = '\u221e';
  16676. if (!isInfinity && numStr.indexOf('e') !== -1) {
  16677. var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
  16678. if (match && match[2] == '-' && match[3] > fractionSize + 1) {
  16679. number = 0;
  16680. } else {
  16681. formatedText = numStr;
  16682. hasExponent = true;
  16683. }
  16684. }
  16685. if (!isInfinity && !hasExponent) {
  16686. var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
  16687. // determine fractionSize if it is not specified
  16688. if (isUndefined(fractionSize)) {
  16689. fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
  16690. }
  16691. // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
  16692. // inspired by:
  16693. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
  16694. number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
  16695. var fraction = ('' + number).split(DECIMAL_SEP);
  16696. var whole = fraction[0];
  16697. fraction = fraction[1] || '';
  16698. var i, pos = 0,
  16699. lgroup = pattern.lgSize,
  16700. group = pattern.gSize;
  16701. if (whole.length >= (lgroup + group)) {
  16702. pos = whole.length - lgroup;
  16703. for (i = 0; i < pos; i++) {
  16704. if ((pos - i) % group === 0 && i !== 0) {
  16705. formatedText += groupSep;
  16706. }
  16707. formatedText += whole.charAt(i);
  16708. }
  16709. }
  16710. for (i = pos; i < whole.length; i++) {
  16711. if ((whole.length - i) % lgroup === 0 && i !== 0) {
  16712. formatedText += groupSep;
  16713. }
  16714. formatedText += whole.charAt(i);
  16715. }
  16716. // format fraction part.
  16717. while (fraction.length < fractionSize) {
  16718. fraction += '0';
  16719. }
  16720. if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
  16721. } else {
  16722. if (fractionSize > 0 && number < 1) {
  16723. formatedText = number.toFixed(fractionSize);
  16724. number = parseFloat(formatedText);
  16725. }
  16726. }
  16727. if (number === 0) {
  16728. isNegative = false;
  16729. }
  16730. parts.push(isNegative ? pattern.negPre : pattern.posPre,
  16731. formatedText,
  16732. isNegative ? pattern.negSuf : pattern.posSuf);
  16733. return parts.join('');
  16734. }
  16735. function padNumber(num, digits, trim) {
  16736. var neg = '';
  16737. if (num < 0) {
  16738. neg = '-';
  16739. num = -num;
  16740. }
  16741. num = '' + num;
  16742. while (num.length < digits) num = '0' + num;
  16743. if (trim) {
  16744. num = num.substr(num.length - digits);
  16745. }
  16746. return neg + num;
  16747. }
  16748. function dateGetter(name, size, offset, trim) {
  16749. offset = offset || 0;
  16750. return function(date) {
  16751. var value = date['get' + name]();
  16752. if (offset > 0 || value > -offset) {
  16753. value += offset;
  16754. }
  16755. if (value === 0 && offset == -12) value = 12;
  16756. return padNumber(value, size, trim);
  16757. };
  16758. }
  16759. function dateStrGetter(name, shortForm) {
  16760. return function(date, formats) {
  16761. var value = date['get' + name]();
  16762. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  16763. return formats[get][value];
  16764. };
  16765. }
  16766. function timeZoneGetter(date, formats, offset) {
  16767. var zone = -1 * offset;
  16768. var paddedZone = (zone >= 0) ? "+" : "";
  16769. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  16770. padNumber(Math.abs(zone % 60), 2);
  16771. return paddedZone;
  16772. }
  16773. function getFirstThursdayOfYear(year) {
  16774. // 0 = index of January
  16775. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  16776. // 4 = index of Thursday (+1 to account for 1st = 5)
  16777. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  16778. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  16779. }
  16780. function getThursdayThisWeek(datetime) {
  16781. return new Date(datetime.getFullYear(), datetime.getMonth(),
  16782. // 4 = index of Thursday
  16783. datetime.getDate() + (4 - datetime.getDay()));
  16784. }
  16785. function weekGetter(size) {
  16786. return function(date) {
  16787. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  16788. thisThurs = getThursdayThisWeek(date);
  16789. var diff = +thisThurs - +firstThurs,
  16790. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  16791. return padNumber(result, size);
  16792. };
  16793. }
  16794. function ampmGetter(date, formats) {
  16795. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  16796. }
  16797. function eraGetter(date, formats) {
  16798. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  16799. }
  16800. function longEraGetter(date, formats) {
  16801. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  16802. }
  16803. var DATE_FORMATS = {
  16804. yyyy: dateGetter('FullYear', 4),
  16805. yy: dateGetter('FullYear', 2, 0, true),
  16806. y: dateGetter('FullYear', 1),
  16807. MMMM: dateStrGetter('Month'),
  16808. MMM: dateStrGetter('Month', true),
  16809. MM: dateGetter('Month', 2, 1),
  16810. M: dateGetter('Month', 1, 1),
  16811. dd: dateGetter('Date', 2),
  16812. d: dateGetter('Date', 1),
  16813. HH: dateGetter('Hours', 2),
  16814. H: dateGetter('Hours', 1),
  16815. hh: dateGetter('Hours', 2, -12),
  16816. h: dateGetter('Hours', 1, -12),
  16817. mm: dateGetter('Minutes', 2),
  16818. m: dateGetter('Minutes', 1),
  16819. ss: dateGetter('Seconds', 2),
  16820. s: dateGetter('Seconds', 1),
  16821. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  16822. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  16823. sss: dateGetter('Milliseconds', 3),
  16824. EEEE: dateStrGetter('Day'),
  16825. EEE: dateStrGetter('Day', true),
  16826. a: ampmGetter,
  16827. Z: timeZoneGetter,
  16828. ww: weekGetter(2),
  16829. w: weekGetter(1),
  16830. G: eraGetter,
  16831. GG: eraGetter,
  16832. GGG: eraGetter,
  16833. GGGG: longEraGetter
  16834. };
  16835. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
  16836. NUMBER_STRING = /^\-?\d+$/;
  16837. /**
  16838. * @ngdoc filter
  16839. * @name date
  16840. * @kind function
  16841. *
  16842. * @description
  16843. * Formats `date` to a string based on the requested `format`.
  16844. *
  16845. * `format` string can be composed of the following elements:
  16846. *
  16847. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  16848. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  16849. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  16850. * * `'MMMM'`: Month in year (January-December)
  16851. * * `'MMM'`: Month in year (Jan-Dec)
  16852. * * `'MM'`: Month in year, padded (01-12)
  16853. * * `'M'`: Month in year (1-12)
  16854. * * `'dd'`: Day in month, padded (01-31)
  16855. * * `'d'`: Day in month (1-31)
  16856. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  16857. * * `'EEE'`: Day in Week, (Sun-Sat)
  16858. * * `'HH'`: Hour in day, padded (00-23)
  16859. * * `'H'`: Hour in day (0-23)
  16860. * * `'hh'`: Hour in AM/PM, padded (01-12)
  16861. * * `'h'`: Hour in AM/PM, (1-12)
  16862. * * `'mm'`: Minute in hour, padded (00-59)
  16863. * * `'m'`: Minute in hour (0-59)
  16864. * * `'ss'`: Second in minute, padded (00-59)
  16865. * * `'s'`: Second in minute (0-59)
  16866. * * `'sss'`: Millisecond in second, padded (000-999)
  16867. * * `'a'`: AM/PM marker
  16868. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  16869. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  16870. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  16871. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  16872. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  16873. *
  16874. * `format` string can also be one of the following predefined
  16875. * {@link guide/i18n localizable formats}:
  16876. *
  16877. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  16878. * (e.g. Sep 3, 2010 12:05:08 PM)
  16879. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  16880. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  16881. * (e.g. Friday, September 3, 2010)
  16882. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  16883. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  16884. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  16885. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  16886. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  16887. *
  16888. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  16889. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  16890. * (e.g. `"h 'o''clock'"`).
  16891. *
  16892. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  16893. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  16894. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  16895. * specified in the string input, the time is considered to be in the local timezone.
  16896. * @param {string=} format Formatting rules (see Description). If not specified,
  16897. * `mediumDate` is used.
  16898. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  16899. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  16900. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  16901. * If not specified, the timezone of the browser will be used.
  16902. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  16903. *
  16904. * @example
  16905. <example>
  16906. <file name="index.html">
  16907. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  16908. <span>{{1288323623006 | date:'medium'}}</span><br>
  16909. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  16910. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  16911. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  16912. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  16913. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  16914. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  16915. </file>
  16916. <file name="protractor.js" type="protractor">
  16917. it('should format date', function() {
  16918. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  16919. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  16920. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  16921. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  16922. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  16923. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  16924. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  16925. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  16926. });
  16927. </file>
  16928. </example>
  16929. */
  16930. dateFilter.$inject = ['$locale'];
  16931. function dateFilter($locale) {
  16932. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  16933. // 1 2 3 4 5 6 7 8 9 10 11
  16934. function jsonStringToDate(string) {
  16935. var match;
  16936. if (match = string.match(R_ISO8601_STR)) {
  16937. var date = new Date(0),
  16938. tzHour = 0,
  16939. tzMin = 0,
  16940. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  16941. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  16942. if (match[9]) {
  16943. tzHour = toInt(match[9] + match[10]);
  16944. tzMin = toInt(match[9] + match[11]);
  16945. }
  16946. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  16947. var h = toInt(match[4] || 0) - tzHour;
  16948. var m = toInt(match[5] || 0) - tzMin;
  16949. var s = toInt(match[6] || 0);
  16950. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  16951. timeSetter.call(date, h, m, s, ms);
  16952. return date;
  16953. }
  16954. return string;
  16955. }
  16956. return function(date, format, timezone) {
  16957. var text = '',
  16958. parts = [],
  16959. fn, match;
  16960. format = format || 'mediumDate';
  16961. format = $locale.DATETIME_FORMATS[format] || format;
  16962. if (isString(date)) {
  16963. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  16964. }
  16965. if (isNumber(date)) {
  16966. date = new Date(date);
  16967. }
  16968. if (!isDate(date) || !isFinite(date.getTime())) {
  16969. return date;
  16970. }
  16971. while (format) {
  16972. match = DATE_FORMATS_SPLIT.exec(format);
  16973. if (match) {
  16974. parts = concat(parts, match, 1);
  16975. format = parts.pop();
  16976. } else {
  16977. parts.push(format);
  16978. format = null;
  16979. }
  16980. }
  16981. var dateTimezoneOffset = date.getTimezoneOffset();
  16982. if (timezone) {
  16983. dateTimezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
  16984. date = convertTimezoneToLocal(date, timezone, true);
  16985. }
  16986. forEach(parts, function(value) {
  16987. fn = DATE_FORMATS[value];
  16988. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  16989. : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  16990. });
  16991. return text;
  16992. };
  16993. }
  16994. /**
  16995. * @ngdoc filter
  16996. * @name json
  16997. * @kind function
  16998. *
  16999. * @description
  17000. * Allows you to convert a JavaScript object into JSON string.
  17001. *
  17002. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  17003. * the binding is automatically converted to JSON.
  17004. *
  17005. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  17006. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  17007. * @returns {string} JSON string.
  17008. *
  17009. *
  17010. * @example
  17011. <example>
  17012. <file name="index.html">
  17013. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  17014. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  17015. </file>
  17016. <file name="protractor.js" type="protractor">
  17017. it('should jsonify filtered objects', function() {
  17018. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  17019. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  17020. });
  17021. </file>
  17022. </example>
  17023. *
  17024. */
  17025. function jsonFilter() {
  17026. return function(object, spacing) {
  17027. if (isUndefined(spacing)) {
  17028. spacing = 2;
  17029. }
  17030. return toJson(object, spacing);
  17031. };
  17032. }
  17033. /**
  17034. * @ngdoc filter
  17035. * @name lowercase
  17036. * @kind function
  17037. * @description
  17038. * Converts string to lowercase.
  17039. * @see angular.lowercase
  17040. */
  17041. var lowercaseFilter = valueFn(lowercase);
  17042. /**
  17043. * @ngdoc filter
  17044. * @name uppercase
  17045. * @kind function
  17046. * @description
  17047. * Converts string to uppercase.
  17048. * @see angular.uppercase
  17049. */
  17050. var uppercaseFilter = valueFn(uppercase);
  17051. /**
  17052. * @ngdoc filter
  17053. * @name limitTo
  17054. * @kind function
  17055. *
  17056. * @description
  17057. * Creates a new array or string containing only a specified number of elements. The elements
  17058. * are taken from either the beginning or the end of the source array, string or number, as specified by
  17059. * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
  17060. * converted to a string.
  17061. *
  17062. * @param {Array|string|number} input Source array, string or number to be limited.
  17063. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  17064. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  17065. * If the number is negative, `limit` number of items from the end of the source array/string
  17066. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  17067. * the input will be returned unchanged.
  17068. * @param {(string|number)=} begin Index at which to begin limitation. As a negative index, `begin`
  17069. * indicates an offset from the end of `input`. Defaults to `0`.
  17070. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  17071. * had less than `limit` elements.
  17072. *
  17073. * @example
  17074. <example module="limitToExample">
  17075. <file name="index.html">
  17076. <script>
  17077. angular.module('limitToExample', [])
  17078. .controller('ExampleController', ['$scope', function($scope) {
  17079. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  17080. $scope.letters = "abcdefghi";
  17081. $scope.longNumber = 2345432342;
  17082. $scope.numLimit = 3;
  17083. $scope.letterLimit = 3;
  17084. $scope.longNumberLimit = 3;
  17085. }]);
  17086. </script>
  17087. <div ng-controller="ExampleController">
  17088. <label>
  17089. Limit {{numbers}} to:
  17090. <input type="number" step="1" ng-model="numLimit">
  17091. </label>
  17092. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  17093. <label>
  17094. Limit {{letters}} to:
  17095. <input type="number" step="1" ng-model="letterLimit">
  17096. </label>
  17097. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  17098. <label>
  17099. Limit {{longNumber}} to:
  17100. <input type="number" step="1" ng-model="longNumberLimit">
  17101. </label>
  17102. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  17103. </div>
  17104. </file>
  17105. <file name="protractor.js" type="protractor">
  17106. var numLimitInput = element(by.model('numLimit'));
  17107. var letterLimitInput = element(by.model('letterLimit'));
  17108. var longNumberLimitInput = element(by.model('longNumberLimit'));
  17109. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  17110. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  17111. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  17112. it('should limit the number array to first three items', function() {
  17113. expect(numLimitInput.getAttribute('value')).toBe('3');
  17114. expect(letterLimitInput.getAttribute('value')).toBe('3');
  17115. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  17116. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  17117. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  17118. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  17119. });
  17120. // There is a bug in safari and protractor that doesn't like the minus key
  17121. // it('should update the output when -3 is entered', function() {
  17122. // numLimitInput.clear();
  17123. // numLimitInput.sendKeys('-3');
  17124. // letterLimitInput.clear();
  17125. // letterLimitInput.sendKeys('-3');
  17126. // longNumberLimitInput.clear();
  17127. // longNumberLimitInput.sendKeys('-3');
  17128. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  17129. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  17130. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  17131. // });
  17132. it('should not exceed the maximum size of input array', function() {
  17133. numLimitInput.clear();
  17134. numLimitInput.sendKeys('100');
  17135. letterLimitInput.clear();
  17136. letterLimitInput.sendKeys('100');
  17137. longNumberLimitInput.clear();
  17138. longNumberLimitInput.sendKeys('100');
  17139. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  17140. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  17141. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  17142. });
  17143. </file>
  17144. </example>
  17145. */
  17146. function limitToFilter() {
  17147. return function(input, limit, begin) {
  17148. if (Math.abs(Number(limit)) === Infinity) {
  17149. limit = Number(limit);
  17150. } else {
  17151. limit = toInt(limit);
  17152. }
  17153. if (isNaN(limit)) return input;
  17154. if (isNumber(input)) input = input.toString();
  17155. if (!isArray(input) && !isString(input)) return input;
  17156. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  17157. begin = (begin < 0 && begin >= -input.length) ? input.length + begin : begin;
  17158. if (limit >= 0) {
  17159. return input.slice(begin, begin + limit);
  17160. } else {
  17161. if (begin === 0) {
  17162. return input.slice(limit, input.length);
  17163. } else {
  17164. return input.slice(Math.max(0, begin + limit), begin);
  17165. }
  17166. }
  17167. };
  17168. }
  17169. /**
  17170. * @ngdoc filter
  17171. * @name orderBy
  17172. * @kind function
  17173. *
  17174. * @description
  17175. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  17176. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  17177. * correctly, make sure they are actually being saved as numbers and not strings.
  17178. *
  17179. * @param {Array} array The array to sort.
  17180. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
  17181. * used by the comparator to determine the order of elements.
  17182. *
  17183. * Can be one of:
  17184. *
  17185. * - `function`: Getter function. The result of this function will be sorted using the
  17186. * `<`, `===`, `>` operator.
  17187. * - `string`: An Angular expression. The result of this expression is used to compare elements
  17188. * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
  17189. * 3 first characters of a property called `name`). The result of a constant expression
  17190. * is interpreted as a property name to be used in comparisons (for example `"special name"`
  17191. * to sort object by the value of their `special name` property). An expression can be
  17192. * optionally prefixed with `+` or `-` to control ascending or descending sort order
  17193. * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
  17194. * element itself is used to compare where sorting.
  17195. * - `Array`: An array of function or string predicates. The first predicate in the array
  17196. * is used for sorting, but when two items are equivalent, the next predicate is used.
  17197. *
  17198. * If the predicate is missing or empty then it defaults to `'+'`.
  17199. *
  17200. * @param {boolean=} reverse Reverse the order of the array.
  17201. * @returns {Array} Sorted copy of the source array.
  17202. *
  17203. *
  17204. * @example
  17205. * The example below demonstrates a simple ngRepeat, where the data is sorted
  17206. * by age in descending order (predicate is set to `'-age'`).
  17207. * `reverse` is not set, which means it defaults to `false`.
  17208. <example module="orderByExample">
  17209. <file name="index.html">
  17210. <script>
  17211. angular.module('orderByExample', [])
  17212. .controller('ExampleController', ['$scope', function($scope) {
  17213. $scope.friends =
  17214. [{name:'John', phone:'555-1212', age:10},
  17215. {name:'Mary', phone:'555-9876', age:19},
  17216. {name:'Mike', phone:'555-4321', age:21},
  17217. {name:'Adam', phone:'555-5678', age:35},
  17218. {name:'Julie', phone:'555-8765', age:29}];
  17219. }]);
  17220. </script>
  17221. <div ng-controller="ExampleController">
  17222. <table class="friend">
  17223. <tr>
  17224. <th>Name</th>
  17225. <th>Phone Number</th>
  17226. <th>Age</th>
  17227. </tr>
  17228. <tr ng-repeat="friend in friends | orderBy:'-age'">
  17229. <td>{{friend.name}}</td>
  17230. <td>{{friend.phone}}</td>
  17231. <td>{{friend.age}}</td>
  17232. </tr>
  17233. </table>
  17234. </div>
  17235. </file>
  17236. </example>
  17237. *
  17238. * The predicate and reverse parameters can be controlled dynamically through scope properties,
  17239. * as shown in the next example.
  17240. * @example
  17241. <example module="orderByExample">
  17242. <file name="index.html">
  17243. <script>
  17244. angular.module('orderByExample', [])
  17245. .controller('ExampleController', ['$scope', function($scope) {
  17246. $scope.friends =
  17247. [{name:'John', phone:'555-1212', age:10},
  17248. {name:'Mary', phone:'555-9876', age:19},
  17249. {name:'Mike', phone:'555-4321', age:21},
  17250. {name:'Adam', phone:'555-5678', age:35},
  17251. {name:'Julie', phone:'555-8765', age:29}];
  17252. $scope.predicate = '-age';
  17253. }]);
  17254. </script>
  17255. <div ng-controller="ExampleController">
  17256. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  17257. <hr/>
  17258. [ <a href="" ng-click="predicate=''">unsorted</a> ]
  17259. <table class="friend">
  17260. <tr>
  17261. <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
  17262. (<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
  17263. <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
  17264. <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
  17265. </tr>
  17266. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  17267. <td>{{friend.name}}</td>
  17268. <td>{{friend.phone}}</td>
  17269. <td>{{friend.age}}</td>
  17270. </tr>
  17271. </table>
  17272. </div>
  17273. </file>
  17274. </example>
  17275. *
  17276. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  17277. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  17278. * desired parameters.
  17279. *
  17280. * Example:
  17281. *
  17282. * @example
  17283. <example module="orderByExample">
  17284. <file name="index.html">
  17285. <div ng-controller="ExampleController">
  17286. <table class="friend">
  17287. <tr>
  17288. <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
  17289. (<a href="" ng-click="order('-name',false)">^</a>)</th>
  17290. <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
  17291. <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
  17292. </tr>
  17293. <tr ng-repeat="friend in friends">
  17294. <td>{{friend.name}}</td>
  17295. <td>{{friend.phone}}</td>
  17296. <td>{{friend.age}}</td>
  17297. </tr>
  17298. </table>
  17299. </div>
  17300. </file>
  17301. <file name="script.js">
  17302. angular.module('orderByExample', [])
  17303. .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
  17304. var orderBy = $filter('orderBy');
  17305. $scope.friends = [
  17306. { name: 'John', phone: '555-1212', age: 10 },
  17307. { name: 'Mary', phone: '555-9876', age: 19 },
  17308. { name: 'Mike', phone: '555-4321', age: 21 },
  17309. { name: 'Adam', phone: '555-5678', age: 35 },
  17310. { name: 'Julie', phone: '555-8765', age: 29 }
  17311. ];
  17312. $scope.order = function(predicate, reverse) {
  17313. $scope.friends = orderBy($scope.friends, predicate, reverse);
  17314. };
  17315. $scope.order('-age',false);
  17316. }]);
  17317. </file>
  17318. </example>
  17319. */
  17320. orderByFilter.$inject = ['$parse'];
  17321. function orderByFilter($parse) {
  17322. return function(array, sortPredicate, reverseOrder) {
  17323. if (!(isArrayLike(array))) return array;
  17324. sortPredicate = isArray(sortPredicate) ? sortPredicate : [sortPredicate];
  17325. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  17326. sortPredicate = sortPredicate.map(function(predicate) {
  17327. var descending = false, get = predicate || identity;
  17328. if (isString(predicate)) {
  17329. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  17330. descending = predicate.charAt(0) == '-';
  17331. predicate = predicate.substring(1);
  17332. }
  17333. if (predicate === '') {
  17334. // Effectively no predicate was passed so we compare identity
  17335. return reverseComparator(compare, descending);
  17336. }
  17337. get = $parse(predicate);
  17338. if (get.constant) {
  17339. var key = get();
  17340. return reverseComparator(function(a, b) {
  17341. return compare(a[key], b[key]);
  17342. }, descending);
  17343. }
  17344. }
  17345. return reverseComparator(function(a, b) {
  17346. return compare(get(a),get(b));
  17347. }, descending);
  17348. });
  17349. return slice.call(array).sort(reverseComparator(comparator, reverseOrder));
  17350. function comparator(o1, o2) {
  17351. for (var i = 0; i < sortPredicate.length; i++) {
  17352. var comp = sortPredicate[i](o1, o2);
  17353. if (comp !== 0) return comp;
  17354. }
  17355. return 0;
  17356. }
  17357. function reverseComparator(comp, descending) {
  17358. return descending
  17359. ? function(a, b) {return comp(b,a);}
  17360. : comp;
  17361. }
  17362. function isPrimitive(value) {
  17363. switch (typeof value) {
  17364. case 'number': /* falls through */
  17365. case 'boolean': /* falls through */
  17366. case 'string':
  17367. return true;
  17368. default:
  17369. return false;
  17370. }
  17371. }
  17372. function objectToString(value) {
  17373. if (value === null) return 'null';
  17374. if (typeof value.valueOf === 'function') {
  17375. value = value.valueOf();
  17376. if (isPrimitive(value)) return value;
  17377. }
  17378. if (typeof value.toString === 'function') {
  17379. value = value.toString();
  17380. if (isPrimitive(value)) return value;
  17381. }
  17382. return '';
  17383. }
  17384. function compare(v1, v2) {
  17385. var t1 = typeof v1;
  17386. var t2 = typeof v2;
  17387. if (t1 === t2 && t1 === "object") {
  17388. v1 = objectToString(v1);
  17389. v2 = objectToString(v2);
  17390. }
  17391. if (t1 === t2) {
  17392. if (t1 === "string") {
  17393. v1 = v1.toLowerCase();
  17394. v2 = v2.toLowerCase();
  17395. }
  17396. if (v1 === v2) return 0;
  17397. return v1 < v2 ? -1 : 1;
  17398. } else {
  17399. return t1 < t2 ? -1 : 1;
  17400. }
  17401. }
  17402. };
  17403. }
  17404. function ngDirective(directive) {
  17405. if (isFunction(directive)) {
  17406. directive = {
  17407. link: directive
  17408. };
  17409. }
  17410. directive.restrict = directive.restrict || 'AC';
  17411. return valueFn(directive);
  17412. }
  17413. /**
  17414. * @ngdoc directive
  17415. * @name a
  17416. * @restrict E
  17417. *
  17418. * @description
  17419. * Modifies the default behavior of the html A tag so that the default action is prevented when
  17420. * the href attribute is empty.
  17421. *
  17422. * This change permits the easy creation of action links with the `ngClick` directive
  17423. * without changing the location or causing page reloads, e.g.:
  17424. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  17425. */
  17426. var htmlAnchorDirective = valueFn({
  17427. restrict: 'E',
  17428. compile: function(element, attr) {
  17429. if (!attr.href && !attr.xlinkHref) {
  17430. return function(scope, element) {
  17431. // If the linked element is not an anchor tag anymore, do nothing
  17432. if (element[0].nodeName.toLowerCase() !== 'a') return;
  17433. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  17434. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  17435. 'xlink:href' : 'href';
  17436. element.on('click', function(event) {
  17437. // if we have no href url, then don't navigate anywhere.
  17438. if (!element.attr(href)) {
  17439. event.preventDefault();
  17440. }
  17441. });
  17442. };
  17443. }
  17444. }
  17445. });
  17446. /**
  17447. * @ngdoc directive
  17448. * @name ngHref
  17449. * @restrict A
  17450. * @priority 99
  17451. *
  17452. * @description
  17453. * Using Angular markup like `{{hash}}` in an href attribute will
  17454. * make the link go to the wrong URL if the user clicks it before
  17455. * Angular has a chance to replace the `{{hash}}` markup with its
  17456. * value. Until Angular replaces the markup the link will be broken
  17457. * and will most likely return a 404 error. The `ngHref` directive
  17458. * solves this problem.
  17459. *
  17460. * The wrong way to write it:
  17461. * ```html
  17462. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  17463. * ```
  17464. *
  17465. * The correct way to write it:
  17466. * ```html
  17467. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  17468. * ```
  17469. *
  17470. * @element A
  17471. * @param {template} ngHref any string which can contain `{{}}` markup.
  17472. *
  17473. * @example
  17474. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  17475. * in links and their different behaviors:
  17476. <example>
  17477. <file name="index.html">
  17478. <input ng-model="value" /><br />
  17479. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  17480. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  17481. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  17482. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  17483. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  17484. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  17485. </file>
  17486. <file name="protractor.js" type="protractor">
  17487. it('should execute ng-click but not reload when href without value', function() {
  17488. element(by.id('link-1')).click();
  17489. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  17490. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  17491. });
  17492. it('should execute ng-click but not reload when href empty string', function() {
  17493. element(by.id('link-2')).click();
  17494. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  17495. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  17496. });
  17497. it('should execute ng-click and change url when ng-href specified', function() {
  17498. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  17499. element(by.id('link-3')).click();
  17500. // At this point, we navigate away from an Angular page, so we need
  17501. // to use browser.driver to get the base webdriver.
  17502. browser.wait(function() {
  17503. return browser.driver.getCurrentUrl().then(function(url) {
  17504. return url.match(/\/123$/);
  17505. });
  17506. }, 5000, 'page should navigate to /123');
  17507. });
  17508. it('should execute ng-click but not reload when href empty string and name specified', function() {
  17509. element(by.id('link-4')).click();
  17510. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  17511. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  17512. });
  17513. it('should execute ng-click but not reload when no href but name specified', function() {
  17514. element(by.id('link-5')).click();
  17515. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  17516. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  17517. });
  17518. it('should only change url when only ng-href', function() {
  17519. element(by.model('value')).clear();
  17520. element(by.model('value')).sendKeys('6');
  17521. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  17522. element(by.id('link-6')).click();
  17523. // At this point, we navigate away from an Angular page, so we need
  17524. // to use browser.driver to get the base webdriver.
  17525. browser.wait(function() {
  17526. return browser.driver.getCurrentUrl().then(function(url) {
  17527. return url.match(/\/6$/);
  17528. });
  17529. }, 5000, 'page should navigate to /6');
  17530. });
  17531. </file>
  17532. </example>
  17533. */
  17534. /**
  17535. * @ngdoc directive
  17536. * @name ngSrc
  17537. * @restrict A
  17538. * @priority 99
  17539. *
  17540. * @description
  17541. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  17542. * work right: The browser will fetch from the URL with the literal
  17543. * text `{{hash}}` until Angular replaces the expression inside
  17544. * `{{hash}}`. The `ngSrc` directive solves this problem.
  17545. *
  17546. * The buggy way to write it:
  17547. * ```html
  17548. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  17549. * ```
  17550. *
  17551. * The correct way to write it:
  17552. * ```html
  17553. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  17554. * ```
  17555. *
  17556. * @element IMG
  17557. * @param {template} ngSrc any string which can contain `{{}}` markup.
  17558. */
  17559. /**
  17560. * @ngdoc directive
  17561. * @name ngSrcset
  17562. * @restrict A
  17563. * @priority 99
  17564. *
  17565. * @description
  17566. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  17567. * work right: The browser will fetch from the URL with the literal
  17568. * text `{{hash}}` until Angular replaces the expression inside
  17569. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  17570. *
  17571. * The buggy way to write it:
  17572. * ```html
  17573. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  17574. * ```
  17575. *
  17576. * The correct way to write it:
  17577. * ```html
  17578. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  17579. * ```
  17580. *
  17581. * @element IMG
  17582. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  17583. */
  17584. /**
  17585. * @ngdoc directive
  17586. * @name ngDisabled
  17587. * @restrict A
  17588. * @priority 100
  17589. *
  17590. * @description
  17591. *
  17592. * This directive sets the `disabled` attribute on the element if the
  17593. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  17594. *
  17595. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  17596. * attribute. The following example would make the button enabled on Chrome/Firefox
  17597. * but not on older IEs:
  17598. *
  17599. * ```html
  17600. * <!-- See below for an example of ng-disabled being used correctly -->
  17601. * <div ng-init="isDisabled = false">
  17602. * <button disabled="{{isDisabled}}">Disabled</button>
  17603. * </div>
  17604. * ```
  17605. *
  17606. * This is because the HTML specification does not require browsers to preserve the values of
  17607. * boolean attributes such as `disabled` (Their presence means true and their absence means false.)
  17608. * If we put an Angular interpolation expression into such an attribute then the
  17609. * binding information would be lost when the browser removes the attribute.
  17610. *
  17611. * @example
  17612. <example>
  17613. <file name="index.html">
  17614. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  17615. <button ng-model="button" ng-disabled="checked">Button</button>
  17616. </file>
  17617. <file name="protractor.js" type="protractor">
  17618. it('should toggle button', function() {
  17619. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  17620. element(by.model('checked')).click();
  17621. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  17622. });
  17623. </file>
  17624. </example>
  17625. *
  17626. * @element INPUT
  17627. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  17628. * then the `disabled` attribute will be set on the element
  17629. */
  17630. /**
  17631. * @ngdoc directive
  17632. * @name ngChecked
  17633. * @restrict A
  17634. * @priority 100
  17635. *
  17636. * @description
  17637. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17638. * such as checked. (Their presence means true and their absence means false.)
  17639. * If we put an Angular interpolation expression into such an attribute then the
  17640. * binding information would be lost when the browser removes the attribute.
  17641. * The `ngChecked` directive solves this problem for the `checked` attribute.
  17642. * This complementary directive is not removed by the browser and so provides
  17643. * a permanent reliable place to store the binding information.
  17644. * @example
  17645. <example>
  17646. <file name="index.html">
  17647. <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
  17648. <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
  17649. </file>
  17650. <file name="protractor.js" type="protractor">
  17651. it('should check both checkBoxes', function() {
  17652. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  17653. element(by.model('master')).click();
  17654. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  17655. });
  17656. </file>
  17657. </example>
  17658. *
  17659. * @element INPUT
  17660. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  17661. * then special attribute "checked" will be set on the element
  17662. */
  17663. /**
  17664. * @ngdoc directive
  17665. * @name ngReadonly
  17666. * @restrict A
  17667. * @priority 100
  17668. *
  17669. * @description
  17670. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17671. * such as readonly. (Their presence means true and their absence means false.)
  17672. * If we put an Angular interpolation expression into such an attribute then the
  17673. * binding information would be lost when the browser removes the attribute.
  17674. * The `ngReadonly` directive solves this problem for the `readonly` attribute.
  17675. * This complementary directive is not removed by the browser and so provides
  17676. * a permanent reliable place to store the binding information.
  17677. * @example
  17678. <example>
  17679. <file name="index.html">
  17680. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  17681. <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
  17682. </file>
  17683. <file name="protractor.js" type="protractor">
  17684. it('should toggle readonly attr', function() {
  17685. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  17686. element(by.model('checked')).click();
  17687. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  17688. });
  17689. </file>
  17690. </example>
  17691. *
  17692. * @element INPUT
  17693. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  17694. * then special attribute "readonly" will be set on the element
  17695. */
  17696. /**
  17697. * @ngdoc directive
  17698. * @name ngSelected
  17699. * @restrict A
  17700. * @priority 100
  17701. *
  17702. * @description
  17703. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17704. * such as selected. (Their presence means true and their absence means false.)
  17705. * If we put an Angular interpolation expression into such an attribute then the
  17706. * binding information would be lost when the browser removes the attribute.
  17707. * The `ngSelected` directive solves this problem for the `selected` attribute.
  17708. * This complementary directive is not removed by the browser and so provides
  17709. * a permanent reliable place to store the binding information.
  17710. *
  17711. * @example
  17712. <example>
  17713. <file name="index.html">
  17714. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  17715. <select aria-label="ngSelected demo">
  17716. <option>Hello!</option>
  17717. <option id="greet" ng-selected="selected">Greetings!</option>
  17718. </select>
  17719. </file>
  17720. <file name="protractor.js" type="protractor">
  17721. it('should select Greetings!', function() {
  17722. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  17723. element(by.model('selected')).click();
  17724. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  17725. });
  17726. </file>
  17727. </example>
  17728. *
  17729. * @element OPTION
  17730. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  17731. * then special attribute "selected" will be set on the element
  17732. */
  17733. /**
  17734. * @ngdoc directive
  17735. * @name ngOpen
  17736. * @restrict A
  17737. * @priority 100
  17738. *
  17739. * @description
  17740. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17741. * such as open. (Their presence means true and their absence means false.)
  17742. * If we put an Angular interpolation expression into such an attribute then the
  17743. * binding information would be lost when the browser removes the attribute.
  17744. * The `ngOpen` directive solves this problem for the `open` attribute.
  17745. * This complementary directive is not removed by the browser and so provides
  17746. * a permanent reliable place to store the binding information.
  17747. * @example
  17748. <example>
  17749. <file name="index.html">
  17750. <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
  17751. <details id="details" ng-open="open">
  17752. <summary>Show/Hide me</summary>
  17753. </details>
  17754. </file>
  17755. <file name="protractor.js" type="protractor">
  17756. it('should toggle open', function() {
  17757. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  17758. element(by.model('open')).click();
  17759. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  17760. });
  17761. </file>
  17762. </example>
  17763. *
  17764. * @element DETAILS
  17765. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  17766. * then special attribute "open" will be set on the element
  17767. */
  17768. var ngAttributeAliasDirectives = {};
  17769. // boolean attrs are evaluated
  17770. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  17771. // binding to multiple is not supported
  17772. if (propName == "multiple") return;
  17773. function defaultLinkFn(scope, element, attr) {
  17774. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  17775. attr.$set(attrName, !!value);
  17776. });
  17777. }
  17778. var normalized = directiveNormalize('ng-' + attrName);
  17779. var linkFn = defaultLinkFn;
  17780. if (propName === 'checked') {
  17781. linkFn = function(scope, element, attr) {
  17782. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  17783. if (attr.ngModel !== attr[normalized]) {
  17784. defaultLinkFn(scope, element, attr);
  17785. }
  17786. };
  17787. }
  17788. ngAttributeAliasDirectives[normalized] = function() {
  17789. return {
  17790. restrict: 'A',
  17791. priority: 100,
  17792. link: linkFn
  17793. };
  17794. };
  17795. });
  17796. // aliased input attrs are evaluated
  17797. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  17798. ngAttributeAliasDirectives[ngAttr] = function() {
  17799. return {
  17800. priority: 100,
  17801. link: function(scope, element, attr) {
  17802. //special case ngPattern when a literal regular expression value
  17803. //is used as the expression (this way we don't have to watch anything).
  17804. if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
  17805. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  17806. if (match) {
  17807. attr.$set("ngPattern", new RegExp(match[1], match[2]));
  17808. return;
  17809. }
  17810. }
  17811. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  17812. attr.$set(ngAttr, value);
  17813. });
  17814. }
  17815. };
  17816. };
  17817. });
  17818. // ng-src, ng-srcset, ng-href are interpolated
  17819. forEach(['src', 'srcset', 'href'], function(attrName) {
  17820. var normalized = directiveNormalize('ng-' + attrName);
  17821. ngAttributeAliasDirectives[normalized] = function() {
  17822. return {
  17823. priority: 99, // it needs to run after the attributes are interpolated
  17824. link: function(scope, element, attr) {
  17825. var propName = attrName,
  17826. name = attrName;
  17827. if (attrName === 'href' &&
  17828. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  17829. name = 'xlinkHref';
  17830. attr.$attr[name] = 'xlink:href';
  17831. propName = null;
  17832. }
  17833. attr.$observe(normalized, function(value) {
  17834. if (!value) {
  17835. if (attrName === 'href') {
  17836. attr.$set(name, null);
  17837. }
  17838. return;
  17839. }
  17840. attr.$set(name, value);
  17841. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  17842. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  17843. // to set the property as well to achieve the desired effect.
  17844. // we use attr[attrName] value since $set can sanitize the url.
  17845. if (msie && propName) element.prop(propName, attr[name]);
  17846. });
  17847. }
  17848. };
  17849. };
  17850. });
  17851. /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
  17852. */
  17853. var nullFormCtrl = {
  17854. $addControl: noop,
  17855. $$renameControl: nullFormRenameControl,
  17856. $removeControl: noop,
  17857. $setValidity: noop,
  17858. $setDirty: noop,
  17859. $setPristine: noop,
  17860. $setSubmitted: noop
  17861. },
  17862. SUBMITTED_CLASS = 'ng-submitted';
  17863. function nullFormRenameControl(control, name) {
  17864. control.$name = name;
  17865. }
  17866. /**
  17867. * @ngdoc type
  17868. * @name form.FormController
  17869. *
  17870. * @property {boolean} $pristine True if user has not interacted with the form yet.
  17871. * @property {boolean} $dirty True if user has already interacted with the form.
  17872. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  17873. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  17874. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  17875. *
  17876. * @property {Object} $error Is an object hash, containing references to controls or
  17877. * forms with failing validators, where:
  17878. *
  17879. * - keys are validation tokens (error names),
  17880. * - values are arrays of controls or forms that have a failing validator for given error name.
  17881. *
  17882. * Built-in validation tokens:
  17883. *
  17884. * - `email`
  17885. * - `max`
  17886. * - `maxlength`
  17887. * - `min`
  17888. * - `minlength`
  17889. * - `number`
  17890. * - `pattern`
  17891. * - `required`
  17892. * - `url`
  17893. * - `date`
  17894. * - `datetimelocal`
  17895. * - `time`
  17896. * - `week`
  17897. * - `month`
  17898. *
  17899. * @description
  17900. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  17901. * such as being valid/invalid or dirty/pristine.
  17902. *
  17903. * Each {@link ng.directive:form form} directive creates an instance
  17904. * of `FormController`.
  17905. *
  17906. */
  17907. //asks for $scope to fool the BC controller module
  17908. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  17909. function FormController(element, attrs, $scope, $animate, $interpolate) {
  17910. var form = this,
  17911. controls = [];
  17912. var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl;
  17913. // init state
  17914. form.$error = {};
  17915. form.$$success = {};
  17916. form.$pending = undefined;
  17917. form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
  17918. form.$dirty = false;
  17919. form.$pristine = true;
  17920. form.$valid = true;
  17921. form.$invalid = false;
  17922. form.$submitted = false;
  17923. parentForm.$addControl(form);
  17924. /**
  17925. * @ngdoc method
  17926. * @name form.FormController#$rollbackViewValue
  17927. *
  17928. * @description
  17929. * Rollback all form controls pending updates to the `$modelValue`.
  17930. *
  17931. * Updates may be pending by a debounced event or because the input is waiting for a some future
  17932. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  17933. * a form that uses `ng-model-options` to pend updates.
  17934. */
  17935. form.$rollbackViewValue = function() {
  17936. forEach(controls, function(control) {
  17937. control.$rollbackViewValue();
  17938. });
  17939. };
  17940. /**
  17941. * @ngdoc method
  17942. * @name form.FormController#$commitViewValue
  17943. *
  17944. * @description
  17945. * Commit all form controls pending updates to the `$modelValue`.
  17946. *
  17947. * Updates may be pending by a debounced event or because the input is waiting for a some future
  17948. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  17949. * usually handles calling this in response to input events.
  17950. */
  17951. form.$commitViewValue = function() {
  17952. forEach(controls, function(control) {
  17953. control.$commitViewValue();
  17954. });
  17955. };
  17956. /**
  17957. * @ngdoc method
  17958. * @name form.FormController#$addControl
  17959. *
  17960. * @description
  17961. * Register a control with the form.
  17962. *
  17963. * Input elements using ngModelController do this automatically when they are linked.
  17964. */
  17965. form.$addControl = function(control) {
  17966. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  17967. // and not added to the scope. Now we throw an error.
  17968. assertNotHasOwnProperty(control.$name, 'input');
  17969. controls.push(control);
  17970. if (control.$name) {
  17971. form[control.$name] = control;
  17972. }
  17973. };
  17974. // Private API: rename a form control
  17975. form.$$renameControl = function(control, newName) {
  17976. var oldName = control.$name;
  17977. if (form[oldName] === control) {
  17978. delete form[oldName];
  17979. }
  17980. form[newName] = control;
  17981. control.$name = newName;
  17982. };
  17983. /**
  17984. * @ngdoc method
  17985. * @name form.FormController#$removeControl
  17986. *
  17987. * @description
  17988. * Deregister a control from the form.
  17989. *
  17990. * Input elements using ngModelController do this automatically when they are destroyed.
  17991. */
  17992. form.$removeControl = function(control) {
  17993. if (control.$name && form[control.$name] === control) {
  17994. delete form[control.$name];
  17995. }
  17996. forEach(form.$pending, function(value, name) {
  17997. form.$setValidity(name, null, control);
  17998. });
  17999. forEach(form.$error, function(value, name) {
  18000. form.$setValidity(name, null, control);
  18001. });
  18002. forEach(form.$$success, function(value, name) {
  18003. form.$setValidity(name, null, control);
  18004. });
  18005. arrayRemove(controls, control);
  18006. };
  18007. /**
  18008. * @ngdoc method
  18009. * @name form.FormController#$setValidity
  18010. *
  18011. * @description
  18012. * Sets the validity of a form control.
  18013. *
  18014. * This method will also propagate to parent forms.
  18015. */
  18016. addSetValidityMethod({
  18017. ctrl: this,
  18018. $element: element,
  18019. set: function(object, property, controller) {
  18020. var list = object[property];
  18021. if (!list) {
  18022. object[property] = [controller];
  18023. } else {
  18024. var index = list.indexOf(controller);
  18025. if (index === -1) {
  18026. list.push(controller);
  18027. }
  18028. }
  18029. },
  18030. unset: function(object, property, controller) {
  18031. var list = object[property];
  18032. if (!list) {
  18033. return;
  18034. }
  18035. arrayRemove(list, controller);
  18036. if (list.length === 0) {
  18037. delete object[property];
  18038. }
  18039. },
  18040. parentForm: parentForm,
  18041. $animate: $animate
  18042. });
  18043. /**
  18044. * @ngdoc method
  18045. * @name form.FormController#$setDirty
  18046. *
  18047. * @description
  18048. * Sets the form to a dirty state.
  18049. *
  18050. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  18051. * state (ng-dirty class). This method will also propagate to parent forms.
  18052. */
  18053. form.$setDirty = function() {
  18054. $animate.removeClass(element, PRISTINE_CLASS);
  18055. $animate.addClass(element, DIRTY_CLASS);
  18056. form.$dirty = true;
  18057. form.$pristine = false;
  18058. parentForm.$setDirty();
  18059. };
  18060. /**
  18061. * @ngdoc method
  18062. * @name form.FormController#$setPristine
  18063. *
  18064. * @description
  18065. * Sets the form to its pristine state.
  18066. *
  18067. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  18068. * state (ng-pristine class). This method will also propagate to all the controls contained
  18069. * in this form.
  18070. *
  18071. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  18072. * saving or resetting it.
  18073. */
  18074. form.$setPristine = function() {
  18075. $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  18076. form.$dirty = false;
  18077. form.$pristine = true;
  18078. form.$submitted = false;
  18079. forEach(controls, function(control) {
  18080. control.$setPristine();
  18081. });
  18082. };
  18083. /**
  18084. * @ngdoc method
  18085. * @name form.FormController#$setUntouched
  18086. *
  18087. * @description
  18088. * Sets the form to its untouched state.
  18089. *
  18090. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  18091. * untouched state (ng-untouched class).
  18092. *
  18093. * Setting a form controls back to their untouched state is often useful when setting the form
  18094. * back to its pristine state.
  18095. */
  18096. form.$setUntouched = function() {
  18097. forEach(controls, function(control) {
  18098. control.$setUntouched();
  18099. });
  18100. };
  18101. /**
  18102. * @ngdoc method
  18103. * @name form.FormController#$setSubmitted
  18104. *
  18105. * @description
  18106. * Sets the form to its submitted state.
  18107. */
  18108. form.$setSubmitted = function() {
  18109. $animate.addClass(element, SUBMITTED_CLASS);
  18110. form.$submitted = true;
  18111. parentForm.$setSubmitted();
  18112. };
  18113. }
  18114. /**
  18115. * @ngdoc directive
  18116. * @name ngForm
  18117. * @restrict EAC
  18118. *
  18119. * @description
  18120. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  18121. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  18122. * sub-group of controls needs to be determined.
  18123. *
  18124. * Note: the purpose of `ngForm` is to group controls,
  18125. * but not to be a replacement for the `<form>` tag with all of its capabilities
  18126. * (e.g. posting to the server, ...).
  18127. *
  18128. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  18129. * related scope, under this name.
  18130. *
  18131. */
  18132. /**
  18133. * @ngdoc directive
  18134. * @name form
  18135. * @restrict E
  18136. *
  18137. * @description
  18138. * Directive that instantiates
  18139. * {@link form.FormController FormController}.
  18140. *
  18141. * If the `name` attribute is specified, the form controller is published onto the current scope under
  18142. * this name.
  18143. *
  18144. * # Alias: {@link ng.directive:ngForm `ngForm`}
  18145. *
  18146. * In Angular, forms can be nested. This means that the outer form is valid when all of the child
  18147. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  18148. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
  18149. * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
  18150. * using Angular validation directives in forms that are dynamically generated using the
  18151. * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
  18152. * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
  18153. * `ngForm` directive and nest these in an outer `form` element.
  18154. *
  18155. *
  18156. * # CSS classes
  18157. * - `ng-valid` is set if the form is valid.
  18158. * - `ng-invalid` is set if the form is invalid.
  18159. * - `ng-pristine` is set if the form is pristine.
  18160. * - `ng-dirty` is set if the form is dirty.
  18161. * - `ng-submitted` is set if the form was submitted.
  18162. *
  18163. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  18164. *
  18165. *
  18166. * # Submitting a form and preventing the default action
  18167. *
  18168. * Since the role of forms in client-side Angular applications is different than in classical
  18169. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  18170. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  18171. * to handle the form submission in an application-specific way.
  18172. *
  18173. * For this reason, Angular prevents the default action (form submission to the server) unless the
  18174. * `<form>` element has an `action` attribute specified.
  18175. *
  18176. * You can use one of the following two ways to specify what javascript method should be called when
  18177. * a form is submitted:
  18178. *
  18179. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  18180. * - {@link ng.directive:ngClick ngClick} directive on the first
  18181. * button or input field of type submit (input[type=submit])
  18182. *
  18183. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  18184. * or {@link ng.directive:ngClick ngClick} directives.
  18185. * This is because of the following form submission rules in the HTML specification:
  18186. *
  18187. * - If a form has only one input field then hitting enter in this field triggers form submit
  18188. * (`ngSubmit`)
  18189. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  18190. * doesn't trigger submit
  18191. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  18192. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  18193. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  18194. *
  18195. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  18196. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  18197. * to have access to the updated model.
  18198. *
  18199. * ## Animation Hooks
  18200. *
  18201. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  18202. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  18203. * other validations that are performed within the form. Animations in ngForm are similar to how
  18204. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  18205. * as JS animations.
  18206. *
  18207. * The following example shows a simple way to utilize CSS transitions to style a form element
  18208. * that has been rendered as invalid after it has been validated:
  18209. *
  18210. * <pre>
  18211. * //be sure to include ngAnimate as a module to hook into more
  18212. * //advanced animations
  18213. * .my-form {
  18214. * transition:0.5s linear all;
  18215. * background: white;
  18216. * }
  18217. * .my-form.ng-invalid {
  18218. * background: red;
  18219. * color:white;
  18220. * }
  18221. * </pre>
  18222. *
  18223. * @example
  18224. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  18225. <file name="index.html">
  18226. <script>
  18227. angular.module('formExample', [])
  18228. .controller('FormController', ['$scope', function($scope) {
  18229. $scope.userType = 'guest';
  18230. }]);
  18231. </script>
  18232. <style>
  18233. .my-form {
  18234. -webkit-transition:all linear 0.5s;
  18235. transition:all linear 0.5s;
  18236. background: transparent;
  18237. }
  18238. .my-form.ng-invalid {
  18239. background: red;
  18240. }
  18241. </style>
  18242. <form name="myForm" ng-controller="FormController" class="my-form">
  18243. userType: <input name="input" ng-model="userType" required>
  18244. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  18245. <code>userType = {{userType}}</code><br>
  18246. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  18247. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  18248. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  18249. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  18250. </form>
  18251. </file>
  18252. <file name="protractor.js" type="protractor">
  18253. it('should initialize to model', function() {
  18254. var userType = element(by.binding('userType'));
  18255. var valid = element(by.binding('myForm.input.$valid'));
  18256. expect(userType.getText()).toContain('guest');
  18257. expect(valid.getText()).toContain('true');
  18258. });
  18259. it('should be invalid if empty', function() {
  18260. var userType = element(by.binding('userType'));
  18261. var valid = element(by.binding('myForm.input.$valid'));
  18262. var userInput = element(by.model('userType'));
  18263. userInput.clear();
  18264. userInput.sendKeys('');
  18265. expect(userType.getText()).toEqual('userType =');
  18266. expect(valid.getText()).toContain('false');
  18267. });
  18268. </file>
  18269. </example>
  18270. *
  18271. * @param {string=} name Name of the form. If specified, the form controller will be published into
  18272. * related scope, under this name.
  18273. */
  18274. var formDirectiveFactory = function(isNgForm) {
  18275. return ['$timeout', function($timeout) {
  18276. var formDirective = {
  18277. name: 'form',
  18278. restrict: isNgForm ? 'EAC' : 'E',
  18279. controller: FormController,
  18280. compile: function ngFormCompile(formElement, attr) {
  18281. // Setup initial state of the control
  18282. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  18283. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  18284. return {
  18285. pre: function ngFormPreLink(scope, formElement, attr, controller) {
  18286. // if `action` attr is not present on the form, prevent the default action (submission)
  18287. if (!('action' in attr)) {
  18288. // we can't use jq events because if a form is destroyed during submission the default
  18289. // action is not prevented. see #1238
  18290. //
  18291. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  18292. // page reload if the form was destroyed by submission of the form via a click handler
  18293. // on a button in the form. Looks like an IE9 specific bug.
  18294. var handleFormSubmission = function(event) {
  18295. scope.$apply(function() {
  18296. controller.$commitViewValue();
  18297. controller.$setSubmitted();
  18298. });
  18299. event.preventDefault();
  18300. };
  18301. addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  18302. // unregister the preventDefault listener so that we don't not leak memory but in a
  18303. // way that will achieve the prevention of the default action.
  18304. formElement.on('$destroy', function() {
  18305. $timeout(function() {
  18306. removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  18307. }, 0, false);
  18308. });
  18309. }
  18310. var parentFormCtrl = controller.$$parentForm;
  18311. if (nameAttr) {
  18312. setter(scope, controller.$name, controller, controller.$name);
  18313. attr.$observe(nameAttr, function(newValue) {
  18314. if (controller.$name === newValue) return;
  18315. setter(scope, controller.$name, undefined, controller.$name);
  18316. parentFormCtrl.$$renameControl(controller, newValue);
  18317. setter(scope, controller.$name, controller, controller.$name);
  18318. });
  18319. }
  18320. formElement.on('$destroy', function() {
  18321. parentFormCtrl.$removeControl(controller);
  18322. if (nameAttr) {
  18323. setter(scope, attr[nameAttr], undefined, controller.$name);
  18324. }
  18325. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  18326. });
  18327. }
  18328. };
  18329. }
  18330. };
  18331. return formDirective;
  18332. }];
  18333. };
  18334. var formDirective = formDirectiveFactory();
  18335. var ngFormDirective = formDirectiveFactory(true);
  18336. /* global VALID_CLASS: false,
  18337. INVALID_CLASS: false,
  18338. PRISTINE_CLASS: false,
  18339. DIRTY_CLASS: false,
  18340. UNTOUCHED_CLASS: false,
  18341. TOUCHED_CLASS: false,
  18342. $ngModelMinErr: false,
  18343. */
  18344. // Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  18345. 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)/;
  18346. var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
  18347. 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;
  18348. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
  18349. var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
  18350. var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  18351. var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
  18352. var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
  18353. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  18354. var inputType = {
  18355. /**
  18356. * @ngdoc input
  18357. * @name input[text]
  18358. *
  18359. * @description
  18360. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  18361. *
  18362. *
  18363. * @param {string} ngModel Assignable angular expression to data-bind to.
  18364. * @param {string=} name Property name of the form under which the control is published.
  18365. * @param {string=} required Adds `required` validation error key if the value is not entered.
  18366. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18367. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18368. * `required` when you want to data-bind to the `required` attribute.
  18369. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  18370. * minlength.
  18371. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  18372. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  18373. * any length.
  18374. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  18375. * that contains the regular expression body that will be converted to a regular expression
  18376. * as in the ngPattern directive.
  18377. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  18378. * a RegExp found by evaluating the Angular expression given in the attribute value.
  18379. * If the expression evaluates to a RegExp object, then this is used directly.
  18380. * If the expression evaluates to a string, then it will be converted to a RegExp
  18381. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  18382. * `new RegExp('^abc$')`.<br />
  18383. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  18384. * start at the index of the last search's match, thus not taking the whole input value into
  18385. * account.
  18386. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18387. * interaction with the input element.
  18388. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  18389. * This parameter is ignored for input[type=password] controls, which will never trim the
  18390. * input.
  18391. *
  18392. * @example
  18393. <example name="text-input-directive" module="textInputExample">
  18394. <file name="index.html">
  18395. <script>
  18396. angular.module('textInputExample', [])
  18397. .controller('ExampleController', ['$scope', function($scope) {
  18398. $scope.example = {
  18399. text: 'guest',
  18400. word: /^\s*\w*\s*$/
  18401. };
  18402. }]);
  18403. </script>
  18404. <form name="myForm" ng-controller="ExampleController">
  18405. <label>Single word:
  18406. <input type="text" name="input" ng-model="example.text"
  18407. ng-pattern="example.word" required ng-trim="false">
  18408. </label>
  18409. <div role="alert">
  18410. <span class="error" ng-show="myForm.input.$error.required">
  18411. Required!</span>
  18412. <span class="error" ng-show="myForm.input.$error.pattern">
  18413. Single word only!</span>
  18414. </div>
  18415. <tt>text = {{example.text}}</tt><br/>
  18416. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18417. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18418. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18419. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18420. </form>
  18421. </file>
  18422. <file name="protractor.js" type="protractor">
  18423. var text = element(by.binding('example.text'));
  18424. var valid = element(by.binding('myForm.input.$valid'));
  18425. var input = element(by.model('example.text'));
  18426. it('should initialize to model', function() {
  18427. expect(text.getText()).toContain('guest');
  18428. expect(valid.getText()).toContain('true');
  18429. });
  18430. it('should be invalid if empty', function() {
  18431. input.clear();
  18432. input.sendKeys('');
  18433. expect(text.getText()).toEqual('text =');
  18434. expect(valid.getText()).toContain('false');
  18435. });
  18436. it('should be invalid if multi word', function() {
  18437. input.clear();
  18438. input.sendKeys('hello world');
  18439. expect(valid.getText()).toContain('false');
  18440. });
  18441. </file>
  18442. </example>
  18443. */
  18444. 'text': textInputType,
  18445. /**
  18446. * @ngdoc input
  18447. * @name input[date]
  18448. *
  18449. * @description
  18450. * Input with date validation and transformation. In browsers that do not yet support
  18451. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  18452. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  18453. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  18454. * expected input format via a placeholder or label.
  18455. *
  18456. * The model must always be a Date object, otherwise Angular will throw an error.
  18457. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18458. *
  18459. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18460. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18461. *
  18462. * @param {string} ngModel Assignable angular expression to data-bind to.
  18463. * @param {string=} name Property name of the form under which the control is published.
  18464. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  18465. * valid ISO date string (yyyy-MM-dd).
  18466. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  18467. * a valid ISO date string (yyyy-MM-dd).
  18468. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18469. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18470. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18471. * `required` when you want to data-bind to the `required` attribute.
  18472. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18473. * interaction with the input element.
  18474. *
  18475. * @example
  18476. <example name="date-input-directive" module="dateInputExample">
  18477. <file name="index.html">
  18478. <script>
  18479. angular.module('dateInputExample', [])
  18480. .controller('DateController', ['$scope', function($scope) {
  18481. $scope.example = {
  18482. value: new Date(2013, 9, 22)
  18483. };
  18484. }]);
  18485. </script>
  18486. <form name="myForm" ng-controller="DateController as dateCtrl">
  18487. <label for="exampleInput">Pick a date in 2013:</label>
  18488. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  18489. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  18490. <div role="alert">
  18491. <span class="error" ng-show="myForm.input.$error.required">
  18492. Required!</span>
  18493. <span class="error" ng-show="myForm.input.$error.date">
  18494. Not a valid date!</span>
  18495. </div>
  18496. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  18497. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18498. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18499. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18500. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18501. </form>
  18502. </file>
  18503. <file name="protractor.js" type="protractor">
  18504. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  18505. var valid = element(by.binding('myForm.input.$valid'));
  18506. var input = element(by.model('example.value'));
  18507. // currently protractor/webdriver does not support
  18508. // sending keys to all known HTML5 input controls
  18509. // for various browsers (see https://github.com/angular/protractor/issues/562).
  18510. function setInput(val) {
  18511. // set the value of the element and force validation.
  18512. var scr = "var ipt = document.getElementById('exampleInput'); " +
  18513. "ipt.value = '" + val + "';" +
  18514. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  18515. browser.executeScript(scr);
  18516. }
  18517. it('should initialize to model', function() {
  18518. expect(value.getText()).toContain('2013-10-22');
  18519. expect(valid.getText()).toContain('myForm.input.$valid = true');
  18520. });
  18521. it('should be invalid if empty', function() {
  18522. setInput('');
  18523. expect(value.getText()).toEqual('value =');
  18524. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18525. });
  18526. it('should be invalid if over max', function() {
  18527. setInput('2015-01-01');
  18528. expect(value.getText()).toContain('');
  18529. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18530. });
  18531. </file>
  18532. </example>
  18533. */
  18534. 'date': createDateInputType('date', DATE_REGEXP,
  18535. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  18536. 'yyyy-MM-dd'),
  18537. /**
  18538. * @ngdoc input
  18539. * @name input[datetime-local]
  18540. *
  18541. * @description
  18542. * Input with datetime validation and transformation. In browsers that do not yet support
  18543. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  18544. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  18545. *
  18546. * The model must always be a Date object, otherwise Angular will throw an error.
  18547. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18548. *
  18549. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18550. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18551. *
  18552. * @param {string} ngModel Assignable angular expression to data-bind to.
  18553. * @param {string=} name Property name of the form under which the control is published.
  18554. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  18555. * valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  18556. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  18557. * a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  18558. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18559. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18560. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18561. * `required` when you want to data-bind to the `required` attribute.
  18562. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18563. * interaction with the input element.
  18564. *
  18565. * @example
  18566. <example name="datetimelocal-input-directive" module="dateExample">
  18567. <file name="index.html">
  18568. <script>
  18569. angular.module('dateExample', [])
  18570. .controller('DateController', ['$scope', function($scope) {
  18571. $scope.example = {
  18572. value: new Date(2010, 11, 28, 14, 57)
  18573. };
  18574. }]);
  18575. </script>
  18576. <form name="myForm" ng-controller="DateController as dateCtrl">
  18577. <label for="exampleInput">Pick a date between in 2013:</label>
  18578. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  18579. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  18580. <div role="alert">
  18581. <span class="error" ng-show="myForm.input.$error.required">
  18582. Required!</span>
  18583. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  18584. Not a valid date!</span>
  18585. </div>
  18586. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  18587. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18588. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18589. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18590. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18591. </form>
  18592. </file>
  18593. <file name="protractor.js" type="protractor">
  18594. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  18595. var valid = element(by.binding('myForm.input.$valid'));
  18596. var input = element(by.model('example.value'));
  18597. // currently protractor/webdriver does not support
  18598. // sending keys to all known HTML5 input controls
  18599. // for various browsers (https://github.com/angular/protractor/issues/562).
  18600. function setInput(val) {
  18601. // set the value of the element and force validation.
  18602. var scr = "var ipt = document.getElementById('exampleInput'); " +
  18603. "ipt.value = '" + val + "';" +
  18604. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  18605. browser.executeScript(scr);
  18606. }
  18607. it('should initialize to model', function() {
  18608. expect(value.getText()).toContain('2010-12-28T14:57:00');
  18609. expect(valid.getText()).toContain('myForm.input.$valid = true');
  18610. });
  18611. it('should be invalid if empty', function() {
  18612. setInput('');
  18613. expect(value.getText()).toEqual('value =');
  18614. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18615. });
  18616. it('should be invalid if over max', function() {
  18617. setInput('2015-01-01T23:59:00');
  18618. expect(value.getText()).toContain('');
  18619. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18620. });
  18621. </file>
  18622. </example>
  18623. */
  18624. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  18625. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  18626. 'yyyy-MM-ddTHH:mm:ss.sss'),
  18627. /**
  18628. * @ngdoc input
  18629. * @name input[time]
  18630. *
  18631. * @description
  18632. * Input with time validation and transformation. In browsers that do not yet support
  18633. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  18634. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  18635. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  18636. *
  18637. * The model must always be a Date object, otherwise Angular will throw an error.
  18638. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18639. *
  18640. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18641. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18642. *
  18643. * @param {string} ngModel Assignable angular expression to data-bind to.
  18644. * @param {string=} name Property name of the form under which the control is published.
  18645. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  18646. * valid ISO time format (HH:mm:ss).
  18647. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a
  18648. * valid ISO time format (HH:mm:ss).
  18649. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18650. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18651. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18652. * `required` when you want to data-bind to the `required` attribute.
  18653. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18654. * interaction with the input element.
  18655. *
  18656. * @example
  18657. <example name="time-input-directive" module="timeExample">
  18658. <file name="index.html">
  18659. <script>
  18660. angular.module('timeExample', [])
  18661. .controller('DateController', ['$scope', function($scope) {
  18662. $scope.example = {
  18663. value: new Date(1970, 0, 1, 14, 57, 0)
  18664. };
  18665. }]);
  18666. </script>
  18667. <form name="myForm" ng-controller="DateController as dateCtrl">
  18668. <label for="exampleInput">Pick a between 8am and 5pm:</label>
  18669. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  18670. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  18671. <div role="alert">
  18672. <span class="error" ng-show="myForm.input.$error.required">
  18673. Required!</span>
  18674. <span class="error" ng-show="myForm.input.$error.time">
  18675. Not a valid date!</span>
  18676. </div>
  18677. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  18678. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18679. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18680. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18681. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18682. </form>
  18683. </file>
  18684. <file name="protractor.js" type="protractor">
  18685. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  18686. var valid = element(by.binding('myForm.input.$valid'));
  18687. var input = element(by.model('example.value'));
  18688. // currently protractor/webdriver does not support
  18689. // sending keys to all known HTML5 input controls
  18690. // for various browsers (https://github.com/angular/protractor/issues/562).
  18691. function setInput(val) {
  18692. // set the value of the element and force validation.
  18693. var scr = "var ipt = document.getElementById('exampleInput'); " +
  18694. "ipt.value = '" + val + "';" +
  18695. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  18696. browser.executeScript(scr);
  18697. }
  18698. it('should initialize to model', function() {
  18699. expect(value.getText()).toContain('14:57:00');
  18700. expect(valid.getText()).toContain('myForm.input.$valid = true');
  18701. });
  18702. it('should be invalid if empty', function() {
  18703. setInput('');
  18704. expect(value.getText()).toEqual('value =');
  18705. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18706. });
  18707. it('should be invalid if over max', function() {
  18708. setInput('23:59:00');
  18709. expect(value.getText()).toContain('');
  18710. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18711. });
  18712. </file>
  18713. </example>
  18714. */
  18715. 'time': createDateInputType('time', TIME_REGEXP,
  18716. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  18717. 'HH:mm:ss.sss'),
  18718. /**
  18719. * @ngdoc input
  18720. * @name input[week]
  18721. *
  18722. * @description
  18723. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  18724. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  18725. * week format (yyyy-W##), for example: `2013-W02`.
  18726. *
  18727. * The model must always be a Date object, otherwise Angular will throw an error.
  18728. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18729. *
  18730. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18731. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18732. *
  18733. * @param {string} ngModel Assignable angular expression to data-bind to.
  18734. * @param {string=} name Property name of the form under which the control is published.
  18735. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  18736. * valid ISO week format (yyyy-W##).
  18737. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  18738. * a valid ISO week format (yyyy-W##).
  18739. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18740. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18741. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18742. * `required` when you want to data-bind to the `required` attribute.
  18743. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18744. * interaction with the input element.
  18745. *
  18746. * @example
  18747. <example name="week-input-directive" module="weekExample">
  18748. <file name="index.html">
  18749. <script>
  18750. angular.module('weekExample', [])
  18751. .controller('DateController', ['$scope', function($scope) {
  18752. $scope.example = {
  18753. value: new Date(2013, 0, 3)
  18754. };
  18755. }]);
  18756. </script>
  18757. <form name="myForm" ng-controller="DateController as dateCtrl">
  18758. <label>Pick a date between in 2013:
  18759. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  18760. placeholder="YYYY-W##" min="2012-W32"
  18761. max="2013-W52" required />
  18762. </label>
  18763. <div role="alert">
  18764. <span class="error" ng-show="myForm.input.$error.required">
  18765. Required!</span>
  18766. <span class="error" ng-show="myForm.input.$error.week">
  18767. Not a valid date!</span>
  18768. </div>
  18769. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  18770. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18771. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18772. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18773. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18774. </form>
  18775. </file>
  18776. <file name="protractor.js" type="protractor">
  18777. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  18778. var valid = element(by.binding('myForm.input.$valid'));
  18779. var input = element(by.model('example.value'));
  18780. // currently protractor/webdriver does not support
  18781. // sending keys to all known HTML5 input controls
  18782. // for various browsers (https://github.com/angular/protractor/issues/562).
  18783. function setInput(val) {
  18784. // set the value of the element and force validation.
  18785. var scr = "var ipt = document.getElementById('exampleInput'); " +
  18786. "ipt.value = '" + val + "';" +
  18787. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  18788. browser.executeScript(scr);
  18789. }
  18790. it('should initialize to model', function() {
  18791. expect(value.getText()).toContain('2013-W01');
  18792. expect(valid.getText()).toContain('myForm.input.$valid = true');
  18793. });
  18794. it('should be invalid if empty', function() {
  18795. setInput('');
  18796. expect(value.getText()).toEqual('value =');
  18797. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18798. });
  18799. it('should be invalid if over max', function() {
  18800. setInput('2015-W01');
  18801. expect(value.getText()).toContain('');
  18802. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18803. });
  18804. </file>
  18805. </example>
  18806. */
  18807. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  18808. /**
  18809. * @ngdoc input
  18810. * @name input[month]
  18811. *
  18812. * @description
  18813. * Input with month validation and transformation. In browsers that do not yet support
  18814. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  18815. * month format (yyyy-MM), for example: `2009-01`.
  18816. *
  18817. * The model must always be a Date object, otherwise Angular will throw an error.
  18818. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18819. * If the model is not set to the first of the month, the next view to model update will set it
  18820. * to the first of the month.
  18821. *
  18822. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18823. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18824. *
  18825. * @param {string} ngModel Assignable angular expression to data-bind to.
  18826. * @param {string=} name Property name of the form under which the control is published.
  18827. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be
  18828. * a valid ISO month format (yyyy-MM).
  18829. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must
  18830. * be a valid ISO month format (yyyy-MM).
  18831. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18832. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18833. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18834. * `required` when you want to data-bind to the `required` attribute.
  18835. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18836. * interaction with the input element.
  18837. *
  18838. * @example
  18839. <example name="month-input-directive" module="monthExample">
  18840. <file name="index.html">
  18841. <script>
  18842. angular.module('monthExample', [])
  18843. .controller('DateController', ['$scope', function($scope) {
  18844. $scope.example = {
  18845. value: new Date(2013, 9, 1)
  18846. };
  18847. }]);
  18848. </script>
  18849. <form name="myForm" ng-controller="DateController as dateCtrl">
  18850. <label for="exampleInput">Pick a month in 2013:</label>
  18851. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  18852. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  18853. <div role="alert">
  18854. <span class="error" ng-show="myForm.input.$error.required">
  18855. Required!</span>
  18856. <span class="error" ng-show="myForm.input.$error.month">
  18857. Not a valid month!</span>
  18858. </div>
  18859. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  18860. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18861. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18862. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18863. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18864. </form>
  18865. </file>
  18866. <file name="protractor.js" type="protractor">
  18867. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  18868. var valid = element(by.binding('myForm.input.$valid'));
  18869. var input = element(by.model('example.value'));
  18870. // currently protractor/webdriver does not support
  18871. // sending keys to all known HTML5 input controls
  18872. // for various browsers (https://github.com/angular/protractor/issues/562).
  18873. function setInput(val) {
  18874. // set the value of the element and force validation.
  18875. var scr = "var ipt = document.getElementById('exampleInput'); " +
  18876. "ipt.value = '" + val + "';" +
  18877. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  18878. browser.executeScript(scr);
  18879. }
  18880. it('should initialize to model', function() {
  18881. expect(value.getText()).toContain('2013-10');
  18882. expect(valid.getText()).toContain('myForm.input.$valid = true');
  18883. });
  18884. it('should be invalid if empty', function() {
  18885. setInput('');
  18886. expect(value.getText()).toEqual('value =');
  18887. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18888. });
  18889. it('should be invalid if over max', function() {
  18890. setInput('2015-01');
  18891. expect(value.getText()).toContain('');
  18892. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18893. });
  18894. </file>
  18895. </example>
  18896. */
  18897. 'month': createDateInputType('month', MONTH_REGEXP,
  18898. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  18899. 'yyyy-MM'),
  18900. /**
  18901. * @ngdoc input
  18902. * @name input[number]
  18903. *
  18904. * @description
  18905. * Text input with number validation and transformation. Sets the `number` validation
  18906. * error if not a valid number.
  18907. *
  18908. * <div class="alert alert-warning">
  18909. * The model must always be of type `number` otherwise Angular will throw an error.
  18910. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  18911. * error docs for more information and an example of how to convert your model if necessary.
  18912. * </div>
  18913. *
  18914. * @param {string} ngModel Assignable angular expression to data-bind to.
  18915. * @param {string=} name Property name of the form under which the control is published.
  18916. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  18917. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  18918. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18919. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18920. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18921. * `required` when you want to data-bind to the `required` attribute.
  18922. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  18923. * minlength.
  18924. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  18925. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  18926. * any length.
  18927. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  18928. * that contains the regular expression body that will be converted to a regular expression
  18929. * as in the ngPattern directive.
  18930. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  18931. * a RegExp found by evaluating the Angular expression given in the attribute value.
  18932. * If the expression evaluates to a RegExp object, then this is used directly.
  18933. * If the expression evaluates to a string, then it will be converted to a RegExp
  18934. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  18935. * `new RegExp('^abc$')`.<br />
  18936. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  18937. * start at the index of the last search's match, thus not taking the whole input value into
  18938. * account.
  18939. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18940. * interaction with the input element.
  18941. *
  18942. * @example
  18943. <example name="number-input-directive" module="numberExample">
  18944. <file name="index.html">
  18945. <script>
  18946. angular.module('numberExample', [])
  18947. .controller('ExampleController', ['$scope', function($scope) {
  18948. $scope.example = {
  18949. value: 12
  18950. };
  18951. }]);
  18952. </script>
  18953. <form name="myForm" ng-controller="ExampleController">
  18954. <label>Number:
  18955. <input type="number" name="input" ng-model="example.value"
  18956. min="0" max="99" required>
  18957. </label>
  18958. <div role="alert">
  18959. <span class="error" ng-show="myForm.input.$error.required">
  18960. Required!</span>
  18961. <span class="error" ng-show="myForm.input.$error.number">
  18962. Not valid number!</span>
  18963. </div>
  18964. <tt>value = {{example.value}}</tt><br/>
  18965. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18966. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18967. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18968. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18969. </form>
  18970. </file>
  18971. <file name="protractor.js" type="protractor">
  18972. var value = element(by.binding('example.value'));
  18973. var valid = element(by.binding('myForm.input.$valid'));
  18974. var input = element(by.model('example.value'));
  18975. it('should initialize to model', function() {
  18976. expect(value.getText()).toContain('12');
  18977. expect(valid.getText()).toContain('true');
  18978. });
  18979. it('should be invalid if empty', function() {
  18980. input.clear();
  18981. input.sendKeys('');
  18982. expect(value.getText()).toEqual('value =');
  18983. expect(valid.getText()).toContain('false');
  18984. });
  18985. it('should be invalid if over max', function() {
  18986. input.clear();
  18987. input.sendKeys('123');
  18988. expect(value.getText()).toEqual('value =');
  18989. expect(valid.getText()).toContain('false');
  18990. });
  18991. </file>
  18992. </example>
  18993. */
  18994. 'number': numberInputType,
  18995. /**
  18996. * @ngdoc input
  18997. * @name input[url]
  18998. *
  18999. * @description
  19000. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  19001. * valid URL.
  19002. *
  19003. * <div class="alert alert-warning">
  19004. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  19005. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  19006. * the built-in validators (see the {@link guide/forms Forms guide})
  19007. * </div>
  19008. *
  19009. * @param {string} ngModel Assignable angular expression to data-bind to.
  19010. * @param {string=} name Property name of the form under which the control is published.
  19011. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19012. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19013. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19014. * `required` when you want to data-bind to the `required` attribute.
  19015. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19016. * minlength.
  19017. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19018. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19019. * any length.
  19020. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19021. * that contains the regular expression body that will be converted to a regular expression
  19022. * as in the ngPattern directive.
  19023. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19024. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19025. * If the expression evaluates to a RegExp object, then this is used directly.
  19026. * If the expression evaluates to a string, then it will be converted to a RegExp
  19027. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19028. * `new RegExp('^abc$')`.<br />
  19029. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19030. * start at the index of the last search's match, thus not taking the whole input value into
  19031. * account.
  19032. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19033. * interaction with the input element.
  19034. *
  19035. * @example
  19036. <example name="url-input-directive" module="urlExample">
  19037. <file name="index.html">
  19038. <script>
  19039. angular.module('urlExample', [])
  19040. .controller('ExampleController', ['$scope', function($scope) {
  19041. $scope.url = {
  19042. text: 'http://google.com'
  19043. };
  19044. }]);
  19045. </script>
  19046. <form name="myForm" ng-controller="ExampleController">
  19047. <label>URL:
  19048. <input type="url" name="input" ng-model="url.text" required>
  19049. <label>
  19050. <div role="alert">
  19051. <span class="error" ng-show="myForm.input.$error.required">
  19052. Required!</span>
  19053. <span class="error" ng-show="myForm.input.$error.url">
  19054. Not valid url!</span>
  19055. </div>
  19056. <tt>text = {{url.text}}</tt><br/>
  19057. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19058. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19059. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19060. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19061. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  19062. </form>
  19063. </file>
  19064. <file name="protractor.js" type="protractor">
  19065. var text = element(by.binding('url.text'));
  19066. var valid = element(by.binding('myForm.input.$valid'));
  19067. var input = element(by.model('url.text'));
  19068. it('should initialize to model', function() {
  19069. expect(text.getText()).toContain('http://google.com');
  19070. expect(valid.getText()).toContain('true');
  19071. });
  19072. it('should be invalid if empty', function() {
  19073. input.clear();
  19074. input.sendKeys('');
  19075. expect(text.getText()).toEqual('text =');
  19076. expect(valid.getText()).toContain('false');
  19077. });
  19078. it('should be invalid if not url', function() {
  19079. input.clear();
  19080. input.sendKeys('box');
  19081. expect(valid.getText()).toContain('false');
  19082. });
  19083. </file>
  19084. </example>
  19085. */
  19086. 'url': urlInputType,
  19087. /**
  19088. * @ngdoc input
  19089. * @name input[email]
  19090. *
  19091. * @description
  19092. * Text input with email validation. Sets the `email` validation error key if not a valid email
  19093. * address.
  19094. *
  19095. * <div class="alert alert-warning">
  19096. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  19097. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  19098. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  19099. * </div>
  19100. *
  19101. * @param {string} ngModel Assignable angular expression to data-bind to.
  19102. * @param {string=} name Property name of the form under which the control is published.
  19103. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19104. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19105. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19106. * `required` when you want to data-bind to the `required` attribute.
  19107. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19108. * minlength.
  19109. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19110. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19111. * any length.
  19112. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19113. * that contains the regular expression body that will be converted to a regular expression
  19114. * as in the ngPattern directive.
  19115. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19116. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19117. * If the expression evaluates to a RegExp object, then this is used directly.
  19118. * If the expression evaluates to a string, then it will be converted to a RegExp
  19119. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19120. * `new RegExp('^abc$')`.<br />
  19121. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19122. * start at the index of the last search's match, thus not taking the whole input value into
  19123. * account.
  19124. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19125. * interaction with the input element.
  19126. *
  19127. * @example
  19128. <example name="email-input-directive" module="emailExample">
  19129. <file name="index.html">
  19130. <script>
  19131. angular.module('emailExample', [])
  19132. .controller('ExampleController', ['$scope', function($scope) {
  19133. $scope.email = {
  19134. text: 'me@example.com'
  19135. };
  19136. }]);
  19137. </script>
  19138. <form name="myForm" ng-controller="ExampleController">
  19139. <label>Email:
  19140. <input type="email" name="input" ng-model="email.text" required>
  19141. </label>
  19142. <div role="alert">
  19143. <span class="error" ng-show="myForm.input.$error.required">
  19144. Required!</span>
  19145. <span class="error" ng-show="myForm.input.$error.email">
  19146. Not valid email!</span>
  19147. </div>
  19148. <tt>text = {{email.text}}</tt><br/>
  19149. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19150. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19151. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19152. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19153. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  19154. </form>
  19155. </file>
  19156. <file name="protractor.js" type="protractor">
  19157. var text = element(by.binding('email.text'));
  19158. var valid = element(by.binding('myForm.input.$valid'));
  19159. var input = element(by.model('email.text'));
  19160. it('should initialize to model', function() {
  19161. expect(text.getText()).toContain('me@example.com');
  19162. expect(valid.getText()).toContain('true');
  19163. });
  19164. it('should be invalid if empty', function() {
  19165. input.clear();
  19166. input.sendKeys('');
  19167. expect(text.getText()).toEqual('text =');
  19168. expect(valid.getText()).toContain('false');
  19169. });
  19170. it('should be invalid if not email', function() {
  19171. input.clear();
  19172. input.sendKeys('xxx');
  19173. expect(valid.getText()).toContain('false');
  19174. });
  19175. </file>
  19176. </example>
  19177. */
  19178. 'email': emailInputType,
  19179. /**
  19180. * @ngdoc input
  19181. * @name input[radio]
  19182. *
  19183. * @description
  19184. * HTML radio button.
  19185. *
  19186. * @param {string} ngModel Assignable angular expression to data-bind to.
  19187. * @param {string} value The value to which the expression should be set when selected.
  19188. * @param {string=} name Property name of the form under which the control is published.
  19189. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19190. * interaction with the input element.
  19191. * @param {string} ngValue Angular expression which sets the value to which the expression should
  19192. * be set when selected.
  19193. *
  19194. * @example
  19195. <example name="radio-input-directive" module="radioExample">
  19196. <file name="index.html">
  19197. <script>
  19198. angular.module('radioExample', [])
  19199. .controller('ExampleController', ['$scope', function($scope) {
  19200. $scope.color = {
  19201. name: 'blue'
  19202. };
  19203. $scope.specialValue = {
  19204. "id": "12345",
  19205. "value": "green"
  19206. };
  19207. }]);
  19208. </script>
  19209. <form name="myForm" ng-controller="ExampleController">
  19210. <label>
  19211. <input type="radio" ng-model="color.name" value="red">
  19212. Red
  19213. </label><br/>
  19214. <label>
  19215. <input type="radio" ng-model="color.name" ng-value="specialValue">
  19216. Green
  19217. </label><br/>
  19218. <label>
  19219. <input type="radio" ng-model="color.name" value="blue">
  19220. Blue
  19221. </label><br/>
  19222. <tt>color = {{color.name | json}}</tt><br/>
  19223. </form>
  19224. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  19225. </file>
  19226. <file name="protractor.js" type="protractor">
  19227. it('should change state', function() {
  19228. var color = element(by.binding('color.name'));
  19229. expect(color.getText()).toContain('blue');
  19230. element.all(by.model('color.name')).get(0).click();
  19231. expect(color.getText()).toContain('red');
  19232. });
  19233. </file>
  19234. </example>
  19235. */
  19236. 'radio': radioInputType,
  19237. /**
  19238. * @ngdoc input
  19239. * @name input[checkbox]
  19240. *
  19241. * @description
  19242. * HTML checkbox.
  19243. *
  19244. * @param {string} ngModel Assignable angular expression to data-bind to.
  19245. * @param {string=} name Property name of the form under which the control is published.
  19246. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  19247. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  19248. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19249. * interaction with the input element.
  19250. *
  19251. * @example
  19252. <example name="checkbox-input-directive" module="checkboxExample">
  19253. <file name="index.html">
  19254. <script>
  19255. angular.module('checkboxExample', [])
  19256. .controller('ExampleController', ['$scope', function($scope) {
  19257. $scope.checkboxModel = {
  19258. value1 : true,
  19259. value2 : 'YES'
  19260. };
  19261. }]);
  19262. </script>
  19263. <form name="myForm" ng-controller="ExampleController">
  19264. <label>Value1:
  19265. <input type="checkbox" ng-model="checkboxModel.value1">
  19266. </label><br/>
  19267. <label>Value2:
  19268. <input type="checkbox" ng-model="checkboxModel.value2"
  19269. ng-true-value="'YES'" ng-false-value="'NO'">
  19270. </label><br/>
  19271. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  19272. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  19273. </form>
  19274. </file>
  19275. <file name="protractor.js" type="protractor">
  19276. it('should change state', function() {
  19277. var value1 = element(by.binding('checkboxModel.value1'));
  19278. var value2 = element(by.binding('checkboxModel.value2'));
  19279. expect(value1.getText()).toContain('true');
  19280. expect(value2.getText()).toContain('YES');
  19281. element(by.model('checkboxModel.value1')).click();
  19282. element(by.model('checkboxModel.value2')).click();
  19283. expect(value1.getText()).toContain('false');
  19284. expect(value2.getText()).toContain('NO');
  19285. });
  19286. </file>
  19287. </example>
  19288. */
  19289. 'checkbox': checkboxInputType,
  19290. 'hidden': noop,
  19291. 'button': noop,
  19292. 'submit': noop,
  19293. 'reset': noop,
  19294. 'file': noop
  19295. };
  19296. function stringBasedInputType(ctrl) {
  19297. ctrl.$formatters.push(function(value) {
  19298. return ctrl.$isEmpty(value) ? value : value.toString();
  19299. });
  19300. }
  19301. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19302. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19303. stringBasedInputType(ctrl);
  19304. }
  19305. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19306. var type = lowercase(element[0].type);
  19307. // In composition mode, users are still inputing intermediate text buffer,
  19308. // hold the listener until composition is done.
  19309. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  19310. if (!$sniffer.android) {
  19311. var composing = false;
  19312. element.on('compositionstart', function(data) {
  19313. composing = true;
  19314. });
  19315. element.on('compositionend', function() {
  19316. composing = false;
  19317. listener();
  19318. });
  19319. }
  19320. var listener = function(ev) {
  19321. if (timeout) {
  19322. $browser.defer.cancel(timeout);
  19323. timeout = null;
  19324. }
  19325. if (composing) return;
  19326. var value = element.val(),
  19327. event = ev && ev.type;
  19328. // By default we will trim the value
  19329. // If the attribute ng-trim exists we will avoid trimming
  19330. // If input type is 'password', the value is never trimmed
  19331. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  19332. value = trim(value);
  19333. }
  19334. // If a control is suffering from bad input (due to native validators), browsers discard its
  19335. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  19336. // control's value is the same empty value twice in a row.
  19337. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  19338. ctrl.$setViewValue(value, event);
  19339. }
  19340. };
  19341. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  19342. // input event on backspace, delete or cut
  19343. if ($sniffer.hasEvent('input')) {
  19344. element.on('input', listener);
  19345. } else {
  19346. var timeout;
  19347. var deferListener = function(ev, input, origValue) {
  19348. if (!timeout) {
  19349. timeout = $browser.defer(function() {
  19350. timeout = null;
  19351. if (!input || input.value !== origValue) {
  19352. listener(ev);
  19353. }
  19354. });
  19355. }
  19356. };
  19357. element.on('keydown', function(event) {
  19358. var key = event.keyCode;
  19359. // ignore
  19360. // command modifiers arrows
  19361. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  19362. deferListener(event, this, this.value);
  19363. });
  19364. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  19365. if ($sniffer.hasEvent('paste')) {
  19366. element.on('paste cut', deferListener);
  19367. }
  19368. }
  19369. // if user paste into input using mouse on older browser
  19370. // or form autocomplete on newer browser, we need "change" event to catch it
  19371. element.on('change', listener);
  19372. ctrl.$render = function() {
  19373. element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
  19374. };
  19375. }
  19376. function weekParser(isoWeek, existingDate) {
  19377. if (isDate(isoWeek)) {
  19378. return isoWeek;
  19379. }
  19380. if (isString(isoWeek)) {
  19381. WEEK_REGEXP.lastIndex = 0;
  19382. var parts = WEEK_REGEXP.exec(isoWeek);
  19383. if (parts) {
  19384. var year = +parts[1],
  19385. week = +parts[2],
  19386. hours = 0,
  19387. minutes = 0,
  19388. seconds = 0,
  19389. milliseconds = 0,
  19390. firstThurs = getFirstThursdayOfYear(year),
  19391. addDays = (week - 1) * 7;
  19392. if (existingDate) {
  19393. hours = existingDate.getHours();
  19394. minutes = existingDate.getMinutes();
  19395. seconds = existingDate.getSeconds();
  19396. milliseconds = existingDate.getMilliseconds();
  19397. }
  19398. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  19399. }
  19400. }
  19401. return NaN;
  19402. }
  19403. function createDateParser(regexp, mapping) {
  19404. return function(iso, date) {
  19405. var parts, map;
  19406. if (isDate(iso)) {
  19407. return iso;
  19408. }
  19409. if (isString(iso)) {
  19410. // When a date is JSON'ified to wraps itself inside of an extra
  19411. // set of double quotes. This makes the date parsing code unable
  19412. // to match the date string and parse it as a date.
  19413. if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
  19414. iso = iso.substring(1, iso.length - 1);
  19415. }
  19416. if (ISO_DATE_REGEXP.test(iso)) {
  19417. return new Date(iso);
  19418. }
  19419. regexp.lastIndex = 0;
  19420. parts = regexp.exec(iso);
  19421. if (parts) {
  19422. parts.shift();
  19423. if (date) {
  19424. map = {
  19425. yyyy: date.getFullYear(),
  19426. MM: date.getMonth() + 1,
  19427. dd: date.getDate(),
  19428. HH: date.getHours(),
  19429. mm: date.getMinutes(),
  19430. ss: date.getSeconds(),
  19431. sss: date.getMilliseconds() / 1000
  19432. };
  19433. } else {
  19434. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  19435. }
  19436. forEach(parts, function(part, index) {
  19437. if (index < mapping.length) {
  19438. map[mapping[index]] = +part;
  19439. }
  19440. });
  19441. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  19442. }
  19443. }
  19444. return NaN;
  19445. };
  19446. }
  19447. function createDateInputType(type, regexp, parseDate, format) {
  19448. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  19449. badInputChecker(scope, element, attr, ctrl);
  19450. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19451. var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
  19452. var previousDate;
  19453. ctrl.$$parserName = type;
  19454. ctrl.$parsers.push(function(value) {
  19455. if (ctrl.$isEmpty(value)) return null;
  19456. if (regexp.test(value)) {
  19457. // Note: We cannot read ctrl.$modelValue, as there might be a different
  19458. // parser/formatter in the processing chain so that the model
  19459. // contains some different data format!
  19460. var parsedDate = parseDate(value, previousDate);
  19461. if (timezone) {
  19462. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  19463. }
  19464. return parsedDate;
  19465. }
  19466. return undefined;
  19467. });
  19468. ctrl.$formatters.push(function(value) {
  19469. if (value && !isDate(value)) {
  19470. throw $ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  19471. }
  19472. if (isValidDate(value)) {
  19473. previousDate = value;
  19474. if (previousDate && timezone) {
  19475. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  19476. }
  19477. return $filter('date')(value, format, timezone);
  19478. } else {
  19479. previousDate = null;
  19480. return '';
  19481. }
  19482. });
  19483. if (isDefined(attr.min) || attr.ngMin) {
  19484. var minVal;
  19485. ctrl.$validators.min = function(value) {
  19486. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  19487. };
  19488. attr.$observe('min', function(val) {
  19489. minVal = parseObservedDateValue(val);
  19490. ctrl.$validate();
  19491. });
  19492. }
  19493. if (isDefined(attr.max) || attr.ngMax) {
  19494. var maxVal;
  19495. ctrl.$validators.max = function(value) {
  19496. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  19497. };
  19498. attr.$observe('max', function(val) {
  19499. maxVal = parseObservedDateValue(val);
  19500. ctrl.$validate();
  19501. });
  19502. }
  19503. function isValidDate(value) {
  19504. // Invalid Date: getTime() returns NaN
  19505. return value && !(value.getTime && value.getTime() !== value.getTime());
  19506. }
  19507. function parseObservedDateValue(val) {
  19508. return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined;
  19509. }
  19510. };
  19511. }
  19512. function badInputChecker(scope, element, attr, ctrl) {
  19513. var node = element[0];
  19514. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  19515. if (nativeValidation) {
  19516. ctrl.$parsers.push(function(value) {
  19517. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  19518. // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):
  19519. // - also sets validity.badInput (should only be validity.typeMismatch).
  19520. // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)
  19521. // - can ignore this case as we can still read out the erroneous email...
  19522. return validity.badInput && !validity.typeMismatch ? undefined : value;
  19523. });
  19524. }
  19525. }
  19526. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19527. badInputChecker(scope, element, attr, ctrl);
  19528. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19529. ctrl.$$parserName = 'number';
  19530. ctrl.$parsers.push(function(value) {
  19531. if (ctrl.$isEmpty(value)) return null;
  19532. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  19533. return undefined;
  19534. });
  19535. ctrl.$formatters.push(function(value) {
  19536. if (!ctrl.$isEmpty(value)) {
  19537. if (!isNumber(value)) {
  19538. throw $ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  19539. }
  19540. value = value.toString();
  19541. }
  19542. return value;
  19543. });
  19544. if (isDefined(attr.min) || attr.ngMin) {
  19545. var minVal;
  19546. ctrl.$validators.min = function(value) {
  19547. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  19548. };
  19549. attr.$observe('min', function(val) {
  19550. if (isDefined(val) && !isNumber(val)) {
  19551. val = parseFloat(val, 10);
  19552. }
  19553. minVal = isNumber(val) && !isNaN(val) ? val : undefined;
  19554. // TODO(matsko): implement validateLater to reduce number of validations
  19555. ctrl.$validate();
  19556. });
  19557. }
  19558. if (isDefined(attr.max) || attr.ngMax) {
  19559. var maxVal;
  19560. ctrl.$validators.max = function(value) {
  19561. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  19562. };
  19563. attr.$observe('max', function(val) {
  19564. if (isDefined(val) && !isNumber(val)) {
  19565. val = parseFloat(val, 10);
  19566. }
  19567. maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
  19568. // TODO(matsko): implement validateLater to reduce number of validations
  19569. ctrl.$validate();
  19570. });
  19571. }
  19572. }
  19573. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19574. // Note: no badInputChecker here by purpose as `url` is only a validation
  19575. // in browsers, i.e. we can always read out input.value even if it is not valid!
  19576. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19577. stringBasedInputType(ctrl);
  19578. ctrl.$$parserName = 'url';
  19579. ctrl.$validators.url = function(modelValue, viewValue) {
  19580. var value = modelValue || viewValue;
  19581. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  19582. };
  19583. }
  19584. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19585. // Note: no badInputChecker here by purpose as `url` is only a validation
  19586. // in browsers, i.e. we can always read out input.value even if it is not valid!
  19587. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19588. stringBasedInputType(ctrl);
  19589. ctrl.$$parserName = 'email';
  19590. ctrl.$validators.email = function(modelValue, viewValue) {
  19591. var value = modelValue || viewValue;
  19592. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  19593. };
  19594. }
  19595. function radioInputType(scope, element, attr, ctrl) {
  19596. // make the name unique, if not defined
  19597. if (isUndefined(attr.name)) {
  19598. element.attr('name', nextUid());
  19599. }
  19600. var listener = function(ev) {
  19601. if (element[0].checked) {
  19602. ctrl.$setViewValue(attr.value, ev && ev.type);
  19603. }
  19604. };
  19605. element.on('click', listener);
  19606. ctrl.$render = function() {
  19607. var value = attr.value;
  19608. element[0].checked = (value == ctrl.$viewValue);
  19609. };
  19610. attr.$observe('value', ctrl.$render);
  19611. }
  19612. function parseConstantExpr($parse, context, name, expression, fallback) {
  19613. var parseFn;
  19614. if (isDefined(expression)) {
  19615. parseFn = $parse(expression);
  19616. if (!parseFn.constant) {
  19617. throw minErr('ngModel')('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  19618. '`{1}`.', name, expression);
  19619. }
  19620. return parseFn(context);
  19621. }
  19622. return fallback;
  19623. }
  19624. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  19625. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  19626. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  19627. var listener = function(ev) {
  19628. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  19629. };
  19630. element.on('click', listener);
  19631. ctrl.$render = function() {
  19632. element[0].checked = ctrl.$viewValue;
  19633. };
  19634. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  19635. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  19636. // it to a boolean.
  19637. ctrl.$isEmpty = function(value) {
  19638. return value === false;
  19639. };
  19640. ctrl.$formatters.push(function(value) {
  19641. return equals(value, trueValue);
  19642. });
  19643. ctrl.$parsers.push(function(value) {
  19644. return value ? trueValue : falseValue;
  19645. });
  19646. }
  19647. /**
  19648. * @ngdoc directive
  19649. * @name textarea
  19650. * @restrict E
  19651. *
  19652. * @description
  19653. * HTML textarea element control with angular data-binding. The data-binding and validation
  19654. * properties of this element are exactly the same as those of the
  19655. * {@link ng.directive:input input element}.
  19656. *
  19657. * @param {string} ngModel Assignable angular expression to data-bind to.
  19658. * @param {string=} name Property name of the form under which the control is published.
  19659. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19660. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19661. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19662. * `required` when you want to data-bind to the `required` attribute.
  19663. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19664. * minlength.
  19665. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19666. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  19667. * length.
  19668. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19669. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19670. * If the expression evaluates to a RegExp object, then this is used directly.
  19671. * If the expression evaluates to a string, then it will be converted to a RegExp
  19672. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19673. * `new RegExp('^abc$')`.<br />
  19674. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19675. * start at the index of the last search's match, thus not taking the whole input value into
  19676. * account.
  19677. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19678. * interaction with the input element.
  19679. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  19680. */
  19681. /**
  19682. * @ngdoc directive
  19683. * @name input
  19684. * @restrict E
  19685. *
  19686. * @description
  19687. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  19688. * input state control, and validation.
  19689. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  19690. *
  19691. * <div class="alert alert-warning">
  19692. * **Note:** Not every feature offered is available for all input types.
  19693. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  19694. * </div>
  19695. *
  19696. * @param {string} ngModel Assignable angular expression to data-bind to.
  19697. * @param {string=} name Property name of the form under which the control is published.
  19698. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19699. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  19700. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19701. * minlength.
  19702. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19703. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  19704. * length.
  19705. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19706. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19707. * If the expression evaluates to a RegExp object, then this is used directly.
  19708. * If the expression evaluates to a string, then it will be converted to a RegExp
  19709. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19710. * `new RegExp('^abc$')`.<br />
  19711. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19712. * start at the index of the last search's match, thus not taking the whole input value into
  19713. * account.
  19714. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19715. * interaction with the input element.
  19716. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  19717. * This parameter is ignored for input[type=password] controls, which will never trim the
  19718. * input.
  19719. *
  19720. * @example
  19721. <example name="input-directive" module="inputExample">
  19722. <file name="index.html">
  19723. <script>
  19724. angular.module('inputExample', [])
  19725. .controller('ExampleController', ['$scope', function($scope) {
  19726. $scope.user = {name: 'guest', last: 'visitor'};
  19727. }]);
  19728. </script>
  19729. <div ng-controller="ExampleController">
  19730. <form name="myForm">
  19731. <label>
  19732. User name:
  19733. <input type="text" name="userName" ng-model="user.name" required>
  19734. </label>
  19735. <div role="alert">
  19736. <span class="error" ng-show="myForm.userName.$error.required">
  19737. Required!</span>
  19738. </div>
  19739. <label>
  19740. Last name:
  19741. <input type="text" name="lastName" ng-model="user.last"
  19742. ng-minlength="3" ng-maxlength="10">
  19743. </label>
  19744. <div role="alert">
  19745. <span class="error" ng-show="myForm.lastName.$error.minlength">
  19746. Too short!</span>
  19747. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  19748. Too long!</span>
  19749. </div>
  19750. </form>
  19751. <hr>
  19752. <tt>user = {{user}}</tt><br/>
  19753. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  19754. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  19755. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  19756. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  19757. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19758. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19759. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  19760. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  19761. </div>
  19762. </file>
  19763. <file name="protractor.js" type="protractor">
  19764. var user = element(by.exactBinding('user'));
  19765. var userNameValid = element(by.binding('myForm.userName.$valid'));
  19766. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  19767. var lastNameError = element(by.binding('myForm.lastName.$error'));
  19768. var formValid = element(by.binding('myForm.$valid'));
  19769. var userNameInput = element(by.model('user.name'));
  19770. var userLastInput = element(by.model('user.last'));
  19771. it('should initialize to model', function() {
  19772. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  19773. expect(userNameValid.getText()).toContain('true');
  19774. expect(formValid.getText()).toContain('true');
  19775. });
  19776. it('should be invalid if empty when required', function() {
  19777. userNameInput.clear();
  19778. userNameInput.sendKeys('');
  19779. expect(user.getText()).toContain('{"last":"visitor"}');
  19780. expect(userNameValid.getText()).toContain('false');
  19781. expect(formValid.getText()).toContain('false');
  19782. });
  19783. it('should be valid if empty when min length is set', function() {
  19784. userLastInput.clear();
  19785. userLastInput.sendKeys('');
  19786. expect(user.getText()).toContain('{"name":"guest","last":""}');
  19787. expect(lastNameValid.getText()).toContain('true');
  19788. expect(formValid.getText()).toContain('true');
  19789. });
  19790. it('should be invalid if less than required min length', function() {
  19791. userLastInput.clear();
  19792. userLastInput.sendKeys('xx');
  19793. expect(user.getText()).toContain('{"name":"guest"}');
  19794. expect(lastNameValid.getText()).toContain('false');
  19795. expect(lastNameError.getText()).toContain('minlength');
  19796. expect(formValid.getText()).toContain('false');
  19797. });
  19798. it('should be invalid if longer than max length', function() {
  19799. userLastInput.clear();
  19800. userLastInput.sendKeys('some ridiculously long name');
  19801. expect(user.getText()).toContain('{"name":"guest"}');
  19802. expect(lastNameValid.getText()).toContain('false');
  19803. expect(lastNameError.getText()).toContain('maxlength');
  19804. expect(formValid.getText()).toContain('false');
  19805. });
  19806. </file>
  19807. </example>
  19808. */
  19809. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  19810. function($browser, $sniffer, $filter, $parse) {
  19811. return {
  19812. restrict: 'E',
  19813. require: ['?ngModel'],
  19814. link: {
  19815. pre: function(scope, element, attr, ctrls) {
  19816. if (ctrls[0]) {
  19817. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  19818. $browser, $filter, $parse);
  19819. }
  19820. }
  19821. }
  19822. };
  19823. }];
  19824. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  19825. /**
  19826. * @ngdoc directive
  19827. * @name ngValue
  19828. *
  19829. * @description
  19830. * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
  19831. * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
  19832. * the bound value.
  19833. *
  19834. * `ngValue` is useful when dynamically generating lists of radio buttons using
  19835. * {@link ngRepeat `ngRepeat`}, as shown below.
  19836. *
  19837. * Likewise, `ngValue` can be used to generate `<option>` elements for
  19838. * the {@link select `select`} element. In that case however, only strings are supported
  19839. * for the `value `attribute, so the resulting `ngModel` will always be a string.
  19840. * Support for `select` models with non-string values is available via `ngOptions`.
  19841. *
  19842. * @element input
  19843. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  19844. * of the `input` element
  19845. *
  19846. * @example
  19847. <example name="ngValue-directive" module="valueExample">
  19848. <file name="index.html">
  19849. <script>
  19850. angular.module('valueExample', [])
  19851. .controller('ExampleController', ['$scope', function($scope) {
  19852. $scope.names = ['pizza', 'unicorns', 'robots'];
  19853. $scope.my = { favorite: 'unicorns' };
  19854. }]);
  19855. </script>
  19856. <form ng-controller="ExampleController">
  19857. <h2>Which is your favorite?</h2>
  19858. <label ng-repeat="name in names" for="{{name}}">
  19859. {{name}}
  19860. <input type="radio"
  19861. ng-model="my.favorite"
  19862. ng-value="name"
  19863. id="{{name}}"
  19864. name="favorite">
  19865. </label>
  19866. <div>You chose {{my.favorite}}</div>
  19867. </form>
  19868. </file>
  19869. <file name="protractor.js" type="protractor">
  19870. var favorite = element(by.binding('my.favorite'));
  19871. it('should initialize to model', function() {
  19872. expect(favorite.getText()).toContain('unicorns');
  19873. });
  19874. it('should bind the values to the inputs', function() {
  19875. element.all(by.model('my.favorite')).get(0).click();
  19876. expect(favorite.getText()).toContain('pizza');
  19877. });
  19878. </file>
  19879. </example>
  19880. */
  19881. var ngValueDirective = function() {
  19882. return {
  19883. restrict: 'A',
  19884. priority: 100,
  19885. compile: function(tpl, tplAttr) {
  19886. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  19887. return function ngValueConstantLink(scope, elm, attr) {
  19888. attr.$set('value', scope.$eval(attr.ngValue));
  19889. };
  19890. } else {
  19891. return function ngValueLink(scope, elm, attr) {
  19892. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  19893. attr.$set('value', value);
  19894. });
  19895. };
  19896. }
  19897. }
  19898. };
  19899. };
  19900. /**
  19901. * @ngdoc directive
  19902. * @name ngBind
  19903. * @restrict AC
  19904. *
  19905. * @description
  19906. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  19907. * with the value of a given expression, and to update the text content when the value of that
  19908. * expression changes.
  19909. *
  19910. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  19911. * `{{ expression }}` which is similar but less verbose.
  19912. *
  19913. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  19914. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  19915. * element attribute, it makes the bindings invisible to the user while the page is loading.
  19916. *
  19917. * An alternative solution to this problem would be using the
  19918. * {@link ng.directive:ngCloak ngCloak} directive.
  19919. *
  19920. *
  19921. * @element ANY
  19922. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  19923. *
  19924. * @example
  19925. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  19926. <example module="bindExample">
  19927. <file name="index.html">
  19928. <script>
  19929. angular.module('bindExample', [])
  19930. .controller('ExampleController', ['$scope', function($scope) {
  19931. $scope.name = 'Whirled';
  19932. }]);
  19933. </script>
  19934. <div ng-controller="ExampleController">
  19935. <label>Enter name: <input type="text" ng-model="name"></label><br>
  19936. Hello <span ng-bind="name"></span>!
  19937. </div>
  19938. </file>
  19939. <file name="protractor.js" type="protractor">
  19940. it('should check ng-bind', function() {
  19941. var nameInput = element(by.model('name'));
  19942. expect(element(by.binding('name')).getText()).toBe('Whirled');
  19943. nameInput.clear();
  19944. nameInput.sendKeys('world');
  19945. expect(element(by.binding('name')).getText()).toBe('world');
  19946. });
  19947. </file>
  19948. </example>
  19949. */
  19950. var ngBindDirective = ['$compile', function($compile) {
  19951. return {
  19952. restrict: 'AC',
  19953. compile: function ngBindCompile(templateElement) {
  19954. $compile.$$addBindingClass(templateElement);
  19955. return function ngBindLink(scope, element, attr) {
  19956. $compile.$$addBindingInfo(element, attr.ngBind);
  19957. element = element[0];
  19958. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  19959. element.textContent = value === undefined ? '' : value;
  19960. });
  19961. };
  19962. }
  19963. };
  19964. }];
  19965. /**
  19966. * @ngdoc directive
  19967. * @name ngBindTemplate
  19968. *
  19969. * @description
  19970. * The `ngBindTemplate` directive specifies that the element
  19971. * text content should be replaced with the interpolation of the template
  19972. * in the `ngBindTemplate` attribute.
  19973. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  19974. * expressions. This directive is needed since some HTML elements
  19975. * (such as TITLE and OPTION) cannot contain SPAN elements.
  19976. *
  19977. * @element ANY
  19978. * @param {string} ngBindTemplate template of form
  19979. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  19980. *
  19981. * @example
  19982. * Try it here: enter text in text box and watch the greeting change.
  19983. <example module="bindExample">
  19984. <file name="index.html">
  19985. <script>
  19986. angular.module('bindExample', [])
  19987. .controller('ExampleController', ['$scope', function($scope) {
  19988. $scope.salutation = 'Hello';
  19989. $scope.name = 'World';
  19990. }]);
  19991. </script>
  19992. <div ng-controller="ExampleController">
  19993. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  19994. <label>Name: <input type="text" ng-model="name"></label><br>
  19995. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  19996. </div>
  19997. </file>
  19998. <file name="protractor.js" type="protractor">
  19999. it('should check ng-bind', function() {
  20000. var salutationElem = element(by.binding('salutation'));
  20001. var salutationInput = element(by.model('salutation'));
  20002. var nameInput = element(by.model('name'));
  20003. expect(salutationElem.getText()).toBe('Hello World!');
  20004. salutationInput.clear();
  20005. salutationInput.sendKeys('Greetings');
  20006. nameInput.clear();
  20007. nameInput.sendKeys('user');
  20008. expect(salutationElem.getText()).toBe('Greetings user!');
  20009. });
  20010. </file>
  20011. </example>
  20012. */
  20013. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  20014. return {
  20015. compile: function ngBindTemplateCompile(templateElement) {
  20016. $compile.$$addBindingClass(templateElement);
  20017. return function ngBindTemplateLink(scope, element, attr) {
  20018. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  20019. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  20020. element = element[0];
  20021. attr.$observe('ngBindTemplate', function(value) {
  20022. element.textContent = value === undefined ? '' : value;
  20023. });
  20024. };
  20025. }
  20026. };
  20027. }];
  20028. /**
  20029. * @ngdoc directive
  20030. * @name ngBindHtml
  20031. *
  20032. * @description
  20033. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  20034. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  20035. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  20036. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  20037. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  20038. *
  20039. * You may also bypass sanitization for values you know are safe. To do so, bind to
  20040. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  20041. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  20042. *
  20043. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  20044. * will have an exception (instead of an exploit.)
  20045. *
  20046. * @element ANY
  20047. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  20048. *
  20049. * @example
  20050. <example module="bindHtmlExample" deps="angular-sanitize.js">
  20051. <file name="index.html">
  20052. <div ng-controller="ExampleController">
  20053. <p ng-bind-html="myHTML"></p>
  20054. </div>
  20055. </file>
  20056. <file name="script.js">
  20057. angular.module('bindHtmlExample', ['ngSanitize'])
  20058. .controller('ExampleController', ['$scope', function($scope) {
  20059. $scope.myHTML =
  20060. 'I am an <code>HTML</code>string with ' +
  20061. '<a href="#">links!</a> and other <em>stuff</em>';
  20062. }]);
  20063. </file>
  20064. <file name="protractor.js" type="protractor">
  20065. it('should check ng-bind-html', function() {
  20066. expect(element(by.binding('myHTML')).getText()).toBe(
  20067. 'I am an HTMLstring with links! and other stuff');
  20068. });
  20069. </file>
  20070. </example>
  20071. */
  20072. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  20073. return {
  20074. restrict: 'A',
  20075. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  20076. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  20077. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
  20078. return (value || '').toString();
  20079. });
  20080. $compile.$$addBindingClass(tElement);
  20081. return function ngBindHtmlLink(scope, element, attr) {
  20082. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  20083. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  20084. // we re-evaluate the expr because we want a TrustedValueHolderType
  20085. // for $sce, not a string
  20086. element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
  20087. });
  20088. };
  20089. }
  20090. };
  20091. }];
  20092. /**
  20093. * @ngdoc directive
  20094. * @name ngChange
  20095. *
  20096. * @description
  20097. * Evaluate the given expression when the user changes the input.
  20098. * The expression is evaluated immediately, unlike the JavaScript onchange event
  20099. * which only triggers at the end of a change (usually, when the user leaves the
  20100. * form element or presses the return key).
  20101. *
  20102. * The `ngChange` expression is only evaluated when a change in the input value causes
  20103. * a new value to be committed to the model.
  20104. *
  20105. * It will not be evaluated:
  20106. * * if the value returned from the `$parsers` transformation pipeline has not changed
  20107. * * if the input has continued to be invalid since the model will stay `null`
  20108. * * if the model is changed programmatically and not by a change to the input value
  20109. *
  20110. *
  20111. * Note, this directive requires `ngModel` to be present.
  20112. *
  20113. * @element input
  20114. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  20115. * in input value.
  20116. *
  20117. * @example
  20118. * <example name="ngChange-directive" module="changeExample">
  20119. * <file name="index.html">
  20120. * <script>
  20121. * angular.module('changeExample', [])
  20122. * .controller('ExampleController', ['$scope', function($scope) {
  20123. * $scope.counter = 0;
  20124. * $scope.change = function() {
  20125. * $scope.counter++;
  20126. * };
  20127. * }]);
  20128. * </script>
  20129. * <div ng-controller="ExampleController">
  20130. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  20131. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  20132. * <label for="ng-change-example2">Confirmed</label><br />
  20133. * <tt>debug = {{confirmed}}</tt><br/>
  20134. * <tt>counter = {{counter}}</tt><br/>
  20135. * </div>
  20136. * </file>
  20137. * <file name="protractor.js" type="protractor">
  20138. * var counter = element(by.binding('counter'));
  20139. * var debug = element(by.binding('confirmed'));
  20140. *
  20141. * it('should evaluate the expression if changing from view', function() {
  20142. * expect(counter.getText()).toContain('0');
  20143. *
  20144. * element(by.id('ng-change-example1')).click();
  20145. *
  20146. * expect(counter.getText()).toContain('1');
  20147. * expect(debug.getText()).toContain('true');
  20148. * });
  20149. *
  20150. * it('should not evaluate the expression if changing from model', function() {
  20151. * element(by.id('ng-change-example2')).click();
  20152. * expect(counter.getText()).toContain('0');
  20153. * expect(debug.getText()).toContain('true');
  20154. * });
  20155. * </file>
  20156. * </example>
  20157. */
  20158. var ngChangeDirective = valueFn({
  20159. restrict: 'A',
  20160. require: 'ngModel',
  20161. link: function(scope, element, attr, ctrl) {
  20162. ctrl.$viewChangeListeners.push(function() {
  20163. scope.$eval(attr.ngChange);
  20164. });
  20165. }
  20166. });
  20167. function classDirective(name, selector) {
  20168. name = 'ngClass' + name;
  20169. return ['$animate', function($animate) {
  20170. return {
  20171. restrict: 'AC',
  20172. link: function(scope, element, attr) {
  20173. var oldVal;
  20174. scope.$watch(attr[name], ngClassWatchAction, true);
  20175. attr.$observe('class', function(value) {
  20176. ngClassWatchAction(scope.$eval(attr[name]));
  20177. });
  20178. if (name !== 'ngClass') {
  20179. scope.$watch('$index', function($index, old$index) {
  20180. // jshint bitwise: false
  20181. var mod = $index & 1;
  20182. if (mod !== (old$index & 1)) {
  20183. var classes = arrayClasses(scope.$eval(attr[name]));
  20184. mod === selector ?
  20185. addClasses(classes) :
  20186. removeClasses(classes);
  20187. }
  20188. });
  20189. }
  20190. function addClasses(classes) {
  20191. var newClasses = digestClassCounts(classes, 1);
  20192. attr.$addClass(newClasses);
  20193. }
  20194. function removeClasses(classes) {
  20195. var newClasses = digestClassCounts(classes, -1);
  20196. attr.$removeClass(newClasses);
  20197. }
  20198. function digestClassCounts(classes, count) {
  20199. // Use createMap() to prevent class assumptions involving property
  20200. // names in Object.prototype
  20201. var classCounts = element.data('$classCounts') || createMap();
  20202. var classesToUpdate = [];
  20203. forEach(classes, function(className) {
  20204. if (count > 0 || classCounts[className]) {
  20205. classCounts[className] = (classCounts[className] || 0) + count;
  20206. if (classCounts[className] === +(count > 0)) {
  20207. classesToUpdate.push(className);
  20208. }
  20209. }
  20210. });
  20211. element.data('$classCounts', classCounts);
  20212. return classesToUpdate.join(' ');
  20213. }
  20214. function updateClasses(oldClasses, newClasses) {
  20215. var toAdd = arrayDifference(newClasses, oldClasses);
  20216. var toRemove = arrayDifference(oldClasses, newClasses);
  20217. toAdd = digestClassCounts(toAdd, 1);
  20218. toRemove = digestClassCounts(toRemove, -1);
  20219. if (toAdd && toAdd.length) {
  20220. $animate.addClass(element, toAdd);
  20221. }
  20222. if (toRemove && toRemove.length) {
  20223. $animate.removeClass(element, toRemove);
  20224. }
  20225. }
  20226. function ngClassWatchAction(newVal) {
  20227. if (selector === true || scope.$index % 2 === selector) {
  20228. var newClasses = arrayClasses(newVal || []);
  20229. if (!oldVal) {
  20230. addClasses(newClasses);
  20231. } else if (!equals(newVal,oldVal)) {
  20232. var oldClasses = arrayClasses(oldVal);
  20233. updateClasses(oldClasses, newClasses);
  20234. }
  20235. }
  20236. oldVal = shallowCopy(newVal);
  20237. }
  20238. }
  20239. };
  20240. function arrayDifference(tokens1, tokens2) {
  20241. var values = [];
  20242. outer:
  20243. for (var i = 0; i < tokens1.length; i++) {
  20244. var token = tokens1[i];
  20245. for (var j = 0; j < tokens2.length; j++) {
  20246. if (token == tokens2[j]) continue outer;
  20247. }
  20248. values.push(token);
  20249. }
  20250. return values;
  20251. }
  20252. function arrayClasses(classVal) {
  20253. var classes = [];
  20254. if (isArray(classVal)) {
  20255. forEach(classVal, function(v) {
  20256. classes = classes.concat(arrayClasses(v));
  20257. });
  20258. return classes;
  20259. } else if (isString(classVal)) {
  20260. return classVal.split(' ');
  20261. } else if (isObject(classVal)) {
  20262. forEach(classVal, function(v, k) {
  20263. if (v) {
  20264. classes = classes.concat(k.split(' '));
  20265. }
  20266. });
  20267. return classes;
  20268. }
  20269. return classVal;
  20270. }
  20271. }];
  20272. }
  20273. /**
  20274. * @ngdoc directive
  20275. * @name ngClass
  20276. * @restrict AC
  20277. *
  20278. * @description
  20279. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  20280. * an expression that represents all classes to be added.
  20281. *
  20282. * The directive operates in three different ways, depending on which of three types the expression
  20283. * evaluates to:
  20284. *
  20285. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  20286. * names.
  20287. *
  20288. * 2. If the expression evaluates to an object, then for each key-value pair of the
  20289. * object with a truthy value the corresponding key is used as a class name.
  20290. *
  20291. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  20292. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  20293. * to give you more control over what CSS classes appear. See the code below for an example of this.
  20294. *
  20295. *
  20296. * The directive won't add duplicate classes if a particular class was already set.
  20297. *
  20298. * When the expression changes, the previously added classes are removed and only then are the
  20299. * new classes added.
  20300. *
  20301. * @animations
  20302. * **add** - happens just before the class is applied to the elements
  20303. *
  20304. * **remove** - happens just before the class is removed from the element
  20305. *
  20306. * @element ANY
  20307. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  20308. * of the evaluation can be a string representing space delimited class
  20309. * names, an array, or a map of class names to boolean values. In the case of a map, the
  20310. * names of the properties whose values are truthy will be added as css classes to the
  20311. * element.
  20312. *
  20313. * @example Example that demonstrates basic bindings via ngClass directive.
  20314. <example>
  20315. <file name="index.html">
  20316. <p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p>
  20317. <label>
  20318. <input type="checkbox" ng-model="deleted">
  20319. deleted (apply "strike" class)
  20320. </label><br>
  20321. <label>
  20322. <input type="checkbox" ng-model="important">
  20323. important (apply "bold" class)
  20324. </label><br>
  20325. <label>
  20326. <input type="checkbox" ng-model="error">
  20327. error (apply "red" class)
  20328. </label>
  20329. <hr>
  20330. <p ng-class="style">Using String Syntax</p>
  20331. <input type="text" ng-model="style"
  20332. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  20333. <hr>
  20334. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  20335. <input ng-model="style1"
  20336. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  20337. <input ng-model="style2"
  20338. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  20339. <input ng-model="style3"
  20340. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  20341. <hr>
  20342. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  20343. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  20344. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  20345. </file>
  20346. <file name="style.css">
  20347. .strike {
  20348. text-decoration: line-through;
  20349. }
  20350. .bold {
  20351. font-weight: bold;
  20352. }
  20353. .red {
  20354. color: red;
  20355. }
  20356. .orange {
  20357. color: orange;
  20358. }
  20359. </file>
  20360. <file name="protractor.js" type="protractor">
  20361. var ps = element.all(by.css('p'));
  20362. it('should let you toggle the class', function() {
  20363. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  20364. expect(ps.first().getAttribute('class')).not.toMatch(/red/);
  20365. element(by.model('important')).click();
  20366. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  20367. element(by.model('error')).click();
  20368. expect(ps.first().getAttribute('class')).toMatch(/red/);
  20369. });
  20370. it('should let you toggle string example', function() {
  20371. expect(ps.get(1).getAttribute('class')).toBe('');
  20372. element(by.model('style')).clear();
  20373. element(by.model('style')).sendKeys('red');
  20374. expect(ps.get(1).getAttribute('class')).toBe('red');
  20375. });
  20376. it('array example should have 3 classes', function() {
  20377. expect(ps.get(2).getAttribute('class')).toBe('');
  20378. element(by.model('style1')).sendKeys('bold');
  20379. element(by.model('style2')).sendKeys('strike');
  20380. element(by.model('style3')).sendKeys('red');
  20381. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  20382. });
  20383. it('array with map example should have 2 classes', function() {
  20384. expect(ps.last().getAttribute('class')).toBe('');
  20385. element(by.model('style4')).sendKeys('bold');
  20386. element(by.model('warning')).click();
  20387. expect(ps.last().getAttribute('class')).toBe('bold orange');
  20388. });
  20389. </file>
  20390. </example>
  20391. ## Animations
  20392. The example below demonstrates how to perform animations using ngClass.
  20393. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  20394. <file name="index.html">
  20395. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  20396. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  20397. <br>
  20398. <span class="base-class" ng-class="myVar">Sample Text</span>
  20399. </file>
  20400. <file name="style.css">
  20401. .base-class {
  20402. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20403. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20404. }
  20405. .base-class.my-class {
  20406. color: red;
  20407. font-size:3em;
  20408. }
  20409. </file>
  20410. <file name="protractor.js" type="protractor">
  20411. it('should check ng-class', function() {
  20412. expect(element(by.css('.base-class')).getAttribute('class')).not.
  20413. toMatch(/my-class/);
  20414. element(by.id('setbtn')).click();
  20415. expect(element(by.css('.base-class')).getAttribute('class')).
  20416. toMatch(/my-class/);
  20417. element(by.id('clearbtn')).click();
  20418. expect(element(by.css('.base-class')).getAttribute('class')).not.
  20419. toMatch(/my-class/);
  20420. });
  20421. </file>
  20422. </example>
  20423. ## ngClass and pre-existing CSS3 Transitions/Animations
  20424. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  20425. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  20426. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  20427. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  20428. {@link $animate#removeClass $animate.removeClass}.
  20429. */
  20430. var ngClassDirective = classDirective('', true);
  20431. /**
  20432. * @ngdoc directive
  20433. * @name ngClassOdd
  20434. * @restrict AC
  20435. *
  20436. * @description
  20437. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  20438. * {@link ng.directive:ngClass ngClass}, except they work in
  20439. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  20440. *
  20441. * This directive can be applied only within the scope of an
  20442. * {@link ng.directive:ngRepeat ngRepeat}.
  20443. *
  20444. * @element ANY
  20445. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  20446. * of the evaluation can be a string representing space delimited class names or an array.
  20447. *
  20448. * @example
  20449. <example>
  20450. <file name="index.html">
  20451. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  20452. <li ng-repeat="name in names">
  20453. <span ng-class-odd="'odd'" ng-class-even="'even'">
  20454. {{name}}
  20455. </span>
  20456. </li>
  20457. </ol>
  20458. </file>
  20459. <file name="style.css">
  20460. .odd {
  20461. color: red;
  20462. }
  20463. .even {
  20464. color: blue;
  20465. }
  20466. </file>
  20467. <file name="protractor.js" type="protractor">
  20468. it('should check ng-class-odd and ng-class-even', function() {
  20469. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  20470. toMatch(/odd/);
  20471. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  20472. toMatch(/even/);
  20473. });
  20474. </file>
  20475. </example>
  20476. */
  20477. var ngClassOddDirective = classDirective('Odd', 0);
  20478. /**
  20479. * @ngdoc directive
  20480. * @name ngClassEven
  20481. * @restrict AC
  20482. *
  20483. * @description
  20484. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  20485. * {@link ng.directive:ngClass ngClass}, except they work in
  20486. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  20487. *
  20488. * This directive can be applied only within the scope of an
  20489. * {@link ng.directive:ngRepeat ngRepeat}.
  20490. *
  20491. * @element ANY
  20492. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  20493. * result of the evaluation can be a string representing space delimited class names or an array.
  20494. *
  20495. * @example
  20496. <example>
  20497. <file name="index.html">
  20498. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  20499. <li ng-repeat="name in names">
  20500. <span ng-class-odd="'odd'" ng-class-even="'even'">
  20501. {{name}} &nbsp; &nbsp; &nbsp;
  20502. </span>
  20503. </li>
  20504. </ol>
  20505. </file>
  20506. <file name="style.css">
  20507. .odd {
  20508. color: red;
  20509. }
  20510. .even {
  20511. color: blue;
  20512. }
  20513. </file>
  20514. <file name="protractor.js" type="protractor">
  20515. it('should check ng-class-odd and ng-class-even', function() {
  20516. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  20517. toMatch(/odd/);
  20518. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  20519. toMatch(/even/);
  20520. });
  20521. </file>
  20522. </example>
  20523. */
  20524. var ngClassEvenDirective = classDirective('Even', 1);
  20525. /**
  20526. * @ngdoc directive
  20527. * @name ngCloak
  20528. * @restrict AC
  20529. *
  20530. * @description
  20531. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  20532. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  20533. * directive to avoid the undesirable flicker effect caused by the html template display.
  20534. *
  20535. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  20536. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  20537. * of the browser view.
  20538. *
  20539. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  20540. * `angular.min.js`.
  20541. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  20542. *
  20543. * ```css
  20544. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  20545. * display: none !important;
  20546. * }
  20547. * ```
  20548. *
  20549. * When this css rule is loaded by the browser, all html elements (including their children) that
  20550. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  20551. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  20552. * the compiled element visible.
  20553. *
  20554. * For the best result, the `angular.js` script must be loaded in the head section of the html
  20555. * document; alternatively, the css rule above must be included in the external stylesheet of the
  20556. * application.
  20557. *
  20558. * @element ANY
  20559. *
  20560. * @example
  20561. <example>
  20562. <file name="index.html">
  20563. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  20564. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  20565. </file>
  20566. <file name="protractor.js" type="protractor">
  20567. it('should remove the template directive and css class', function() {
  20568. expect($('#template1').getAttribute('ng-cloak')).
  20569. toBeNull();
  20570. expect($('#template2').getAttribute('ng-cloak')).
  20571. toBeNull();
  20572. });
  20573. </file>
  20574. </example>
  20575. *
  20576. */
  20577. var ngCloakDirective = ngDirective({
  20578. compile: function(element, attr) {
  20579. attr.$set('ngCloak', undefined);
  20580. element.removeClass('ng-cloak');
  20581. }
  20582. });
  20583. /**
  20584. * @ngdoc directive
  20585. * @name ngController
  20586. *
  20587. * @description
  20588. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  20589. * supports the principles behind the Model-View-Controller design pattern.
  20590. *
  20591. * MVC components in angular:
  20592. *
  20593. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  20594. * are accessed through bindings.
  20595. * * View — The template (HTML with data bindings) that is rendered into the View.
  20596. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  20597. * logic behind the application to decorate the scope with functions and values
  20598. *
  20599. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  20600. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  20601. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  20602. * and executed twice.
  20603. *
  20604. * @element ANY
  20605. * @scope
  20606. * @priority 500
  20607. * @param {expression} ngController Name of a constructor function registered with the current
  20608. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  20609. * that on the current scope evaluates to a constructor function.
  20610. *
  20611. * The controller instance can be published into a scope property by specifying
  20612. * `ng-controller="as propertyName"`.
  20613. *
  20614. * If the current `$controllerProvider` is configured to use globals (via
  20615. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  20616. * also be the name of a globally accessible constructor function (not recommended).
  20617. *
  20618. * @example
  20619. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  20620. * greeting are methods declared on the controller (see source tab). These methods can
  20621. * easily be called from the angular markup. Any changes to the data are automatically reflected
  20622. * in the View without the need for a manual update.
  20623. *
  20624. * Two different declaration styles are included below:
  20625. *
  20626. * * one binds methods and properties directly onto the controller using `this`:
  20627. * `ng-controller="SettingsController1 as settings"`
  20628. * * one injects `$scope` into the controller:
  20629. * `ng-controller="SettingsController2"`
  20630. *
  20631. * The second option is more common in the Angular community, and is generally used in boilerplates
  20632. * and in this guide. However, there are advantages to binding properties directly to the controller
  20633. * and avoiding scope.
  20634. *
  20635. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  20636. * multiple controllers apply to an element.
  20637. * * If you are writing your controllers as classes you have easier access to the properties and
  20638. * methods, which will appear on the scope, from inside the controller code.
  20639. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  20640. * inheritance masking primitives.
  20641. *
  20642. * This example demonstrates the `controller as` syntax.
  20643. *
  20644. * <example name="ngControllerAs" module="controllerAsExample">
  20645. * <file name="index.html">
  20646. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  20647. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  20648. * <button ng-click="settings.greet()">greet</button><br/>
  20649. * Contact:
  20650. * <ul>
  20651. * <li ng-repeat="contact in settings.contacts">
  20652. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  20653. * <option>phone</option>
  20654. * <option>email</option>
  20655. * </select>
  20656. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  20657. * <button ng-click="settings.clearContact(contact)">clear</button>
  20658. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  20659. * </li>
  20660. * <li><button ng-click="settings.addContact()">add</button></li>
  20661. * </ul>
  20662. * </div>
  20663. * </file>
  20664. * <file name="app.js">
  20665. * angular.module('controllerAsExample', [])
  20666. * .controller('SettingsController1', SettingsController1);
  20667. *
  20668. * function SettingsController1() {
  20669. * this.name = "John Smith";
  20670. * this.contacts = [
  20671. * {type: 'phone', value: '408 555 1212'},
  20672. * {type: 'email', value: 'john.smith@example.org'} ];
  20673. * }
  20674. *
  20675. * SettingsController1.prototype.greet = function() {
  20676. * alert(this.name);
  20677. * };
  20678. *
  20679. * SettingsController1.prototype.addContact = function() {
  20680. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  20681. * };
  20682. *
  20683. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  20684. * var index = this.contacts.indexOf(contactToRemove);
  20685. * this.contacts.splice(index, 1);
  20686. * };
  20687. *
  20688. * SettingsController1.prototype.clearContact = function(contact) {
  20689. * contact.type = 'phone';
  20690. * contact.value = '';
  20691. * };
  20692. * </file>
  20693. * <file name="protractor.js" type="protractor">
  20694. * it('should check controller as', function() {
  20695. * var container = element(by.id('ctrl-as-exmpl'));
  20696. * expect(container.element(by.model('settings.name'))
  20697. * .getAttribute('value')).toBe('John Smith');
  20698. *
  20699. * var firstRepeat =
  20700. * container.element(by.repeater('contact in settings.contacts').row(0));
  20701. * var secondRepeat =
  20702. * container.element(by.repeater('contact in settings.contacts').row(1));
  20703. *
  20704. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20705. * .toBe('408 555 1212');
  20706. *
  20707. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  20708. * .toBe('john.smith@example.org');
  20709. *
  20710. * firstRepeat.element(by.buttonText('clear')).click();
  20711. *
  20712. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20713. * .toBe('');
  20714. *
  20715. * container.element(by.buttonText('add')).click();
  20716. *
  20717. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  20718. * .element(by.model('contact.value'))
  20719. * .getAttribute('value'))
  20720. * .toBe('yourname@example.org');
  20721. * });
  20722. * </file>
  20723. * </example>
  20724. *
  20725. * This example demonstrates the "attach to `$scope`" style of controller.
  20726. *
  20727. * <example name="ngController" module="controllerExample">
  20728. * <file name="index.html">
  20729. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  20730. * <label>Name: <input type="text" ng-model="name"/></label>
  20731. * <button ng-click="greet()">greet</button><br/>
  20732. * Contact:
  20733. * <ul>
  20734. * <li ng-repeat="contact in contacts">
  20735. * <select ng-model="contact.type" id="select_{{$index}}">
  20736. * <option>phone</option>
  20737. * <option>email</option>
  20738. * </select>
  20739. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  20740. * <button ng-click="clearContact(contact)">clear</button>
  20741. * <button ng-click="removeContact(contact)">X</button>
  20742. * </li>
  20743. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  20744. * </ul>
  20745. * </div>
  20746. * </file>
  20747. * <file name="app.js">
  20748. * angular.module('controllerExample', [])
  20749. * .controller('SettingsController2', ['$scope', SettingsController2]);
  20750. *
  20751. * function SettingsController2($scope) {
  20752. * $scope.name = "John Smith";
  20753. * $scope.contacts = [
  20754. * {type:'phone', value:'408 555 1212'},
  20755. * {type:'email', value:'john.smith@example.org'} ];
  20756. *
  20757. * $scope.greet = function() {
  20758. * alert($scope.name);
  20759. * };
  20760. *
  20761. * $scope.addContact = function() {
  20762. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  20763. * };
  20764. *
  20765. * $scope.removeContact = function(contactToRemove) {
  20766. * var index = $scope.contacts.indexOf(contactToRemove);
  20767. * $scope.contacts.splice(index, 1);
  20768. * };
  20769. *
  20770. * $scope.clearContact = function(contact) {
  20771. * contact.type = 'phone';
  20772. * contact.value = '';
  20773. * };
  20774. * }
  20775. * </file>
  20776. * <file name="protractor.js" type="protractor">
  20777. * it('should check controller', function() {
  20778. * var container = element(by.id('ctrl-exmpl'));
  20779. *
  20780. * expect(container.element(by.model('name'))
  20781. * .getAttribute('value')).toBe('John Smith');
  20782. *
  20783. * var firstRepeat =
  20784. * container.element(by.repeater('contact in contacts').row(0));
  20785. * var secondRepeat =
  20786. * container.element(by.repeater('contact in contacts').row(1));
  20787. *
  20788. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20789. * .toBe('408 555 1212');
  20790. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  20791. * .toBe('john.smith@example.org');
  20792. *
  20793. * firstRepeat.element(by.buttonText('clear')).click();
  20794. *
  20795. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20796. * .toBe('');
  20797. *
  20798. * container.element(by.buttonText('add')).click();
  20799. *
  20800. * expect(container.element(by.repeater('contact in contacts').row(2))
  20801. * .element(by.model('contact.value'))
  20802. * .getAttribute('value'))
  20803. * .toBe('yourname@example.org');
  20804. * });
  20805. * </file>
  20806. *</example>
  20807. */
  20808. var ngControllerDirective = [function() {
  20809. return {
  20810. restrict: 'A',
  20811. scope: true,
  20812. controller: '@',
  20813. priority: 500
  20814. };
  20815. }];
  20816. /**
  20817. * @ngdoc directive
  20818. * @name ngCsp
  20819. *
  20820. * @element html
  20821. * @description
  20822. * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
  20823. *
  20824. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  20825. *
  20826. * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
  20827. * For Angular to be CSP compatible there are only two things that we need to do differently:
  20828. *
  20829. * - don't use `Function` constructor to generate optimized value getters
  20830. * - don't inject custom stylesheet into the document
  20831. *
  20832. * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`
  20833. * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will
  20834. * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
  20835. * be raised.
  20836. *
  20837. * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically
  20838. * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).
  20839. * To make those directives work in CSP mode, include the `angular-csp.css` manually.
  20840. *
  20841. * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This
  20842. * autodetection however triggers a CSP error to be logged in the console:
  20843. *
  20844. * ```
  20845. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  20846. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  20847. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  20848. * ```
  20849. *
  20850. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  20851. * directive on the root element of the application or on the `angular.js` script tag, whichever
  20852. * appears first in the html document.
  20853. *
  20854. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  20855. *
  20856. * @example
  20857. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  20858. ```html
  20859. <!doctype html>
  20860. <html ng-app ng-csp>
  20861. ...
  20862. ...
  20863. </html>
  20864. ```
  20865. * @example
  20866. // Note: the suffix `.csp` in the example name triggers
  20867. // csp mode in our http server!
  20868. <example name="example.csp" module="cspExample" ng-csp="true">
  20869. <file name="index.html">
  20870. <div ng-controller="MainController as ctrl">
  20871. <div>
  20872. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  20873. <span id="counter">
  20874. {{ctrl.counter}}
  20875. </span>
  20876. </div>
  20877. <div>
  20878. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  20879. <span id="evilError">
  20880. {{ctrl.evilError}}
  20881. </span>
  20882. </div>
  20883. </div>
  20884. </file>
  20885. <file name="script.js">
  20886. angular.module('cspExample', [])
  20887. .controller('MainController', function() {
  20888. this.counter = 0;
  20889. this.inc = function() {
  20890. this.counter++;
  20891. };
  20892. this.evil = function() {
  20893. // jshint evil:true
  20894. try {
  20895. eval('1+2');
  20896. } catch (e) {
  20897. this.evilError = e.message;
  20898. }
  20899. };
  20900. });
  20901. </file>
  20902. <file name="protractor.js" type="protractor">
  20903. var util, webdriver;
  20904. var incBtn = element(by.id('inc'));
  20905. var counter = element(by.id('counter'));
  20906. var evilBtn = element(by.id('evil'));
  20907. var evilError = element(by.id('evilError'));
  20908. function getAndClearSevereErrors() {
  20909. return browser.manage().logs().get('browser').then(function(browserLog) {
  20910. return browserLog.filter(function(logEntry) {
  20911. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  20912. });
  20913. });
  20914. }
  20915. function clearErrors() {
  20916. getAndClearSevereErrors();
  20917. }
  20918. function expectNoErrors() {
  20919. getAndClearSevereErrors().then(function(filteredLog) {
  20920. expect(filteredLog.length).toEqual(0);
  20921. if (filteredLog.length) {
  20922. console.log('browser console errors: ' + util.inspect(filteredLog));
  20923. }
  20924. });
  20925. }
  20926. function expectError(regex) {
  20927. getAndClearSevereErrors().then(function(filteredLog) {
  20928. var found = false;
  20929. filteredLog.forEach(function(log) {
  20930. if (log.message.match(regex)) {
  20931. found = true;
  20932. }
  20933. });
  20934. if (!found) {
  20935. throw new Error('expected an error that matches ' + regex);
  20936. }
  20937. });
  20938. }
  20939. beforeEach(function() {
  20940. util = require('util');
  20941. webdriver = require('protractor/node_modules/selenium-webdriver');
  20942. });
  20943. // For now, we only test on Chrome,
  20944. // as Safari does not load the page with Protractor's injected scripts,
  20945. // and Firefox webdriver always disables content security policy (#6358)
  20946. if (browser.params.browser !== 'chrome') {
  20947. return;
  20948. }
  20949. it('should not report errors when the page is loaded', function() {
  20950. // clear errors so we are not dependent on previous tests
  20951. clearErrors();
  20952. // Need to reload the page as the page is already loaded when
  20953. // we come here
  20954. browser.driver.getCurrentUrl().then(function(url) {
  20955. browser.get(url);
  20956. });
  20957. expectNoErrors();
  20958. });
  20959. it('should evaluate expressions', function() {
  20960. expect(counter.getText()).toEqual('0');
  20961. incBtn.click();
  20962. expect(counter.getText()).toEqual('1');
  20963. expectNoErrors();
  20964. });
  20965. it('should throw and report an error when using "eval"', function() {
  20966. evilBtn.click();
  20967. expect(evilError.getText()).toMatch(/Content Security Policy/);
  20968. expectError(/Content Security Policy/);
  20969. });
  20970. </file>
  20971. </example>
  20972. */
  20973. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  20974. // bootstrap the system (before $parse is instantiated), for this reason we just have
  20975. // the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc
  20976. /**
  20977. * @ngdoc directive
  20978. * @name ngClick
  20979. *
  20980. * @description
  20981. * The ngClick directive allows you to specify custom behavior when
  20982. * an element is clicked.
  20983. *
  20984. * @element ANY
  20985. * @priority 0
  20986. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  20987. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  20988. *
  20989. * @example
  20990. <example>
  20991. <file name="index.html">
  20992. <button ng-click="count = count + 1" ng-init="count=0">
  20993. Increment
  20994. </button>
  20995. <span>
  20996. count: {{count}}
  20997. </span>
  20998. </file>
  20999. <file name="protractor.js" type="protractor">
  21000. it('should check ng-click', function() {
  21001. expect(element(by.binding('count')).getText()).toMatch('0');
  21002. element(by.css('button')).click();
  21003. expect(element(by.binding('count')).getText()).toMatch('1');
  21004. });
  21005. </file>
  21006. </example>
  21007. */
  21008. /*
  21009. * A collection of directives that allows creation of custom event handlers that are defined as
  21010. * angular expressions and are compiled and executed within the current scope.
  21011. */
  21012. var ngEventDirectives = {};
  21013. // For events that might fire synchronously during DOM manipulation
  21014. // we need to execute their event handlers asynchronously using $evalAsync,
  21015. // so that they are not executed in an inconsistent state.
  21016. var forceAsyncEvents = {
  21017. 'blur': true,
  21018. 'focus': true
  21019. };
  21020. forEach(
  21021. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  21022. function(eventName) {
  21023. var directiveName = directiveNormalize('ng-' + eventName);
  21024. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  21025. return {
  21026. restrict: 'A',
  21027. compile: function($element, attr) {
  21028. // We expose the powerful $event object on the scope that provides access to the Window,
  21029. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  21030. // checks at the cost of speed since event handler expressions are not executed as
  21031. // frequently as regular change detection.
  21032. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
  21033. return function ngEventHandler(scope, element) {
  21034. element.on(eventName, function(event) {
  21035. var callback = function() {
  21036. fn(scope, {$event:event});
  21037. };
  21038. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  21039. scope.$evalAsync(callback);
  21040. } else {
  21041. scope.$apply(callback);
  21042. }
  21043. });
  21044. };
  21045. }
  21046. };
  21047. }];
  21048. }
  21049. );
  21050. /**
  21051. * @ngdoc directive
  21052. * @name ngDblclick
  21053. *
  21054. * @description
  21055. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  21056. *
  21057. * @element ANY
  21058. * @priority 0
  21059. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  21060. * a dblclick. (The Event object is available as `$event`)
  21061. *
  21062. * @example
  21063. <example>
  21064. <file name="index.html">
  21065. <button ng-dblclick="count = count + 1" ng-init="count=0">
  21066. Increment (on double click)
  21067. </button>
  21068. count: {{count}}
  21069. </file>
  21070. </example>
  21071. */
  21072. /**
  21073. * @ngdoc directive
  21074. * @name ngMousedown
  21075. *
  21076. * @description
  21077. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  21078. *
  21079. * @element ANY
  21080. * @priority 0
  21081. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  21082. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  21083. *
  21084. * @example
  21085. <example>
  21086. <file name="index.html">
  21087. <button ng-mousedown="count = count + 1" ng-init="count=0">
  21088. Increment (on mouse down)
  21089. </button>
  21090. count: {{count}}
  21091. </file>
  21092. </example>
  21093. */
  21094. /**
  21095. * @ngdoc directive
  21096. * @name ngMouseup
  21097. *
  21098. * @description
  21099. * Specify custom behavior on mouseup event.
  21100. *
  21101. * @element ANY
  21102. * @priority 0
  21103. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  21104. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  21105. *
  21106. * @example
  21107. <example>
  21108. <file name="index.html">
  21109. <button ng-mouseup="count = count + 1" ng-init="count=0">
  21110. Increment (on mouse up)
  21111. </button>
  21112. count: {{count}}
  21113. </file>
  21114. </example>
  21115. */
  21116. /**
  21117. * @ngdoc directive
  21118. * @name ngMouseover
  21119. *
  21120. * @description
  21121. * Specify custom behavior on mouseover event.
  21122. *
  21123. * @element ANY
  21124. * @priority 0
  21125. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  21126. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  21127. *
  21128. * @example
  21129. <example>
  21130. <file name="index.html">
  21131. <button ng-mouseover="count = count + 1" ng-init="count=0">
  21132. Increment (when mouse is over)
  21133. </button>
  21134. count: {{count}}
  21135. </file>
  21136. </example>
  21137. */
  21138. /**
  21139. * @ngdoc directive
  21140. * @name ngMouseenter
  21141. *
  21142. * @description
  21143. * Specify custom behavior on mouseenter event.
  21144. *
  21145. * @element ANY
  21146. * @priority 0
  21147. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  21148. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  21149. *
  21150. * @example
  21151. <example>
  21152. <file name="index.html">
  21153. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  21154. Increment (when mouse enters)
  21155. </button>
  21156. count: {{count}}
  21157. </file>
  21158. </example>
  21159. */
  21160. /**
  21161. * @ngdoc directive
  21162. * @name ngMouseleave
  21163. *
  21164. * @description
  21165. * Specify custom behavior on mouseleave event.
  21166. *
  21167. * @element ANY
  21168. * @priority 0
  21169. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  21170. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  21171. *
  21172. * @example
  21173. <example>
  21174. <file name="index.html">
  21175. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  21176. Increment (when mouse leaves)
  21177. </button>
  21178. count: {{count}}
  21179. </file>
  21180. </example>
  21181. */
  21182. /**
  21183. * @ngdoc directive
  21184. * @name ngMousemove
  21185. *
  21186. * @description
  21187. * Specify custom behavior on mousemove event.
  21188. *
  21189. * @element ANY
  21190. * @priority 0
  21191. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  21192. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  21193. *
  21194. * @example
  21195. <example>
  21196. <file name="index.html">
  21197. <button ng-mousemove="count = count + 1" ng-init="count=0">
  21198. Increment (when mouse moves)
  21199. </button>
  21200. count: {{count}}
  21201. </file>
  21202. </example>
  21203. */
  21204. /**
  21205. * @ngdoc directive
  21206. * @name ngKeydown
  21207. *
  21208. * @description
  21209. * Specify custom behavior on keydown event.
  21210. *
  21211. * @element ANY
  21212. * @priority 0
  21213. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  21214. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  21215. *
  21216. * @example
  21217. <example>
  21218. <file name="index.html">
  21219. <input ng-keydown="count = count + 1" ng-init="count=0">
  21220. key down count: {{count}}
  21221. </file>
  21222. </example>
  21223. */
  21224. /**
  21225. * @ngdoc directive
  21226. * @name ngKeyup
  21227. *
  21228. * @description
  21229. * Specify custom behavior on keyup event.
  21230. *
  21231. * @element ANY
  21232. * @priority 0
  21233. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  21234. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  21235. *
  21236. * @example
  21237. <example>
  21238. <file name="index.html">
  21239. <p>Typing in the input box below updates the key count</p>
  21240. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  21241. <p>Typing in the input box below updates the keycode</p>
  21242. <input ng-keyup="event=$event">
  21243. <p>event keyCode: {{ event.keyCode }}</p>
  21244. <p>event altKey: {{ event.altKey }}</p>
  21245. </file>
  21246. </example>
  21247. */
  21248. /**
  21249. * @ngdoc directive
  21250. * @name ngKeypress
  21251. *
  21252. * @description
  21253. * Specify custom behavior on keypress event.
  21254. *
  21255. * @element ANY
  21256. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  21257. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  21258. * and can be interrogated for keyCode, altKey, etc.)
  21259. *
  21260. * @example
  21261. <example>
  21262. <file name="index.html">
  21263. <input ng-keypress="count = count + 1" ng-init="count=0">
  21264. key press count: {{count}}
  21265. </file>
  21266. </example>
  21267. */
  21268. /**
  21269. * @ngdoc directive
  21270. * @name ngSubmit
  21271. *
  21272. * @description
  21273. * Enables binding angular expressions to onsubmit events.
  21274. *
  21275. * Additionally it prevents the default action (which for form means sending the request to the
  21276. * server and reloading the current page), but only if the form does not contain `action`,
  21277. * `data-action`, or `x-action` attributes.
  21278. *
  21279. * <div class="alert alert-warning">
  21280. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  21281. * `ngSubmit` handlers together. See the
  21282. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  21283. * for a detailed discussion of when `ngSubmit` may be triggered.
  21284. * </div>
  21285. *
  21286. * @element form
  21287. * @priority 0
  21288. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  21289. * ({@link guide/expression#-event- Event object is available as `$event`})
  21290. *
  21291. * @example
  21292. <example module="submitExample">
  21293. <file name="index.html">
  21294. <script>
  21295. angular.module('submitExample', [])
  21296. .controller('ExampleController', ['$scope', function($scope) {
  21297. $scope.list = [];
  21298. $scope.text = 'hello';
  21299. $scope.submit = function() {
  21300. if ($scope.text) {
  21301. $scope.list.push(this.text);
  21302. $scope.text = '';
  21303. }
  21304. };
  21305. }]);
  21306. </script>
  21307. <form ng-submit="submit()" ng-controller="ExampleController">
  21308. Enter text and hit enter:
  21309. <input type="text" ng-model="text" name="text" />
  21310. <input type="submit" id="submit" value="Submit" />
  21311. <pre>list={{list}}</pre>
  21312. </form>
  21313. </file>
  21314. <file name="protractor.js" type="protractor">
  21315. it('should check ng-submit', function() {
  21316. expect(element(by.binding('list')).getText()).toBe('list=[]');
  21317. element(by.css('#submit')).click();
  21318. expect(element(by.binding('list')).getText()).toContain('hello');
  21319. expect(element(by.model('text')).getAttribute('value')).toBe('');
  21320. });
  21321. it('should ignore empty strings', function() {
  21322. expect(element(by.binding('list')).getText()).toBe('list=[]');
  21323. element(by.css('#submit')).click();
  21324. element(by.css('#submit')).click();
  21325. expect(element(by.binding('list')).getText()).toContain('hello');
  21326. });
  21327. </file>
  21328. </example>
  21329. */
  21330. /**
  21331. * @ngdoc directive
  21332. * @name ngFocus
  21333. *
  21334. * @description
  21335. * Specify custom behavior on focus event.
  21336. *
  21337. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  21338. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  21339. * during an `$apply` to ensure a consistent state.
  21340. *
  21341. * @element window, input, select, textarea, a
  21342. * @priority 0
  21343. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  21344. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  21345. *
  21346. * @example
  21347. * See {@link ng.directive:ngClick ngClick}
  21348. */
  21349. /**
  21350. * @ngdoc directive
  21351. * @name ngBlur
  21352. *
  21353. * @description
  21354. * Specify custom behavior on blur event.
  21355. *
  21356. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  21357. * an element has lost focus.
  21358. *
  21359. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  21360. * (e.g. removing a focussed input),
  21361. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  21362. * during an `$apply` to ensure a consistent state.
  21363. *
  21364. * @element window, input, select, textarea, a
  21365. * @priority 0
  21366. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  21367. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  21368. *
  21369. * @example
  21370. * See {@link ng.directive:ngClick ngClick}
  21371. */
  21372. /**
  21373. * @ngdoc directive
  21374. * @name ngCopy
  21375. *
  21376. * @description
  21377. * Specify custom behavior on copy event.
  21378. *
  21379. * @element window, input, select, textarea, a
  21380. * @priority 0
  21381. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  21382. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  21383. *
  21384. * @example
  21385. <example>
  21386. <file name="index.html">
  21387. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  21388. copied: {{copied}}
  21389. </file>
  21390. </example>
  21391. */
  21392. /**
  21393. * @ngdoc directive
  21394. * @name ngCut
  21395. *
  21396. * @description
  21397. * Specify custom behavior on cut event.
  21398. *
  21399. * @element window, input, select, textarea, a
  21400. * @priority 0
  21401. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  21402. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  21403. *
  21404. * @example
  21405. <example>
  21406. <file name="index.html">
  21407. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  21408. cut: {{cut}}
  21409. </file>
  21410. </example>
  21411. */
  21412. /**
  21413. * @ngdoc directive
  21414. * @name ngPaste
  21415. *
  21416. * @description
  21417. * Specify custom behavior on paste event.
  21418. *
  21419. * @element window, input, select, textarea, a
  21420. * @priority 0
  21421. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  21422. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  21423. *
  21424. * @example
  21425. <example>
  21426. <file name="index.html">
  21427. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  21428. pasted: {{paste}}
  21429. </file>
  21430. </example>
  21431. */
  21432. /**
  21433. * @ngdoc directive
  21434. * @name ngIf
  21435. * @restrict A
  21436. *
  21437. * @description
  21438. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  21439. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  21440. * value then the element is removed from the DOM, otherwise a clone of the
  21441. * element is reinserted into the DOM.
  21442. *
  21443. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  21444. * element in the DOM rather than changing its visibility via the `display` css property. A common
  21445. * case when this difference is significant is when using css selectors that rely on an element's
  21446. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  21447. *
  21448. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  21449. * is created when the element is restored. The scope created within `ngIf` inherits from
  21450. * its parent scope using
  21451. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  21452. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  21453. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  21454. * variable within the child scope will override (hide) the value in the parent scope.
  21455. *
  21456. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  21457. * is if an element's class attribute is directly modified after it's compiled, using something like
  21458. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  21459. * the added class will be lost because the original compiled state is used to regenerate the element.
  21460. *
  21461. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  21462. * and `leave` effects.
  21463. *
  21464. * @animations
  21465. * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
  21466. * leave - happens just before the `ngIf` contents are removed from the DOM
  21467. *
  21468. * @element ANY
  21469. * @scope
  21470. * @priority 600
  21471. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  21472. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  21473. * element is added to the DOM tree.
  21474. *
  21475. * @example
  21476. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  21477. <file name="index.html">
  21478. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  21479. Show when checked:
  21480. <span ng-if="checked" class="animate-if">
  21481. This is removed when the checkbox is unchecked.
  21482. </span>
  21483. </file>
  21484. <file name="animations.css">
  21485. .animate-if {
  21486. background:white;
  21487. border:1px solid black;
  21488. padding:10px;
  21489. }
  21490. .animate-if.ng-enter, .animate-if.ng-leave {
  21491. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21492. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21493. }
  21494. .animate-if.ng-enter,
  21495. .animate-if.ng-leave.ng-leave-active {
  21496. opacity:0;
  21497. }
  21498. .animate-if.ng-leave,
  21499. .animate-if.ng-enter.ng-enter-active {
  21500. opacity:1;
  21501. }
  21502. </file>
  21503. </example>
  21504. */
  21505. var ngIfDirective = ['$animate', function($animate) {
  21506. return {
  21507. multiElement: true,
  21508. transclude: 'element',
  21509. priority: 600,
  21510. terminal: true,
  21511. restrict: 'A',
  21512. $$tlb: true,
  21513. link: function($scope, $element, $attr, ctrl, $transclude) {
  21514. var block, childScope, previousElements;
  21515. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  21516. if (value) {
  21517. if (!childScope) {
  21518. $transclude(function(clone, newScope) {
  21519. childScope = newScope;
  21520. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  21521. // Note: We only need the first/last node of the cloned nodes.
  21522. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  21523. // by a directive with templateUrl when its template arrives.
  21524. block = {
  21525. clone: clone
  21526. };
  21527. $animate.enter(clone, $element.parent(), $element);
  21528. });
  21529. }
  21530. } else {
  21531. if (previousElements) {
  21532. previousElements.remove();
  21533. previousElements = null;
  21534. }
  21535. if (childScope) {
  21536. childScope.$destroy();
  21537. childScope = null;
  21538. }
  21539. if (block) {
  21540. previousElements = getBlockNodes(block.clone);
  21541. $animate.leave(previousElements).then(function() {
  21542. previousElements = null;
  21543. });
  21544. block = null;
  21545. }
  21546. }
  21547. });
  21548. }
  21549. };
  21550. }];
  21551. /**
  21552. * @ngdoc directive
  21553. * @name ngInclude
  21554. * @restrict ECA
  21555. *
  21556. * @description
  21557. * Fetches, compiles and includes an external HTML fragment.
  21558. *
  21559. * By default, the template URL is restricted to the same domain and protocol as the
  21560. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  21561. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  21562. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  21563. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  21564. * ng.$sce Strict Contextual Escaping}.
  21565. *
  21566. * In addition, the browser's
  21567. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  21568. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  21569. * policy may further restrict whether the template is successfully loaded.
  21570. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  21571. * access on some browsers.
  21572. *
  21573. * @animations
  21574. * enter - animation is used to bring new content into the browser.
  21575. * leave - animation is used to animate existing content away.
  21576. *
  21577. * The enter and leave animation occur concurrently.
  21578. *
  21579. * @scope
  21580. * @priority 400
  21581. *
  21582. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  21583. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  21584. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  21585. *
  21586. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  21587. * $anchorScroll} to scroll the viewport after the content is loaded.
  21588. *
  21589. * - If the attribute is not set, disable scrolling.
  21590. * - If the attribute is set without value, enable scrolling.
  21591. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  21592. *
  21593. * @example
  21594. <example module="includeExample" deps="angular-animate.js" animations="true">
  21595. <file name="index.html">
  21596. <div ng-controller="ExampleController">
  21597. <select ng-model="template" ng-options="t.name for t in templates">
  21598. <option value="">(blank)</option>
  21599. </select>
  21600. url of the template: <code>{{template.url}}</code>
  21601. <hr/>
  21602. <div class="slide-animate-container">
  21603. <div class="slide-animate" ng-include="template.url"></div>
  21604. </div>
  21605. </div>
  21606. </file>
  21607. <file name="script.js">
  21608. angular.module('includeExample', ['ngAnimate'])
  21609. .controller('ExampleController', ['$scope', function($scope) {
  21610. $scope.templates =
  21611. [ { name: 'template1.html', url: 'template1.html'},
  21612. { name: 'template2.html', url: 'template2.html'} ];
  21613. $scope.template = $scope.templates[0];
  21614. }]);
  21615. </file>
  21616. <file name="template1.html">
  21617. Content of template1.html
  21618. </file>
  21619. <file name="template2.html">
  21620. Content of template2.html
  21621. </file>
  21622. <file name="animations.css">
  21623. .slide-animate-container {
  21624. position:relative;
  21625. background:white;
  21626. border:1px solid black;
  21627. height:40px;
  21628. overflow:hidden;
  21629. }
  21630. .slide-animate {
  21631. padding:10px;
  21632. }
  21633. .slide-animate.ng-enter, .slide-animate.ng-leave {
  21634. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21635. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21636. position:absolute;
  21637. top:0;
  21638. left:0;
  21639. right:0;
  21640. bottom:0;
  21641. display:block;
  21642. padding:10px;
  21643. }
  21644. .slide-animate.ng-enter {
  21645. top:-50px;
  21646. }
  21647. .slide-animate.ng-enter.ng-enter-active {
  21648. top:0;
  21649. }
  21650. .slide-animate.ng-leave {
  21651. top:0;
  21652. }
  21653. .slide-animate.ng-leave.ng-leave-active {
  21654. top:50px;
  21655. }
  21656. </file>
  21657. <file name="protractor.js" type="protractor">
  21658. var templateSelect = element(by.model('template'));
  21659. var includeElem = element(by.css('[ng-include]'));
  21660. it('should load template1.html', function() {
  21661. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  21662. });
  21663. it('should load template2.html', function() {
  21664. if (browser.params.browser == 'firefox') {
  21665. // Firefox can't handle using selects
  21666. // See https://github.com/angular/protractor/issues/480
  21667. return;
  21668. }
  21669. templateSelect.click();
  21670. templateSelect.all(by.css('option')).get(2).click();
  21671. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  21672. });
  21673. it('should change to blank', function() {
  21674. if (browser.params.browser == 'firefox') {
  21675. // Firefox can't handle using selects
  21676. return;
  21677. }
  21678. templateSelect.click();
  21679. templateSelect.all(by.css('option')).get(0).click();
  21680. expect(includeElem.isPresent()).toBe(false);
  21681. });
  21682. </file>
  21683. </example>
  21684. */
  21685. /**
  21686. * @ngdoc event
  21687. * @name ngInclude#$includeContentRequested
  21688. * @eventType emit on the scope ngInclude was declared in
  21689. * @description
  21690. * Emitted every time the ngInclude content is requested.
  21691. *
  21692. * @param {Object} angularEvent Synthetic event object.
  21693. * @param {String} src URL of content to load.
  21694. */
  21695. /**
  21696. * @ngdoc event
  21697. * @name ngInclude#$includeContentLoaded
  21698. * @eventType emit on the current ngInclude scope
  21699. * @description
  21700. * Emitted every time the ngInclude content is reloaded.
  21701. *
  21702. * @param {Object} angularEvent Synthetic event object.
  21703. * @param {String} src URL of content to load.
  21704. */
  21705. /**
  21706. * @ngdoc event
  21707. * @name ngInclude#$includeContentError
  21708. * @eventType emit on the scope ngInclude was declared in
  21709. * @description
  21710. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  21711. *
  21712. * @param {Object} angularEvent Synthetic event object.
  21713. * @param {String} src URL of content to load.
  21714. */
  21715. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate', '$sce',
  21716. function($templateRequest, $anchorScroll, $animate, $sce) {
  21717. return {
  21718. restrict: 'ECA',
  21719. priority: 400,
  21720. terminal: true,
  21721. transclude: 'element',
  21722. controller: angular.noop,
  21723. compile: function(element, attr) {
  21724. var srcExp = attr.ngInclude || attr.src,
  21725. onloadExp = attr.onload || '',
  21726. autoScrollExp = attr.autoscroll;
  21727. return function(scope, $element, $attr, ctrl, $transclude) {
  21728. var changeCounter = 0,
  21729. currentScope,
  21730. previousElement,
  21731. currentElement;
  21732. var cleanupLastIncludeContent = function() {
  21733. if (previousElement) {
  21734. previousElement.remove();
  21735. previousElement = null;
  21736. }
  21737. if (currentScope) {
  21738. currentScope.$destroy();
  21739. currentScope = null;
  21740. }
  21741. if (currentElement) {
  21742. $animate.leave(currentElement).then(function() {
  21743. previousElement = null;
  21744. });
  21745. previousElement = currentElement;
  21746. currentElement = null;
  21747. }
  21748. };
  21749. scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {
  21750. var afterAnimation = function() {
  21751. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  21752. $anchorScroll();
  21753. }
  21754. };
  21755. var thisChangeId = ++changeCounter;
  21756. if (src) {
  21757. //set the 2nd param to true to ignore the template request error so that the inner
  21758. //contents and scope can be cleaned up.
  21759. $templateRequest(src, true).then(function(response) {
  21760. if (thisChangeId !== changeCounter) return;
  21761. var newScope = scope.$new();
  21762. ctrl.template = response;
  21763. // Note: This will also link all children of ng-include that were contained in the original
  21764. // html. If that content contains controllers, ... they could pollute/change the scope.
  21765. // However, using ng-include on an element with additional content does not make sense...
  21766. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  21767. // function is called before linking the content, which would apply child
  21768. // directives to non existing elements.
  21769. var clone = $transclude(newScope, function(clone) {
  21770. cleanupLastIncludeContent();
  21771. $animate.enter(clone, null, $element).then(afterAnimation);
  21772. });
  21773. currentScope = newScope;
  21774. currentElement = clone;
  21775. currentScope.$emit('$includeContentLoaded', src);
  21776. scope.$eval(onloadExp);
  21777. }, function() {
  21778. if (thisChangeId === changeCounter) {
  21779. cleanupLastIncludeContent();
  21780. scope.$emit('$includeContentError', src);
  21781. }
  21782. });
  21783. scope.$emit('$includeContentRequested', src);
  21784. } else {
  21785. cleanupLastIncludeContent();
  21786. ctrl.template = null;
  21787. }
  21788. });
  21789. };
  21790. }
  21791. };
  21792. }];
  21793. // This directive is called during the $transclude call of the first `ngInclude` directive.
  21794. // It will replace and compile the content of the element with the loaded template.
  21795. // We need this directive so that the element content is already filled when
  21796. // the link function of another directive on the same element as ngInclude
  21797. // is called.
  21798. var ngIncludeFillContentDirective = ['$compile',
  21799. function($compile) {
  21800. return {
  21801. restrict: 'ECA',
  21802. priority: -400,
  21803. require: 'ngInclude',
  21804. link: function(scope, $element, $attr, ctrl) {
  21805. if (/SVG/.test($element[0].toString())) {
  21806. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  21807. // support innerHTML, so detect this here and try to generate the contents
  21808. // specially.
  21809. $element.empty();
  21810. $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
  21811. function namespaceAdaptedClone(clone) {
  21812. $element.append(clone);
  21813. }, {futureParentElement: $element});
  21814. return;
  21815. }
  21816. $element.html(ctrl.template);
  21817. $compile($element.contents())(scope);
  21818. }
  21819. };
  21820. }];
  21821. /**
  21822. * @ngdoc directive
  21823. * @name ngInit
  21824. * @restrict AC
  21825. *
  21826. * @description
  21827. * The `ngInit` directive allows you to evaluate an expression in the
  21828. * current scope.
  21829. *
  21830. * <div class="alert alert-danger">
  21831. * The only appropriate use of `ngInit` is for aliasing special properties of
  21832. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
  21833. * should use {@link guide/controller controllers} rather than `ngInit`
  21834. * to initialize values on a scope.
  21835. * </div>
  21836. * <div class="alert alert-warning">
  21837. * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
  21838. * sure you have parenthesis for correct precedence:
  21839. * <pre class="prettyprint">
  21840. * `<div ng-init="test1 = (data | orderBy:'name')"></div>`
  21841. * </pre>
  21842. * </div>
  21843. *
  21844. * @priority 450
  21845. *
  21846. * @element ANY
  21847. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  21848. *
  21849. * @example
  21850. <example module="initExample">
  21851. <file name="index.html">
  21852. <script>
  21853. angular.module('initExample', [])
  21854. .controller('ExampleController', ['$scope', function($scope) {
  21855. $scope.list = [['a', 'b'], ['c', 'd']];
  21856. }]);
  21857. </script>
  21858. <div ng-controller="ExampleController">
  21859. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  21860. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  21861. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  21862. </div>
  21863. </div>
  21864. </div>
  21865. </file>
  21866. <file name="protractor.js" type="protractor">
  21867. it('should alias index positions', function() {
  21868. var elements = element.all(by.css('.example-init'));
  21869. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  21870. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  21871. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  21872. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  21873. });
  21874. </file>
  21875. </example>
  21876. */
  21877. var ngInitDirective = ngDirective({
  21878. priority: 450,
  21879. compile: function() {
  21880. return {
  21881. pre: function(scope, element, attrs) {
  21882. scope.$eval(attrs.ngInit);
  21883. }
  21884. };
  21885. }
  21886. });
  21887. /**
  21888. * @ngdoc directive
  21889. * @name ngList
  21890. *
  21891. * @description
  21892. * Text input that converts between a delimited string and an array of strings. The default
  21893. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  21894. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  21895. *
  21896. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  21897. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  21898. * list item is respected. This implies that the user of the directive is responsible for
  21899. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  21900. * tab or newline character.
  21901. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  21902. * when joining the list items back together) and whitespace around each list item is stripped
  21903. * before it is added to the model.
  21904. *
  21905. * ### Example with Validation
  21906. *
  21907. * <example name="ngList-directive" module="listExample">
  21908. * <file name="app.js">
  21909. * angular.module('listExample', [])
  21910. * .controller('ExampleController', ['$scope', function($scope) {
  21911. * $scope.names = ['morpheus', 'neo', 'trinity'];
  21912. * }]);
  21913. * </file>
  21914. * <file name="index.html">
  21915. * <form name="myForm" ng-controller="ExampleController">
  21916. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  21917. * <span role="alert">
  21918. * <span class="error" ng-show="myForm.namesInput.$error.required">
  21919. * Required!</span>
  21920. * </span>
  21921. * <br>
  21922. * <tt>names = {{names}}</tt><br/>
  21923. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  21924. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  21925. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21926. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21927. * </form>
  21928. * </file>
  21929. * <file name="protractor.js" type="protractor">
  21930. * var listInput = element(by.model('names'));
  21931. * var names = element(by.exactBinding('names'));
  21932. * var valid = element(by.binding('myForm.namesInput.$valid'));
  21933. * var error = element(by.css('span.error'));
  21934. *
  21935. * it('should initialize to model', function() {
  21936. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  21937. * expect(valid.getText()).toContain('true');
  21938. * expect(error.getCssValue('display')).toBe('none');
  21939. * });
  21940. *
  21941. * it('should be invalid if empty', function() {
  21942. * listInput.clear();
  21943. * listInput.sendKeys('');
  21944. *
  21945. * expect(names.getText()).toContain('');
  21946. * expect(valid.getText()).toContain('false');
  21947. * expect(error.getCssValue('display')).not.toBe('none');
  21948. * });
  21949. * </file>
  21950. * </example>
  21951. *
  21952. * ### Example - splitting on whitespace
  21953. * <example name="ngList-directive-newlines">
  21954. * <file name="index.html">
  21955. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  21956. * <pre>{{ list | json }}</pre>
  21957. * </file>
  21958. * <file name="protractor.js" type="protractor">
  21959. * it("should split the text by newlines", function() {
  21960. * var listInput = element(by.model('list'));
  21961. * var output = element(by.binding('list | json'));
  21962. * listInput.sendKeys('abc\ndef\nghi');
  21963. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  21964. * });
  21965. * </file>
  21966. * </example>
  21967. *
  21968. * @element input
  21969. * @param {string=} ngList optional delimiter that should be used to split the value.
  21970. */
  21971. var ngListDirective = function() {
  21972. return {
  21973. restrict: 'A',
  21974. priority: 100,
  21975. require: 'ngModel',
  21976. link: function(scope, element, attr, ctrl) {
  21977. // We want to control whitespace trimming so we use this convoluted approach
  21978. // to access the ngList attribute, which doesn't pre-trim the attribute
  21979. var ngList = element.attr(attr.$attr.ngList) || ', ';
  21980. var trimValues = attr.ngTrim !== 'false';
  21981. var separator = trimValues ? trim(ngList) : ngList;
  21982. var parse = function(viewValue) {
  21983. // If the viewValue is invalid (say required but empty) it will be `undefined`
  21984. if (isUndefined(viewValue)) return;
  21985. var list = [];
  21986. if (viewValue) {
  21987. forEach(viewValue.split(separator), function(value) {
  21988. if (value) list.push(trimValues ? trim(value) : value);
  21989. });
  21990. }
  21991. return list;
  21992. };
  21993. ctrl.$parsers.push(parse);
  21994. ctrl.$formatters.push(function(value) {
  21995. if (isArray(value)) {
  21996. return value.join(ngList);
  21997. }
  21998. return undefined;
  21999. });
  22000. // Override the standard $isEmpty because an empty array means the input is empty.
  22001. ctrl.$isEmpty = function(value) {
  22002. return !value || !value.length;
  22003. };
  22004. }
  22005. };
  22006. };
  22007. /* global VALID_CLASS: true,
  22008. INVALID_CLASS: true,
  22009. PRISTINE_CLASS: true,
  22010. DIRTY_CLASS: true,
  22011. UNTOUCHED_CLASS: true,
  22012. TOUCHED_CLASS: true,
  22013. */
  22014. var VALID_CLASS = 'ng-valid',
  22015. INVALID_CLASS = 'ng-invalid',
  22016. PRISTINE_CLASS = 'ng-pristine',
  22017. DIRTY_CLASS = 'ng-dirty',
  22018. UNTOUCHED_CLASS = 'ng-untouched',
  22019. TOUCHED_CLASS = 'ng-touched',
  22020. PENDING_CLASS = 'ng-pending';
  22021. var $ngModelMinErr = new minErr('ngModel');
  22022. /**
  22023. * @ngdoc type
  22024. * @name ngModel.NgModelController
  22025. *
  22026. * @property {string} $viewValue Actual string value in the view.
  22027. * @property {*} $modelValue The value in the model that the control is bound to.
  22028. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  22029. the control reads value from the DOM. The functions are called in array order, each passing
  22030. its return value through to the next. The last return value is forwarded to the
  22031. {@link ngModel.NgModelController#$validators `$validators`} collection.
  22032. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  22033. `$viewValue`}.
  22034. Returning `undefined` from a parser means a parse error occurred. In that case,
  22035. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  22036. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  22037. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  22038. *
  22039. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  22040. the model value changes. The functions are called in reverse array order, each passing the value through to the
  22041. next. The last return value is used as the actual DOM value.
  22042. Used to format / convert values for display in the control.
  22043. * ```js
  22044. * function formatter(value) {
  22045. * if (value) {
  22046. * return value.toUpperCase();
  22047. * }
  22048. * }
  22049. * ngModel.$formatters.push(formatter);
  22050. * ```
  22051. *
  22052. * @property {Object.<string, function>} $validators A collection of validators that are applied
  22053. * whenever the model value changes. The key value within the object refers to the name of the
  22054. * validator while the function refers to the validation operation. The validation operation is
  22055. * provided with the model value as an argument and must return a true or false value depending
  22056. * on the response of that validation.
  22057. *
  22058. * ```js
  22059. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  22060. * var value = modelValue || viewValue;
  22061. * return /[0-9]+/.test(value) &&
  22062. * /[a-z]+/.test(value) &&
  22063. * /[A-Z]+/.test(value) &&
  22064. * /\W+/.test(value);
  22065. * };
  22066. * ```
  22067. *
  22068. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  22069. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  22070. * is expected to return a promise when it is run during the model validation process. Once the promise
  22071. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  22072. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  22073. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  22074. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  22075. * will only run once all synchronous validators have passed.
  22076. *
  22077. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  22078. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  22079. *
  22080. * ```js
  22081. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  22082. * var value = modelValue || viewValue;
  22083. *
  22084. * // Lookup user by username
  22085. * return $http.get('/api/users/' + value).
  22086. * then(function resolved() {
  22087. * //username exists, this means validation fails
  22088. * return $q.reject('exists');
  22089. * }, function rejected() {
  22090. * //username does not exist, therefore this validation passes
  22091. * return true;
  22092. * });
  22093. * };
  22094. * ```
  22095. *
  22096. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  22097. * view value has changed. It is called with no arguments, and its return value is ignored.
  22098. * This can be used in place of additional $watches against the model value.
  22099. *
  22100. * @property {Object} $error An object hash with all failing validator ids as keys.
  22101. * @property {Object} $pending An object hash with all pending validator ids as keys.
  22102. *
  22103. * @property {boolean} $untouched True if control has not lost focus yet.
  22104. * @property {boolean} $touched True if control has lost focus.
  22105. * @property {boolean} $pristine True if user has not interacted with the control yet.
  22106. * @property {boolean} $dirty True if user has already interacted with the control.
  22107. * @property {boolean} $valid True if there is no error.
  22108. * @property {boolean} $invalid True if at least one error on the control.
  22109. * @property {string} $name The name attribute of the control.
  22110. *
  22111. * @description
  22112. *
  22113. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  22114. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  22115. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  22116. * listening to DOM events.
  22117. * Such DOM related logic should be provided by other directives which make use of
  22118. * `NgModelController` for data-binding to control elements.
  22119. * Angular provides this DOM logic for most {@link input `input`} elements.
  22120. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  22121. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  22122. *
  22123. * @example
  22124. * ### Custom Control Example
  22125. * This example shows how to use `NgModelController` with a custom control to achieve
  22126. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  22127. * collaborate together to achieve the desired result.
  22128. *
  22129. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  22130. * contents be edited in place by the user.
  22131. *
  22132. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  22133. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  22134. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  22135. * that content using the `$sce` service.
  22136. *
  22137. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  22138. <file name="style.css">
  22139. [contenteditable] {
  22140. border: 1px solid black;
  22141. background-color: white;
  22142. min-height: 20px;
  22143. }
  22144. .ng-invalid {
  22145. border: 1px solid red;
  22146. }
  22147. </file>
  22148. <file name="script.js">
  22149. angular.module('customControl', ['ngSanitize']).
  22150. directive('contenteditable', ['$sce', function($sce) {
  22151. return {
  22152. restrict: 'A', // only activate on element attribute
  22153. require: '?ngModel', // get a hold of NgModelController
  22154. link: function(scope, element, attrs, ngModel) {
  22155. if (!ngModel) return; // do nothing if no ng-model
  22156. // Specify how UI should be updated
  22157. ngModel.$render = function() {
  22158. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  22159. };
  22160. // Listen for change events to enable binding
  22161. element.on('blur keyup change', function() {
  22162. scope.$evalAsync(read);
  22163. });
  22164. read(); // initialize
  22165. // Write data to the model
  22166. function read() {
  22167. var html = element.html();
  22168. // When we clear the content editable the browser leaves a <br> behind
  22169. // If strip-br attribute is provided then we strip this out
  22170. if ( attrs.stripBr && html == '<br>' ) {
  22171. html = '';
  22172. }
  22173. ngModel.$setViewValue(html);
  22174. }
  22175. }
  22176. };
  22177. }]);
  22178. </file>
  22179. <file name="index.html">
  22180. <form name="myForm">
  22181. <div contenteditable
  22182. name="myWidget" ng-model="userContent"
  22183. strip-br="true"
  22184. required>Change me!</div>
  22185. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  22186. <hr>
  22187. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  22188. </form>
  22189. </file>
  22190. <file name="protractor.js" type="protractor">
  22191. it('should data-bind and become invalid', function() {
  22192. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  22193. // SafariDriver can't handle contenteditable
  22194. // and Firefox driver can't clear contenteditables very well
  22195. return;
  22196. }
  22197. var contentEditable = element(by.css('[contenteditable]'));
  22198. var content = 'Change me!';
  22199. expect(contentEditable.getText()).toEqual(content);
  22200. contentEditable.clear();
  22201. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  22202. expect(contentEditable.getText()).toEqual('');
  22203. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  22204. });
  22205. </file>
  22206. * </example>
  22207. *
  22208. *
  22209. */
  22210. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
  22211. function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
  22212. this.$viewValue = Number.NaN;
  22213. this.$modelValue = Number.NaN;
  22214. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  22215. this.$validators = {};
  22216. this.$asyncValidators = {};
  22217. this.$parsers = [];
  22218. this.$formatters = [];
  22219. this.$viewChangeListeners = [];
  22220. this.$untouched = true;
  22221. this.$touched = false;
  22222. this.$pristine = true;
  22223. this.$dirty = false;
  22224. this.$valid = true;
  22225. this.$invalid = false;
  22226. this.$error = {}; // keep invalid keys here
  22227. this.$$success = {}; // keep valid keys here
  22228. this.$pending = undefined; // keep pending keys here
  22229. this.$name = $interpolate($attr.name || '', false)($scope);
  22230. var parsedNgModel = $parse($attr.ngModel),
  22231. parsedNgModelAssign = parsedNgModel.assign,
  22232. ngModelGet = parsedNgModel,
  22233. ngModelSet = parsedNgModelAssign,
  22234. pendingDebounce = null,
  22235. parserValid,
  22236. ctrl = this;
  22237. this.$$setOptions = function(options) {
  22238. ctrl.$options = options;
  22239. if (options && options.getterSetter) {
  22240. var invokeModelGetter = $parse($attr.ngModel + '()'),
  22241. invokeModelSetter = $parse($attr.ngModel + '($$$p)');
  22242. ngModelGet = function($scope) {
  22243. var modelValue = parsedNgModel($scope);
  22244. if (isFunction(modelValue)) {
  22245. modelValue = invokeModelGetter($scope);
  22246. }
  22247. return modelValue;
  22248. };
  22249. ngModelSet = function($scope, newValue) {
  22250. if (isFunction(parsedNgModel($scope))) {
  22251. invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
  22252. } else {
  22253. parsedNgModelAssign($scope, ctrl.$modelValue);
  22254. }
  22255. };
  22256. } else if (!parsedNgModel.assign) {
  22257. throw $ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  22258. $attr.ngModel, startingTag($element));
  22259. }
  22260. };
  22261. /**
  22262. * @ngdoc method
  22263. * @name ngModel.NgModelController#$render
  22264. *
  22265. * @description
  22266. * Called when the view needs to be updated. It is expected that the user of the ng-model
  22267. * directive will implement this method.
  22268. *
  22269. * The `$render()` method is invoked in the following situations:
  22270. *
  22271. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  22272. * committed value then `$render()` is called to update the input control.
  22273. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  22274. * the `$viewValue` are different from last time.
  22275. *
  22276. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  22277. * `$modelValue` and `$viewValue` are actually different from their previous value. If `$modelValue`
  22278. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  22279. * invoked if you only change a property on the objects.
  22280. */
  22281. this.$render = noop;
  22282. /**
  22283. * @ngdoc method
  22284. * @name ngModel.NgModelController#$isEmpty
  22285. *
  22286. * @description
  22287. * This is called when we need to determine if the value of an input is empty.
  22288. *
  22289. * For instance, the required directive does this to work out if the input has data or not.
  22290. *
  22291. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  22292. *
  22293. * You can override this for input directives whose concept of being empty is different from the
  22294. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  22295. * implies empty.
  22296. *
  22297. * @param {*} value The value of the input to check for emptiness.
  22298. * @returns {boolean} True if `value` is "empty".
  22299. */
  22300. this.$isEmpty = function(value) {
  22301. return isUndefined(value) || value === '' || value === null || value !== value;
  22302. };
  22303. var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
  22304. currentValidationRunId = 0;
  22305. /**
  22306. * @ngdoc method
  22307. * @name ngModel.NgModelController#$setValidity
  22308. *
  22309. * @description
  22310. * Change the validity state, and notify the form.
  22311. *
  22312. * This method can be called within $parsers/$formatters or a custom validation implementation.
  22313. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  22314. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  22315. *
  22316. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  22317. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  22318. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  22319. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  22320. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  22321. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  22322. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  22323. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  22324. * Skipped is used by Angular when validators do not run because of parse errors and
  22325. * when `$asyncValidators` do not run because any of the `$validators` failed.
  22326. */
  22327. addSetValidityMethod({
  22328. ctrl: this,
  22329. $element: $element,
  22330. set: function(object, property) {
  22331. object[property] = true;
  22332. },
  22333. unset: function(object, property) {
  22334. delete object[property];
  22335. },
  22336. parentForm: parentForm,
  22337. $animate: $animate
  22338. });
  22339. /**
  22340. * @ngdoc method
  22341. * @name ngModel.NgModelController#$setPristine
  22342. *
  22343. * @description
  22344. * Sets the control to its pristine state.
  22345. *
  22346. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  22347. * state (`ng-pristine` class). A model is considered to be pristine when the control
  22348. * has not been changed from when first compiled.
  22349. */
  22350. this.$setPristine = function() {
  22351. ctrl.$dirty = false;
  22352. ctrl.$pristine = true;
  22353. $animate.removeClass($element, DIRTY_CLASS);
  22354. $animate.addClass($element, PRISTINE_CLASS);
  22355. };
  22356. /**
  22357. * @ngdoc method
  22358. * @name ngModel.NgModelController#$setDirty
  22359. *
  22360. * @description
  22361. * Sets the control to its dirty state.
  22362. *
  22363. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  22364. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  22365. * from when first compiled.
  22366. */
  22367. this.$setDirty = function() {
  22368. ctrl.$dirty = true;
  22369. ctrl.$pristine = false;
  22370. $animate.removeClass($element, PRISTINE_CLASS);
  22371. $animate.addClass($element, DIRTY_CLASS);
  22372. parentForm.$setDirty();
  22373. };
  22374. /**
  22375. * @ngdoc method
  22376. * @name ngModel.NgModelController#$setUntouched
  22377. *
  22378. * @description
  22379. * Sets the control to its untouched state.
  22380. *
  22381. * This method can be called to remove the `ng-touched` class and set the control to its
  22382. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  22383. * by default, however this function can be used to restore that state if the model has
  22384. * already been touched by the user.
  22385. */
  22386. this.$setUntouched = function() {
  22387. ctrl.$touched = false;
  22388. ctrl.$untouched = true;
  22389. $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  22390. };
  22391. /**
  22392. * @ngdoc method
  22393. * @name ngModel.NgModelController#$setTouched
  22394. *
  22395. * @description
  22396. * Sets the control to its touched state.
  22397. *
  22398. * This method can be called to remove the `ng-untouched` class and set the control to its
  22399. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  22400. * first focused the control element and then shifted focus away from the control (blur event).
  22401. */
  22402. this.$setTouched = function() {
  22403. ctrl.$touched = true;
  22404. ctrl.$untouched = false;
  22405. $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  22406. };
  22407. /**
  22408. * @ngdoc method
  22409. * @name ngModel.NgModelController#$rollbackViewValue
  22410. *
  22411. * @description
  22412. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  22413. * which may be caused by a pending debounced event or because the input is waiting for a some
  22414. * future event.
  22415. *
  22416. * If you have an input that uses `ng-model-options` to set up debounced events or events such
  22417. * as blur you can have a situation where there is a period when the `$viewValue`
  22418. * is out of synch with the ngModel's `$modelValue`.
  22419. *
  22420. * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`
  22421. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  22422. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  22423. *
  22424. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  22425. * input which may have such events pending. This is important in order to make sure that the
  22426. * input field will be updated with the new model value and any pending operations are cancelled.
  22427. *
  22428. * <example name="ng-model-cancel-update" module="cancel-update-example">
  22429. * <file name="app.js">
  22430. * angular.module('cancel-update-example', [])
  22431. *
  22432. * .controller('CancelUpdateController', ['$scope', function($scope) {
  22433. * $scope.resetWithCancel = function(e) {
  22434. * if (e.keyCode == 27) {
  22435. * $scope.myForm.myInput1.$rollbackViewValue();
  22436. * $scope.myValue = '';
  22437. * }
  22438. * };
  22439. * $scope.resetWithoutCancel = function(e) {
  22440. * if (e.keyCode == 27) {
  22441. * $scope.myValue = '';
  22442. * }
  22443. * };
  22444. * }]);
  22445. * </file>
  22446. * <file name="index.html">
  22447. * <div ng-controller="CancelUpdateController">
  22448. * <p>Try typing something in each input. See that the model only updates when you
  22449. * blur off the input.
  22450. * </p>
  22451. * <p>Now see what happens if you start typing then press the Escape key</p>
  22452. *
  22453. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  22454. * <p id="inputDescription1">With $rollbackViewValue()</p>
  22455. * <input name="myInput1" aria-describedby="inputDescription1" ng-model="myValue"
  22456. * ng-keydown="resetWithCancel($event)"><br/>
  22457. * myValue: "{{ myValue }}"
  22458. *
  22459. * <p id="inputDescription2">Without $rollbackViewValue()</p>
  22460. * <input name="myInput2" aria-describedby="inputDescription2" ng-model="myValue"
  22461. * ng-keydown="resetWithoutCancel($event)"><br/>
  22462. * myValue: "{{ myValue }}"
  22463. * </form>
  22464. * </div>
  22465. * </file>
  22466. * </example>
  22467. */
  22468. this.$rollbackViewValue = function() {
  22469. $timeout.cancel(pendingDebounce);
  22470. ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
  22471. ctrl.$render();
  22472. };
  22473. /**
  22474. * @ngdoc method
  22475. * @name ngModel.NgModelController#$validate
  22476. *
  22477. * @description
  22478. * Runs each of the registered validators (first synchronous validators and then
  22479. * asynchronous validators).
  22480. * If the validity changes to invalid, the model will be set to `undefined`,
  22481. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  22482. * If the validity changes to valid, it will set the model to the last available valid
  22483. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  22484. */
  22485. this.$validate = function() {
  22486. // ignore $validate before model is initialized
  22487. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  22488. return;
  22489. }
  22490. var viewValue = ctrl.$$lastCommittedViewValue;
  22491. // Note: we use the $$rawModelValue as $modelValue might have been
  22492. // set to undefined during a view -> model update that found validation
  22493. // errors. We can't parse the view here, since that could change
  22494. // the model although neither viewValue nor the model on the scope changed
  22495. var modelValue = ctrl.$$rawModelValue;
  22496. var prevValid = ctrl.$valid;
  22497. var prevModelValue = ctrl.$modelValue;
  22498. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  22499. ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
  22500. // If there was no change in validity, don't update the model
  22501. // This prevents changing an invalid modelValue to undefined
  22502. if (!allowInvalid && prevValid !== allValid) {
  22503. // Note: Don't check ctrl.$valid here, as we could have
  22504. // external validators (e.g. calculated on the server),
  22505. // that just call $setValidity and need the model value
  22506. // to calculate their validity.
  22507. ctrl.$modelValue = allValid ? modelValue : undefined;
  22508. if (ctrl.$modelValue !== prevModelValue) {
  22509. ctrl.$$writeModelToScope();
  22510. }
  22511. }
  22512. });
  22513. };
  22514. this.$$runValidators = function(modelValue, viewValue, doneCallback) {
  22515. currentValidationRunId++;
  22516. var localValidationRunId = currentValidationRunId;
  22517. // check parser error
  22518. if (!processParseErrors()) {
  22519. validationDone(false);
  22520. return;
  22521. }
  22522. if (!processSyncValidators()) {
  22523. validationDone(false);
  22524. return;
  22525. }
  22526. processAsyncValidators();
  22527. function processParseErrors() {
  22528. var errorKey = ctrl.$$parserName || 'parse';
  22529. if (parserValid === undefined) {
  22530. setValidity(errorKey, null);
  22531. } else {
  22532. if (!parserValid) {
  22533. forEach(ctrl.$validators, function(v, name) {
  22534. setValidity(name, null);
  22535. });
  22536. forEach(ctrl.$asyncValidators, function(v, name) {
  22537. setValidity(name, null);
  22538. });
  22539. }
  22540. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  22541. setValidity(errorKey, parserValid);
  22542. return parserValid;
  22543. }
  22544. return true;
  22545. }
  22546. function processSyncValidators() {
  22547. var syncValidatorsValid = true;
  22548. forEach(ctrl.$validators, function(validator, name) {
  22549. var result = validator(modelValue, viewValue);
  22550. syncValidatorsValid = syncValidatorsValid && result;
  22551. setValidity(name, result);
  22552. });
  22553. if (!syncValidatorsValid) {
  22554. forEach(ctrl.$asyncValidators, function(v, name) {
  22555. setValidity(name, null);
  22556. });
  22557. return false;
  22558. }
  22559. return true;
  22560. }
  22561. function processAsyncValidators() {
  22562. var validatorPromises = [];
  22563. var allValid = true;
  22564. forEach(ctrl.$asyncValidators, function(validator, name) {
  22565. var promise = validator(modelValue, viewValue);
  22566. if (!isPromiseLike(promise)) {
  22567. throw $ngModelMinErr("$asyncValidators",
  22568. "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
  22569. }
  22570. setValidity(name, undefined);
  22571. validatorPromises.push(promise.then(function() {
  22572. setValidity(name, true);
  22573. }, function(error) {
  22574. allValid = false;
  22575. setValidity(name, false);
  22576. }));
  22577. });
  22578. if (!validatorPromises.length) {
  22579. validationDone(true);
  22580. } else {
  22581. $q.all(validatorPromises).then(function() {
  22582. validationDone(allValid);
  22583. }, noop);
  22584. }
  22585. }
  22586. function setValidity(name, isValid) {
  22587. if (localValidationRunId === currentValidationRunId) {
  22588. ctrl.$setValidity(name, isValid);
  22589. }
  22590. }
  22591. function validationDone(allValid) {
  22592. if (localValidationRunId === currentValidationRunId) {
  22593. doneCallback(allValid);
  22594. }
  22595. }
  22596. };
  22597. /**
  22598. * @ngdoc method
  22599. * @name ngModel.NgModelController#$commitViewValue
  22600. *
  22601. * @description
  22602. * Commit a pending update to the `$modelValue`.
  22603. *
  22604. * Updates may be pending by a debounced event or because the input is waiting for a some future
  22605. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  22606. * usually handles calling this in response to input events.
  22607. */
  22608. this.$commitViewValue = function() {
  22609. var viewValue = ctrl.$viewValue;
  22610. $timeout.cancel(pendingDebounce);
  22611. // If the view value has not changed then we should just exit, except in the case where there is
  22612. // a native validator on the element. In this case the validation state may have changed even though
  22613. // the viewValue has stayed empty.
  22614. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
  22615. return;
  22616. }
  22617. ctrl.$$lastCommittedViewValue = viewValue;
  22618. // change to dirty
  22619. if (ctrl.$pristine) {
  22620. this.$setDirty();
  22621. }
  22622. this.$$parseAndValidate();
  22623. };
  22624. this.$$parseAndValidate = function() {
  22625. var viewValue = ctrl.$$lastCommittedViewValue;
  22626. var modelValue = viewValue;
  22627. parserValid = isUndefined(modelValue) ? undefined : true;
  22628. if (parserValid) {
  22629. for (var i = 0; i < ctrl.$parsers.length; i++) {
  22630. modelValue = ctrl.$parsers[i](modelValue);
  22631. if (isUndefined(modelValue)) {
  22632. parserValid = false;
  22633. break;
  22634. }
  22635. }
  22636. }
  22637. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  22638. // ctrl.$modelValue has not been touched yet...
  22639. ctrl.$modelValue = ngModelGet($scope);
  22640. }
  22641. var prevModelValue = ctrl.$modelValue;
  22642. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  22643. ctrl.$$rawModelValue = modelValue;
  22644. if (allowInvalid) {
  22645. ctrl.$modelValue = modelValue;
  22646. writeToModelIfNeeded();
  22647. }
  22648. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  22649. // This can happen if e.g. $setViewValue is called from inside a parser
  22650. ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
  22651. if (!allowInvalid) {
  22652. // Note: Don't check ctrl.$valid here, as we could have
  22653. // external validators (e.g. calculated on the server),
  22654. // that just call $setValidity and need the model value
  22655. // to calculate their validity.
  22656. ctrl.$modelValue = allValid ? modelValue : undefined;
  22657. writeToModelIfNeeded();
  22658. }
  22659. });
  22660. function writeToModelIfNeeded() {
  22661. if (ctrl.$modelValue !== prevModelValue) {
  22662. ctrl.$$writeModelToScope();
  22663. }
  22664. }
  22665. };
  22666. this.$$writeModelToScope = function() {
  22667. ngModelSet($scope, ctrl.$modelValue);
  22668. forEach(ctrl.$viewChangeListeners, function(listener) {
  22669. try {
  22670. listener();
  22671. } catch (e) {
  22672. $exceptionHandler(e);
  22673. }
  22674. });
  22675. };
  22676. /**
  22677. * @ngdoc method
  22678. * @name ngModel.NgModelController#$setViewValue
  22679. *
  22680. * @description
  22681. * Update the view value.
  22682. *
  22683. * This method should be called when an input directive want to change the view value; typically,
  22684. * this is done from within a DOM event handler.
  22685. *
  22686. * For example {@link ng.directive:input input} calls it when the value of the input changes and
  22687. * {@link ng.directive:select select} calls it when an option is selected.
  22688. *
  22689. * If the new `value` is an object (rather than a string or a number), we should make a copy of the
  22690. * object before passing it to `$setViewValue`. This is because `ngModel` does not perform a deep
  22691. * watch of objects, it only looks for a change of identity. If you only change the property of
  22692. * the object then ngModel will not realise that the object has changed and will not invoke the
  22693. * `$parsers` and `$validators` pipelines.
  22694. *
  22695. * For this reason, you should not change properties of the copy once it has been passed to
  22696. * `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly.
  22697. *
  22698. * When this method is called, the new `value` will be staged for committing through the `$parsers`
  22699. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  22700. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  22701. * **expression** specified in the `ng-model` attribute.
  22702. *
  22703. * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
  22704. *
  22705. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  22706. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  22707. * `updateOn` events is triggered on the DOM element.
  22708. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  22709. * directive is used with a custom debounce for this particular event.
  22710. *
  22711. * Note that calling this function does not trigger a `$digest`.
  22712. *
  22713. * @param {string} value Value from the view.
  22714. * @param {string} trigger Event that triggered the update.
  22715. */
  22716. this.$setViewValue = function(value, trigger) {
  22717. ctrl.$viewValue = value;
  22718. if (!ctrl.$options || ctrl.$options.updateOnDefault) {
  22719. ctrl.$$debounceViewValueCommit(trigger);
  22720. }
  22721. };
  22722. this.$$debounceViewValueCommit = function(trigger) {
  22723. var debounceDelay = 0,
  22724. options = ctrl.$options,
  22725. debounce;
  22726. if (options && isDefined(options.debounce)) {
  22727. debounce = options.debounce;
  22728. if (isNumber(debounce)) {
  22729. debounceDelay = debounce;
  22730. } else if (isNumber(debounce[trigger])) {
  22731. debounceDelay = debounce[trigger];
  22732. } else if (isNumber(debounce['default'])) {
  22733. debounceDelay = debounce['default'];
  22734. }
  22735. }
  22736. $timeout.cancel(pendingDebounce);
  22737. if (debounceDelay) {
  22738. pendingDebounce = $timeout(function() {
  22739. ctrl.$commitViewValue();
  22740. }, debounceDelay);
  22741. } else if ($rootScope.$$phase) {
  22742. ctrl.$commitViewValue();
  22743. } else {
  22744. $scope.$apply(function() {
  22745. ctrl.$commitViewValue();
  22746. });
  22747. }
  22748. };
  22749. // model -> value
  22750. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  22751. // 1. scope value is 'a'
  22752. // 2. user enters 'b'
  22753. // 3. ng-change kicks in and reverts scope value to 'a'
  22754. // -> scope value did not change since the last digest as
  22755. // ng-change executes in apply phase
  22756. // 4. view should be changed back to 'a'
  22757. $scope.$watch(function ngModelWatch() {
  22758. var modelValue = ngModelGet($scope);
  22759. // if scope model value and ngModel value are out of sync
  22760. // TODO(perf): why not move this to the action fn?
  22761. if (modelValue !== ctrl.$modelValue &&
  22762. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  22763. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  22764. ) {
  22765. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  22766. parserValid = undefined;
  22767. var formatters = ctrl.$formatters,
  22768. idx = formatters.length;
  22769. var viewValue = modelValue;
  22770. while (idx--) {
  22771. viewValue = formatters[idx](viewValue);
  22772. }
  22773. if (ctrl.$viewValue !== viewValue) {
  22774. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  22775. ctrl.$render();
  22776. ctrl.$$runValidators(modelValue, viewValue, noop);
  22777. }
  22778. }
  22779. return modelValue;
  22780. });
  22781. }];
  22782. /**
  22783. * @ngdoc directive
  22784. * @name ngModel
  22785. *
  22786. * @element input
  22787. * @priority 1
  22788. *
  22789. * @description
  22790. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  22791. * property on the scope using {@link ngModel.NgModelController NgModelController},
  22792. * which is created and exposed by this directive.
  22793. *
  22794. * `ngModel` is responsible for:
  22795. *
  22796. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  22797. * require.
  22798. * - Providing validation behavior (i.e. required, number, email, url).
  22799. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  22800. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.
  22801. * - Registering the control with its parent {@link ng.directive:form form}.
  22802. *
  22803. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  22804. * current scope. If the property doesn't already exist on this scope, it will be created
  22805. * implicitly and added to the scope.
  22806. *
  22807. * For best practices on using `ngModel`, see:
  22808. *
  22809. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  22810. *
  22811. * For basic examples, how to use `ngModel`, see:
  22812. *
  22813. * - {@link ng.directive:input input}
  22814. * - {@link input[text] text}
  22815. * - {@link input[checkbox] checkbox}
  22816. * - {@link input[radio] radio}
  22817. * - {@link input[number] number}
  22818. * - {@link input[email] email}
  22819. * - {@link input[url] url}
  22820. * - {@link input[date] date}
  22821. * - {@link input[datetime-local] datetime-local}
  22822. * - {@link input[time] time}
  22823. * - {@link input[month] month}
  22824. * - {@link input[week] week}
  22825. * - {@link ng.directive:select select}
  22826. * - {@link ng.directive:textarea textarea}
  22827. *
  22828. * # CSS classes
  22829. * The following CSS classes are added and removed on the associated input/select/textarea element
  22830. * depending on the validity of the model.
  22831. *
  22832. * - `ng-valid`: the model is valid
  22833. * - `ng-invalid`: the model is invalid
  22834. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  22835. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  22836. * - `ng-pristine`: the control hasn't been interacted with yet
  22837. * - `ng-dirty`: the control has been interacted with
  22838. * - `ng-touched`: the control has been blurred
  22839. * - `ng-untouched`: the control hasn't been blurred
  22840. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  22841. *
  22842. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  22843. *
  22844. * ## Animation Hooks
  22845. *
  22846. * Animations within models are triggered when any of the associated CSS classes are added and removed
  22847. * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
  22848. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  22849. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  22850. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  22851. *
  22852. * The following example shows a simple way to utilize CSS transitions to style an input element
  22853. * that has been rendered as invalid after it has been validated:
  22854. *
  22855. * <pre>
  22856. * //be sure to include ngAnimate as a module to hook into more
  22857. * //advanced animations
  22858. * .my-input {
  22859. * transition:0.5s linear all;
  22860. * background: white;
  22861. * }
  22862. * .my-input.ng-invalid {
  22863. * background: red;
  22864. * color:white;
  22865. * }
  22866. * </pre>
  22867. *
  22868. * @example
  22869. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  22870. <file name="index.html">
  22871. <script>
  22872. angular.module('inputExample', [])
  22873. .controller('ExampleController', ['$scope', function($scope) {
  22874. $scope.val = '1';
  22875. }]);
  22876. </script>
  22877. <style>
  22878. .my-input {
  22879. -webkit-transition:all linear 0.5s;
  22880. transition:all linear 0.5s;
  22881. background: transparent;
  22882. }
  22883. .my-input.ng-invalid {
  22884. color:white;
  22885. background: red;
  22886. }
  22887. </style>
  22888. <p id="inputDescription">
  22889. Update input to see transitions when valid/invalid.
  22890. Integer is a valid value.
  22891. </p>
  22892. <form name="testForm" ng-controller="ExampleController">
  22893. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  22894. aria-describedby="inputDescription" />
  22895. </form>
  22896. </file>
  22897. * </example>
  22898. *
  22899. * ## Binding to a getter/setter
  22900. *
  22901. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  22902. * function that returns a representation of the model when called with zero arguments, and sets
  22903. * the internal state of a model when called with an argument. It's sometimes useful to use this
  22904. * for models that have an internal representation that's different from what the model exposes
  22905. * to the view.
  22906. *
  22907. * <div class="alert alert-success">
  22908. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  22909. * frequently than other parts of your code.
  22910. * </div>
  22911. *
  22912. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  22913. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  22914. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  22915. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  22916. *
  22917. * The following example shows how to use `ngModel` with a getter/setter:
  22918. *
  22919. * @example
  22920. * <example name="ngModel-getter-setter" module="getterSetterExample">
  22921. <file name="index.html">
  22922. <div ng-controller="ExampleController">
  22923. <form name="userForm">
  22924. <label>Name:
  22925. <input type="text" name="userName"
  22926. ng-model="user.name"
  22927. ng-model-options="{ getterSetter: true }" />
  22928. </label>
  22929. </form>
  22930. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  22931. </div>
  22932. </file>
  22933. <file name="app.js">
  22934. angular.module('getterSetterExample', [])
  22935. .controller('ExampleController', ['$scope', function($scope) {
  22936. var _name = 'Brian';
  22937. $scope.user = {
  22938. name: function(newName) {
  22939. // Note that newName can be undefined for two reasons:
  22940. // 1. Because it is called as a getter and thus called with no arguments
  22941. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  22942. // input is invalid
  22943. return arguments.length ? (_name = newName) : _name;
  22944. }
  22945. };
  22946. }]);
  22947. </file>
  22948. * </example>
  22949. */
  22950. var ngModelDirective = ['$rootScope', function($rootScope) {
  22951. return {
  22952. restrict: 'A',
  22953. require: ['ngModel', '^?form', '^?ngModelOptions'],
  22954. controller: NgModelController,
  22955. // Prelink needs to run before any input directive
  22956. // so that we can set the NgModelOptions in NgModelController
  22957. // before anyone else uses it.
  22958. priority: 1,
  22959. compile: function ngModelCompile(element) {
  22960. // Setup initial state of the control
  22961. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  22962. return {
  22963. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  22964. var modelCtrl = ctrls[0],
  22965. formCtrl = ctrls[1] || nullFormCtrl;
  22966. modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
  22967. // notify others, especially parent forms
  22968. formCtrl.$addControl(modelCtrl);
  22969. attr.$observe('name', function(newValue) {
  22970. if (modelCtrl.$name !== newValue) {
  22971. formCtrl.$$renameControl(modelCtrl, newValue);
  22972. }
  22973. });
  22974. scope.$on('$destroy', function() {
  22975. formCtrl.$removeControl(modelCtrl);
  22976. });
  22977. },
  22978. post: function ngModelPostLink(scope, element, attr, ctrls) {
  22979. var modelCtrl = ctrls[0];
  22980. if (modelCtrl.$options && modelCtrl.$options.updateOn) {
  22981. element.on(modelCtrl.$options.updateOn, function(ev) {
  22982. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  22983. });
  22984. }
  22985. element.on('blur', function(ev) {
  22986. if (modelCtrl.$touched) return;
  22987. if ($rootScope.$$phase) {
  22988. scope.$evalAsync(modelCtrl.$setTouched);
  22989. } else {
  22990. scope.$apply(modelCtrl.$setTouched);
  22991. }
  22992. });
  22993. }
  22994. };
  22995. }
  22996. };
  22997. }];
  22998. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  22999. /**
  23000. * @ngdoc directive
  23001. * @name ngModelOptions
  23002. *
  23003. * @description
  23004. * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
  23005. * events that will trigger a model update and/or a debouncing delay so that the actual update only
  23006. * takes place when a timer expires; this timer will be reset after another change takes place.
  23007. *
  23008. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  23009. * be different from the value in the actual model. This means that if you update the model you
  23010. * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
  23011. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  23012. *
  23013. * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
  23014. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  23015. * important because `form` controllers are published to the related scope under the name in their
  23016. * `name` attribute.
  23017. *
  23018. * Any pending changes will take place immediately when an enclosing form is submitted via the
  23019. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  23020. * to have access to the updated model.
  23021. *
  23022. * `ngModelOptions` has an effect on the element it's declared on and its descendants.
  23023. *
  23024. * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
  23025. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  23026. * events using an space delimited list. There is a special event called `default` that
  23027. * matches the default events belonging of the control.
  23028. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  23029. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  23030. * custom value for each event. For example:
  23031. * `ng-model-options="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }"`
  23032. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  23033. * not validate correctly instead of the default behavior of setting the model to undefined.
  23034. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  23035. `ngModel` as getters/setters.
  23036. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  23037. * `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
  23038. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  23039. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  23040. * If not specified, the timezone of the browser will be used.
  23041. *
  23042. * @example
  23043. The following example shows how to override immediate updates. Changes on the inputs within the
  23044. form will update the model only when the control loses focus (blur event). If `escape` key is
  23045. pressed while the input field is focused, the value is reset to the value in the current model.
  23046. <example name="ngModelOptions-directive-blur" module="optionsExample">
  23047. <file name="index.html">
  23048. <div ng-controller="ExampleController">
  23049. <form name="userForm">
  23050. <label>Name:
  23051. <input type="text" name="userName"
  23052. ng-model="user.name"
  23053. ng-model-options="{ updateOn: 'blur' }"
  23054. ng-keyup="cancel($event)" />
  23055. </label><br />
  23056. <label>Other data:
  23057. <input type="text" ng-model="user.data" />
  23058. </label><br />
  23059. </form>
  23060. <pre>user.name = <span ng-bind="user.name"></span></pre>
  23061. </div>
  23062. </file>
  23063. <file name="app.js">
  23064. angular.module('optionsExample', [])
  23065. .controller('ExampleController', ['$scope', function($scope) {
  23066. $scope.user = { name: 'say', data: '' };
  23067. $scope.cancel = function(e) {
  23068. if (e.keyCode == 27) {
  23069. $scope.userForm.userName.$rollbackViewValue();
  23070. }
  23071. };
  23072. }]);
  23073. </file>
  23074. <file name="protractor.js" type="protractor">
  23075. var model = element(by.binding('user.name'));
  23076. var input = element(by.model('user.name'));
  23077. var other = element(by.model('user.data'));
  23078. it('should allow custom events', function() {
  23079. input.sendKeys(' hello');
  23080. input.click();
  23081. expect(model.getText()).toEqual('say');
  23082. other.click();
  23083. expect(model.getText()).toEqual('say hello');
  23084. });
  23085. it('should $rollbackViewValue when model changes', function() {
  23086. input.sendKeys(' hello');
  23087. expect(input.getAttribute('value')).toEqual('say hello');
  23088. input.sendKeys(protractor.Key.ESCAPE);
  23089. expect(input.getAttribute('value')).toEqual('say');
  23090. other.click();
  23091. expect(model.getText()).toEqual('say');
  23092. });
  23093. </file>
  23094. </example>
  23095. This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
  23096. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  23097. <example name="ngModelOptions-directive-debounce" module="optionsExample">
  23098. <file name="index.html">
  23099. <div ng-controller="ExampleController">
  23100. <form name="userForm">
  23101. <label>Name:
  23102. <input type="text" name="userName"
  23103. ng-model="user.name"
  23104. ng-model-options="{ debounce: 1000 }" />
  23105. </label>
  23106. <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
  23107. <br />
  23108. </form>
  23109. <pre>user.name = <span ng-bind="user.name"></span></pre>
  23110. </div>
  23111. </file>
  23112. <file name="app.js">
  23113. angular.module('optionsExample', [])
  23114. .controller('ExampleController', ['$scope', function($scope) {
  23115. $scope.user = { name: 'say' };
  23116. }]);
  23117. </file>
  23118. </example>
  23119. This one shows how to bind to getter/setters:
  23120. <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  23121. <file name="index.html">
  23122. <div ng-controller="ExampleController">
  23123. <form name="userForm">
  23124. <label>Name:
  23125. <input type="text" name="userName"
  23126. ng-model="user.name"
  23127. ng-model-options="{ getterSetter: true }" />
  23128. </label>
  23129. </form>
  23130. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  23131. </div>
  23132. </file>
  23133. <file name="app.js">
  23134. angular.module('getterSetterExample', [])
  23135. .controller('ExampleController', ['$scope', function($scope) {
  23136. var _name = 'Brian';
  23137. $scope.user = {
  23138. name: function(newName) {
  23139. // Note that newName can be undefined for two reasons:
  23140. // 1. Because it is called as a getter and thus called with no arguments
  23141. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  23142. // input is invalid
  23143. return arguments.length ? (_name = newName) : _name;
  23144. }
  23145. };
  23146. }]);
  23147. </file>
  23148. </example>
  23149. */
  23150. var ngModelOptionsDirective = function() {
  23151. return {
  23152. restrict: 'A',
  23153. controller: ['$scope', '$attrs', function($scope, $attrs) {
  23154. var that = this;
  23155. this.$options = copy($scope.$eval($attrs.ngModelOptions));
  23156. // Allow adding/overriding bound events
  23157. if (this.$options.updateOn !== undefined) {
  23158. this.$options.updateOnDefault = false;
  23159. // extract "default" pseudo-event from list of events that can trigger a model update
  23160. this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
  23161. that.$options.updateOnDefault = true;
  23162. return ' ';
  23163. }));
  23164. } else {
  23165. this.$options.updateOnDefault = true;
  23166. }
  23167. }]
  23168. };
  23169. };
  23170. // helper methods
  23171. function addSetValidityMethod(context) {
  23172. var ctrl = context.ctrl,
  23173. $element = context.$element,
  23174. classCache = {},
  23175. set = context.set,
  23176. unset = context.unset,
  23177. parentForm = context.parentForm,
  23178. $animate = context.$animate;
  23179. classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
  23180. ctrl.$setValidity = setValidity;
  23181. function setValidity(validationErrorKey, state, controller) {
  23182. if (state === undefined) {
  23183. createAndSet('$pending', validationErrorKey, controller);
  23184. } else {
  23185. unsetAndCleanup('$pending', validationErrorKey, controller);
  23186. }
  23187. if (!isBoolean(state)) {
  23188. unset(ctrl.$error, validationErrorKey, controller);
  23189. unset(ctrl.$$success, validationErrorKey, controller);
  23190. } else {
  23191. if (state) {
  23192. unset(ctrl.$error, validationErrorKey, controller);
  23193. set(ctrl.$$success, validationErrorKey, controller);
  23194. } else {
  23195. set(ctrl.$error, validationErrorKey, controller);
  23196. unset(ctrl.$$success, validationErrorKey, controller);
  23197. }
  23198. }
  23199. if (ctrl.$pending) {
  23200. cachedToggleClass(PENDING_CLASS, true);
  23201. ctrl.$valid = ctrl.$invalid = undefined;
  23202. toggleValidationCss('', null);
  23203. } else {
  23204. cachedToggleClass(PENDING_CLASS, false);
  23205. ctrl.$valid = isObjectEmpty(ctrl.$error);
  23206. ctrl.$invalid = !ctrl.$valid;
  23207. toggleValidationCss('', ctrl.$valid);
  23208. }
  23209. // re-read the state as the set/unset methods could have
  23210. // combined state in ctrl.$error[validationError] (used for forms),
  23211. // where setting/unsetting only increments/decrements the value,
  23212. // and does not replace it.
  23213. var combinedState;
  23214. if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
  23215. combinedState = undefined;
  23216. } else if (ctrl.$error[validationErrorKey]) {
  23217. combinedState = false;
  23218. } else if (ctrl.$$success[validationErrorKey]) {
  23219. combinedState = true;
  23220. } else {
  23221. combinedState = null;
  23222. }
  23223. toggleValidationCss(validationErrorKey, combinedState);
  23224. parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
  23225. }
  23226. function createAndSet(name, value, controller) {
  23227. if (!ctrl[name]) {
  23228. ctrl[name] = {};
  23229. }
  23230. set(ctrl[name], value, controller);
  23231. }
  23232. function unsetAndCleanup(name, value, controller) {
  23233. if (ctrl[name]) {
  23234. unset(ctrl[name], value, controller);
  23235. }
  23236. if (isObjectEmpty(ctrl[name])) {
  23237. ctrl[name] = undefined;
  23238. }
  23239. }
  23240. function cachedToggleClass(className, switchValue) {
  23241. if (switchValue && !classCache[className]) {
  23242. $animate.addClass($element, className);
  23243. classCache[className] = true;
  23244. } else if (!switchValue && classCache[className]) {
  23245. $animate.removeClass($element, className);
  23246. classCache[className] = false;
  23247. }
  23248. }
  23249. function toggleValidationCss(validationErrorKey, isValid) {
  23250. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  23251. cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
  23252. cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
  23253. }
  23254. }
  23255. function isObjectEmpty(obj) {
  23256. if (obj) {
  23257. for (var prop in obj) {
  23258. return false;
  23259. }
  23260. }
  23261. return true;
  23262. }
  23263. /**
  23264. * @ngdoc directive
  23265. * @name ngNonBindable
  23266. * @restrict AC
  23267. * @priority 1000
  23268. *
  23269. * @description
  23270. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  23271. * DOM element. This is useful if the element contains what appears to be Angular directives and
  23272. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  23273. * displays snippets of code, for instance.
  23274. *
  23275. * @element ANY
  23276. *
  23277. * @example
  23278. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  23279. * but the one wrapped in `ngNonBindable` is left alone.
  23280. *
  23281. * @example
  23282. <example>
  23283. <file name="index.html">
  23284. <div>Normal: {{1 + 2}}</div>
  23285. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  23286. </file>
  23287. <file name="protractor.js" type="protractor">
  23288. it('should check ng-non-bindable', function() {
  23289. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  23290. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  23291. });
  23292. </file>
  23293. </example>
  23294. */
  23295. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  23296. /* global jqLiteRemove */
  23297. var ngOptionsMinErr = minErr('ngOptions');
  23298. /**
  23299. * @ngdoc directive
  23300. * @name ngOptions
  23301. * @restrict A
  23302. *
  23303. * @description
  23304. *
  23305. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  23306. * elements for the `<select>` element using the array or object obtained by evaluating the
  23307. * `ngOptions` comprehension expression.
  23308. *
  23309. * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
  23310. * similar result. However, `ngOptions` provides some benefits such as reducing memory and
  23311. * increasing speed by not creating a new scope for each repeated instance, as well as providing
  23312. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  23313. * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
  23314. * to a non-string value. This is because an option element can only be bound to string values at
  23315. * present.
  23316. *
  23317. * When an item in the `<select>` menu is selected, the array element or object property
  23318. * represented by the selected option will be bound to the model identified by the `ngModel`
  23319. * directive.
  23320. *
  23321. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  23322. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  23323. * option. See example below for demonstration.
  23324. *
  23325. * ## Complex Models (objects or collections)
  23326. *
  23327. * **Note:** By default, `ngModel` watches the model by reference, not value. This is important when
  23328. * binding any input directive to a model that is an object or a collection.
  23329. *
  23330. * Since this is a common situation for `ngOptions` the directive additionally watches the model using
  23331. * `$watchCollection` when the select has the `multiple` attribute or when there is a `track by` clause in
  23332. * the options expression. This allows ngOptions to trigger a re-rendering of the options even if the actual
  23333. * object/collection has not changed identity but only a property on the object or an item in the collection
  23334. * changes.
  23335. *
  23336. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  23337. * if the model is an array). This means that changing a property deeper inside the object/collection that the
  23338. * first level will not trigger a re-rendering.
  23339. *
  23340. *
  23341. * ## `select` **`as`**
  23342. *
  23343. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  23344. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  23345. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  23346. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  23347. *
  23348. *
  23349. * ### `select` **`as`** and **`track by`**
  23350. *
  23351. * <div class="alert alert-warning">
  23352. * Do not use `select` **`as`** and **`track by`** in the same expression. They are not designed to work together.
  23353. * </div>
  23354. *
  23355. * Consider the following example:
  23356. *
  23357. * ```html
  23358. * <select ng-options="item.subItem as item.label for item in values track by item.id" ng-model="selected">
  23359. * ```
  23360. *
  23361. * ```js
  23362. * $scope.values = [{
  23363. * id: 1,
  23364. * label: 'aLabel',
  23365. * subItem: { name: 'aSubItem' }
  23366. * }, {
  23367. * id: 2,
  23368. * label: 'bLabel',
  23369. * subItem: { name: 'bSubItem' }
  23370. * }];
  23371. *
  23372. * $scope.selected = { name: 'aSubItem' };
  23373. * ```
  23374. *
  23375. * With the purpose of preserving the selection, the **`track by`** expression is always applied to the element
  23376. * of the data source (to `item` in this example). To calculate whether an element is selected, we do the
  23377. * following:
  23378. *
  23379. * 1. Apply **`track by`** to the elements in the array. In the example: `[1, 2]`
  23380. * 2. Apply **`track by`** to the already selected value in `ngModel`.
  23381. * In the example: this is not possible as **`track by`** refers to `item.id`, but the selected
  23382. * value from `ngModel` is `{name: 'aSubItem'}`, so the **`track by`** expression is applied to
  23383. * a wrong object, the selected element can't be found, `<select>` is always reset to the "not
  23384. * selected" option.
  23385. *
  23386. *
  23387. * @param {string} ngModel Assignable angular expression to data-bind to.
  23388. * @param {string=} name Property name of the form under which the control is published.
  23389. * @param {string=} required The control is considered valid only if value is entered.
  23390. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23391. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23392. * `required` when you want to data-bind to the `required` attribute.
  23393. * @param {comprehension_expression=} ngOptions in one of the following forms:
  23394. *
  23395. * * for array data sources:
  23396. * * `label` **`for`** `value` **`in`** `array`
  23397. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  23398. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  23399. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  23400. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  23401. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  23402. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  23403. * (for including a filter with `track by`)
  23404. * * for object data sources:
  23405. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  23406. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  23407. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  23408. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  23409. * * `select` **`as`** `label` **`group by`** `group`
  23410. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  23411. * * `select` **`as`** `label` **`disable when`** `disable`
  23412. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  23413. *
  23414. * Where:
  23415. *
  23416. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  23417. * * `value`: local variable which will refer to each item in the `array` or each property value
  23418. * of `object` during iteration.
  23419. * * `key`: local variable which will refer to a property name in `object` during iteration.
  23420. * * `label`: The result of this expression will be the label for `<option>` element. The
  23421. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  23422. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  23423. * element. If not specified, `select` expression will default to `value`.
  23424. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  23425. * DOM element.
  23426. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  23427. * element. Return `true` to disable.
  23428. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  23429. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  23430. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  23431. * even when the options are recreated (e.g. reloaded from the server).
  23432. *
  23433. * @example
  23434. <example module="selectExample">
  23435. <file name="index.html">
  23436. <script>
  23437. angular.module('selectExample', [])
  23438. .controller('ExampleController', ['$scope', function($scope) {
  23439. $scope.colors = [
  23440. {name:'black', shade:'dark'},
  23441. {name:'white', shade:'light', notAnOption: true},
  23442. {name:'red', shade:'dark'},
  23443. {name:'blue', shade:'dark', notAnOption: true},
  23444. {name:'yellow', shade:'light', notAnOption: false}
  23445. ];
  23446. $scope.myColor = $scope.colors[2]; // red
  23447. }]);
  23448. </script>
  23449. <div ng-controller="ExampleController">
  23450. <ul>
  23451. <li ng-repeat="color in colors">
  23452. <label>Name: <input ng-model="color.name"></label>
  23453. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  23454. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  23455. </li>
  23456. <li>
  23457. <button ng-click="colors.push({})">add</button>
  23458. </li>
  23459. </ul>
  23460. <hr/>
  23461. <label>Color (null not allowed):
  23462. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  23463. </label><br/>
  23464. <label>Color (null allowed):
  23465. <span class="nullable">
  23466. <select ng-model="myColor" ng-options="color.name for color in colors">
  23467. <option value="">-- choose color --</option>
  23468. </select>
  23469. </span></label><br/>
  23470. <label>Color grouped by shade:
  23471. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  23472. </select>
  23473. </label><br/>
  23474. <label>Color grouped by shade, with some disabled:
  23475. <select ng-model="myColor"
  23476. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  23477. </select>
  23478. </label><br/>
  23479. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  23480. <br/>
  23481. <hr/>
  23482. Currently selected: {{ {selected_color:myColor} }}
  23483. <div style="border:solid 1px black; height:20px"
  23484. ng-style="{'background-color':myColor.name}">
  23485. </div>
  23486. </div>
  23487. </file>
  23488. <file name="protractor.js" type="protractor">
  23489. it('should check ng-options', function() {
  23490. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  23491. element.all(by.model('myColor')).first().click();
  23492. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  23493. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  23494. element(by.css('.nullable select[ng-model="myColor"]')).click();
  23495. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  23496. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  23497. });
  23498. </file>
  23499. </example>
  23500. */
  23501. // jshint maxlen: false
  23502. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
  23503. 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]+?))?$/;
  23504. // 1: value expression (valueFn)
  23505. // 2: label expression (displayFn)
  23506. // 3: group by expression (groupByFn)
  23507. // 4: disable when expression (disableWhenFn)
  23508. // 5: array item variable name
  23509. // 6: object item key variable name
  23510. // 7: object item value variable name
  23511. // 8: collection expression
  23512. // 9: track by expression
  23513. // jshint maxlen: 100
  23514. var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
  23515. function parseOptionsExpression(optionsExp, selectElement, scope) {
  23516. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  23517. if (!(match)) {
  23518. throw ngOptionsMinErr('iexp',
  23519. "Expected expression in form of " +
  23520. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  23521. " but got '{0}'. Element: {1}",
  23522. optionsExp, startingTag(selectElement));
  23523. }
  23524. // Extract the parts from the ngOptions expression
  23525. // The variable name for the value of the item in the collection
  23526. var valueName = match[5] || match[7];
  23527. // The variable name for the key of the item in the collection
  23528. var keyName = match[6];
  23529. // An expression that generates the viewValue for an option if there is a label expression
  23530. var selectAs = / as /.test(match[0]) && match[1];
  23531. // An expression that is used to track the id of each object in the options collection
  23532. var trackBy = match[9];
  23533. // An expression that generates the viewValue for an option if there is no label expression
  23534. var valueFn = $parse(match[2] ? match[1] : valueName);
  23535. var selectAsFn = selectAs && $parse(selectAs);
  23536. var viewValueFn = selectAsFn || valueFn;
  23537. var trackByFn = trackBy && $parse(trackBy);
  23538. // Get the value by which we are going to track the option
  23539. // if we have a trackFn then use that (passing scope and locals)
  23540. // otherwise just hash the given viewValue
  23541. var getTrackByValueFn = trackBy ?
  23542. function(value, locals) { return trackByFn(scope, locals); } :
  23543. function getHashOfValue(value) { return hashKey(value); };
  23544. var getTrackByValue = function(value, key) {
  23545. return getTrackByValueFn(value, getLocals(value, key));
  23546. };
  23547. var displayFn = $parse(match[2] || match[1]);
  23548. var groupByFn = $parse(match[3] || '');
  23549. var disableWhenFn = $parse(match[4] || '');
  23550. var valuesFn = $parse(match[8]);
  23551. var locals = {};
  23552. var getLocals = keyName ? function(value, key) {
  23553. locals[keyName] = key;
  23554. locals[valueName] = value;
  23555. return locals;
  23556. } : function(value) {
  23557. locals[valueName] = value;
  23558. return locals;
  23559. };
  23560. function Option(selectValue, viewValue, label, group, disabled) {
  23561. this.selectValue = selectValue;
  23562. this.viewValue = viewValue;
  23563. this.label = label;
  23564. this.group = group;
  23565. this.disabled = disabled;
  23566. }
  23567. return {
  23568. trackBy: trackBy,
  23569. getTrackByValue: getTrackByValue,
  23570. getWatchables: $parse(valuesFn, function(values) {
  23571. // Create a collection of things that we would like to watch (watchedArray)
  23572. // so that they can all be watched using a single $watchCollection
  23573. // that only runs the handler once if anything changes
  23574. var watchedArray = [];
  23575. values = values || [];
  23576. Object.keys(values).forEach(function getWatchable(key) {
  23577. var locals = getLocals(values[key], key);
  23578. var selectValue = getTrackByValueFn(values[key], locals);
  23579. watchedArray.push(selectValue);
  23580. // Only need to watch the displayFn if there is a specific label expression
  23581. if (match[2] || match[1]) {
  23582. var label = displayFn(scope, locals);
  23583. watchedArray.push(label);
  23584. }
  23585. // Only need to watch the disableWhenFn if there is a specific disable expression
  23586. if (match[4]) {
  23587. var disableWhen = disableWhenFn(scope, locals);
  23588. watchedArray.push(disableWhen);
  23589. }
  23590. });
  23591. return watchedArray;
  23592. }),
  23593. getOptions: function() {
  23594. var optionItems = [];
  23595. var selectValueMap = {};
  23596. // The option values were already computed in the `getWatchables` fn,
  23597. // which must have been called to trigger `getOptions`
  23598. var optionValues = valuesFn(scope) || [];
  23599. var optionValuesKeys;
  23600. if (!keyName && isArrayLike(optionValues)) {
  23601. optionValuesKeys = optionValues;
  23602. } else {
  23603. // if object, extract keys, in enumeration order, unsorted
  23604. optionValuesKeys = [];
  23605. for (var itemKey in optionValues) {
  23606. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  23607. optionValuesKeys.push(itemKey);
  23608. }
  23609. }
  23610. }
  23611. var optionValuesLength = optionValuesKeys.length;
  23612. for (var index = 0; index < optionValuesLength; index++) {
  23613. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  23614. var value = optionValues[key];
  23615. var locals = getLocals(value, key);
  23616. var viewValue = viewValueFn(scope, locals);
  23617. var selectValue = getTrackByValueFn(viewValue, locals);
  23618. var label = displayFn(scope, locals);
  23619. var group = groupByFn(scope, locals);
  23620. var disabled = disableWhenFn(scope, locals);
  23621. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  23622. optionItems.push(optionItem);
  23623. selectValueMap[selectValue] = optionItem;
  23624. }
  23625. return {
  23626. items: optionItems,
  23627. selectValueMap: selectValueMap,
  23628. getOptionFromViewValue: function(value) {
  23629. return selectValueMap[getTrackByValue(value)];
  23630. },
  23631. getViewValueFromOption: function(option) {
  23632. // If the viewValue could be an object that may be mutated by the application,
  23633. // we need to make a copy and not return the reference to the value on the option.
  23634. return trackBy ? angular.copy(option.viewValue) : option.viewValue;
  23635. }
  23636. };
  23637. }
  23638. };
  23639. }
  23640. // we can't just jqLite('<option>') since jqLite is not smart enough
  23641. // to create it in <select> and IE barfs otherwise.
  23642. var optionTemplate = document.createElement('option'),
  23643. optGroupTemplate = document.createElement('optgroup');
  23644. return {
  23645. restrict: 'A',
  23646. terminal: true,
  23647. require: ['select', '?ngModel'],
  23648. link: function(scope, selectElement, attr, ctrls) {
  23649. // if ngModel is not defined, we don't need to do anything
  23650. var ngModelCtrl = ctrls[1];
  23651. if (!ngModelCtrl) return;
  23652. var selectCtrl = ctrls[0];
  23653. var multiple = attr.multiple;
  23654. // The emptyOption allows the application developer to provide their own custom "empty"
  23655. // option when the viewValue does not match any of the option values.
  23656. var emptyOption;
  23657. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  23658. if (children[i].value === '') {
  23659. emptyOption = children.eq(i);
  23660. break;
  23661. }
  23662. }
  23663. var providedEmptyOption = !!emptyOption;
  23664. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  23665. unknownOption.val('?');
  23666. var options;
  23667. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  23668. var renderEmptyOption = function() {
  23669. if (!providedEmptyOption) {
  23670. selectElement.prepend(emptyOption);
  23671. }
  23672. selectElement.val('');
  23673. emptyOption.prop('selected', true); // needed for IE
  23674. emptyOption.attr('selected', true);
  23675. };
  23676. var removeEmptyOption = function() {
  23677. if (!providedEmptyOption) {
  23678. emptyOption.remove();
  23679. }
  23680. };
  23681. var renderUnknownOption = function() {
  23682. selectElement.prepend(unknownOption);
  23683. selectElement.val('?');
  23684. unknownOption.prop('selected', true); // needed for IE
  23685. unknownOption.attr('selected', true);
  23686. };
  23687. var removeUnknownOption = function() {
  23688. unknownOption.remove();
  23689. };
  23690. // Update the controller methods for multiple selectable options
  23691. if (!multiple) {
  23692. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  23693. var option = options.getOptionFromViewValue(value);
  23694. if (option && !option.disabled) {
  23695. if (selectElement[0].value !== option.selectValue) {
  23696. removeUnknownOption();
  23697. removeEmptyOption();
  23698. selectElement[0].value = option.selectValue;
  23699. option.element.selected = true;
  23700. option.element.setAttribute('selected', 'selected');
  23701. }
  23702. } else {
  23703. if (value === null || providedEmptyOption) {
  23704. removeUnknownOption();
  23705. renderEmptyOption();
  23706. } else {
  23707. removeEmptyOption();
  23708. renderUnknownOption();
  23709. }
  23710. }
  23711. };
  23712. selectCtrl.readValue = function readNgOptionsValue() {
  23713. var selectedOption = options.selectValueMap[selectElement.val()];
  23714. if (selectedOption && !selectedOption.disabled) {
  23715. removeEmptyOption();
  23716. removeUnknownOption();
  23717. return options.getViewValueFromOption(selectedOption);
  23718. }
  23719. return null;
  23720. };
  23721. // If we are using `track by` then we must watch the tracked value on the model
  23722. // since ngModel only watches for object identity change
  23723. if (ngOptions.trackBy) {
  23724. scope.$watch(
  23725. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  23726. function() { ngModelCtrl.$render(); }
  23727. );
  23728. }
  23729. } else {
  23730. ngModelCtrl.$isEmpty = function(value) {
  23731. return !value || value.length === 0;
  23732. };
  23733. selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
  23734. options.items.forEach(function(option) {
  23735. option.element.selected = false;
  23736. });
  23737. if (value) {
  23738. value.forEach(function(item) {
  23739. var option = options.getOptionFromViewValue(item);
  23740. if (option && !option.disabled) option.element.selected = true;
  23741. });
  23742. }
  23743. };
  23744. selectCtrl.readValue = function readNgOptionsMultiple() {
  23745. var selectedValues = selectElement.val() || [],
  23746. selections = [];
  23747. forEach(selectedValues, function(value) {
  23748. var option = options.selectValueMap[value];
  23749. if (!option.disabled) selections.push(options.getViewValueFromOption(option));
  23750. });
  23751. return selections;
  23752. };
  23753. // If we are using `track by` then we must watch these tracked values on the model
  23754. // since ngModel only watches for object identity change
  23755. if (ngOptions.trackBy) {
  23756. scope.$watchCollection(function() {
  23757. if (isArray(ngModelCtrl.$viewValue)) {
  23758. return ngModelCtrl.$viewValue.map(function(value) {
  23759. return ngOptions.getTrackByValue(value);
  23760. });
  23761. }
  23762. }, function() {
  23763. ngModelCtrl.$render();
  23764. });
  23765. }
  23766. }
  23767. if (providedEmptyOption) {
  23768. // we need to remove it before calling selectElement.empty() because otherwise IE will
  23769. // remove the label from the element. wtf?
  23770. emptyOption.remove();
  23771. // compile the element since there might be bindings in it
  23772. $compile(emptyOption)(scope);
  23773. // remove the class, which is added automatically because we recompile the element and it
  23774. // becomes the compilation root
  23775. emptyOption.removeClass('ng-scope');
  23776. } else {
  23777. emptyOption = jqLite(optionTemplate.cloneNode(false));
  23778. }
  23779. // We need to do this here to ensure that the options object is defined
  23780. // when we first hit it in writeNgOptionsValue
  23781. updateOptions();
  23782. // We will re-render the option elements if the option values or labels change
  23783. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  23784. // ------------------------------------------------------------------ //
  23785. function updateOptionElement(option, element) {
  23786. option.element = element;
  23787. element.disabled = option.disabled;
  23788. if (option.value !== element.value) element.value = option.selectValue;
  23789. if (option.label !== element.label) {
  23790. element.label = option.label;
  23791. element.textContent = option.label;
  23792. }
  23793. }
  23794. function addOrReuseElement(parent, current, type, templateElement) {
  23795. var element;
  23796. // Check whether we can reuse the next element
  23797. if (current && lowercase(current.nodeName) === type) {
  23798. // The next element is the right type so reuse it
  23799. element = current;
  23800. } else {
  23801. // The next element is not the right type so create a new one
  23802. element = templateElement.cloneNode(false);
  23803. if (!current) {
  23804. // There are no more elements so just append it to the select
  23805. parent.appendChild(element);
  23806. } else {
  23807. // The next element is not a group so insert the new one
  23808. parent.insertBefore(element, current);
  23809. }
  23810. }
  23811. return element;
  23812. }
  23813. function removeExcessElements(current) {
  23814. var next;
  23815. while (current) {
  23816. next = current.nextSibling;
  23817. jqLiteRemove(current);
  23818. current = next;
  23819. }
  23820. }
  23821. function skipEmptyAndUnknownOptions(current) {
  23822. var emptyOption_ = emptyOption && emptyOption[0];
  23823. var unknownOption_ = unknownOption && unknownOption[0];
  23824. if (emptyOption_ || unknownOption_) {
  23825. while (current &&
  23826. (current === emptyOption_ ||
  23827. current === unknownOption_)) {
  23828. current = current.nextSibling;
  23829. }
  23830. }
  23831. return current;
  23832. }
  23833. function updateOptions() {
  23834. var previousValue = options && selectCtrl.readValue();
  23835. options = ngOptions.getOptions();
  23836. var groupMap = {};
  23837. var currentElement = selectElement[0].firstChild;
  23838. // Ensure that the empty option is always there if it was explicitly provided
  23839. if (providedEmptyOption) {
  23840. selectElement.prepend(emptyOption);
  23841. }
  23842. currentElement = skipEmptyAndUnknownOptions(currentElement);
  23843. options.items.forEach(function updateOption(option) {
  23844. var group;
  23845. var groupElement;
  23846. var optionElement;
  23847. if (option.group) {
  23848. // This option is to live in a group
  23849. // See if we have already created this group
  23850. group = groupMap[option.group];
  23851. if (!group) {
  23852. // We have not already created this group
  23853. groupElement = addOrReuseElement(selectElement[0],
  23854. currentElement,
  23855. 'optgroup',
  23856. optGroupTemplate);
  23857. // Move to the next element
  23858. currentElement = groupElement.nextSibling;
  23859. // Update the label on the group element
  23860. groupElement.label = option.group;
  23861. // Store it for use later
  23862. group = groupMap[option.group] = {
  23863. groupElement: groupElement,
  23864. currentOptionElement: groupElement.firstChild
  23865. };
  23866. }
  23867. // So now we have a group for this option we add the option to the group
  23868. optionElement = addOrReuseElement(group.groupElement,
  23869. group.currentOptionElement,
  23870. 'option',
  23871. optionTemplate);
  23872. updateOptionElement(option, optionElement);
  23873. // Move to the next element
  23874. group.currentOptionElement = optionElement.nextSibling;
  23875. } else {
  23876. // This option is not in a group
  23877. optionElement = addOrReuseElement(selectElement[0],
  23878. currentElement,
  23879. 'option',
  23880. optionTemplate);
  23881. updateOptionElement(option, optionElement);
  23882. // Move to the next element
  23883. currentElement = optionElement.nextSibling;
  23884. }
  23885. });
  23886. // Now remove all excess options and group
  23887. Object.keys(groupMap).forEach(function(key) {
  23888. removeExcessElements(groupMap[key].currentOptionElement);
  23889. });
  23890. removeExcessElements(currentElement);
  23891. ngModelCtrl.$render();
  23892. // Check to see if the value has changed due to the update to the options
  23893. if (!ngModelCtrl.$isEmpty(previousValue)) {
  23894. var nextValue = selectCtrl.readValue();
  23895. if (ngOptions.trackBy && !equals(previousValue, nextValue) ||
  23896. previousValue !== nextValue) {
  23897. ngModelCtrl.$setViewValue(nextValue);
  23898. ngModelCtrl.$render();
  23899. }
  23900. }
  23901. }
  23902. }
  23903. };
  23904. }];
  23905. /**
  23906. * @ngdoc directive
  23907. * @name ngPluralize
  23908. * @restrict EA
  23909. *
  23910. * @description
  23911. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  23912. * These rules are bundled with angular.js, but can be overridden
  23913. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  23914. * by specifying the mappings between
  23915. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  23916. * and the strings to be displayed.
  23917. *
  23918. * # Plural categories and explicit number rules
  23919. * There are two
  23920. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  23921. * in Angular's default en-US locale: "one" and "other".
  23922. *
  23923. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  23924. * any number that is not 1), an explicit number rule can only match one number. For example, the
  23925. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  23926. * and explicit number rules throughout the rest of this documentation.
  23927. *
  23928. * # Configuring ngPluralize
  23929. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  23930. * You can also provide an optional attribute, `offset`.
  23931. *
  23932. * The value of the `count` attribute can be either a string or an {@link guide/expression
  23933. * Angular expression}; these are evaluated on the current scope for its bound value.
  23934. *
  23935. * The `when` attribute specifies the mappings between plural categories and the actual
  23936. * string to be displayed. The value of the attribute should be a JSON object.
  23937. *
  23938. * The following example shows how to configure ngPluralize:
  23939. *
  23940. * ```html
  23941. * <ng-pluralize count="personCount"
  23942. when="{'0': 'Nobody is viewing.',
  23943. * 'one': '1 person is viewing.',
  23944. * 'other': '{} people are viewing.'}">
  23945. * </ng-pluralize>
  23946. *```
  23947. *
  23948. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  23949. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  23950. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  23951. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  23952. * show "a dozen people are viewing".
  23953. *
  23954. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  23955. * into pluralized strings. In the previous example, Angular will replace `{}` with
  23956. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  23957. * for <span ng-non-bindable>{{numberExpression}}</span>.
  23958. *
  23959. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  23960. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  23961. *
  23962. * # Configuring ngPluralize with offset
  23963. * The `offset` attribute allows further customization of pluralized text, which can result in
  23964. * a better user experience. For example, instead of the message "4 people are viewing this document",
  23965. * you might display "John, Kate and 2 others are viewing this document".
  23966. * The offset attribute allows you to offset a number by any desired value.
  23967. * Let's take a look at an example:
  23968. *
  23969. * ```html
  23970. * <ng-pluralize count="personCount" offset=2
  23971. * when="{'0': 'Nobody is viewing.',
  23972. * '1': '{{person1}} is viewing.',
  23973. * '2': '{{person1}} and {{person2}} are viewing.',
  23974. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  23975. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  23976. * </ng-pluralize>
  23977. * ```
  23978. *
  23979. * Notice that we are still using two plural categories(one, other), but we added
  23980. * three explicit number rules 0, 1 and 2.
  23981. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  23982. * When three people view the document, no explicit number rule is found, so
  23983. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  23984. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  23985. * is shown.
  23986. *
  23987. * Note that when you specify offsets, you must provide explicit number rules for
  23988. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  23989. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  23990. * plural categories "one" and "other".
  23991. *
  23992. * @param {string|expression} count The variable to be bound to.
  23993. * @param {string} when The mapping between plural category to its corresponding strings.
  23994. * @param {number=} offset Offset to deduct from the total number.
  23995. *
  23996. * @example
  23997. <example module="pluralizeExample">
  23998. <file name="index.html">
  23999. <script>
  24000. angular.module('pluralizeExample', [])
  24001. .controller('ExampleController', ['$scope', function($scope) {
  24002. $scope.person1 = 'Igor';
  24003. $scope.person2 = 'Misko';
  24004. $scope.personCount = 1;
  24005. }]);
  24006. </script>
  24007. <div ng-controller="ExampleController">
  24008. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  24009. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  24010. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  24011. <!--- Example with simple pluralization rules for en locale --->
  24012. Without Offset:
  24013. <ng-pluralize count="personCount"
  24014. when="{'0': 'Nobody is viewing.',
  24015. 'one': '1 person is viewing.',
  24016. 'other': '{} people are viewing.'}">
  24017. </ng-pluralize><br>
  24018. <!--- Example with offset --->
  24019. With Offset(2):
  24020. <ng-pluralize count="personCount" offset=2
  24021. when="{'0': 'Nobody is viewing.',
  24022. '1': '{{person1}} is viewing.',
  24023. '2': '{{person1}} and {{person2}} are viewing.',
  24024. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  24025. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  24026. </ng-pluralize>
  24027. </div>
  24028. </file>
  24029. <file name="protractor.js" type="protractor">
  24030. it('should show correct pluralized string', function() {
  24031. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  24032. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  24033. var countInput = element(by.model('personCount'));
  24034. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  24035. expect(withOffset.getText()).toEqual('Igor is viewing.');
  24036. countInput.clear();
  24037. countInput.sendKeys('0');
  24038. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  24039. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  24040. countInput.clear();
  24041. countInput.sendKeys('2');
  24042. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  24043. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  24044. countInput.clear();
  24045. countInput.sendKeys('3');
  24046. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  24047. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  24048. countInput.clear();
  24049. countInput.sendKeys('4');
  24050. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  24051. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  24052. });
  24053. it('should show data-bound names', function() {
  24054. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  24055. var personCount = element(by.model('personCount'));
  24056. var person1 = element(by.model('person1'));
  24057. var person2 = element(by.model('person2'));
  24058. personCount.clear();
  24059. personCount.sendKeys('4');
  24060. person1.clear();
  24061. person1.sendKeys('Di');
  24062. person2.clear();
  24063. person2.sendKeys('Vojta');
  24064. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  24065. });
  24066. </file>
  24067. </example>
  24068. */
  24069. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  24070. var BRACE = /{}/g,
  24071. IS_WHEN = /^when(Minus)?(.+)$/;
  24072. return {
  24073. link: function(scope, element, attr) {
  24074. var numberExp = attr.count,
  24075. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  24076. offset = attr.offset || 0,
  24077. whens = scope.$eval(whenExp) || {},
  24078. whensExpFns = {},
  24079. startSymbol = $interpolate.startSymbol(),
  24080. endSymbol = $interpolate.endSymbol(),
  24081. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  24082. watchRemover = angular.noop,
  24083. lastCount;
  24084. forEach(attr, function(expression, attributeName) {
  24085. var tmpMatch = IS_WHEN.exec(attributeName);
  24086. if (tmpMatch) {
  24087. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  24088. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  24089. }
  24090. });
  24091. forEach(whens, function(expression, key) {
  24092. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  24093. });
  24094. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  24095. var count = parseFloat(newVal);
  24096. var countIsNaN = isNaN(count);
  24097. if (!countIsNaN && !(count in whens)) {
  24098. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  24099. // Otherwise, check it against pluralization rules in $locale service.
  24100. count = $locale.pluralCat(count - offset);
  24101. }
  24102. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  24103. // In JS `NaN !== NaN`, so we have to exlicitly check.
  24104. if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {
  24105. watchRemover();
  24106. var whenExpFn = whensExpFns[count];
  24107. if (isUndefined(whenExpFn)) {
  24108. if (newVal != null) {
  24109. $log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp);
  24110. }
  24111. watchRemover = noop;
  24112. updateElementText();
  24113. } else {
  24114. watchRemover = scope.$watch(whenExpFn, updateElementText);
  24115. }
  24116. lastCount = count;
  24117. }
  24118. });
  24119. function updateElementText(newText) {
  24120. element.text(newText || '');
  24121. }
  24122. }
  24123. };
  24124. }];
  24125. /**
  24126. * @ngdoc directive
  24127. * @name ngRepeat
  24128. *
  24129. * @description
  24130. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  24131. * instance gets its own scope, where the given loop variable is set to the current collection item,
  24132. * and `$index` is set to the item index or key.
  24133. *
  24134. * Special properties are exposed on the local scope of each template instance, including:
  24135. *
  24136. * | Variable | Type | Details |
  24137. * |-----------|-----------------|-----------------------------------------------------------------------------|
  24138. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  24139. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  24140. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  24141. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  24142. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  24143. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  24144. *
  24145. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  24146. * This may be useful when, for instance, nesting ngRepeats.
  24147. *
  24148. *
  24149. * # Iterating over object properties
  24150. *
  24151. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  24152. * syntax:
  24153. *
  24154. * ```js
  24155. * <div ng-repeat="(key, value) in myObj"> ... </div>
  24156. * ```
  24157. *
  24158. * You need to be aware that the JavaScript specification does not define the order of keys
  24159. * returned for an object. (To mitigate this in Angular 1.3 the `ngRepeat` directive
  24160. * used to sort the keys alphabetically.)
  24161. *
  24162. * Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser
  24163. * when running `for key in myObj`. It seems that browsers generally follow the strategy of providing
  24164. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  24165. * and reinstated. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_issues
  24166. *
  24167. * If this is not desired, the recommended workaround is to convert your object into an array
  24168. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  24169. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  24170. * or implement a `$watch` on the object yourself.
  24171. *
  24172. *
  24173. * # Tracking and Duplicates
  24174. *
  24175. * When the contents of the collection change, `ngRepeat` makes the corresponding changes to the DOM:
  24176. *
  24177. * * When an item is added, a new instance of the template is added to the DOM.
  24178. * * When an item is removed, its template instance is removed from the DOM.
  24179. * * When items are reordered, their respective templates are reordered in the DOM.
  24180. *
  24181. * By default, `ngRepeat` does not allow duplicate items in arrays. This is because when
  24182. * there are duplicates, it is not possible to maintain a one-to-one mapping between collection
  24183. * items and DOM elements.
  24184. *
  24185. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  24186. * with your own using the `track by` expression.
  24187. *
  24188. * For example, you may track items by the index of each item in the collection, using the
  24189. * special scope property `$index`:
  24190. * ```html
  24191. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  24192. * {{n}}
  24193. * </div>
  24194. * ```
  24195. *
  24196. * You may use arbitrary expressions in `track by`, including references to custom functions
  24197. * on the scope:
  24198. * ```html
  24199. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  24200. * {{n}}
  24201. * </div>
  24202. * ```
  24203. *
  24204. * If you are working with objects that have an identifier property, you can track
  24205. * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
  24206. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  24207. * JavaScript objects in the collection have been substituted for new ones:
  24208. * ```html
  24209. * <div ng-repeat="model in collection track by model.id">
  24210. * {{model.name}}
  24211. * </div>
  24212. * ```
  24213. *
  24214. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  24215. * `$id` function, which tracks items by their identity:
  24216. * ```html
  24217. * <div ng-repeat="obj in collection track by $id(obj)">
  24218. * {{obj.prop}}
  24219. * </div>
  24220. * ```
  24221. *
  24222. * # Special repeat start and end points
  24223. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  24224. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  24225. * 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)
  24226. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  24227. *
  24228. * The example below makes use of this feature:
  24229. * ```html
  24230. * <header ng-repeat-start="item in items">
  24231. * Header {{ item }}
  24232. * </header>
  24233. * <div class="body">
  24234. * Body {{ item }}
  24235. * </div>
  24236. * <footer ng-repeat-end>
  24237. * Footer {{ item }}
  24238. * </footer>
  24239. * ```
  24240. *
  24241. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  24242. * ```html
  24243. * <header>
  24244. * Header A
  24245. * </header>
  24246. * <div class="body">
  24247. * Body A
  24248. * </div>
  24249. * <footer>
  24250. * Footer A
  24251. * </footer>
  24252. * <header>
  24253. * Header B
  24254. * </header>
  24255. * <div class="body">
  24256. * Body B
  24257. * </div>
  24258. * <footer>
  24259. * Footer B
  24260. * </footer>
  24261. * ```
  24262. *
  24263. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  24264. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  24265. *
  24266. * @animations
  24267. * **.enter** - when a new item is added to the list or when an item is revealed after a filter
  24268. *
  24269. * **.leave** - when an item is removed from the list or when an item is filtered out
  24270. *
  24271. * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
  24272. *
  24273. * @element ANY
  24274. * @scope
  24275. * @priority 1000
  24276. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  24277. * formats are currently supported:
  24278. *
  24279. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  24280. * is a scope expression giving the collection to enumerate.
  24281. *
  24282. * For example: `album in artist.albums`.
  24283. *
  24284. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  24285. * and `expression` is the scope expression giving the collection to enumerate.
  24286. *
  24287. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  24288. *
  24289. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  24290. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  24291. * is specified, ng-repeat associates elements by identity. It is an error to have
  24292. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  24293. * mapped to the same DOM element, which is not possible.) If filters are used in the expression, they should be
  24294. * applied before the tracking expression.
  24295. *
  24296. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  24297. * will be associated by item identity in the array.
  24298. *
  24299. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  24300. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  24301. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  24302. * element in the same way in the DOM.
  24303. *
  24304. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  24305. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  24306. * property is same.
  24307. *
  24308. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  24309. * to items in conjunction with a tracking expression.
  24310. *
  24311. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  24312. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  24313. * when a filter is active on the repeater, but the filtered result set is empty.
  24314. *
  24315. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  24316. * the items have been processed through the filter.
  24317. *
  24318. * 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
  24319. * (and not as operator, inside an expression).
  24320. *
  24321. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
  24322. *
  24323. * @example
  24324. * This example initializes the scope to a list of names and
  24325. * then uses `ngRepeat` to display every person:
  24326. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  24327. <file name="index.html">
  24328. <div ng-init="friends = [
  24329. {name:'John', age:25, gender:'boy'},
  24330. {name:'Jessie', age:30, gender:'girl'},
  24331. {name:'Johanna', age:28, gender:'girl'},
  24332. {name:'Joy', age:15, gender:'girl'},
  24333. {name:'Mary', age:28, gender:'girl'},
  24334. {name:'Peter', age:95, gender:'boy'},
  24335. {name:'Sebastian', age:50, gender:'boy'},
  24336. {name:'Erika', age:27, gender:'girl'},
  24337. {name:'Patrick', age:40, gender:'boy'},
  24338. {name:'Samantha', age:60, gender:'girl'}
  24339. ]">
  24340. I have {{friends.length}} friends. They are:
  24341. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  24342. <ul class="example-animate-container">
  24343. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  24344. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  24345. </li>
  24346. <li class="animate-repeat" ng-if="results.length == 0">
  24347. <strong>No results found...</strong>
  24348. </li>
  24349. </ul>
  24350. </div>
  24351. </file>
  24352. <file name="animations.css">
  24353. .example-animate-container {
  24354. background:white;
  24355. border:1px solid black;
  24356. list-style:none;
  24357. margin:0;
  24358. padding:0 10px;
  24359. }
  24360. .animate-repeat {
  24361. line-height:40px;
  24362. list-style:none;
  24363. box-sizing:border-box;
  24364. }
  24365. .animate-repeat.ng-move,
  24366. .animate-repeat.ng-enter,
  24367. .animate-repeat.ng-leave {
  24368. -webkit-transition:all linear 0.5s;
  24369. transition:all linear 0.5s;
  24370. }
  24371. .animate-repeat.ng-leave.ng-leave-active,
  24372. .animate-repeat.ng-move,
  24373. .animate-repeat.ng-enter {
  24374. opacity:0;
  24375. max-height:0;
  24376. }
  24377. .animate-repeat.ng-leave,
  24378. .animate-repeat.ng-move.ng-move-active,
  24379. .animate-repeat.ng-enter.ng-enter-active {
  24380. opacity:1;
  24381. max-height:40px;
  24382. }
  24383. </file>
  24384. <file name="protractor.js" type="protractor">
  24385. var friends = element.all(by.repeater('friend in friends'));
  24386. it('should render initial data set', function() {
  24387. expect(friends.count()).toBe(10);
  24388. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  24389. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  24390. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  24391. expect(element(by.binding('friends.length')).getText())
  24392. .toMatch("I have 10 friends. They are:");
  24393. });
  24394. it('should update repeater when filter predicate changes', function() {
  24395. expect(friends.count()).toBe(10);
  24396. element(by.model('q')).sendKeys('ma');
  24397. expect(friends.count()).toBe(2);
  24398. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  24399. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  24400. });
  24401. </file>
  24402. </example>
  24403. */
  24404. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  24405. var NG_REMOVED = '$$NG_REMOVED';
  24406. var ngRepeatMinErr = minErr('ngRepeat');
  24407. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  24408. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  24409. scope[valueIdentifier] = value;
  24410. if (keyIdentifier) scope[keyIdentifier] = key;
  24411. scope.$index = index;
  24412. scope.$first = (index === 0);
  24413. scope.$last = (index === (arrayLength - 1));
  24414. scope.$middle = !(scope.$first || scope.$last);
  24415. // jshint bitwise: false
  24416. scope.$odd = !(scope.$even = (index&1) === 0);
  24417. // jshint bitwise: true
  24418. };
  24419. var getBlockStart = function(block) {
  24420. return block.clone[0];
  24421. };
  24422. var getBlockEnd = function(block) {
  24423. return block.clone[block.clone.length - 1];
  24424. };
  24425. return {
  24426. restrict: 'A',
  24427. multiElement: true,
  24428. transclude: 'element',
  24429. priority: 1000,
  24430. terminal: true,
  24431. $$tlb: true,
  24432. compile: function ngRepeatCompile($element, $attr) {
  24433. var expression = $attr.ngRepeat;
  24434. var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
  24435. 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*$/);
  24436. if (!match) {
  24437. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  24438. expression);
  24439. }
  24440. var lhs = match[1];
  24441. var rhs = match[2];
  24442. var aliasAs = match[3];
  24443. var trackByExp = match[4];
  24444. match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
  24445. if (!match) {
  24446. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  24447. lhs);
  24448. }
  24449. var valueIdentifier = match[3] || match[1];
  24450. var keyIdentifier = match[2];
  24451. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  24452. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  24453. throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
  24454. aliasAs);
  24455. }
  24456. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  24457. var hashFnLocals = {$id: hashKey};
  24458. if (trackByExp) {
  24459. trackByExpGetter = $parse(trackByExp);
  24460. } else {
  24461. trackByIdArrayFn = function(key, value) {
  24462. return hashKey(value);
  24463. };
  24464. trackByIdObjFn = function(key) {
  24465. return key;
  24466. };
  24467. }
  24468. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  24469. if (trackByExpGetter) {
  24470. trackByIdExpFn = function(key, value, index) {
  24471. // assign key, value, and $index to the locals so that they can be used in hash functions
  24472. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  24473. hashFnLocals[valueIdentifier] = value;
  24474. hashFnLocals.$index = index;
  24475. return trackByExpGetter($scope, hashFnLocals);
  24476. };
  24477. }
  24478. // Store a list of elements from previous run. This is a hash where key is the item from the
  24479. // iterator, and the value is objects with following properties.
  24480. // - scope: bound scope
  24481. // - element: previous element.
  24482. // - index: position
  24483. //
  24484. // We are using no-proto object so that we don't need to guard against inherited props via
  24485. // hasOwnProperty.
  24486. var lastBlockMap = createMap();
  24487. //watch props
  24488. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  24489. var index, length,
  24490. previousNode = $element[0], // node that cloned nodes should be inserted after
  24491. // initialized to the comment node anchor
  24492. nextNode,
  24493. // Same as lastBlockMap but it has the current state. It will become the
  24494. // lastBlockMap on the next iteration.
  24495. nextBlockMap = createMap(),
  24496. collectionLength,
  24497. key, value, // key/value of iteration
  24498. trackById,
  24499. trackByIdFn,
  24500. collectionKeys,
  24501. block, // last object information {scope, element, id}
  24502. nextBlockOrder,
  24503. elementsToRemove;
  24504. if (aliasAs) {
  24505. $scope[aliasAs] = collection;
  24506. }
  24507. if (isArrayLike(collection)) {
  24508. collectionKeys = collection;
  24509. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  24510. } else {
  24511. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  24512. // if object, extract keys, in enumeration order, unsorted
  24513. collectionKeys = [];
  24514. for (var itemKey in collection) {
  24515. if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  24516. collectionKeys.push(itemKey);
  24517. }
  24518. }
  24519. }
  24520. collectionLength = collectionKeys.length;
  24521. nextBlockOrder = new Array(collectionLength);
  24522. // locate existing items
  24523. for (index = 0; index < collectionLength; index++) {
  24524. key = (collection === collectionKeys) ? index : collectionKeys[index];
  24525. value = collection[key];
  24526. trackById = trackByIdFn(key, value, index);
  24527. if (lastBlockMap[trackById]) {
  24528. // found previously seen block
  24529. block = lastBlockMap[trackById];
  24530. delete lastBlockMap[trackById];
  24531. nextBlockMap[trackById] = block;
  24532. nextBlockOrder[index] = block;
  24533. } else if (nextBlockMap[trackById]) {
  24534. // if collision detected. restore lastBlockMap and throw an error
  24535. forEach(nextBlockOrder, function(block) {
  24536. if (block && block.scope) lastBlockMap[block.id] = block;
  24537. });
  24538. throw ngRepeatMinErr('dupes',
  24539. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  24540. expression, trackById, value);
  24541. } else {
  24542. // new never before seen block
  24543. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  24544. nextBlockMap[trackById] = true;
  24545. }
  24546. }
  24547. // remove leftover items
  24548. for (var blockKey in lastBlockMap) {
  24549. block = lastBlockMap[blockKey];
  24550. elementsToRemove = getBlockNodes(block.clone);
  24551. $animate.leave(elementsToRemove);
  24552. if (elementsToRemove[0].parentNode) {
  24553. // if the element was not removed yet because of pending animation, mark it as deleted
  24554. // so that we can ignore it later
  24555. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  24556. elementsToRemove[index][NG_REMOVED] = true;
  24557. }
  24558. }
  24559. block.scope.$destroy();
  24560. }
  24561. // we are not using forEach for perf reasons (trying to avoid #call)
  24562. for (index = 0; index < collectionLength; index++) {
  24563. key = (collection === collectionKeys) ? index : collectionKeys[index];
  24564. value = collection[key];
  24565. block = nextBlockOrder[index];
  24566. if (block.scope) {
  24567. // if we have already seen this object, then we need to reuse the
  24568. // associated scope/element
  24569. nextNode = previousNode;
  24570. // skip nodes that are already pending removal via leave animation
  24571. do {
  24572. nextNode = nextNode.nextSibling;
  24573. } while (nextNode && nextNode[NG_REMOVED]);
  24574. if (getBlockStart(block) != nextNode) {
  24575. // existing item which got moved
  24576. $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
  24577. }
  24578. previousNode = getBlockEnd(block);
  24579. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  24580. } else {
  24581. // new item which we don't know about
  24582. $transclude(function ngRepeatTransclude(clone, scope) {
  24583. block.scope = scope;
  24584. // http://jsperf.com/clone-vs-createcomment
  24585. var endNode = ngRepeatEndComment.cloneNode(false);
  24586. clone[clone.length++] = endNode;
  24587. // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
  24588. $animate.enter(clone, null, jqLite(previousNode));
  24589. previousNode = endNode;
  24590. // Note: We only need the first/last node of the cloned nodes.
  24591. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  24592. // by a directive with templateUrl when its template arrives.
  24593. block.clone = clone;
  24594. nextBlockMap[block.id] = block;
  24595. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  24596. });
  24597. }
  24598. }
  24599. lastBlockMap = nextBlockMap;
  24600. });
  24601. };
  24602. }
  24603. };
  24604. }];
  24605. var NG_HIDE_CLASS = 'ng-hide';
  24606. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  24607. /**
  24608. * @ngdoc directive
  24609. * @name ngShow
  24610. *
  24611. * @description
  24612. * The `ngShow` directive shows or hides the given HTML element based on the expression
  24613. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  24614. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  24615. * in AngularJS and sets the display style to none (using an !important flag).
  24616. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  24617. *
  24618. * ```html
  24619. * <!-- when $scope.myValue is truthy (element is visible) -->
  24620. * <div ng-show="myValue"></div>
  24621. *
  24622. * <!-- when $scope.myValue is falsy (element is hidden) -->
  24623. * <div ng-show="myValue" class="ng-hide"></div>
  24624. * ```
  24625. *
  24626. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
  24627. * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
  24628. * from the element causing the element not to appear hidden.
  24629. *
  24630. * ## Why is !important used?
  24631. *
  24632. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  24633. * can be easily overridden by heavier selectors. For example, something as simple
  24634. * as changing the display style on a HTML list item would make hidden elements appear visible.
  24635. * This also becomes a bigger issue when dealing with CSS frameworks.
  24636. *
  24637. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  24638. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  24639. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  24640. *
  24641. * ### Overriding `.ng-hide`
  24642. *
  24643. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  24644. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  24645. * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
  24646. * with extra animation classes that can be added.
  24647. *
  24648. * ```css
  24649. * .ng-hide:not(.ng-hide-animate) {
  24650. * /&#42; this is just another form of hiding an element &#42;/
  24651. * display: block!important;
  24652. * position: absolute;
  24653. * top: -9999px;
  24654. * left: -9999px;
  24655. * }
  24656. * ```
  24657. *
  24658. * By default you don't need to override in CSS anything and the animations will work around the display style.
  24659. *
  24660. * ## A note about animations with `ngShow`
  24661. *
  24662. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  24663. * is true and false. This system works like the animation system present with ngClass except that
  24664. * you must also include the !important flag to override the display property
  24665. * so that you can perform an animation when the element is hidden during the time of the animation.
  24666. *
  24667. * ```css
  24668. * //
  24669. * //a working example can be found at the bottom of this page
  24670. * //
  24671. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  24672. * /&#42; this is required as of 1.3x to properly
  24673. * apply all styling in a show/hide animation &#42;/
  24674. * transition: 0s linear all;
  24675. * }
  24676. *
  24677. * .my-element.ng-hide-add-active,
  24678. * .my-element.ng-hide-remove-active {
  24679. * /&#42; the transition is defined in the active class &#42;/
  24680. * transition: 1s linear all;
  24681. * }
  24682. *
  24683. * .my-element.ng-hide-add { ... }
  24684. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  24685. * .my-element.ng-hide-remove { ... }
  24686. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  24687. * ```
  24688. *
  24689. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  24690. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  24691. *
  24692. * @animations
  24693. * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
  24694. * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
  24695. *
  24696. * @element ANY
  24697. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  24698. * then the element is shown or hidden respectively.
  24699. *
  24700. * @example
  24701. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  24702. <file name="index.html">
  24703. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
  24704. <div>
  24705. Show:
  24706. <div class="check-element animate-show" ng-show="checked">
  24707. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  24708. </div>
  24709. </div>
  24710. <div>
  24711. Hide:
  24712. <div class="check-element animate-show" ng-hide="checked">
  24713. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  24714. </div>
  24715. </div>
  24716. </file>
  24717. <file name="glyphicons.css">
  24718. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  24719. </file>
  24720. <file name="animations.css">
  24721. .animate-show {
  24722. line-height: 20px;
  24723. opacity: 1;
  24724. padding: 10px;
  24725. border: 1px solid black;
  24726. background: white;
  24727. }
  24728. .animate-show.ng-hide-add.ng-hide-add-active,
  24729. .animate-show.ng-hide-remove.ng-hide-remove-active {
  24730. -webkit-transition: all linear 0.5s;
  24731. transition: all linear 0.5s;
  24732. }
  24733. .animate-show.ng-hide {
  24734. line-height: 0;
  24735. opacity: 0;
  24736. padding: 0 10px;
  24737. }
  24738. .check-element {
  24739. padding: 10px;
  24740. border: 1px solid black;
  24741. background: white;
  24742. }
  24743. </file>
  24744. <file name="protractor.js" type="protractor">
  24745. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  24746. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  24747. it('should check ng-show / ng-hide', function() {
  24748. expect(thumbsUp.isDisplayed()).toBeFalsy();
  24749. expect(thumbsDown.isDisplayed()).toBeTruthy();
  24750. element(by.model('checked')).click();
  24751. expect(thumbsUp.isDisplayed()).toBeTruthy();
  24752. expect(thumbsDown.isDisplayed()).toBeFalsy();
  24753. });
  24754. </file>
  24755. </example>
  24756. */
  24757. var ngShowDirective = ['$animate', function($animate) {
  24758. return {
  24759. restrict: 'A',
  24760. multiElement: true,
  24761. link: function(scope, element, attr) {
  24762. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  24763. // we're adding a temporary, animation-specific class for ng-hide since this way
  24764. // we can control when the element is actually displayed on screen without having
  24765. // to have a global/greedy CSS selector that breaks when other animations are run.
  24766. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  24767. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  24768. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  24769. });
  24770. });
  24771. }
  24772. };
  24773. }];
  24774. /**
  24775. * @ngdoc directive
  24776. * @name ngHide
  24777. *
  24778. * @description
  24779. * The `ngHide` directive shows or hides the given HTML element based on the expression
  24780. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  24781. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  24782. * in AngularJS and sets the display style to none (using an !important flag).
  24783. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  24784. *
  24785. * ```html
  24786. * <!-- when $scope.myValue is truthy (element is hidden) -->
  24787. * <div ng-hide="myValue" class="ng-hide"></div>
  24788. *
  24789. * <!-- when $scope.myValue is falsy (element is visible) -->
  24790. * <div ng-hide="myValue"></div>
  24791. * ```
  24792. *
  24793. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
  24794. * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
  24795. * from the element causing the element not to appear hidden.
  24796. *
  24797. * ## Why is !important used?
  24798. *
  24799. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  24800. * can be easily overridden by heavier selectors. For example, something as simple
  24801. * as changing the display style on a HTML list item would make hidden elements appear visible.
  24802. * This also becomes a bigger issue when dealing with CSS frameworks.
  24803. *
  24804. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  24805. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  24806. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  24807. *
  24808. * ### Overriding `.ng-hide`
  24809. *
  24810. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  24811. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  24812. * class in CSS:
  24813. *
  24814. * ```css
  24815. * .ng-hide {
  24816. * /&#42; this is just another form of hiding an element &#42;/
  24817. * display: block!important;
  24818. * position: absolute;
  24819. * top: -9999px;
  24820. * left: -9999px;
  24821. * }
  24822. * ```
  24823. *
  24824. * By default you don't need to override in CSS anything and the animations will work around the display style.
  24825. *
  24826. * ## A note about animations with `ngHide`
  24827. *
  24828. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  24829. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  24830. * CSS class is added and removed for you instead of your own CSS class.
  24831. *
  24832. * ```css
  24833. * //
  24834. * //a working example can be found at the bottom of this page
  24835. * //
  24836. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  24837. * transition: 0.5s linear all;
  24838. * }
  24839. *
  24840. * .my-element.ng-hide-add { ... }
  24841. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  24842. * .my-element.ng-hide-remove { ... }
  24843. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  24844. * ```
  24845. *
  24846. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  24847. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  24848. *
  24849. * @animations
  24850. * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
  24851. * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
  24852. *
  24853. * @element ANY
  24854. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  24855. * the element is shown or hidden respectively.
  24856. *
  24857. * @example
  24858. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  24859. <file name="index.html">
  24860. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
  24861. <div>
  24862. Show:
  24863. <div class="check-element animate-hide" ng-show="checked">
  24864. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  24865. </div>
  24866. </div>
  24867. <div>
  24868. Hide:
  24869. <div class="check-element animate-hide" ng-hide="checked">
  24870. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  24871. </div>
  24872. </div>
  24873. </file>
  24874. <file name="glyphicons.css">
  24875. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  24876. </file>
  24877. <file name="animations.css">
  24878. .animate-hide {
  24879. -webkit-transition: all linear 0.5s;
  24880. transition: all linear 0.5s;
  24881. line-height: 20px;
  24882. opacity: 1;
  24883. padding: 10px;
  24884. border: 1px solid black;
  24885. background: white;
  24886. }
  24887. .animate-hide.ng-hide {
  24888. line-height: 0;
  24889. opacity: 0;
  24890. padding: 0 10px;
  24891. }
  24892. .check-element {
  24893. padding: 10px;
  24894. border: 1px solid black;
  24895. background: white;
  24896. }
  24897. </file>
  24898. <file name="protractor.js" type="protractor">
  24899. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  24900. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  24901. it('should check ng-show / ng-hide', function() {
  24902. expect(thumbsUp.isDisplayed()).toBeFalsy();
  24903. expect(thumbsDown.isDisplayed()).toBeTruthy();
  24904. element(by.model('checked')).click();
  24905. expect(thumbsUp.isDisplayed()).toBeTruthy();
  24906. expect(thumbsDown.isDisplayed()).toBeFalsy();
  24907. });
  24908. </file>
  24909. </example>
  24910. */
  24911. var ngHideDirective = ['$animate', function($animate) {
  24912. return {
  24913. restrict: 'A',
  24914. multiElement: true,
  24915. link: function(scope, element, attr) {
  24916. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  24917. // The comment inside of the ngShowDirective explains why we add and
  24918. // remove a temporary class for the show/hide animation
  24919. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  24920. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  24921. });
  24922. });
  24923. }
  24924. };
  24925. }];
  24926. /**
  24927. * @ngdoc directive
  24928. * @name ngStyle
  24929. * @restrict AC
  24930. *
  24931. * @description
  24932. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  24933. *
  24934. * @element ANY
  24935. * @param {expression} ngStyle
  24936. *
  24937. * {@link guide/expression Expression} which evals to an
  24938. * object whose keys are CSS style names and values are corresponding values for those CSS
  24939. * keys.
  24940. *
  24941. * Since some CSS style names are not valid keys for an object, they must be quoted.
  24942. * See the 'background-color' style in the example below.
  24943. *
  24944. * @example
  24945. <example>
  24946. <file name="index.html">
  24947. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  24948. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  24949. <input type="button" value="clear" ng-click="myStyle={}">
  24950. <br/>
  24951. <span ng-style="myStyle">Sample Text</span>
  24952. <pre>myStyle={{myStyle}}</pre>
  24953. </file>
  24954. <file name="style.css">
  24955. span {
  24956. color: black;
  24957. }
  24958. </file>
  24959. <file name="protractor.js" type="protractor">
  24960. var colorSpan = element(by.css('span'));
  24961. it('should check ng-style', function() {
  24962. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  24963. element(by.css('input[value=\'set color\']')).click();
  24964. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  24965. element(by.css('input[value=clear]')).click();
  24966. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  24967. });
  24968. </file>
  24969. </example>
  24970. */
  24971. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  24972. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  24973. if (oldStyles && (newStyles !== oldStyles)) {
  24974. forEach(oldStyles, function(val, style) { element.css(style, '');});
  24975. }
  24976. if (newStyles) element.css(newStyles);
  24977. }, true);
  24978. });
  24979. /**
  24980. * @ngdoc directive
  24981. * @name ngSwitch
  24982. * @restrict EA
  24983. *
  24984. * @description
  24985. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  24986. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  24987. * as specified in the template.
  24988. *
  24989. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  24990. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  24991. * matches the value obtained from the evaluated expression. In other words, you define a container element
  24992. * (where you place the directive), place an expression on the **`on="..."` attribute**
  24993. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  24994. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  24995. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  24996. * attribute is displayed.
  24997. *
  24998. * <div class="alert alert-info">
  24999. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  25000. * as literal string values to match against.
  25001. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  25002. * value of the expression `$scope.someVal`.
  25003. * </div>
  25004. * @animations
  25005. * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
  25006. * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
  25007. *
  25008. * @usage
  25009. *
  25010. * ```
  25011. * <ANY ng-switch="expression">
  25012. * <ANY ng-switch-when="matchValue1">...</ANY>
  25013. * <ANY ng-switch-when="matchValue2">...</ANY>
  25014. * <ANY ng-switch-default>...</ANY>
  25015. * </ANY>
  25016. * ```
  25017. *
  25018. *
  25019. * @scope
  25020. * @priority 1200
  25021. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  25022. * On child elements add:
  25023. *
  25024. * * `ngSwitchWhen`: the case statement to match against. If match then this
  25025. * case will be displayed. If the same match appears multiple times, all the
  25026. * elements will be displayed.
  25027. * * `ngSwitchDefault`: the default case when no other case match. If there
  25028. * are multiple default cases, all of them will be displayed when no other
  25029. * case match.
  25030. *
  25031. *
  25032. * @example
  25033. <example module="switchExample" deps="angular-animate.js" animations="true">
  25034. <file name="index.html">
  25035. <div ng-controller="ExampleController">
  25036. <select ng-model="selection" ng-options="item for item in items">
  25037. </select>
  25038. <code>selection={{selection}}</code>
  25039. <hr/>
  25040. <div class="animate-switch-container"
  25041. ng-switch on="selection">
  25042. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  25043. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  25044. <div class="animate-switch" ng-switch-default>default</div>
  25045. </div>
  25046. </div>
  25047. </file>
  25048. <file name="script.js">
  25049. angular.module('switchExample', ['ngAnimate'])
  25050. .controller('ExampleController', ['$scope', function($scope) {
  25051. $scope.items = ['settings', 'home', 'other'];
  25052. $scope.selection = $scope.items[0];
  25053. }]);
  25054. </file>
  25055. <file name="animations.css">
  25056. .animate-switch-container {
  25057. position:relative;
  25058. background:white;
  25059. border:1px solid black;
  25060. height:40px;
  25061. overflow:hidden;
  25062. }
  25063. .animate-switch {
  25064. padding:10px;
  25065. }
  25066. .animate-switch.ng-animate {
  25067. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  25068. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  25069. position:absolute;
  25070. top:0;
  25071. left:0;
  25072. right:0;
  25073. bottom:0;
  25074. }
  25075. .animate-switch.ng-leave.ng-leave-active,
  25076. .animate-switch.ng-enter {
  25077. top:-50px;
  25078. }
  25079. .animate-switch.ng-leave,
  25080. .animate-switch.ng-enter.ng-enter-active {
  25081. top:0;
  25082. }
  25083. </file>
  25084. <file name="protractor.js" type="protractor">
  25085. var switchElem = element(by.css('[ng-switch]'));
  25086. var select = element(by.model('selection'));
  25087. it('should start in settings', function() {
  25088. expect(switchElem.getText()).toMatch(/Settings Div/);
  25089. });
  25090. it('should change to home', function() {
  25091. select.all(by.css('option')).get(1).click();
  25092. expect(switchElem.getText()).toMatch(/Home Span/);
  25093. });
  25094. it('should select default', function() {
  25095. select.all(by.css('option')).get(2).click();
  25096. expect(switchElem.getText()).toMatch(/default/);
  25097. });
  25098. </file>
  25099. </example>
  25100. */
  25101. var ngSwitchDirective = ['$animate', function($animate) {
  25102. return {
  25103. require: 'ngSwitch',
  25104. // asks for $scope to fool the BC controller module
  25105. controller: ['$scope', function ngSwitchController() {
  25106. this.cases = {};
  25107. }],
  25108. link: function(scope, element, attr, ngSwitchController) {
  25109. var watchExpr = attr.ngSwitch || attr.on,
  25110. selectedTranscludes = [],
  25111. selectedElements = [],
  25112. previousLeaveAnimations = [],
  25113. selectedScopes = [];
  25114. var spliceFactory = function(array, index) {
  25115. return function() { array.splice(index, 1); };
  25116. };
  25117. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  25118. var i, ii;
  25119. for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
  25120. $animate.cancel(previousLeaveAnimations[i]);
  25121. }
  25122. previousLeaveAnimations.length = 0;
  25123. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  25124. var selected = getBlockNodes(selectedElements[i].clone);
  25125. selectedScopes[i].$destroy();
  25126. var promise = previousLeaveAnimations[i] = $animate.leave(selected);
  25127. promise.then(spliceFactory(previousLeaveAnimations, i));
  25128. }
  25129. selectedElements.length = 0;
  25130. selectedScopes.length = 0;
  25131. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  25132. forEach(selectedTranscludes, function(selectedTransclude) {
  25133. selectedTransclude.transclude(function(caseElement, selectedScope) {
  25134. selectedScopes.push(selectedScope);
  25135. var anchor = selectedTransclude.element;
  25136. caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
  25137. var block = { clone: caseElement };
  25138. selectedElements.push(block);
  25139. $animate.enter(caseElement, anchor.parent(), anchor);
  25140. });
  25141. });
  25142. }
  25143. });
  25144. }
  25145. };
  25146. }];
  25147. var ngSwitchWhenDirective = ngDirective({
  25148. transclude: 'element',
  25149. priority: 1200,
  25150. require: '^ngSwitch',
  25151. multiElement: true,
  25152. link: function(scope, element, attrs, ctrl, $transclude) {
  25153. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  25154. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  25155. }
  25156. });
  25157. var ngSwitchDefaultDirective = ngDirective({
  25158. transclude: 'element',
  25159. priority: 1200,
  25160. require: '^ngSwitch',
  25161. multiElement: true,
  25162. link: function(scope, element, attr, ctrl, $transclude) {
  25163. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  25164. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  25165. }
  25166. });
  25167. /**
  25168. * @ngdoc directive
  25169. * @name ngTransclude
  25170. * @restrict EAC
  25171. *
  25172. * @description
  25173. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  25174. *
  25175. * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
  25176. *
  25177. * @element ANY
  25178. *
  25179. * @example
  25180. <example module="transcludeExample">
  25181. <file name="index.html">
  25182. <script>
  25183. angular.module('transcludeExample', [])
  25184. .directive('pane', function(){
  25185. return {
  25186. restrict: 'E',
  25187. transclude: true,
  25188. scope: { title:'@' },
  25189. template: '<div style="border: 1px solid black;">' +
  25190. '<div style="background-color: gray">{{title}}</div>' +
  25191. '<ng-transclude></ng-transclude>' +
  25192. '</div>'
  25193. };
  25194. })
  25195. .controller('ExampleController', ['$scope', function($scope) {
  25196. $scope.title = 'Lorem Ipsum';
  25197. $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  25198. }]);
  25199. </script>
  25200. <div ng-controller="ExampleController">
  25201. <input ng-model="title" aria-label="title"> <br/>
  25202. <textarea ng-model="text" aria-label="text"></textarea> <br/>
  25203. <pane title="{{title}}">{{text}}</pane>
  25204. </div>
  25205. </file>
  25206. <file name="protractor.js" type="protractor">
  25207. it('should have transcluded', function() {
  25208. var titleElement = element(by.model('title'));
  25209. titleElement.clear();
  25210. titleElement.sendKeys('TITLE');
  25211. var textElement = element(by.model('text'));
  25212. textElement.clear();
  25213. textElement.sendKeys('TEXT');
  25214. expect(element(by.binding('title')).getText()).toEqual('TITLE');
  25215. expect(element(by.binding('text')).getText()).toEqual('TEXT');
  25216. });
  25217. </file>
  25218. </example>
  25219. *
  25220. */
  25221. var ngTranscludeDirective = ngDirective({
  25222. restrict: 'EAC',
  25223. link: function($scope, $element, $attrs, controller, $transclude) {
  25224. if (!$transclude) {
  25225. throw minErr('ngTransclude')('orphan',
  25226. 'Illegal use of ngTransclude directive in the template! ' +
  25227. 'No parent directive that requires a transclusion found. ' +
  25228. 'Element: {0}',
  25229. startingTag($element));
  25230. }
  25231. $transclude(function(clone) {
  25232. $element.empty();
  25233. $element.append(clone);
  25234. });
  25235. }
  25236. });
  25237. /**
  25238. * @ngdoc directive
  25239. * @name script
  25240. * @restrict E
  25241. *
  25242. * @description
  25243. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  25244. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  25245. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  25246. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  25247. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  25248. *
  25249. * @param {string} type Must be set to `'text/ng-template'`.
  25250. * @param {string} id Cache name of the template.
  25251. *
  25252. * @example
  25253. <example>
  25254. <file name="index.html">
  25255. <script type="text/ng-template" id="/tpl.html">
  25256. Content of the template.
  25257. </script>
  25258. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  25259. <div id="tpl-content" ng-include src="currentTpl"></div>
  25260. </file>
  25261. <file name="protractor.js" type="protractor">
  25262. it('should load template defined inside script tag', function() {
  25263. element(by.css('#tpl-link')).click();
  25264. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  25265. });
  25266. </file>
  25267. </example>
  25268. */
  25269. var scriptDirective = ['$templateCache', function($templateCache) {
  25270. return {
  25271. restrict: 'E',
  25272. terminal: true,
  25273. compile: function(element, attr) {
  25274. if (attr.type == 'text/ng-template') {
  25275. var templateUrl = attr.id,
  25276. text = element[0].text;
  25277. $templateCache.put(templateUrl, text);
  25278. }
  25279. }
  25280. };
  25281. }];
  25282. var noopNgModelController = { $setViewValue: noop, $render: noop };
  25283. /**
  25284. * @ngdoc type
  25285. * @name select.SelectController
  25286. * @description
  25287. * The controller for the `<select>` directive. This provides support for reading
  25288. * and writing the selected value(s) of the control and also coordinates dynamically
  25289. * added `<option>` elements, perhaps by an `ngRepeat` directive.
  25290. */
  25291. var SelectController =
  25292. ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  25293. var self = this,
  25294. optionsMap = new HashMap();
  25295. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  25296. self.ngModelCtrl = noopNgModelController;
  25297. // The "unknown" option is one that is prepended to the list if the viewValue
  25298. // does not match any of the options. When it is rendered the value of the unknown
  25299. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  25300. //
  25301. // We can't just jqLite('<option>') since jqLite is not smart enough
  25302. // to create it in <select> and IE barfs otherwise.
  25303. self.unknownOption = jqLite(document.createElement('option'));
  25304. self.renderUnknownOption = function(val) {
  25305. var unknownVal = '? ' + hashKey(val) + ' ?';
  25306. self.unknownOption.val(unknownVal);
  25307. $element.prepend(self.unknownOption);
  25308. $element.val(unknownVal);
  25309. };
  25310. $scope.$on('$destroy', function() {
  25311. // disable unknown option so that we don't do work when the whole select is being destroyed
  25312. self.renderUnknownOption = noop;
  25313. });
  25314. self.removeUnknownOption = function() {
  25315. if (self.unknownOption.parent()) self.unknownOption.remove();
  25316. };
  25317. // Read the value of the select control, the implementation of this changes depending
  25318. // upon whether the select can have multiple values and whether ngOptions is at work.
  25319. self.readValue = function readSingleValue() {
  25320. self.removeUnknownOption();
  25321. return $element.val();
  25322. };
  25323. // Write the value to the select control, the implementation of this changes depending
  25324. // upon whether the select can have multiple values and whether ngOptions is at work.
  25325. self.writeValue = function writeSingleValue(value) {
  25326. if (self.hasOption(value)) {
  25327. self.removeUnknownOption();
  25328. $element.val(value);
  25329. if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy
  25330. } else {
  25331. if (value == null && self.emptyOption) {
  25332. self.removeUnknownOption();
  25333. $element.val('');
  25334. } else {
  25335. self.renderUnknownOption(value);
  25336. }
  25337. }
  25338. };
  25339. // Tell the select control that an option, with the given value, has been added
  25340. self.addOption = function(value, element) {
  25341. assertNotHasOwnProperty(value, '"option value"');
  25342. if (value === '') {
  25343. self.emptyOption = element;
  25344. }
  25345. var count = optionsMap.get(value) || 0;
  25346. optionsMap.put(value, count + 1);
  25347. };
  25348. // Tell the select control that an option, with the given value, has been removed
  25349. self.removeOption = function(value) {
  25350. var count = optionsMap.get(value);
  25351. if (count) {
  25352. if (count === 1) {
  25353. optionsMap.remove(value);
  25354. if (value === '') {
  25355. self.emptyOption = undefined;
  25356. }
  25357. } else {
  25358. optionsMap.put(value, count - 1);
  25359. }
  25360. }
  25361. };
  25362. // Check whether the select control has an option matching the given value
  25363. self.hasOption = function(value) {
  25364. return !!optionsMap.get(value);
  25365. };
  25366. }];
  25367. /**
  25368. * @ngdoc directive
  25369. * @name select
  25370. * @restrict E
  25371. *
  25372. * @description
  25373. * HTML `SELECT` element with angular data-binding.
  25374. *
  25375. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  25376. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits such as reducing
  25377. * memory and increasing speed by not creating a new scope for each repeated instance, as well as providing
  25378. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  25379. * comprehension expression.
  25380. *
  25381. * When an item in the `<select>` menu is selected, the array element or object property
  25382. * represented by the selected option will be bound to the model identified by the `ngModel`
  25383. * directive.
  25384. *
  25385. * If the viewValue contains a value that doesn't match any of the options then the control
  25386. * will automatically add an "unknown" option, which it then removes when this is resolved.
  25387. *
  25388. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  25389. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  25390. * option. See example below for demonstration.
  25391. *
  25392. * <div class="alert alert-info">
  25393. * The value of a `select` directive used without `ngOptions` is always a string.
  25394. * When the model needs to be bound to a non-string value, you must either explictly convert it
  25395. * using a directive (see example below) or use `ngOptions` to specify the set of options.
  25396. * This is because an option element can only be bound to string values at present.
  25397. * </div>
  25398. *
  25399. * ### Example (binding `select` to a non-string value)
  25400. *
  25401. * <example name="select-with-non-string-options" module="nonStringSelect">
  25402. * <file name="index.html">
  25403. * <select ng-model="model.id" convert-to-number>
  25404. * <option value="0">Zero</option>
  25405. * <option value="1">One</option>
  25406. * <option value="2">Two</option>
  25407. * </select>
  25408. * {{ model }}
  25409. * </file>
  25410. * <file name="app.js">
  25411. * angular.module('nonStringSelect', [])
  25412. * .run(function($rootScope) {
  25413. * $rootScope.model = { id: 2 };
  25414. * })
  25415. * .directive('convertToNumber', function() {
  25416. * return {
  25417. * require: 'ngModel',
  25418. * link: function(scope, element, attrs, ngModel) {
  25419. * ngModel.$parsers.push(function(val) {
  25420. * return parseInt(val, 10);
  25421. * });
  25422. * ngModel.$formatters.push(function(val) {
  25423. * return '' + val;
  25424. * });
  25425. * }
  25426. * };
  25427. * });
  25428. * </file>
  25429. * <file name="protractor.js" type="protractor">
  25430. * it('should initialize to model', function() {
  25431. * var select = element(by.css('select'));
  25432. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  25433. * });
  25434. * </file>
  25435. * </example>
  25436. *
  25437. */
  25438. var selectDirective = function() {
  25439. return {
  25440. restrict: 'E',
  25441. require: ['select', '?ngModel'],
  25442. controller: SelectController,
  25443. link: function(scope, element, attr, ctrls) {
  25444. // if ngModel is not defined, we don't need to do anything
  25445. var ngModelCtrl = ctrls[1];
  25446. if (!ngModelCtrl) return;
  25447. var selectCtrl = ctrls[0];
  25448. selectCtrl.ngModelCtrl = ngModelCtrl;
  25449. // We delegate rendering to the `writeValue` method, which can be changed
  25450. // if the select can have multiple selected values or if the options are being
  25451. // generated by `ngOptions`
  25452. ngModelCtrl.$render = function() {
  25453. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  25454. };
  25455. // When the selected item(s) changes we delegate getting the value of the select control
  25456. // to the `readValue` method, which can be changed if the select can have multiple
  25457. // selected values or if the options are being generated by `ngOptions`
  25458. element.on('change', function() {
  25459. scope.$apply(function() {
  25460. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  25461. });
  25462. });
  25463. // If the select allows multiple values then we need to modify how we read and write
  25464. // values from and to the control; also what it means for the value to be empty and
  25465. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  25466. // doesn't trigger rendering if only an item in the array changes.
  25467. if (attr.multiple) {
  25468. // Read value now needs to check each option to see if it is selected
  25469. selectCtrl.readValue = function readMultipleValue() {
  25470. var array = [];
  25471. forEach(element.find('option'), function(option) {
  25472. if (option.selected) {
  25473. array.push(option.value);
  25474. }
  25475. });
  25476. return array;
  25477. };
  25478. // Write value now needs to set the selected property of each matching option
  25479. selectCtrl.writeValue = function writeMultipleValue(value) {
  25480. var items = new HashMap(value);
  25481. forEach(element.find('option'), function(option) {
  25482. option.selected = isDefined(items.get(option.value));
  25483. });
  25484. };
  25485. // we have to do it on each watch since ngModel watches reference, but
  25486. // we need to work of an array, so we need to see if anything was inserted/removed
  25487. var lastView, lastViewRef = NaN;
  25488. scope.$watch(function selectMultipleWatch() {
  25489. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  25490. lastView = shallowCopy(ngModelCtrl.$viewValue);
  25491. ngModelCtrl.$render();
  25492. }
  25493. lastViewRef = ngModelCtrl.$viewValue;
  25494. });
  25495. // If we are a multiple select then value is now a collection
  25496. // so the meaning of $isEmpty changes
  25497. ngModelCtrl.$isEmpty = function(value) {
  25498. return !value || value.length === 0;
  25499. };
  25500. }
  25501. }
  25502. };
  25503. };
  25504. // The option directive is purely designed to communicate the existence (or lack of)
  25505. // of dynamically created (and destroyed) option elements to their containing select
  25506. // directive via its controller.
  25507. var optionDirective = ['$interpolate', function($interpolate) {
  25508. function chromeHack(optionElement) {
  25509. // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
  25510. // Adding an <option selected="selected"> element to a <select required="required"> should
  25511. // automatically select the new element
  25512. if (optionElement[0].hasAttribute('selected')) {
  25513. optionElement[0].selected = true;
  25514. }
  25515. }
  25516. return {
  25517. restrict: 'E',
  25518. priority: 100,
  25519. compile: function(element, attr) {
  25520. // If the value attribute is not defined then we fall back to the
  25521. // text content of the option element, which may be interpolated
  25522. if (isUndefined(attr.value)) {
  25523. var interpolateFn = $interpolate(element.text(), true);
  25524. if (!interpolateFn) {
  25525. attr.$set('value', element.text());
  25526. }
  25527. }
  25528. return function(scope, element, attr) {
  25529. // This is an optimization over using ^^ since we don't want to have to search
  25530. // all the way to the root of the DOM for every single option element
  25531. var selectCtrlName = '$selectController',
  25532. parent = element.parent(),
  25533. selectCtrl = parent.data(selectCtrlName) ||
  25534. parent.parent().data(selectCtrlName); // in case we are in optgroup
  25535. // Only update trigger option updates if this is an option within a `select`
  25536. // that also has `ngModel` attached
  25537. if (selectCtrl && selectCtrl.ngModelCtrl) {
  25538. if (interpolateFn) {
  25539. scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
  25540. attr.$set('value', newVal);
  25541. if (oldVal !== newVal) {
  25542. selectCtrl.removeOption(oldVal);
  25543. }
  25544. selectCtrl.addOption(newVal, element);
  25545. selectCtrl.ngModelCtrl.$render();
  25546. chromeHack(element);
  25547. });
  25548. } else {
  25549. selectCtrl.addOption(attr.value, element);
  25550. selectCtrl.ngModelCtrl.$render();
  25551. chromeHack(element);
  25552. }
  25553. element.on('$destroy', function() {
  25554. selectCtrl.removeOption(attr.value);
  25555. selectCtrl.ngModelCtrl.$render();
  25556. });
  25557. }
  25558. };
  25559. }
  25560. };
  25561. }];
  25562. var styleDirective = valueFn({
  25563. restrict: 'E',
  25564. terminal: false
  25565. });
  25566. var requiredDirective = function() {
  25567. return {
  25568. restrict: 'A',
  25569. require: '?ngModel',
  25570. link: function(scope, elm, attr, ctrl) {
  25571. if (!ctrl) return;
  25572. attr.required = true; // force truthy in case we are on non input element
  25573. ctrl.$validators.required = function(modelValue, viewValue) {
  25574. return !attr.required || !ctrl.$isEmpty(viewValue);
  25575. };
  25576. attr.$observe('required', function() {
  25577. ctrl.$validate();
  25578. });
  25579. }
  25580. };
  25581. };
  25582. var patternDirective = function() {
  25583. return {
  25584. restrict: 'A',
  25585. require: '?ngModel',
  25586. link: function(scope, elm, attr, ctrl) {
  25587. if (!ctrl) return;
  25588. var regexp, patternExp = attr.ngPattern || attr.pattern;
  25589. attr.$observe('pattern', function(regex) {
  25590. if (isString(regex) && regex.length > 0) {
  25591. regex = new RegExp('^' + regex + '$');
  25592. }
  25593. if (regex && !regex.test) {
  25594. throw minErr('ngPattern')('noregexp',
  25595. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  25596. regex, startingTag(elm));
  25597. }
  25598. regexp = regex || undefined;
  25599. ctrl.$validate();
  25600. });
  25601. ctrl.$validators.pattern = function(value) {
  25602. return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value);
  25603. };
  25604. }
  25605. };
  25606. };
  25607. var maxlengthDirective = function() {
  25608. return {
  25609. restrict: 'A',
  25610. require: '?ngModel',
  25611. link: function(scope, elm, attr, ctrl) {
  25612. if (!ctrl) return;
  25613. var maxlength = -1;
  25614. attr.$observe('maxlength', function(value) {
  25615. var intVal = toInt(value);
  25616. maxlength = isNaN(intVal) ? -1 : intVal;
  25617. ctrl.$validate();
  25618. });
  25619. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  25620. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  25621. };
  25622. }
  25623. };
  25624. };
  25625. var minlengthDirective = function() {
  25626. return {
  25627. restrict: 'A',
  25628. require: '?ngModel',
  25629. link: function(scope, elm, attr, ctrl) {
  25630. if (!ctrl) return;
  25631. var minlength = 0;
  25632. attr.$observe('minlength', function(value) {
  25633. minlength = toInt(value) || 0;
  25634. ctrl.$validate();
  25635. });
  25636. ctrl.$validators.minlength = function(modelValue, viewValue) {
  25637. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  25638. };
  25639. }
  25640. };
  25641. };
  25642. if (window.angular.bootstrap) {
  25643. //AngularJS is already loaded, so we can return here...
  25644. console.log('WARNING: Tried to load angular more than once.');
  25645. return;
  25646. }
  25647. //try to bind to jquery now so that one can write jqLite(document).ready()
  25648. //but we will rebind on bootstrap again.
  25649. bindJQuery();
  25650. publishExternalAPI(angular);
  25651. jqLite(document).ready(function() {
  25652. angularInit(document, bootstrap);
  25653. });
  25654. })(window, document);
  25655. !window.angular.$$csp() && window.angular.element(document).find('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>');