angular.js 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461
  1. /**
  2. * @license AngularJS v1.5.1-build.4601+sha.c966876
  3. * (c) 2010-2016 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window, document, undefined) {'use strict';
  7. /**
  8. * @description
  9. *
  10. * This object provides a utility for producing rich Error messages within
  11. * Angular. It can be called as follows:
  12. *
  13. * var exampleMinErr = minErr('example');
  14. * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
  15. *
  16. * The above creates an instance of minErr in the example namespace. The
  17. * resulting error will have a namespaced error code of example.one. The
  18. * resulting error will replace {0} with the value of foo, and {1} with the
  19. * value of bar. The object is not restricted in the number of arguments it can
  20. * take.
  21. *
  22. * If fewer arguments are specified than necessary for interpolation, the extra
  23. * interpolation markers will be preserved in the final string.
  24. *
  25. * Since data will be parsed statically during a build step, some restrictions
  26. * are applied with respect to how minErr instances are created and called.
  27. * Instances should have names of the form namespaceMinErr for a minErr created
  28. * using minErr('namespace') . Error codes, namespaces and template strings
  29. * should all be static strings, not variables or general expressions.
  30. *
  31. * @param {string} module The namespace to use for the new minErr instance.
  32. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
  33. * error from returned function, for cases when a particular type of error is useful.
  34. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
  35. */
  36. function minErr(module, ErrorConstructor) {
  37. ErrorConstructor = ErrorConstructor || Error;
  38. return function() {
  39. var SKIP_INDEXES = 2;
  40. var templateArgs = arguments,
  41. code = templateArgs[0],
  42. message = '[' + (module ? module + ':' : '') + code + '] ',
  43. template = templateArgs[1],
  44. paramPrefix, i;
  45. message += template.replace(/\{\d+\}/g, function(match) {
  46. var index = +match.slice(1, -1),
  47. shiftedIndex = index + SKIP_INDEXES;
  48. if (shiftedIndex < templateArgs.length) {
  49. return toDebugString(templateArgs[shiftedIndex]);
  50. }
  51. return match;
  52. });
  53. message += '\nhttp://errors.angularjs.org/1.5.1-build.4601+sha.c966876/' +
  54. (module ? module + '/' : '') + code;
  55. for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
  56. message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
  57. encodeURIComponent(toDebugString(templateArgs[i]));
  58. }
  59. return new ErrorConstructor(message);
  60. };
  61. }
  62. /* We need to tell jshint what variables are being exported */
  63. /* global angular: true,
  64. msie: true,
  65. jqLite: true,
  66. jQuery: true,
  67. slice: true,
  68. splice: true,
  69. push: true,
  70. toString: true,
  71. ngMinErr: true,
  72. angularModule: true,
  73. uid: true,
  74. REGEX_STRING_REGEXP: true,
  75. VALIDITY_STATE_PROPERTY: true,
  76. lowercase: true,
  77. uppercase: true,
  78. manualLowercase: true,
  79. manualUppercase: true,
  80. nodeName_: true,
  81. isArrayLike: true,
  82. forEach: true,
  83. forEachSorted: true,
  84. reverseParams: true,
  85. nextUid: true,
  86. setHashKey: true,
  87. extend: true,
  88. toInt: true,
  89. inherit: true,
  90. merge: true,
  91. noop: true,
  92. identity: true,
  93. valueFn: true,
  94. isUndefined: true,
  95. isDefined: true,
  96. isObject: true,
  97. isBlankObject: true,
  98. isString: true,
  99. isNumber: true,
  100. isDate: true,
  101. isArray: true,
  102. isFunction: true,
  103. isRegExp: true,
  104. isWindow: true,
  105. isScope: true,
  106. isFile: true,
  107. isFormData: true,
  108. isBlob: true,
  109. isBoolean: true,
  110. isPromiseLike: true,
  111. trim: true,
  112. escapeForRegexp: true,
  113. isElement: true,
  114. makeMap: true,
  115. includes: true,
  116. arrayRemove: true,
  117. copy: true,
  118. shallowCopy: true,
  119. equals: true,
  120. csp: true,
  121. jq: true,
  122. concat: true,
  123. sliceArgs: true,
  124. bind: true,
  125. toJsonReplacer: true,
  126. toJson: true,
  127. fromJson: true,
  128. convertTimezoneToLocal: true,
  129. timezoneToOffset: true,
  130. startingTag: true,
  131. tryDecodeURIComponent: true,
  132. parseKeyValue: true,
  133. toKeyValue: true,
  134. encodeUriSegment: true,
  135. encodeUriQuery: true,
  136. angularInit: true,
  137. bootstrap: true,
  138. getTestability: true,
  139. snake_case: true,
  140. bindJQuery: true,
  141. assertArg: true,
  142. assertArgFn: true,
  143. assertNotHasOwnProperty: true,
  144. getter: true,
  145. getBlockNodes: true,
  146. hasOwnProperty: true,
  147. createMap: true,
  148. NODE_TYPE_ELEMENT: true,
  149. NODE_TYPE_ATTRIBUTE: true,
  150. NODE_TYPE_TEXT: true,
  151. NODE_TYPE_COMMENT: true,
  152. NODE_TYPE_DOCUMENT: true,
  153. NODE_TYPE_DOCUMENT_FRAGMENT: true,
  154. */
  155. ////////////////////////////////////
  156. /**
  157. * @ngdoc module
  158. * @name ng
  159. * @module ng
  160. * @description
  161. *
  162. * # ng (core module)
  163. * The ng module is loaded by default when an AngularJS application is started. The module itself
  164. * contains the essential components for an AngularJS application to function. The table below
  165. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  166. * components available within this core module.
  167. *
  168. * <div doc-module-components="ng"></div>
  169. */
  170. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  171. // The name of a form control's ValidityState property.
  172. // This is used so that it's possible for internal tests to create mock ValidityStates.
  173. var VALIDITY_STATE_PROPERTY = 'validity';
  174. var hasOwnProperty = Object.prototype.hasOwnProperty;
  175. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  176. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  177. var manualLowercase = function(s) {
  178. /* jshint bitwise: false */
  179. return isString(s)
  180. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  181. : s;
  182. };
  183. var manualUppercase = function(s) {
  184. /* jshint bitwise: false */
  185. return isString(s)
  186. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  187. : s;
  188. };
  189. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  190. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  191. // with correct but slower alternatives. See https://github.com/angular/angular.js/issues/11387
  192. if ('i' !== 'I'.toLowerCase()) {
  193. lowercase = manualLowercase;
  194. uppercase = manualUppercase;
  195. }
  196. var
  197. msie, // holds major version number for IE, or NaN if UA is not IE.
  198. jqLite, // delay binding since jQuery could be loaded after us.
  199. jQuery, // delay binding
  200. slice = [].slice,
  201. splice = [].splice,
  202. push = [].push,
  203. toString = Object.prototype.toString,
  204. getPrototypeOf = Object.getPrototypeOf,
  205. ngMinErr = minErr('ng'),
  206. /** @name angular */
  207. angular = window.angular || (window.angular = {}),
  208. angularModule,
  209. uid = 0;
  210. /**
  211. * documentMode is an IE-only property
  212. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  213. */
  214. msie = document.documentMode;
  215. /**
  216. * @private
  217. * @param {*} obj
  218. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  219. * String ...)
  220. */
  221. function isArrayLike(obj) {
  222. // `null`, `undefined` and `window` are not array-like
  223. if (obj == null || isWindow(obj)) return false;
  224. // arrays, strings and jQuery/jqLite objects are array like
  225. // * jqLite is either the jQuery or jqLite constructor function
  226. // * we have to check the existence of jqLite first as this method is called
  227. // via the forEach method when constructing the jqLite object in the first place
  228. if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
  229. // Support: iOS 8.2 (not reproducible in simulator)
  230. // "length" in obj used to prevent JIT error (gh-11508)
  231. var length = "length" in Object(obj) && obj.length;
  232. // NodeList objects (with `item` method) and
  233. // other objects with suitable length characteristics are array-like
  234. return isNumber(length) &&
  235. (length >= 0 && ((length - 1) in obj || obj instanceof Array) || typeof obj.item == 'function');
  236. }
  237. /**
  238. * @ngdoc function
  239. * @name angular.forEach
  240. * @module ng
  241. * @kind function
  242. *
  243. * @description
  244. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  245. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  246. * is the value of an object property or an array element, `key` is the object property key or
  247. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  248. *
  249. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  250. * using the `hasOwnProperty` method.
  251. *
  252. * Unlike ES262's
  253. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  254. * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  255. * return the value provided.
  256. *
  257. ```js
  258. var values = {name: 'misko', gender: 'male'};
  259. var log = [];
  260. angular.forEach(values, function(value, key) {
  261. this.push(key + ': ' + value);
  262. }, log);
  263. expect(log).toEqual(['name: misko', 'gender: male']);
  264. ```
  265. *
  266. * @param {Object|Array} obj Object to iterate over.
  267. * @param {Function} iterator Iterator function.
  268. * @param {Object=} context Object to become context (`this`) for the iterator function.
  269. * @returns {Object|Array} Reference to `obj`.
  270. */
  271. function forEach(obj, iterator, context) {
  272. var key, length;
  273. if (obj) {
  274. if (isFunction(obj)) {
  275. for (key in obj) {
  276. // Need to check if hasOwnProperty exists,
  277. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  278. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  279. iterator.call(context, obj[key], key, obj);
  280. }
  281. }
  282. } else if (isArray(obj) || isArrayLike(obj)) {
  283. var isPrimitive = typeof obj !== 'object';
  284. for (key = 0, length = obj.length; key < length; key++) {
  285. if (isPrimitive || key in obj) {
  286. iterator.call(context, obj[key], key, obj);
  287. }
  288. }
  289. } else if (obj.forEach && obj.forEach !== forEach) {
  290. obj.forEach(iterator, context, obj);
  291. } else if (isBlankObject(obj)) {
  292. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  293. for (key in obj) {
  294. iterator.call(context, obj[key], key, obj);
  295. }
  296. } else if (typeof obj.hasOwnProperty === 'function') {
  297. // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
  298. for (key in obj) {
  299. if (obj.hasOwnProperty(key)) {
  300. iterator.call(context, obj[key], key, obj);
  301. }
  302. }
  303. } else {
  304. // Slow path for objects which do not have a method `hasOwnProperty`
  305. for (key in obj) {
  306. if (hasOwnProperty.call(obj, key)) {
  307. iterator.call(context, obj[key], key, obj);
  308. }
  309. }
  310. }
  311. }
  312. return obj;
  313. }
  314. function forEachSorted(obj, iterator, context) {
  315. var keys = Object.keys(obj).sort();
  316. for (var i = 0; i < keys.length; i++) {
  317. iterator.call(context, obj[keys[i]], keys[i]);
  318. }
  319. return keys;
  320. }
  321. /**
  322. * when using forEach the params are value, key, but it is often useful to have key, value.
  323. * @param {function(string, *)} iteratorFn
  324. * @returns {function(*, string)}
  325. */
  326. function reverseParams(iteratorFn) {
  327. return function(value, key) {iteratorFn(key, value);};
  328. }
  329. /**
  330. * A consistent way of creating unique IDs in angular.
  331. *
  332. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  333. * we hit number precision issues in JavaScript.
  334. *
  335. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  336. *
  337. * @returns {number} an unique alpha-numeric string
  338. */
  339. function nextUid() {
  340. return ++uid;
  341. }
  342. /**
  343. * Set or clear the hashkey for an object.
  344. * @param obj object
  345. * @param h the hashkey (!truthy to delete the hashkey)
  346. */
  347. function setHashKey(obj, h) {
  348. if (h) {
  349. obj.$$hashKey = h;
  350. } else {
  351. delete obj.$$hashKey;
  352. }
  353. }
  354. function baseExtend(dst, objs, deep) {
  355. var h = dst.$$hashKey;
  356. for (var i = 0, ii = objs.length; i < ii; ++i) {
  357. var obj = objs[i];
  358. if (!isObject(obj) && !isFunction(obj)) continue;
  359. var keys = Object.keys(obj);
  360. for (var j = 0, jj = keys.length; j < jj; j++) {
  361. var key = keys[j];
  362. var src = obj[key];
  363. if (deep && isObject(src)) {
  364. if (isDate(src)) {
  365. dst[key] = new Date(src.valueOf());
  366. } else if (isRegExp(src)) {
  367. dst[key] = new RegExp(src);
  368. } else if (src.nodeName) {
  369. dst[key] = src.cloneNode(true);
  370. } else if (isElement(src)) {
  371. dst[key] = src.clone();
  372. } else {
  373. if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
  374. baseExtend(dst[key], [src], true);
  375. }
  376. } else {
  377. dst[key] = src;
  378. }
  379. }
  380. }
  381. setHashKey(dst, h);
  382. return dst;
  383. }
  384. /**
  385. * @ngdoc function
  386. * @name angular.extend
  387. * @module ng
  388. * @kind function
  389. *
  390. * @description
  391. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  392. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  393. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  394. *
  395. * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
  396. * {@link angular.merge} for this.
  397. *
  398. * @param {Object} dst Destination object.
  399. * @param {...Object} src Source object(s).
  400. * @returns {Object} Reference to `dst`.
  401. */
  402. function extend(dst) {
  403. return baseExtend(dst, slice.call(arguments, 1), false);
  404. }
  405. /**
  406. * @ngdoc function
  407. * @name angular.merge
  408. * @module ng
  409. * @kind function
  410. *
  411. * @description
  412. * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  413. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  414. * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
  415. *
  416. * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
  417. * objects, performing a deep copy.
  418. *
  419. * @param {Object} dst Destination object.
  420. * @param {...Object} src Source object(s).
  421. * @returns {Object} Reference to `dst`.
  422. */
  423. function merge(dst) {
  424. return baseExtend(dst, slice.call(arguments, 1), true);
  425. }
  426. function toInt(str) {
  427. return parseInt(str, 10);
  428. }
  429. function inherit(parent, extra) {
  430. return extend(Object.create(parent), extra);
  431. }
  432. /**
  433. * @ngdoc function
  434. * @name angular.noop
  435. * @module ng
  436. * @kind function
  437. *
  438. * @description
  439. * A function that performs no operations. This function can be useful when writing code in the
  440. * functional style.
  441. ```js
  442. function foo(callback) {
  443. var result = calculateResult();
  444. (callback || angular.noop)(result);
  445. }
  446. ```
  447. */
  448. function noop() {}
  449. noop.$inject = [];
  450. /**
  451. * @ngdoc function
  452. * @name angular.identity
  453. * @module ng
  454. * @kind function
  455. *
  456. * @description
  457. * A function that returns its first argument. This function is useful when writing code in the
  458. * functional style.
  459. *
  460. ```js
  461. function transformer(transformationFn, value) {
  462. return (transformationFn || angular.identity)(value);
  463. };
  464. ```
  465. * @param {*} value to be returned.
  466. * @returns {*} the value passed in.
  467. */
  468. function identity($) {return $;}
  469. identity.$inject = [];
  470. function valueFn(value) {return function() {return value;};}
  471. function hasCustomToString(obj) {
  472. return isFunction(obj.toString) && obj.toString !== toString;
  473. }
  474. /**
  475. * @ngdoc function
  476. * @name angular.isUndefined
  477. * @module ng
  478. * @kind function
  479. *
  480. * @description
  481. * Determines if a reference is undefined.
  482. *
  483. * @param {*} value Reference to check.
  484. * @returns {boolean} True if `value` is undefined.
  485. */
  486. function isUndefined(value) {return typeof value === 'undefined';}
  487. /**
  488. * @ngdoc function
  489. * @name angular.isDefined
  490. * @module ng
  491. * @kind function
  492. *
  493. * @description
  494. * Determines if a reference is defined.
  495. *
  496. * @param {*} value Reference to check.
  497. * @returns {boolean} True if `value` is defined.
  498. */
  499. function isDefined(value) {return typeof value !== 'undefined';}
  500. /**
  501. * @ngdoc function
  502. * @name angular.isObject
  503. * @module ng
  504. * @kind function
  505. *
  506. * @description
  507. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  508. * considered to be objects. Note that JavaScript arrays are objects.
  509. *
  510. * @param {*} value Reference to check.
  511. * @returns {boolean} True if `value` is an `Object` but not `null`.
  512. */
  513. function isObject(value) {
  514. // http://jsperf.com/isobject4
  515. return value !== null && typeof value === 'object';
  516. }
  517. /**
  518. * Determine if a value is an object with a null prototype
  519. *
  520. * @returns {boolean} True if `value` is an `Object` with a null prototype
  521. */
  522. function isBlankObject(value) {
  523. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  524. }
  525. /**
  526. * @ngdoc function
  527. * @name angular.isString
  528. * @module ng
  529. * @kind function
  530. *
  531. * @description
  532. * Determines if a reference is a `String`.
  533. *
  534. * @param {*} value Reference to check.
  535. * @returns {boolean} True if `value` is a `String`.
  536. */
  537. function isString(value) {return typeof value === 'string';}
  538. /**
  539. * @ngdoc function
  540. * @name angular.isNumber
  541. * @module ng
  542. * @kind function
  543. *
  544. * @description
  545. * Determines if a reference is a `Number`.
  546. *
  547. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  548. *
  549. * If you wish to exclude these then you can use the native
  550. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  551. * method.
  552. *
  553. * @param {*} value Reference to check.
  554. * @returns {boolean} True if `value` is a `Number`.
  555. */
  556. function isNumber(value) {return typeof value === 'number';}
  557. /**
  558. * @ngdoc function
  559. * @name angular.isDate
  560. * @module ng
  561. * @kind function
  562. *
  563. * @description
  564. * Determines if a value is a date.
  565. *
  566. * @param {*} value Reference to check.
  567. * @returns {boolean} True if `value` is a `Date`.
  568. */
  569. function isDate(value) {
  570. return toString.call(value) === '[object Date]';
  571. }
  572. /**
  573. * @ngdoc function
  574. * @name angular.isArray
  575. * @module ng
  576. * @kind function
  577. *
  578. * @description
  579. * Determines if a reference is an `Array`.
  580. *
  581. * @param {*} value Reference to check.
  582. * @returns {boolean} True if `value` is an `Array`.
  583. */
  584. var isArray = Array.isArray;
  585. /**
  586. * @ngdoc function
  587. * @name angular.isFunction
  588. * @module ng
  589. * @kind function
  590. *
  591. * @description
  592. * Determines if a reference is a `Function`.
  593. *
  594. * @param {*} value Reference to check.
  595. * @returns {boolean} True if `value` is a `Function`.
  596. */
  597. function isFunction(value) {return typeof value === 'function';}
  598. /**
  599. * Determines if a value is a regular expression object.
  600. *
  601. * @private
  602. * @param {*} value Reference to check.
  603. * @returns {boolean} True if `value` is a `RegExp`.
  604. */
  605. function isRegExp(value) {
  606. return toString.call(value) === '[object RegExp]';
  607. }
  608. /**
  609. * Checks if `obj` is a window object.
  610. *
  611. * @private
  612. * @param {*} obj Object to check
  613. * @returns {boolean} True if `obj` is a window obj.
  614. */
  615. function isWindow(obj) {
  616. return obj && obj.window === obj;
  617. }
  618. function isScope(obj) {
  619. return obj && obj.$evalAsync && obj.$watch;
  620. }
  621. function isFile(obj) {
  622. return toString.call(obj) === '[object File]';
  623. }
  624. function isFormData(obj) {
  625. return toString.call(obj) === '[object FormData]';
  626. }
  627. function isBlob(obj) {
  628. return toString.call(obj) === '[object Blob]';
  629. }
  630. function isBoolean(value) {
  631. return typeof value === 'boolean';
  632. }
  633. function isPromiseLike(obj) {
  634. return obj && isFunction(obj.then);
  635. }
  636. var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array\]$/;
  637. function isTypedArray(value) {
  638. return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
  639. }
  640. function isArrayBuffer(obj) {
  641. return toString.call(obj) === '[object ArrayBuffer]';
  642. }
  643. var trim = function(value) {
  644. return isString(value) ? value.trim() : value;
  645. };
  646. // Copied from:
  647. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  648. // Prereq: s is a string.
  649. var escapeForRegexp = function(s) {
  650. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  651. replace(/\x08/g, '\\x08');
  652. };
  653. /**
  654. * @ngdoc function
  655. * @name angular.isElement
  656. * @module ng
  657. * @kind function
  658. *
  659. * @description
  660. * Determines if a reference is a DOM element (or wrapped jQuery element).
  661. *
  662. * @param {*} value Reference to check.
  663. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  664. */
  665. function isElement(node) {
  666. return !!(node &&
  667. (node.nodeName // we are a direct element
  668. || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
  669. }
  670. /**
  671. * @param str 'key1,key2,...'
  672. * @returns {object} in the form of {key1:true, key2:true, ...}
  673. */
  674. function makeMap(str) {
  675. var obj = {}, items = str.split(','), i;
  676. for (i = 0; i < items.length; i++) {
  677. obj[items[i]] = true;
  678. }
  679. return obj;
  680. }
  681. function nodeName_(element) {
  682. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  683. }
  684. function includes(array, obj) {
  685. return Array.prototype.indexOf.call(array, obj) != -1;
  686. }
  687. function arrayRemove(array, value) {
  688. var index = array.indexOf(value);
  689. if (index >= 0) {
  690. array.splice(index, 1);
  691. }
  692. return index;
  693. }
  694. /**
  695. * @ngdoc function
  696. * @name angular.copy
  697. * @module ng
  698. * @kind function
  699. *
  700. * @description
  701. * Creates a deep copy of `source`, which should be an object or an array.
  702. *
  703. * * If no destination is supplied, a copy of the object or array is created.
  704. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  705. * are deleted and then all elements/properties from the source are copied to it.
  706. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  707. * * If `source` is identical to 'destination' an exception will be thrown.
  708. *
  709. * @param {*} source The source that will be used to make a copy.
  710. * Can be any type, including primitives, `null`, and `undefined`.
  711. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  712. * provided, must be of the same type as `source`.
  713. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  714. *
  715. * @example
  716. <example module="copyExample">
  717. <file name="index.html">
  718. <div ng-controller="ExampleController">
  719. <form novalidate class="simple-form">
  720. Name: <input type="text" ng-model="user.name" /><br />
  721. E-mail: <input type="email" ng-model="user.email" /><br />
  722. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  723. <input type="radio" ng-model="user.gender" value="female" />female<br />
  724. <button ng-click="reset()">RESET</button>
  725. <button ng-click="update(user)">SAVE</button>
  726. </form>
  727. <pre>form = {{user | json}}</pre>
  728. <pre>master = {{master | json}}</pre>
  729. </div>
  730. <script>
  731. angular.module('copyExample', [])
  732. .controller('ExampleController', ['$scope', function($scope) {
  733. $scope.master= {};
  734. $scope.update = function(user) {
  735. // Example with 1 argument
  736. $scope.master= angular.copy(user);
  737. };
  738. $scope.reset = function() {
  739. // Example with 2 arguments
  740. angular.copy($scope.master, $scope.user);
  741. };
  742. $scope.reset();
  743. }]);
  744. </script>
  745. </file>
  746. </example>
  747. */
  748. function copy(source, destination) {
  749. var stackSource = [];
  750. var stackDest = [];
  751. if (destination) {
  752. if (isTypedArray(destination) || isArrayBuffer(destination)) {
  753. throw ngMinErr('cpta', "Can't copy! TypedArray destination cannot be mutated.");
  754. }
  755. if (source === destination) {
  756. throw ngMinErr('cpi', "Can't copy! Source and destination are identical.");
  757. }
  758. // Empty the destination object
  759. if (isArray(destination)) {
  760. destination.length = 0;
  761. } else {
  762. forEach(destination, function(value, key) {
  763. if (key !== '$$hashKey') {
  764. delete destination[key];
  765. }
  766. });
  767. }
  768. stackSource.push(source);
  769. stackDest.push(destination);
  770. return copyRecurse(source, destination);
  771. }
  772. return copyElement(source);
  773. function copyRecurse(source, destination) {
  774. var h = destination.$$hashKey;
  775. var result, key;
  776. if (isArray(source)) {
  777. for (var i = 0, ii = source.length; i < ii; i++) {
  778. destination.push(copyElement(source[i]));
  779. }
  780. } else if (isBlankObject(source)) {
  781. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  782. for (key in source) {
  783. destination[key] = copyElement(source[key]);
  784. }
  785. } else if (source && typeof source.hasOwnProperty === 'function') {
  786. // Slow path, which must rely on hasOwnProperty
  787. for (key in source) {
  788. if (source.hasOwnProperty(key)) {
  789. destination[key] = copyElement(source[key]);
  790. }
  791. }
  792. } else {
  793. // Slowest path --- hasOwnProperty can't be called as a method
  794. for (key in source) {
  795. if (hasOwnProperty.call(source, key)) {
  796. destination[key] = copyElement(source[key]);
  797. }
  798. }
  799. }
  800. setHashKey(destination, h);
  801. return destination;
  802. }
  803. function copyElement(source) {
  804. // Simple values
  805. if (!isObject(source)) {
  806. return source;
  807. }
  808. // Already copied values
  809. var index = stackSource.indexOf(source);
  810. if (index !== -1) {
  811. return stackDest[index];
  812. }
  813. if (isWindow(source) || isScope(source)) {
  814. throw ngMinErr('cpws',
  815. "Can't copy! Making copies of Window or Scope instances is not supported.");
  816. }
  817. var needsRecurse = false;
  818. var destination = copyType(source);
  819. if (destination === undefined) {
  820. destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
  821. needsRecurse = true;
  822. }
  823. stackSource.push(source);
  824. stackDest.push(destination);
  825. return needsRecurse
  826. ? copyRecurse(source, destination)
  827. : destination;
  828. }
  829. function copyType(source) {
  830. switch (toString.call(source)) {
  831. case '[object Int8Array]':
  832. case '[object Int16Array]':
  833. case '[object Int32Array]':
  834. case '[object Float32Array]':
  835. case '[object Float64Array]':
  836. case '[object Uint8Array]':
  837. case '[object Uint8ClampedArray]':
  838. case '[object Uint16Array]':
  839. case '[object Uint32Array]':
  840. return new source.constructor(copyElement(source.buffer));
  841. case '[object ArrayBuffer]':
  842. //Support: IE10
  843. if (!source.slice) {
  844. var copied = new ArrayBuffer(source.byteLength);
  845. new Uint8Array(copied).set(new Uint8Array(source));
  846. return copied;
  847. }
  848. return source.slice(0);
  849. case '[object Boolean]':
  850. case '[object Number]':
  851. case '[object String]':
  852. case '[object Date]':
  853. return new source.constructor(source.valueOf());
  854. case '[object RegExp]':
  855. var re = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  856. re.lastIndex = source.lastIndex;
  857. return re;
  858. }
  859. if (isFunction(source.cloneNode)) {
  860. return source.cloneNode(true);
  861. }
  862. }
  863. }
  864. /**
  865. * Creates a shallow copy of an object, an array or a primitive.
  866. *
  867. * Assumes that there are no proto properties for objects.
  868. */
  869. function shallowCopy(src, dst) {
  870. if (isArray(src)) {
  871. dst = dst || [];
  872. for (var i = 0, ii = src.length; i < ii; i++) {
  873. dst[i] = src[i];
  874. }
  875. } else if (isObject(src)) {
  876. dst = dst || {};
  877. for (var key in src) {
  878. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  879. dst[key] = src[key];
  880. }
  881. }
  882. }
  883. return dst || src;
  884. }
  885. /**
  886. * @ngdoc function
  887. * @name angular.equals
  888. * @module ng
  889. * @kind function
  890. *
  891. * @description
  892. * Determines if two objects or two values are equivalent. Supports value types, regular
  893. * expressions, arrays and objects.
  894. *
  895. * Two objects or values are considered equivalent if at least one of the following is true:
  896. *
  897. * * Both objects or values pass `===` comparison.
  898. * * Both objects or values are of the same type and all of their properties are equal by
  899. * comparing them with `angular.equals`.
  900. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  901. * * Both values represent the same regular expression (In JavaScript,
  902. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  903. * representation matches).
  904. *
  905. * During a property comparison, properties of `function` type and properties with names
  906. * that begin with `$` are ignored.
  907. *
  908. * Scope and DOMWindow objects are being compared only by identify (`===`).
  909. *
  910. * @param {*} o1 Object or value to compare.
  911. * @param {*} o2 Object or value to compare.
  912. * @returns {boolean} True if arguments are equal.
  913. */
  914. function equals(o1, o2) {
  915. if (o1 === o2) return true;
  916. if (o1 === null || o2 === null) return false;
  917. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  918. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  919. if (t1 == t2 && t1 == 'object') {
  920. if (isArray(o1)) {
  921. if (!isArray(o2)) return false;
  922. if ((length = o1.length) == o2.length) {
  923. for (key = 0; key < length; key++) {
  924. if (!equals(o1[key], o2[key])) return false;
  925. }
  926. return true;
  927. }
  928. } else if (isDate(o1)) {
  929. if (!isDate(o2)) return false;
  930. return equals(o1.getTime(), o2.getTime());
  931. } else if (isRegExp(o1)) {
  932. if (!isRegExp(o2)) return false;
  933. return o1.toString() == o2.toString();
  934. } else {
  935. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  936. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  937. keySet = createMap();
  938. for (key in o1) {
  939. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  940. if (!equals(o1[key], o2[key])) return false;
  941. keySet[key] = true;
  942. }
  943. for (key in o2) {
  944. if (!(key in keySet) &&
  945. key.charAt(0) !== '$' &&
  946. isDefined(o2[key]) &&
  947. !isFunction(o2[key])) return false;
  948. }
  949. return true;
  950. }
  951. }
  952. return false;
  953. }
  954. var csp = function() {
  955. if (!isDefined(csp.rules)) {
  956. var ngCspElement = (document.querySelector('[ng-csp]') ||
  957. document.querySelector('[data-ng-csp]'));
  958. if (ngCspElement) {
  959. var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
  960. ngCspElement.getAttribute('data-ng-csp');
  961. csp.rules = {
  962. noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
  963. noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
  964. };
  965. } else {
  966. csp.rules = {
  967. noUnsafeEval: noUnsafeEval(),
  968. noInlineStyle: false
  969. };
  970. }
  971. }
  972. return csp.rules;
  973. function noUnsafeEval() {
  974. try {
  975. /* jshint -W031, -W054 */
  976. new Function('');
  977. /* jshint +W031, +W054 */
  978. return false;
  979. } catch (e) {
  980. return true;
  981. }
  982. }
  983. };
  984. /**
  985. * @ngdoc directive
  986. * @module ng
  987. * @name ngJq
  988. *
  989. * @element ANY
  990. * @param {string=} ngJq the name of the library available under `window`
  991. * to be used for angular.element
  992. * @description
  993. * Use this directive to force the angular.element library. This should be
  994. * used to force either jqLite by leaving ng-jq blank or setting the name of
  995. * the jquery variable under window (eg. jQuery).
  996. *
  997. * Since angular looks for this directive when it is loaded (doesn't wait for the
  998. * DOMContentLoaded event), it must be placed on an element that comes before the script
  999. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  1000. * others ignored.
  1001. *
  1002. * @example
  1003. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  1004. ```html
  1005. <!doctype html>
  1006. <html ng-app ng-jq>
  1007. ...
  1008. ...
  1009. </html>
  1010. ```
  1011. * @example
  1012. * This example shows how to use a jQuery based library of a different name.
  1013. * The library name must be available at the top most 'window'.
  1014. ```html
  1015. <!doctype html>
  1016. <html ng-app ng-jq="jQueryLib">
  1017. ...
  1018. ...
  1019. </html>
  1020. ```
  1021. */
  1022. var jq = function() {
  1023. if (isDefined(jq.name_)) return jq.name_;
  1024. var el;
  1025. var i, ii = ngAttrPrefixes.length, prefix, name;
  1026. for (i = 0; i < ii; ++i) {
  1027. prefix = ngAttrPrefixes[i];
  1028. if (el = document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]')) {
  1029. name = el.getAttribute(prefix + 'jq');
  1030. break;
  1031. }
  1032. }
  1033. return (jq.name_ = name);
  1034. };
  1035. function concat(array1, array2, index) {
  1036. return array1.concat(slice.call(array2, index));
  1037. }
  1038. function sliceArgs(args, startIndex) {
  1039. return slice.call(args, startIndex || 0);
  1040. }
  1041. /* jshint -W101 */
  1042. /**
  1043. * @ngdoc function
  1044. * @name angular.bind
  1045. * @module ng
  1046. * @kind function
  1047. *
  1048. * @description
  1049. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  1050. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  1051. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  1052. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  1053. *
  1054. * @param {Object} self Context which `fn` should be evaluated in.
  1055. * @param {function()} fn Function to be bound.
  1056. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  1057. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  1058. */
  1059. /* jshint +W101 */
  1060. function bind(self, fn) {
  1061. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  1062. if (isFunction(fn) && !(fn instanceof RegExp)) {
  1063. return curryArgs.length
  1064. ? function() {
  1065. return arguments.length
  1066. ? fn.apply(self, concat(curryArgs, arguments, 0))
  1067. : fn.apply(self, curryArgs);
  1068. }
  1069. : function() {
  1070. return arguments.length
  1071. ? fn.apply(self, arguments)
  1072. : fn.call(self);
  1073. };
  1074. } else {
  1075. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  1076. return fn;
  1077. }
  1078. }
  1079. function toJsonReplacer(key, value) {
  1080. var val = value;
  1081. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  1082. val = undefined;
  1083. } else if (isWindow(value)) {
  1084. val = '$WINDOW';
  1085. } else if (value && document === value) {
  1086. val = '$DOCUMENT';
  1087. } else if (isScope(value)) {
  1088. val = '$SCOPE';
  1089. }
  1090. return val;
  1091. }
  1092. /**
  1093. * @ngdoc function
  1094. * @name angular.toJson
  1095. * @module ng
  1096. * @kind function
  1097. *
  1098. * @description
  1099. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  1100. * stripped since angular uses this notation internally.
  1101. *
  1102. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  1103. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  1104. * If set to an integer, the JSON output will contain that many spaces per indentation.
  1105. * @returns {string|undefined} JSON-ified string representing `obj`.
  1106. */
  1107. function toJson(obj, pretty) {
  1108. if (isUndefined(obj)) return undefined;
  1109. if (!isNumber(pretty)) {
  1110. pretty = pretty ? 2 : null;
  1111. }
  1112. return JSON.stringify(obj, toJsonReplacer, pretty);
  1113. }
  1114. /**
  1115. * @ngdoc function
  1116. * @name angular.fromJson
  1117. * @module ng
  1118. * @kind function
  1119. *
  1120. * @description
  1121. * Deserializes a JSON string.
  1122. *
  1123. * @param {string} json JSON string to deserialize.
  1124. * @returns {Object|Array|string|number} Deserialized JSON string.
  1125. */
  1126. function fromJson(json) {
  1127. return isString(json)
  1128. ? JSON.parse(json)
  1129. : json;
  1130. }
  1131. var ALL_COLONS = /:/g;
  1132. function timezoneToOffset(timezone, fallback) {
  1133. // IE/Edge do not "understand" colon (`:`) in timezone
  1134. timezone = timezone.replace(ALL_COLONS, '');
  1135. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  1136. return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  1137. }
  1138. function addDateMinutes(date, minutes) {
  1139. date = new Date(date.getTime());
  1140. date.setMinutes(date.getMinutes() + minutes);
  1141. return date;
  1142. }
  1143. function convertTimezoneToLocal(date, timezone, reverse) {
  1144. reverse = reverse ? -1 : 1;
  1145. var dateTimezoneOffset = date.getTimezoneOffset();
  1146. var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  1147. return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));
  1148. }
  1149. /**
  1150. * @returns {string} Returns the string representation of the element.
  1151. */
  1152. function startingTag(element) {
  1153. element = jqLite(element).clone();
  1154. try {
  1155. // turns out IE does not let you set .html() on elements which
  1156. // are not allowed to have children. So we just ignore it.
  1157. element.empty();
  1158. } catch (e) {}
  1159. var elemHtml = jqLite('<div>').append(element).html();
  1160. try {
  1161. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  1162. elemHtml.
  1163. match(/^(<[^>]+>)/)[1].
  1164. replace(/^<([\w\-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
  1165. } catch (e) {
  1166. return lowercase(elemHtml);
  1167. }
  1168. }
  1169. /////////////////////////////////////////////////
  1170. /**
  1171. * Tries to decode the URI component without throwing an exception.
  1172. *
  1173. * @private
  1174. * @param str value potential URI component to check.
  1175. * @returns {boolean} True if `value` can be decoded
  1176. * with the decodeURIComponent function.
  1177. */
  1178. function tryDecodeURIComponent(value) {
  1179. try {
  1180. return decodeURIComponent(value);
  1181. } catch (e) {
  1182. // Ignore any invalid uri component
  1183. }
  1184. }
  1185. /**
  1186. * Parses an escaped url query string into key-value pairs.
  1187. * @returns {Object.<string,boolean|Array>}
  1188. */
  1189. function parseKeyValue(/**string*/keyValue) {
  1190. var obj = {};
  1191. forEach((keyValue || "").split('&'), function(keyValue) {
  1192. var splitPoint, key, val;
  1193. if (keyValue) {
  1194. key = keyValue = keyValue.replace(/\+/g,'%20');
  1195. splitPoint = keyValue.indexOf('=');
  1196. if (splitPoint !== -1) {
  1197. key = keyValue.substring(0, splitPoint);
  1198. val = keyValue.substring(splitPoint + 1);
  1199. }
  1200. key = tryDecodeURIComponent(key);
  1201. if (isDefined(key)) {
  1202. val = isDefined(val) ? tryDecodeURIComponent(val) : true;
  1203. if (!hasOwnProperty.call(obj, key)) {
  1204. obj[key] = val;
  1205. } else if (isArray(obj[key])) {
  1206. obj[key].push(val);
  1207. } else {
  1208. obj[key] = [obj[key],val];
  1209. }
  1210. }
  1211. }
  1212. });
  1213. return obj;
  1214. }
  1215. function toKeyValue(obj) {
  1216. var parts = [];
  1217. forEach(obj, function(value, key) {
  1218. if (isArray(value)) {
  1219. forEach(value, function(arrayValue) {
  1220. parts.push(encodeUriQuery(key, true) +
  1221. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1222. });
  1223. } else {
  1224. parts.push(encodeUriQuery(key, true) +
  1225. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1226. }
  1227. });
  1228. return parts.length ? parts.join('&') : '';
  1229. }
  1230. /**
  1231. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1232. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1233. * segments:
  1234. * segment = *pchar
  1235. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1236. * pct-encoded = "%" HEXDIG HEXDIG
  1237. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1238. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1239. * / "*" / "+" / "," / ";" / "="
  1240. */
  1241. function encodeUriSegment(val) {
  1242. return encodeUriQuery(val, true).
  1243. replace(/%26/gi, '&').
  1244. replace(/%3D/gi, '=').
  1245. replace(/%2B/gi, '+');
  1246. }
  1247. /**
  1248. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1249. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1250. * encoded per http://tools.ietf.org/html/rfc3986:
  1251. * query = *( pchar / "/" / "?" )
  1252. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1253. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1254. * pct-encoded = "%" HEXDIG HEXDIG
  1255. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1256. * / "*" / "+" / "," / ";" / "="
  1257. */
  1258. function encodeUriQuery(val, pctEncodeSpaces) {
  1259. return encodeURIComponent(val).
  1260. replace(/%40/gi, '@').
  1261. replace(/%3A/gi, ':').
  1262. replace(/%24/g, '$').
  1263. replace(/%2C/gi, ',').
  1264. replace(/%3B/gi, ';').
  1265. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1266. }
  1267. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1268. function getNgAttribute(element, ngAttr) {
  1269. var attr, i, ii = ngAttrPrefixes.length;
  1270. for (i = 0; i < ii; ++i) {
  1271. attr = ngAttrPrefixes[i] + ngAttr;
  1272. if (isString(attr = element.getAttribute(attr))) {
  1273. return attr;
  1274. }
  1275. }
  1276. return null;
  1277. }
  1278. /**
  1279. * @ngdoc directive
  1280. * @name ngApp
  1281. * @module ng
  1282. *
  1283. * @element ANY
  1284. * @param {angular.Module} ngApp an optional application
  1285. * {@link angular.module module} name to load.
  1286. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1287. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1288. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1289. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1290. * tracking down the root of these bugs.
  1291. *
  1292. * @description
  1293. *
  1294. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1295. * designates the **root element** of the application and is typically placed near the root element
  1296. * of the page - e.g. on the `<body>` or `<html>` tags.
  1297. *
  1298. * There are a few things to keep in mind when using `ngApp`:
  1299. * - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1300. * found in the document will be used to define the root element to auto-bootstrap as an
  1301. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1302. * {@link angular.bootstrap} instead.
  1303. * - AngularJS applications cannot be nested within each other.
  1304. * - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`.
  1305. * This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and
  1306. * {@link ngRoute.ngView `ngView`}.
  1307. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1308. * causing animations to stop working and making the injector inaccessible from outside the app.
  1309. *
  1310. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1311. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1312. * should contain the application code needed or have dependencies on other modules that will
  1313. * contain the code. See {@link angular.module} for more information.
  1314. *
  1315. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1316. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1317. * would not be resolved to `3`.
  1318. *
  1319. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1320. *
  1321. <example module="ngAppDemo">
  1322. <file name="index.html">
  1323. <div ng-controller="ngAppDemoController">
  1324. I can add: {{a}} + {{b}} = {{ a+b }}
  1325. </div>
  1326. </file>
  1327. <file name="script.js">
  1328. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1329. $scope.a = 1;
  1330. $scope.b = 2;
  1331. });
  1332. </file>
  1333. </example>
  1334. *
  1335. * Using `ngStrictDi`, you would see something like this:
  1336. *
  1337. <example ng-app-included="true">
  1338. <file name="index.html">
  1339. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1340. <div ng-controller="GoodController1">
  1341. I can add: {{a}} + {{b}} = {{ a+b }}
  1342. <p>This renders because the controller does not fail to
  1343. instantiate, by using explicit annotation style (see
  1344. script.js for details)
  1345. </p>
  1346. </div>
  1347. <div ng-controller="GoodController2">
  1348. Name: <input ng-model="name"><br />
  1349. Hello, {{name}}!
  1350. <p>This renders because the controller does not fail to
  1351. instantiate, by using explicit annotation style
  1352. (see script.js for details)
  1353. </p>
  1354. </div>
  1355. <div ng-controller="BadController">
  1356. I can add: {{a}} + {{b}} = {{ a+b }}
  1357. <p>The controller could not be instantiated, due to relying
  1358. on automatic function annotations (which are disabled in
  1359. strict mode). As such, the content of this section is not
  1360. interpolated, and there should be an error in your web console.
  1361. </p>
  1362. </div>
  1363. </div>
  1364. </file>
  1365. <file name="script.js">
  1366. angular.module('ngAppStrictDemo', [])
  1367. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1368. // rather than an explicit annotation
  1369. .controller('BadController', function($scope) {
  1370. $scope.a = 1;
  1371. $scope.b = 2;
  1372. })
  1373. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1374. // due to using explicit annotations using the array style and $inject property, respectively.
  1375. .controller('GoodController1', ['$scope', function($scope) {
  1376. $scope.a = 1;
  1377. $scope.b = 2;
  1378. }])
  1379. .controller('GoodController2', GoodController2);
  1380. function GoodController2($scope) {
  1381. $scope.name = "World";
  1382. }
  1383. GoodController2.$inject = ['$scope'];
  1384. </file>
  1385. <file name="style.css">
  1386. div[ng-controller] {
  1387. margin-bottom: 1em;
  1388. -webkit-border-radius: 4px;
  1389. border-radius: 4px;
  1390. border: 1px solid;
  1391. padding: .5em;
  1392. }
  1393. div[ng-controller^=Good] {
  1394. border-color: #d6e9c6;
  1395. background-color: #dff0d8;
  1396. color: #3c763d;
  1397. }
  1398. div[ng-controller^=Bad] {
  1399. border-color: #ebccd1;
  1400. background-color: #f2dede;
  1401. color: #a94442;
  1402. margin-bottom: 0;
  1403. }
  1404. </file>
  1405. </example>
  1406. */
  1407. function angularInit(element, bootstrap) {
  1408. var appElement,
  1409. module,
  1410. config = {};
  1411. // The element `element` has priority over any other element
  1412. forEach(ngAttrPrefixes, function(prefix) {
  1413. var name = prefix + 'app';
  1414. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1415. appElement = element;
  1416. module = element.getAttribute(name);
  1417. }
  1418. });
  1419. forEach(ngAttrPrefixes, function(prefix) {
  1420. var name = prefix + 'app';
  1421. var candidate;
  1422. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1423. appElement = candidate;
  1424. module = candidate.getAttribute(name);
  1425. }
  1426. });
  1427. if (appElement) {
  1428. config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
  1429. bootstrap(appElement, module ? [module] : [], config);
  1430. }
  1431. }
  1432. /**
  1433. * @ngdoc function
  1434. * @name angular.bootstrap
  1435. * @module ng
  1436. * @description
  1437. * Use this function to manually start up angular application.
  1438. *
  1439. * For more information, see the {@link guide/bootstrap Bootstrap guide}.
  1440. *
  1441. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1442. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1443. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1444. * multiple instances of Angular try to work on the DOM.
  1445. *
  1446. * <div class="alert alert-warning">
  1447. * **Note:** Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1448. * They must use {@link ng.directive:ngApp ngApp}.
  1449. * </div>
  1450. *
  1451. * <div class="alert alert-warning">
  1452. * **Note:** Do not bootstrap the app on an element with a directive that uses {@link ng.$compile#transclusion transclusion},
  1453. * such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and {@link ngRoute.ngView `ngView`}.
  1454. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1455. * causing animations to stop working and making the injector inaccessible from outside the app.
  1456. * </div>
  1457. *
  1458. * ```html
  1459. * <!doctype html>
  1460. * <html>
  1461. * <body>
  1462. * <div ng-controller="WelcomeController">
  1463. * {{greeting}}
  1464. * </div>
  1465. *
  1466. * <script src="angular.js"></script>
  1467. * <script>
  1468. * var app = angular.module('demo', [])
  1469. * .controller('WelcomeController', function($scope) {
  1470. * $scope.greeting = 'Welcome!';
  1471. * });
  1472. * angular.bootstrap(document, ['demo']);
  1473. * </script>
  1474. * </body>
  1475. * </html>
  1476. * ```
  1477. *
  1478. * @param {DOMElement} element DOM element which is the root of angular application.
  1479. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1480. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1481. * function that will be invoked by the injector as a `config` block.
  1482. * See: {@link angular.module modules}
  1483. * @param {Object=} config an object for defining configuration options for the application. The
  1484. * following keys are supported:
  1485. *
  1486. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1487. * assist in finding bugs which break minified code. Defaults to `false`.
  1488. *
  1489. * @returns {auto.$injector} Returns the newly created injector for this app.
  1490. */
  1491. function bootstrap(element, modules, config) {
  1492. if (!isObject(config)) config = {};
  1493. var defaultConfig = {
  1494. strictDi: false
  1495. };
  1496. config = extend(defaultConfig, config);
  1497. var doBootstrap = function() {
  1498. element = jqLite(element);
  1499. if (element.injector()) {
  1500. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1501. //Encode angle brackets to prevent input from being sanitized to empty string #8683
  1502. throw ngMinErr(
  1503. 'btstrpd',
  1504. "App Already Bootstrapped with this Element '{0}'",
  1505. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1506. }
  1507. modules = modules || [];
  1508. modules.unshift(['$provide', function($provide) {
  1509. $provide.value('$rootElement', element);
  1510. }]);
  1511. if (config.debugInfoEnabled) {
  1512. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1513. modules.push(['$compileProvider', function($compileProvider) {
  1514. $compileProvider.debugInfoEnabled(true);
  1515. }]);
  1516. }
  1517. modules.unshift('ng');
  1518. var injector = createInjector(modules, config.strictDi);
  1519. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1520. function bootstrapApply(scope, element, compile, injector) {
  1521. scope.$apply(function() {
  1522. element.data('$injector', injector);
  1523. compile(element)(scope);
  1524. });
  1525. }]
  1526. );
  1527. return injector;
  1528. };
  1529. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1530. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1531. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1532. config.debugInfoEnabled = true;
  1533. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1534. }
  1535. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1536. return doBootstrap();
  1537. }
  1538. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1539. angular.resumeBootstrap = function(extraModules) {
  1540. forEach(extraModules, function(module) {
  1541. modules.push(module);
  1542. });
  1543. return doBootstrap();
  1544. };
  1545. if (isFunction(angular.resumeDeferredBootstrap)) {
  1546. angular.resumeDeferredBootstrap();
  1547. }
  1548. }
  1549. /**
  1550. * @ngdoc function
  1551. * @name angular.reloadWithDebugInfo
  1552. * @module ng
  1553. * @description
  1554. * Use this function to reload the current application with debug information turned on.
  1555. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1556. *
  1557. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1558. */
  1559. function reloadWithDebugInfo() {
  1560. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1561. window.location.reload();
  1562. }
  1563. /**
  1564. * @name angular.getTestability
  1565. * @module ng
  1566. * @description
  1567. * Get the testability service for the instance of Angular on the given
  1568. * element.
  1569. * @param {DOMElement} element DOM element which is the root of angular application.
  1570. */
  1571. function getTestability(rootElement) {
  1572. var injector = angular.element(rootElement).injector();
  1573. if (!injector) {
  1574. throw ngMinErr('test',
  1575. 'no injector found for element argument to getTestability');
  1576. }
  1577. return injector.get('$$testability');
  1578. }
  1579. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1580. function snake_case(name, separator) {
  1581. separator = separator || '_';
  1582. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1583. return (pos ? separator : '') + letter.toLowerCase();
  1584. });
  1585. }
  1586. var bindJQueryFired = false;
  1587. function bindJQuery() {
  1588. var originalCleanData;
  1589. if (bindJQueryFired) {
  1590. return;
  1591. }
  1592. // bind to jQuery if present;
  1593. var jqName = jq();
  1594. jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
  1595. !jqName ? undefined : // use jqLite
  1596. window[jqName]; // use jQuery specified by `ngJq`
  1597. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1598. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1599. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1600. // versions. It will not work for sure with jQuery <1.7, though.
  1601. if (jQuery && jQuery.fn.on) {
  1602. jqLite = jQuery;
  1603. extend(jQuery.fn, {
  1604. scope: JQLitePrototype.scope,
  1605. isolateScope: JQLitePrototype.isolateScope,
  1606. controller: JQLitePrototype.controller,
  1607. injector: JQLitePrototype.injector,
  1608. inheritedData: JQLitePrototype.inheritedData
  1609. });
  1610. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1611. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1612. // the $destroy event on all removed nodes.
  1613. originalCleanData = jQuery.cleanData;
  1614. jQuery.cleanData = function(elems) {
  1615. var events;
  1616. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1617. events = jQuery._data(elem, "events");
  1618. if (events && events.$destroy) {
  1619. jQuery(elem).triggerHandler('$destroy');
  1620. }
  1621. }
  1622. originalCleanData(elems);
  1623. };
  1624. } else {
  1625. jqLite = JQLite;
  1626. }
  1627. angular.element = jqLite;
  1628. // Prevent double-proxying.
  1629. bindJQueryFired = true;
  1630. }
  1631. /**
  1632. * throw error if the argument is falsy.
  1633. */
  1634. function assertArg(arg, name, reason) {
  1635. if (!arg) {
  1636. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1637. }
  1638. return arg;
  1639. }
  1640. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1641. if (acceptArrayAnnotation && isArray(arg)) {
  1642. arg = arg[arg.length - 1];
  1643. }
  1644. assertArg(isFunction(arg), name, 'not a function, got ' +
  1645. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1646. return arg;
  1647. }
  1648. /**
  1649. * throw error if the name given is hasOwnProperty
  1650. * @param {String} name the name to test
  1651. * @param {String} context the context in which the name is used, such as module or directive
  1652. */
  1653. function assertNotHasOwnProperty(name, context) {
  1654. if (name === 'hasOwnProperty') {
  1655. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1656. }
  1657. }
  1658. /**
  1659. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1660. * @param {Object} obj starting object
  1661. * @param {String} path path to traverse
  1662. * @param {boolean} [bindFnToScope=true]
  1663. * @returns {Object} value as accessible by path
  1664. */
  1665. //TODO(misko): this function needs to be removed
  1666. function getter(obj, path, bindFnToScope) {
  1667. if (!path) return obj;
  1668. var keys = path.split('.');
  1669. var key;
  1670. var lastInstance = obj;
  1671. var len = keys.length;
  1672. for (var i = 0; i < len; i++) {
  1673. key = keys[i];
  1674. if (obj) {
  1675. obj = (lastInstance = obj)[key];
  1676. }
  1677. }
  1678. if (!bindFnToScope && isFunction(obj)) {
  1679. return bind(lastInstance, obj);
  1680. }
  1681. return obj;
  1682. }
  1683. /**
  1684. * Return the DOM siblings between the first and last node in the given array.
  1685. * @param {Array} array like object
  1686. * @returns {Array} the inputted object or a jqLite collection containing the nodes
  1687. */
  1688. function getBlockNodes(nodes) {
  1689. // TODO(perf): update `nodes` instead of creating a new object?
  1690. var node = nodes[0];
  1691. var endNode = nodes[nodes.length - 1];
  1692. var blockNodes;
  1693. for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
  1694. if (blockNodes || nodes[i] !== node) {
  1695. if (!blockNodes) {
  1696. blockNodes = jqLite(slice.call(nodes, 0, i));
  1697. }
  1698. blockNodes.push(node);
  1699. }
  1700. }
  1701. return blockNodes || nodes;
  1702. }
  1703. /**
  1704. * Creates a new object without a prototype. This object is useful for lookup without having to
  1705. * guard against prototypically inherited properties via hasOwnProperty.
  1706. *
  1707. * Related micro-benchmarks:
  1708. * - http://jsperf.com/object-create2
  1709. * - http://jsperf.com/proto-map-lookup/2
  1710. * - http://jsperf.com/for-in-vs-object-keys2
  1711. *
  1712. * @returns {Object}
  1713. */
  1714. function createMap() {
  1715. return Object.create(null);
  1716. }
  1717. var NODE_TYPE_ELEMENT = 1;
  1718. var NODE_TYPE_ATTRIBUTE = 2;
  1719. var NODE_TYPE_TEXT = 3;
  1720. var NODE_TYPE_COMMENT = 8;
  1721. var NODE_TYPE_DOCUMENT = 9;
  1722. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1723. /**
  1724. * @ngdoc type
  1725. * @name angular.Module
  1726. * @module ng
  1727. * @description
  1728. *
  1729. * Interface for configuring angular {@link angular.module modules}.
  1730. */
  1731. function setupModuleLoader(window) {
  1732. var $injectorMinErr = minErr('$injector');
  1733. var ngMinErr = minErr('ng');
  1734. function ensure(obj, name, factory) {
  1735. return obj[name] || (obj[name] = factory());
  1736. }
  1737. var angular = ensure(window, 'angular', Object);
  1738. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1739. angular.$$minErr = angular.$$minErr || minErr;
  1740. return ensure(angular, 'module', function() {
  1741. /** @type {Object.<string, angular.Module>} */
  1742. var modules = {};
  1743. /**
  1744. * @ngdoc function
  1745. * @name angular.module
  1746. * @module ng
  1747. * @description
  1748. *
  1749. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1750. * modules.
  1751. * All modules (angular core or 3rd party) that should be available to an application must be
  1752. * registered using this mechanism.
  1753. *
  1754. * Passing one argument retrieves an existing {@link angular.Module},
  1755. * whereas passing more than one argument creates a new {@link angular.Module}
  1756. *
  1757. *
  1758. * # Module
  1759. *
  1760. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1761. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1762. *
  1763. * ```js
  1764. * // Create a new module
  1765. * var myModule = angular.module('myModule', []);
  1766. *
  1767. * // register a new service
  1768. * myModule.value('appName', 'MyCoolApp');
  1769. *
  1770. * // configure existing services inside initialization blocks.
  1771. * myModule.config(['$locationProvider', function($locationProvider) {
  1772. * // Configure existing providers
  1773. * $locationProvider.hashPrefix('!');
  1774. * }]);
  1775. * ```
  1776. *
  1777. * Then you can create an injector and load your modules like this:
  1778. *
  1779. * ```js
  1780. * var injector = angular.injector(['ng', 'myModule'])
  1781. * ```
  1782. *
  1783. * However it's more likely that you'll just use
  1784. * {@link ng.directive:ngApp ngApp} or
  1785. * {@link angular.bootstrap} to simplify this process for you.
  1786. *
  1787. * @param {!string} name The name of the module to create or retrieve.
  1788. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1789. * unspecified then the module is being retrieved for further configuration.
  1790. * @param {Function=} configFn Optional configuration function for the module. Same as
  1791. * {@link angular.Module#config Module#config()}.
  1792. * @returns {angular.Module} new module with the {@link angular.Module} api.
  1793. */
  1794. return function module(name, requires, configFn) {
  1795. var assertNotHasOwnProperty = function(name, context) {
  1796. if (name === 'hasOwnProperty') {
  1797. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1798. }
  1799. };
  1800. assertNotHasOwnProperty(name, 'module');
  1801. if (requires && modules.hasOwnProperty(name)) {
  1802. modules[name] = null;
  1803. }
  1804. return ensure(modules, name, function() {
  1805. if (!requires) {
  1806. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1807. "the module name or forgot to load it. If registering a module ensure that you " +
  1808. "specify the dependencies as the second argument.", name);
  1809. }
  1810. /** @type {!Array.<Array.<*>>} */
  1811. var invokeQueue = [];
  1812. /** @type {!Array.<Function>} */
  1813. var configBlocks = [];
  1814. /** @type {!Array.<Function>} */
  1815. var runBlocks = [];
  1816. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  1817. /** @type {angular.Module} */
  1818. var moduleInstance = {
  1819. // Private state
  1820. _invokeQueue: invokeQueue,
  1821. _configBlocks: configBlocks,
  1822. _runBlocks: runBlocks,
  1823. /**
  1824. * @ngdoc property
  1825. * @name angular.Module#requires
  1826. * @module ng
  1827. *
  1828. * @description
  1829. * Holds the list of modules which the injector will load before the current module is
  1830. * loaded.
  1831. */
  1832. requires: requires,
  1833. /**
  1834. * @ngdoc property
  1835. * @name angular.Module#name
  1836. * @module ng
  1837. *
  1838. * @description
  1839. * Name of the module.
  1840. */
  1841. name: name,
  1842. /**
  1843. * @ngdoc method
  1844. * @name angular.Module#provider
  1845. * @module ng
  1846. * @param {string} name service name
  1847. * @param {Function} providerType Construction function for creating new instance of the
  1848. * service.
  1849. * @description
  1850. * See {@link auto.$provide#provider $provide.provider()}.
  1851. */
  1852. provider: invokeLaterAndSetModuleName('$provide', 'provider'),
  1853. /**
  1854. * @ngdoc method
  1855. * @name angular.Module#factory
  1856. * @module ng
  1857. * @param {string} name service name
  1858. * @param {Function} providerFunction Function for creating new instance of the service.
  1859. * @description
  1860. * See {@link auto.$provide#factory $provide.factory()}.
  1861. */
  1862. factory: invokeLaterAndSetModuleName('$provide', 'factory'),
  1863. /**
  1864. * @ngdoc method
  1865. * @name angular.Module#service
  1866. * @module ng
  1867. * @param {string} name service name
  1868. * @param {Function} constructor A constructor function that will be instantiated.
  1869. * @description
  1870. * See {@link auto.$provide#service $provide.service()}.
  1871. */
  1872. service: invokeLaterAndSetModuleName('$provide', 'service'),
  1873. /**
  1874. * @ngdoc method
  1875. * @name angular.Module#value
  1876. * @module ng
  1877. * @param {string} name service name
  1878. * @param {*} object Service instance object.
  1879. * @description
  1880. * See {@link auto.$provide#value $provide.value()}.
  1881. */
  1882. value: invokeLater('$provide', 'value'),
  1883. /**
  1884. * @ngdoc method
  1885. * @name angular.Module#constant
  1886. * @module ng
  1887. * @param {string} name constant name
  1888. * @param {*} object Constant value.
  1889. * @description
  1890. * Because the constants are fixed, they get applied before other provide methods.
  1891. * See {@link auto.$provide#constant $provide.constant()}.
  1892. */
  1893. constant: invokeLater('$provide', 'constant', 'unshift'),
  1894. /**
  1895. * @ngdoc method
  1896. * @name angular.Module#decorator
  1897. * @module ng
  1898. * @param {string} The name of the service to decorate.
  1899. * @param {Function} This function will be invoked when the service needs to be
  1900. * instantiated and should return the decorated service instance.
  1901. * @description
  1902. * See {@link auto.$provide#decorator $provide.decorator()}.
  1903. */
  1904. decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
  1905. /**
  1906. * @ngdoc method
  1907. * @name angular.Module#animation
  1908. * @module ng
  1909. * @param {string} name animation name
  1910. * @param {Function} animationFactory Factory function for creating new instance of an
  1911. * animation.
  1912. * @description
  1913. *
  1914. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1915. *
  1916. *
  1917. * Defines an animation hook that can be later used with
  1918. * {@link $animate $animate} service and directives that use this service.
  1919. *
  1920. * ```js
  1921. * module.animation('.animation-name', function($inject1, $inject2) {
  1922. * return {
  1923. * eventName : function(element, done) {
  1924. * //code to run the animation
  1925. * //once complete, then run done()
  1926. * return function cancellationFunction(element) {
  1927. * //code to cancel the animation
  1928. * }
  1929. * }
  1930. * }
  1931. * })
  1932. * ```
  1933. *
  1934. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  1935. * {@link ngAnimate ngAnimate module} for more information.
  1936. */
  1937. animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
  1938. /**
  1939. * @ngdoc method
  1940. * @name angular.Module#filter
  1941. * @module ng
  1942. * @param {string} name Filter name - this must be a valid angular expression identifier
  1943. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1944. * @description
  1945. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1946. *
  1947. * <div class="alert alert-warning">
  1948. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  1949. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  1950. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  1951. * (`myapp_subsection_filterx`).
  1952. * </div>
  1953. */
  1954. filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
  1955. /**
  1956. * @ngdoc method
  1957. * @name angular.Module#controller
  1958. * @module ng
  1959. * @param {string|Object} name Controller name, or an object map of controllers where the
  1960. * keys are the names and the values are the constructors.
  1961. * @param {Function} constructor Controller constructor function.
  1962. * @description
  1963. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1964. */
  1965. controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
  1966. /**
  1967. * @ngdoc method
  1968. * @name angular.Module#directive
  1969. * @module ng
  1970. * @param {string|Object} name Directive name, or an object map of directives where the
  1971. * keys are the names and the values are the factories.
  1972. * @param {Function} directiveFactory Factory function for creating new instance of
  1973. * directives.
  1974. * @description
  1975. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  1976. */
  1977. directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
  1978. /**
  1979. * @ngdoc method
  1980. * @name angular.Module#component
  1981. * @module ng
  1982. * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp)
  1983. * @param {Object} options Component definition object (a simplified
  1984. * {@link ng.$compile#directive-definition-object directive definition object})
  1985. *
  1986. * @description
  1987. * See {@link ng.$compileProvider#component $compileProvider.component()}.
  1988. */
  1989. component: invokeLaterAndSetModuleName('$compileProvider', 'component'),
  1990. /**
  1991. * @ngdoc method
  1992. * @name angular.Module#config
  1993. * @module ng
  1994. * @param {Function} configFn Execute this function on module load. Useful for service
  1995. * configuration.
  1996. * @description
  1997. * Use this method to register work which needs to be performed on module loading.
  1998. * For more about how to configure services, see
  1999. * {@link providers#provider-recipe Provider Recipe}.
  2000. */
  2001. config: config,
  2002. /**
  2003. * @ngdoc method
  2004. * @name angular.Module#run
  2005. * @module ng
  2006. * @param {Function} initializationFn Execute this function after injector creation.
  2007. * Useful for application initialization.
  2008. * @description
  2009. * Use this method to register work which should be performed when the injector is done
  2010. * loading all modules.
  2011. */
  2012. run: function(block) {
  2013. runBlocks.push(block);
  2014. return this;
  2015. }
  2016. };
  2017. if (configFn) {
  2018. config(configFn);
  2019. }
  2020. return moduleInstance;
  2021. /**
  2022. * @param {string} provider
  2023. * @param {string} method
  2024. * @param {String=} insertMethod
  2025. * @returns {angular.Module}
  2026. */
  2027. function invokeLater(provider, method, insertMethod, queue) {
  2028. if (!queue) queue = invokeQueue;
  2029. return function() {
  2030. queue[insertMethod || 'push']([provider, method, arguments]);
  2031. return moduleInstance;
  2032. };
  2033. }
  2034. /**
  2035. * @param {string} provider
  2036. * @param {string} method
  2037. * @returns {angular.Module}
  2038. */
  2039. function invokeLaterAndSetModuleName(provider, method) {
  2040. return function(recipeName, factoryFunction) {
  2041. if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
  2042. invokeQueue.push([provider, method, arguments]);
  2043. return moduleInstance;
  2044. };
  2045. }
  2046. });
  2047. };
  2048. });
  2049. }
  2050. /* global: toDebugString: true */
  2051. function serializeObject(obj) {
  2052. var seen = [];
  2053. return JSON.stringify(obj, function(key, val) {
  2054. val = toJsonReplacer(key, val);
  2055. if (isObject(val)) {
  2056. if (seen.indexOf(val) >= 0) return '...';
  2057. seen.push(val);
  2058. }
  2059. return val;
  2060. });
  2061. }
  2062. function toDebugString(obj) {
  2063. if (typeof obj === 'function') {
  2064. return obj.toString().replace(/ \{[\s\S]*$/, '');
  2065. } else if (isUndefined(obj)) {
  2066. return 'undefined';
  2067. } else if (typeof obj !== 'string') {
  2068. return serializeObject(obj);
  2069. }
  2070. return obj;
  2071. }
  2072. /* global angularModule: true,
  2073. version: true,
  2074. $CompileProvider,
  2075. htmlAnchorDirective,
  2076. inputDirective,
  2077. inputDirective,
  2078. formDirective,
  2079. scriptDirective,
  2080. selectDirective,
  2081. styleDirective,
  2082. optionDirective,
  2083. ngBindDirective,
  2084. ngBindHtmlDirective,
  2085. ngBindTemplateDirective,
  2086. ngClassDirective,
  2087. ngClassEvenDirective,
  2088. ngClassOddDirective,
  2089. ngCloakDirective,
  2090. ngControllerDirective,
  2091. ngFormDirective,
  2092. ngHideDirective,
  2093. ngIfDirective,
  2094. ngIncludeDirective,
  2095. ngIncludeFillContentDirective,
  2096. ngInitDirective,
  2097. ngNonBindableDirective,
  2098. ngPluralizeDirective,
  2099. ngRepeatDirective,
  2100. ngShowDirective,
  2101. ngStyleDirective,
  2102. ngSwitchDirective,
  2103. ngSwitchWhenDirective,
  2104. ngSwitchDefaultDirective,
  2105. ngOptionsDirective,
  2106. ngTranscludeDirective,
  2107. ngModelDirective,
  2108. ngListDirective,
  2109. ngChangeDirective,
  2110. patternDirective,
  2111. patternDirective,
  2112. requiredDirective,
  2113. requiredDirective,
  2114. minlengthDirective,
  2115. minlengthDirective,
  2116. maxlengthDirective,
  2117. maxlengthDirective,
  2118. ngValueDirective,
  2119. ngModelOptionsDirective,
  2120. ngAttributeAliasDirectives,
  2121. ngEventDirectives,
  2122. $AnchorScrollProvider,
  2123. $AnimateProvider,
  2124. $CoreAnimateCssProvider,
  2125. $$CoreAnimateJsProvider,
  2126. $$CoreAnimateQueueProvider,
  2127. $$AnimateRunnerFactoryProvider,
  2128. $$AnimateAsyncRunFactoryProvider,
  2129. $BrowserProvider,
  2130. $CacheFactoryProvider,
  2131. $ControllerProvider,
  2132. $DateProvider,
  2133. $DocumentProvider,
  2134. $ExceptionHandlerProvider,
  2135. $FilterProvider,
  2136. $$ForceReflowProvider,
  2137. $InterpolateProvider,
  2138. $IntervalProvider,
  2139. $$HashMapProvider,
  2140. $HttpProvider,
  2141. $HttpParamSerializerProvider,
  2142. $HttpParamSerializerJQLikeProvider,
  2143. $HttpBackendProvider,
  2144. $xhrFactoryProvider,
  2145. $LocationProvider,
  2146. $LogProvider,
  2147. $ParseProvider,
  2148. $RootScopeProvider,
  2149. $QProvider,
  2150. $$QProvider,
  2151. $$SanitizeUriProvider,
  2152. $SceProvider,
  2153. $SceDelegateProvider,
  2154. $SnifferProvider,
  2155. $TemplateCacheProvider,
  2156. $TemplateRequestProvider,
  2157. $$TestabilityProvider,
  2158. $TimeoutProvider,
  2159. $$RAFProvider,
  2160. $WindowProvider,
  2161. $$jqLiteProvider,
  2162. $$CookieReaderProvider
  2163. */
  2164. /**
  2165. * @ngdoc object
  2166. * @name angular.version
  2167. * @module ng
  2168. * @description
  2169. * An object that contains information about the current AngularJS version.
  2170. *
  2171. * This object has the following properties:
  2172. *
  2173. * - `full` – `{string}` – Full version string, such as "0.9.18".
  2174. * - `major` – `{number}` – Major version number, such as "0".
  2175. * - `minor` – `{number}` – Minor version number, such as "9".
  2176. * - `dot` – `{number}` – Dot version number, such as "18".
  2177. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  2178. */
  2179. var version = {
  2180. full: '1.5.1-build.4601+sha.c966876', // all of these placeholder strings will be replaced by grunt's
  2181. major: 1, // package task
  2182. minor: 5,
  2183. dot: 1,
  2184. codeName: 'snapshot'
  2185. };
  2186. function publishExternalAPI(angular) {
  2187. extend(angular, {
  2188. 'bootstrap': bootstrap,
  2189. 'copy': copy,
  2190. 'extend': extend,
  2191. 'merge': merge,
  2192. 'equals': equals,
  2193. 'element': jqLite,
  2194. 'forEach': forEach,
  2195. 'injector': createInjector,
  2196. 'noop': noop,
  2197. 'bind': bind,
  2198. 'toJson': toJson,
  2199. 'fromJson': fromJson,
  2200. 'identity': identity,
  2201. 'isUndefined': isUndefined,
  2202. 'isDefined': isDefined,
  2203. 'isString': isString,
  2204. 'isFunction': isFunction,
  2205. 'isObject': isObject,
  2206. 'isNumber': isNumber,
  2207. 'isElement': isElement,
  2208. 'isArray': isArray,
  2209. 'version': version,
  2210. 'isDate': isDate,
  2211. 'lowercase': lowercase,
  2212. 'uppercase': uppercase,
  2213. 'callbacks': {counter: 0},
  2214. 'getTestability': getTestability,
  2215. '$$minErr': minErr,
  2216. '$$csp': csp,
  2217. 'reloadWithDebugInfo': reloadWithDebugInfo
  2218. });
  2219. angularModule = setupModuleLoader(window);
  2220. angularModule('ng', ['ngLocale'], ['$provide',
  2221. function ngModule($provide) {
  2222. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  2223. $provide.provider({
  2224. $$sanitizeUri: $$SanitizeUriProvider
  2225. });
  2226. $provide.provider('$compile', $CompileProvider).
  2227. directive({
  2228. a: htmlAnchorDirective,
  2229. input: inputDirective,
  2230. textarea: inputDirective,
  2231. form: formDirective,
  2232. script: scriptDirective,
  2233. select: selectDirective,
  2234. style: styleDirective,
  2235. option: optionDirective,
  2236. ngBind: ngBindDirective,
  2237. ngBindHtml: ngBindHtmlDirective,
  2238. ngBindTemplate: ngBindTemplateDirective,
  2239. ngClass: ngClassDirective,
  2240. ngClassEven: ngClassEvenDirective,
  2241. ngClassOdd: ngClassOddDirective,
  2242. ngCloak: ngCloakDirective,
  2243. ngController: ngControllerDirective,
  2244. ngForm: ngFormDirective,
  2245. ngHide: ngHideDirective,
  2246. ngIf: ngIfDirective,
  2247. ngInclude: ngIncludeDirective,
  2248. ngInit: ngInitDirective,
  2249. ngNonBindable: ngNonBindableDirective,
  2250. ngPluralize: ngPluralizeDirective,
  2251. ngRepeat: ngRepeatDirective,
  2252. ngShow: ngShowDirective,
  2253. ngStyle: ngStyleDirective,
  2254. ngSwitch: ngSwitchDirective,
  2255. ngSwitchWhen: ngSwitchWhenDirective,
  2256. ngSwitchDefault: ngSwitchDefaultDirective,
  2257. ngOptions: ngOptionsDirective,
  2258. ngTransclude: ngTranscludeDirective,
  2259. ngModel: ngModelDirective,
  2260. ngList: ngListDirective,
  2261. ngChange: ngChangeDirective,
  2262. pattern: patternDirective,
  2263. ngPattern: patternDirective,
  2264. required: requiredDirective,
  2265. ngRequired: requiredDirective,
  2266. minlength: minlengthDirective,
  2267. ngMinlength: minlengthDirective,
  2268. maxlength: maxlengthDirective,
  2269. ngMaxlength: maxlengthDirective,
  2270. ngValue: ngValueDirective,
  2271. ngModelOptions: ngModelOptionsDirective
  2272. }).
  2273. directive({
  2274. ngInclude: ngIncludeFillContentDirective
  2275. }).
  2276. directive(ngAttributeAliasDirectives).
  2277. directive(ngEventDirectives);
  2278. $provide.provider({
  2279. $anchorScroll: $AnchorScrollProvider,
  2280. $animate: $AnimateProvider,
  2281. $animateCss: $CoreAnimateCssProvider,
  2282. $$animateJs: $$CoreAnimateJsProvider,
  2283. $$animateQueue: $$CoreAnimateQueueProvider,
  2284. $$AnimateRunner: $$AnimateRunnerFactoryProvider,
  2285. $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,
  2286. $browser: $BrowserProvider,
  2287. $cacheFactory: $CacheFactoryProvider,
  2288. $controller: $ControllerProvider,
  2289. $document: $DocumentProvider,
  2290. $exceptionHandler: $ExceptionHandlerProvider,
  2291. $filter: $FilterProvider,
  2292. $$forceReflow: $$ForceReflowProvider,
  2293. $interpolate: $InterpolateProvider,
  2294. $interval: $IntervalProvider,
  2295. $http: $HttpProvider,
  2296. $httpParamSerializer: $HttpParamSerializerProvider,
  2297. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  2298. $httpBackend: $HttpBackendProvider,
  2299. $xhrFactory: $xhrFactoryProvider,
  2300. $location: $LocationProvider,
  2301. $log: $LogProvider,
  2302. $parse: $ParseProvider,
  2303. $rootScope: $RootScopeProvider,
  2304. $q: $QProvider,
  2305. $$q: $$QProvider,
  2306. $sce: $SceProvider,
  2307. $sceDelegate: $SceDelegateProvider,
  2308. $sniffer: $SnifferProvider,
  2309. $templateCache: $TemplateCacheProvider,
  2310. $templateRequest: $TemplateRequestProvider,
  2311. $$testability: $$TestabilityProvider,
  2312. $timeout: $TimeoutProvider,
  2313. $window: $WindowProvider,
  2314. $$rAF: $$RAFProvider,
  2315. $$jqLite: $$jqLiteProvider,
  2316. $$HashMap: $$HashMapProvider,
  2317. $$cookieReader: $$CookieReaderProvider
  2318. });
  2319. }
  2320. ]);
  2321. }
  2322. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2323. * Any commits to this file should be reviewed with security in mind. *
  2324. * Changes to this file can potentially create security vulnerabilities. *
  2325. * An approval from 2 Core members with history of modifying *
  2326. * this file is required. *
  2327. * *
  2328. * Does the change somehow allow for arbitrary javascript to be executed? *
  2329. * Or allows for someone to change the prototype of built-in objects? *
  2330. * Or gives undesired access to variables likes document or window? *
  2331. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2332. /* global JQLitePrototype: true,
  2333. addEventListenerFn: true,
  2334. removeEventListenerFn: true,
  2335. BOOLEAN_ATTR: true,
  2336. ALIASED_ATTR: true,
  2337. */
  2338. //////////////////////////////////
  2339. //JQLite
  2340. //////////////////////////////////
  2341. /**
  2342. * @ngdoc function
  2343. * @name angular.element
  2344. * @module ng
  2345. * @kind function
  2346. *
  2347. * @description
  2348. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2349. *
  2350. * If jQuery is available, `angular.element` is an alias for the
  2351. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2352. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
  2353. *
  2354. * jqLite is a tiny, API-compatible subset of jQuery that allows
  2355. * Angular to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
  2356. * commonly needed functionality with the goal of having a very small footprint.
  2357. *
  2358. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
  2359. * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
  2360. * specific version of jQuery if multiple versions exist on the page.
  2361. *
  2362. * <div class="alert alert-info">**Note:** All element references in Angular are always wrapped with jQuery or
  2363. * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div>
  2364. *
  2365. * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements
  2366. * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
  2367. * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.</div>
  2368. *
  2369. * ## Angular's jqLite
  2370. * jqLite provides only the following jQuery methods:
  2371. *
  2372. * - [`addClass()`](http://api.jquery.com/addClass/)
  2373. * - [`after()`](http://api.jquery.com/after/)
  2374. * - [`append()`](http://api.jquery.com/append/)
  2375. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2376. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  2377. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2378. * - [`clone()`](http://api.jquery.com/clone/)
  2379. * - [`contents()`](http://api.jquery.com/contents/)
  2380. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
  2381. * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
  2382. * - [`data()`](http://api.jquery.com/data/)
  2383. * - [`detach()`](http://api.jquery.com/detach/)
  2384. * - [`empty()`](http://api.jquery.com/empty/)
  2385. * - [`eq()`](http://api.jquery.com/eq/)
  2386. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2387. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2388. * - [`html()`](http://api.jquery.com/html/)
  2389. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2390. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2391. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
  2392. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2393. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2394. * - [`prepend()`](http://api.jquery.com/prepend/)
  2395. * - [`prop()`](http://api.jquery.com/prop/)
  2396. * - [`ready()`](http://api.jquery.com/ready/)
  2397. * - [`remove()`](http://api.jquery.com/remove/)
  2398. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  2399. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  2400. * - [`removeData()`](http://api.jquery.com/removeData/)
  2401. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2402. * - [`text()`](http://api.jquery.com/text/)
  2403. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  2404. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  2405. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces or event object as parameter
  2406. * - [`val()`](http://api.jquery.com/val/)
  2407. * - [`wrap()`](http://api.jquery.com/wrap/)
  2408. *
  2409. * ## jQuery/jqLite Extras
  2410. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2411. *
  2412. * ### Events
  2413. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2414. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2415. * element before it is removed.
  2416. *
  2417. * ### Methods
  2418. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2419. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2420. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2421. * `'ngModel'`).
  2422. * - `injector()` - retrieves the injector of the current element or its parent.
  2423. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2424. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2425. * be enabled.
  2426. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2427. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2428. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2429. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2430. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2431. * parent element is reached.
  2432. *
  2433. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2434. * @returns {Object} jQuery object.
  2435. */
  2436. JQLite.expando = 'ng339';
  2437. var jqCache = JQLite.cache = {},
  2438. jqId = 1,
  2439. addEventListenerFn = function(element, type, fn) {
  2440. element.addEventListener(type, fn, false);
  2441. },
  2442. removeEventListenerFn = function(element, type, fn) {
  2443. element.removeEventListener(type, fn, false);
  2444. };
  2445. /*
  2446. * !!! This is an undocumented "private" function !!!
  2447. */
  2448. JQLite._data = function(node) {
  2449. //jQuery always returns an object on cache miss
  2450. return this.cache[node[this.expando]] || {};
  2451. };
  2452. function jqNextId() { return ++jqId; }
  2453. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  2454. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  2455. var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
  2456. var jqLiteMinErr = minErr('jqLite');
  2457. /**
  2458. * Converts snake_case to camelCase.
  2459. * Also there is special case for Moz prefix starting with upper case letter.
  2460. * @param name Name to normalize
  2461. */
  2462. function camelCase(name) {
  2463. return name.
  2464. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2465. return offset ? letter.toUpperCase() : letter;
  2466. }).
  2467. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2468. }
  2469. var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
  2470. var HTML_REGEXP = /<|&#?\w+;/;
  2471. var TAG_NAME_REGEXP = /<([\w:-]+)/;
  2472. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
  2473. var wrapMap = {
  2474. 'option': [1, '<select multiple="multiple">', '</select>'],
  2475. 'thead': [1, '<table>', '</table>'],
  2476. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2477. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2478. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2479. '_default': [0, "", ""]
  2480. };
  2481. wrapMap.optgroup = wrapMap.option;
  2482. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2483. wrapMap.th = wrapMap.td;
  2484. function jqLiteIsTextNode(html) {
  2485. return !HTML_REGEXP.test(html);
  2486. }
  2487. function jqLiteAcceptsData(node) {
  2488. // The window object can accept data but has no nodeType
  2489. // Otherwise we are only interested in elements (1) and documents (9)
  2490. var nodeType = node.nodeType;
  2491. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2492. }
  2493. function jqLiteHasData(node) {
  2494. for (var key in jqCache[node.ng339]) {
  2495. return true;
  2496. }
  2497. return false;
  2498. }
  2499. function jqLiteCleanData(nodes) {
  2500. for (var i = 0, ii = nodes.length; i < ii; i++) {
  2501. jqLiteRemoveData(nodes[i]);
  2502. }
  2503. }
  2504. function jqLiteBuildFragment(html, context) {
  2505. var tmp, tag, wrap,
  2506. fragment = context.createDocumentFragment(),
  2507. nodes = [], i;
  2508. if (jqLiteIsTextNode(html)) {
  2509. // Convert non-html into a text node
  2510. nodes.push(context.createTextNode(html));
  2511. } else {
  2512. // Convert html into DOM nodes
  2513. tmp = tmp || fragment.appendChild(context.createElement("div"));
  2514. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2515. wrap = wrapMap[tag] || wrapMap._default;
  2516. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2517. // Descend through wrappers to the right content
  2518. i = wrap[0];
  2519. while (i--) {
  2520. tmp = tmp.lastChild;
  2521. }
  2522. nodes = concat(nodes, tmp.childNodes);
  2523. tmp = fragment.firstChild;
  2524. tmp.textContent = "";
  2525. }
  2526. // Remove wrapper from fragment
  2527. fragment.textContent = "";
  2528. fragment.innerHTML = ""; // Clear inner HTML
  2529. forEach(nodes, function(node) {
  2530. fragment.appendChild(node);
  2531. });
  2532. return fragment;
  2533. }
  2534. function jqLiteParseHTML(html, context) {
  2535. context = context || document;
  2536. var parsed;
  2537. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2538. return [context.createElement(parsed[1])];
  2539. }
  2540. if ((parsed = jqLiteBuildFragment(html, context))) {
  2541. return parsed.childNodes;
  2542. }
  2543. return [];
  2544. }
  2545. function jqLiteWrapNode(node, wrapper) {
  2546. var parent = node.parentNode;
  2547. if (parent) {
  2548. parent.replaceChild(wrapper, node);
  2549. }
  2550. wrapper.appendChild(node);
  2551. }
  2552. // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
  2553. var jqLiteContains = Node.prototype.contains || function(arg) {
  2554. // jshint bitwise: false
  2555. return !!(this.compareDocumentPosition(arg) & 16);
  2556. // jshint bitwise: true
  2557. };
  2558. /////////////////////////////////////////////
  2559. function JQLite(element) {
  2560. if (element instanceof JQLite) {
  2561. return element;
  2562. }
  2563. var argIsString;
  2564. if (isString(element)) {
  2565. element = trim(element);
  2566. argIsString = true;
  2567. }
  2568. if (!(this instanceof JQLite)) {
  2569. if (argIsString && element.charAt(0) != '<') {
  2570. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2571. }
  2572. return new JQLite(element);
  2573. }
  2574. if (argIsString) {
  2575. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2576. } else {
  2577. jqLiteAddNodes(this, element);
  2578. }
  2579. }
  2580. function jqLiteClone(element) {
  2581. return element.cloneNode(true);
  2582. }
  2583. function jqLiteDealoc(element, onlyDescendants) {
  2584. if (!onlyDescendants) jqLiteRemoveData(element);
  2585. if (element.querySelectorAll) {
  2586. var descendants = element.querySelectorAll('*');
  2587. for (var i = 0, l = descendants.length; i < l; i++) {
  2588. jqLiteRemoveData(descendants[i]);
  2589. }
  2590. }
  2591. }
  2592. function jqLiteOff(element, type, fn, unsupported) {
  2593. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2594. var expandoStore = jqLiteExpandoStore(element);
  2595. var events = expandoStore && expandoStore.events;
  2596. var handle = expandoStore && expandoStore.handle;
  2597. if (!handle) return; //no listeners registered
  2598. if (!type) {
  2599. for (type in events) {
  2600. if (type !== '$destroy') {
  2601. removeEventListenerFn(element, type, handle);
  2602. }
  2603. delete events[type];
  2604. }
  2605. } else {
  2606. var removeHandler = function(type) {
  2607. var listenerFns = events[type];
  2608. if (isDefined(fn)) {
  2609. arrayRemove(listenerFns || [], fn);
  2610. }
  2611. if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
  2612. removeEventListenerFn(element, type, handle);
  2613. delete events[type];
  2614. }
  2615. };
  2616. forEach(type.split(' '), function(type) {
  2617. removeHandler(type);
  2618. if (MOUSE_EVENT_MAP[type]) {
  2619. removeHandler(MOUSE_EVENT_MAP[type]);
  2620. }
  2621. });
  2622. }
  2623. }
  2624. function jqLiteRemoveData(element, name) {
  2625. var expandoId = element.ng339;
  2626. var expandoStore = expandoId && jqCache[expandoId];
  2627. if (expandoStore) {
  2628. if (name) {
  2629. delete expandoStore.data[name];
  2630. return;
  2631. }
  2632. if (expandoStore.handle) {
  2633. if (expandoStore.events.$destroy) {
  2634. expandoStore.handle({}, '$destroy');
  2635. }
  2636. jqLiteOff(element);
  2637. }
  2638. delete jqCache[expandoId];
  2639. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2640. }
  2641. }
  2642. function jqLiteExpandoStore(element, createIfNecessary) {
  2643. var expandoId = element.ng339,
  2644. expandoStore = expandoId && jqCache[expandoId];
  2645. if (createIfNecessary && !expandoStore) {
  2646. element.ng339 = expandoId = jqNextId();
  2647. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2648. }
  2649. return expandoStore;
  2650. }
  2651. function jqLiteData(element, key, value) {
  2652. if (jqLiteAcceptsData(element)) {
  2653. var isSimpleSetter = isDefined(value);
  2654. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2655. var massGetter = !key;
  2656. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2657. var data = expandoStore && expandoStore.data;
  2658. if (isSimpleSetter) { // data('key', value)
  2659. data[key] = value;
  2660. } else {
  2661. if (massGetter) { // data()
  2662. return data;
  2663. } else {
  2664. if (isSimpleGetter) { // data('key')
  2665. // don't force creation of expandoStore if it doesn't exist yet
  2666. return data && data[key];
  2667. } else { // mass-setter: data({key1: val1, key2: val2})
  2668. extend(data, key);
  2669. }
  2670. }
  2671. }
  2672. }
  2673. }
  2674. function jqLiteHasClass(element, selector) {
  2675. if (!element.getAttribute) return false;
  2676. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2677. indexOf(" " + selector + " ") > -1);
  2678. }
  2679. function jqLiteRemoveClass(element, cssClasses) {
  2680. if (cssClasses && element.setAttribute) {
  2681. forEach(cssClasses.split(' '), function(cssClass) {
  2682. element.setAttribute('class', trim(
  2683. (" " + (element.getAttribute('class') || '') + " ")
  2684. .replace(/[\n\t]/g, " ")
  2685. .replace(" " + trim(cssClass) + " ", " "))
  2686. );
  2687. });
  2688. }
  2689. }
  2690. function jqLiteAddClass(element, cssClasses) {
  2691. if (cssClasses && element.setAttribute) {
  2692. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2693. .replace(/[\n\t]/g, " ");
  2694. forEach(cssClasses.split(' '), function(cssClass) {
  2695. cssClass = trim(cssClass);
  2696. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2697. existingClasses += cssClass + ' ';
  2698. }
  2699. });
  2700. element.setAttribute('class', trim(existingClasses));
  2701. }
  2702. }
  2703. function jqLiteAddNodes(root, elements) {
  2704. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2705. if (elements) {
  2706. // if a Node (the most common case)
  2707. if (elements.nodeType) {
  2708. root[root.length++] = elements;
  2709. } else {
  2710. var length = elements.length;
  2711. // if an Array or NodeList and not a Window
  2712. if (typeof length === 'number' && elements.window !== elements) {
  2713. if (length) {
  2714. for (var i = 0; i < length; i++) {
  2715. root[root.length++] = elements[i];
  2716. }
  2717. }
  2718. } else {
  2719. root[root.length++] = elements;
  2720. }
  2721. }
  2722. }
  2723. }
  2724. function jqLiteController(element, name) {
  2725. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  2726. }
  2727. function jqLiteInheritedData(element, name, value) {
  2728. // if element is the document object work with the html element instead
  2729. // this makes $(document).scope() possible
  2730. if (element.nodeType == NODE_TYPE_DOCUMENT) {
  2731. element = element.documentElement;
  2732. }
  2733. var names = isArray(name) ? name : [name];
  2734. while (element) {
  2735. for (var i = 0, ii = names.length; i < ii; i++) {
  2736. if (isDefined(value = jqLite.data(element, names[i]))) return value;
  2737. }
  2738. // If dealing with a document fragment node with a host element, and no parent, use the host
  2739. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2740. // to lookup parent controllers.
  2741. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  2742. }
  2743. }
  2744. function jqLiteEmpty(element) {
  2745. jqLiteDealoc(element, true);
  2746. while (element.firstChild) {
  2747. element.removeChild(element.firstChild);
  2748. }
  2749. }
  2750. function jqLiteRemove(element, keepData) {
  2751. if (!keepData) jqLiteDealoc(element);
  2752. var parent = element.parentNode;
  2753. if (parent) parent.removeChild(element);
  2754. }
  2755. function jqLiteDocumentLoaded(action, win) {
  2756. win = win || window;
  2757. if (win.document.readyState === 'complete') {
  2758. // Force the action to be run async for consistent behavior
  2759. // from the action's point of view
  2760. // i.e. it will definitely not be in a $apply
  2761. win.setTimeout(action);
  2762. } else {
  2763. // No need to unbind this handler as load is only ever called once
  2764. jqLite(win).on('load', action);
  2765. }
  2766. }
  2767. //////////////////////////////////////////
  2768. // Functions which are declared directly.
  2769. //////////////////////////////////////////
  2770. var JQLitePrototype = JQLite.prototype = {
  2771. ready: function(fn) {
  2772. var fired = false;
  2773. function trigger() {
  2774. if (fired) return;
  2775. fired = true;
  2776. fn();
  2777. }
  2778. // check if document is already loaded
  2779. if (document.readyState === 'complete') {
  2780. setTimeout(trigger);
  2781. } else {
  2782. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2783. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2784. // jshint -W064
  2785. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2786. // jshint +W064
  2787. }
  2788. },
  2789. toString: function() {
  2790. var value = [];
  2791. forEach(this, function(e) { value.push('' + e);});
  2792. return '[' + value.join(', ') + ']';
  2793. },
  2794. eq: function(index) {
  2795. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2796. },
  2797. length: 0,
  2798. push: push,
  2799. sort: [].sort,
  2800. splice: [].splice
  2801. };
  2802. //////////////////////////////////////////
  2803. // Functions iterating getter/setters.
  2804. // these functions return self on setter and
  2805. // value on get.
  2806. //////////////////////////////////////////
  2807. var BOOLEAN_ATTR = {};
  2808. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2809. BOOLEAN_ATTR[lowercase(value)] = value;
  2810. });
  2811. var BOOLEAN_ELEMENTS = {};
  2812. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2813. BOOLEAN_ELEMENTS[value] = true;
  2814. });
  2815. var ALIASED_ATTR = {
  2816. 'ngMinlength': 'minlength',
  2817. 'ngMaxlength': 'maxlength',
  2818. 'ngMin': 'min',
  2819. 'ngMax': 'max',
  2820. 'ngPattern': 'pattern'
  2821. };
  2822. function getBooleanAttrName(element, name) {
  2823. // check dom last since we will most likely fail on name
  2824. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2825. // booleanAttr is here twice to minimize DOM access
  2826. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  2827. }
  2828. function getAliasedAttrName(name) {
  2829. return ALIASED_ATTR[name];
  2830. }
  2831. forEach({
  2832. data: jqLiteData,
  2833. removeData: jqLiteRemoveData,
  2834. hasData: jqLiteHasData,
  2835. cleanData: jqLiteCleanData
  2836. }, function(fn, name) {
  2837. JQLite[name] = fn;
  2838. });
  2839. forEach({
  2840. data: jqLiteData,
  2841. inheritedData: jqLiteInheritedData,
  2842. scope: function(element) {
  2843. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2844. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2845. },
  2846. isolateScope: function(element) {
  2847. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2848. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  2849. },
  2850. controller: jqLiteController,
  2851. injector: function(element) {
  2852. return jqLiteInheritedData(element, '$injector');
  2853. },
  2854. removeAttr: function(element, name) {
  2855. element.removeAttribute(name);
  2856. },
  2857. hasClass: jqLiteHasClass,
  2858. css: function(element, name, value) {
  2859. name = camelCase(name);
  2860. if (isDefined(value)) {
  2861. element.style[name] = value;
  2862. } else {
  2863. return element.style[name];
  2864. }
  2865. },
  2866. attr: function(element, name, value) {
  2867. var nodeType = element.nodeType;
  2868. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
  2869. return;
  2870. }
  2871. var lowercasedName = lowercase(name);
  2872. if (BOOLEAN_ATTR[lowercasedName]) {
  2873. if (isDefined(value)) {
  2874. if (!!value) {
  2875. element[name] = true;
  2876. element.setAttribute(name, lowercasedName);
  2877. } else {
  2878. element[name] = false;
  2879. element.removeAttribute(lowercasedName);
  2880. }
  2881. } else {
  2882. return (element[name] ||
  2883. (element.attributes.getNamedItem(name) || noop).specified)
  2884. ? lowercasedName
  2885. : undefined;
  2886. }
  2887. } else if (isDefined(value)) {
  2888. element.setAttribute(name, value);
  2889. } else if (element.getAttribute) {
  2890. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2891. // some elements (e.g. Document) don't have get attribute, so return undefined
  2892. var ret = element.getAttribute(name, 2);
  2893. // normalize non-existing attributes to undefined (as jQuery)
  2894. return ret === null ? undefined : ret;
  2895. }
  2896. },
  2897. prop: function(element, name, value) {
  2898. if (isDefined(value)) {
  2899. element[name] = value;
  2900. } else {
  2901. return element[name];
  2902. }
  2903. },
  2904. text: (function() {
  2905. getText.$dv = '';
  2906. return getText;
  2907. function getText(element, value) {
  2908. if (isUndefined(value)) {
  2909. var nodeType = element.nodeType;
  2910. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  2911. }
  2912. element.textContent = value;
  2913. }
  2914. })(),
  2915. val: function(element, value) {
  2916. if (isUndefined(value)) {
  2917. if (element.multiple && nodeName_(element) === 'select') {
  2918. var result = [];
  2919. forEach(element.options, function(option) {
  2920. if (option.selected) {
  2921. result.push(option.value || option.text);
  2922. }
  2923. });
  2924. return result.length === 0 ? null : result;
  2925. }
  2926. return element.value;
  2927. }
  2928. element.value = value;
  2929. },
  2930. html: function(element, value) {
  2931. if (isUndefined(value)) {
  2932. return element.innerHTML;
  2933. }
  2934. jqLiteDealoc(element, true);
  2935. element.innerHTML = value;
  2936. },
  2937. empty: jqLiteEmpty
  2938. }, function(fn, name) {
  2939. /**
  2940. * Properties: writes return selection, reads return first value
  2941. */
  2942. JQLite.prototype[name] = function(arg1, arg2) {
  2943. var i, key;
  2944. var nodeCount = this.length;
  2945. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  2946. // in a way that survives minification.
  2947. // jqLiteEmpty takes no arguments but is a setter.
  2948. if (fn !== jqLiteEmpty &&
  2949. (isUndefined((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
  2950. if (isObject(arg1)) {
  2951. // we are a write, but the object properties are the key/values
  2952. for (i = 0; i < nodeCount; i++) {
  2953. if (fn === jqLiteData) {
  2954. // data() takes the whole object in jQuery
  2955. fn(this[i], arg1);
  2956. } else {
  2957. for (key in arg1) {
  2958. fn(this[i], key, arg1[key]);
  2959. }
  2960. }
  2961. }
  2962. // return self for chaining
  2963. return this;
  2964. } else {
  2965. // we are a read, so read the first child.
  2966. // TODO: do we still need this?
  2967. var value = fn.$dv;
  2968. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  2969. var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
  2970. for (var j = 0; j < jj; j++) {
  2971. var nodeValue = fn(this[j], arg1, arg2);
  2972. value = value ? value + nodeValue : nodeValue;
  2973. }
  2974. return value;
  2975. }
  2976. } else {
  2977. // we are a write, so apply to all children
  2978. for (i = 0; i < nodeCount; i++) {
  2979. fn(this[i], arg1, arg2);
  2980. }
  2981. // return self for chaining
  2982. return this;
  2983. }
  2984. };
  2985. });
  2986. function createEventHandler(element, events) {
  2987. var eventHandler = function(event, type) {
  2988. // jQuery specific api
  2989. event.isDefaultPrevented = function() {
  2990. return event.defaultPrevented;
  2991. };
  2992. var eventFns = events[type || event.type];
  2993. var eventFnsLength = eventFns ? eventFns.length : 0;
  2994. if (!eventFnsLength) return;
  2995. if (isUndefined(event.immediatePropagationStopped)) {
  2996. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  2997. event.stopImmediatePropagation = function() {
  2998. event.immediatePropagationStopped = true;
  2999. if (event.stopPropagation) {
  3000. event.stopPropagation();
  3001. }
  3002. if (originalStopImmediatePropagation) {
  3003. originalStopImmediatePropagation.call(event);
  3004. }
  3005. };
  3006. }
  3007. event.isImmediatePropagationStopped = function() {
  3008. return event.immediatePropagationStopped === true;
  3009. };
  3010. // Some events have special handlers that wrap the real handler
  3011. var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
  3012. // Copy event handlers in case event handlers array is modified during execution.
  3013. if ((eventFnsLength > 1)) {
  3014. eventFns = shallowCopy(eventFns);
  3015. }
  3016. for (var i = 0; i < eventFnsLength; i++) {
  3017. if (!event.isImmediatePropagationStopped()) {
  3018. handlerWrapper(element, event, eventFns[i]);
  3019. }
  3020. }
  3021. };
  3022. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  3023. // events on `element`
  3024. eventHandler.elem = element;
  3025. return eventHandler;
  3026. }
  3027. function defaultHandlerWrapper(element, event, handler) {
  3028. handler.call(element, event);
  3029. }
  3030. function specialMouseHandlerWrapper(target, event, handler) {
  3031. // Refer to jQuery's implementation of mouseenter & mouseleave
  3032. // Read about mouseenter and mouseleave:
  3033. // http://www.quirksmode.org/js/events_mouse.html#link8
  3034. var related = event.relatedTarget;
  3035. // For mousenter/leave call the handler if related is outside the target.
  3036. // NB: No relatedTarget if the mouse left/entered the browser window
  3037. if (!related || (related !== target && !jqLiteContains.call(target, related))) {
  3038. handler.call(target, event);
  3039. }
  3040. }
  3041. //////////////////////////////////////////
  3042. // Functions iterating traversal.
  3043. // These functions chain results into a single
  3044. // selector.
  3045. //////////////////////////////////////////
  3046. forEach({
  3047. removeData: jqLiteRemoveData,
  3048. on: function jqLiteOn(element, type, fn, unsupported) {
  3049. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  3050. // Do not add event handlers to non-elements because they will not be cleaned up.
  3051. if (!jqLiteAcceptsData(element)) {
  3052. return;
  3053. }
  3054. var expandoStore = jqLiteExpandoStore(element, true);
  3055. var events = expandoStore.events;
  3056. var handle = expandoStore.handle;
  3057. if (!handle) {
  3058. handle = expandoStore.handle = createEventHandler(element, events);
  3059. }
  3060. // http://jsperf.com/string-indexof-vs-split
  3061. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  3062. var i = types.length;
  3063. var addHandler = function(type, specialHandlerWrapper, noEventListener) {
  3064. var eventFns = events[type];
  3065. if (!eventFns) {
  3066. eventFns = events[type] = [];
  3067. eventFns.specialHandlerWrapper = specialHandlerWrapper;
  3068. if (type !== '$destroy' && !noEventListener) {
  3069. addEventListenerFn(element, type, handle);
  3070. }
  3071. }
  3072. eventFns.push(fn);
  3073. };
  3074. while (i--) {
  3075. type = types[i];
  3076. if (MOUSE_EVENT_MAP[type]) {
  3077. addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
  3078. addHandler(type, undefined, true);
  3079. } else {
  3080. addHandler(type);
  3081. }
  3082. }
  3083. },
  3084. off: jqLiteOff,
  3085. one: function(element, type, fn) {
  3086. element = jqLite(element);
  3087. //add the listener twice so that when it is called
  3088. //you can remove the original function and still be
  3089. //able to call element.off(ev, fn) normally
  3090. element.on(type, function onFn() {
  3091. element.off(type, fn);
  3092. element.off(type, onFn);
  3093. });
  3094. element.on(type, fn);
  3095. },
  3096. replaceWith: function(element, replaceNode) {
  3097. var index, parent = element.parentNode;
  3098. jqLiteDealoc(element);
  3099. forEach(new JQLite(replaceNode), function(node) {
  3100. if (index) {
  3101. parent.insertBefore(node, index.nextSibling);
  3102. } else {
  3103. parent.replaceChild(node, element);
  3104. }
  3105. index = node;
  3106. });
  3107. },
  3108. children: function(element) {
  3109. var children = [];
  3110. forEach(element.childNodes, function(element) {
  3111. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3112. children.push(element);
  3113. }
  3114. });
  3115. return children;
  3116. },
  3117. contents: function(element) {
  3118. return element.contentDocument || element.childNodes || [];
  3119. },
  3120. append: function(element, node) {
  3121. var nodeType = element.nodeType;
  3122. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  3123. node = new JQLite(node);
  3124. for (var i = 0, ii = node.length; i < ii; i++) {
  3125. var child = node[i];
  3126. element.appendChild(child);
  3127. }
  3128. },
  3129. prepend: function(element, node) {
  3130. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3131. var index = element.firstChild;
  3132. forEach(new JQLite(node), function(child) {
  3133. element.insertBefore(child, index);
  3134. });
  3135. }
  3136. },
  3137. wrap: function(element, wrapNode) {
  3138. jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);
  3139. },
  3140. remove: jqLiteRemove,
  3141. detach: function(element) {
  3142. jqLiteRemove(element, true);
  3143. },
  3144. after: function(element, newElement) {
  3145. var index = element, parent = element.parentNode;
  3146. newElement = new JQLite(newElement);
  3147. for (var i = 0, ii = newElement.length; i < ii; i++) {
  3148. var node = newElement[i];
  3149. parent.insertBefore(node, index.nextSibling);
  3150. index = node;
  3151. }
  3152. },
  3153. addClass: jqLiteAddClass,
  3154. removeClass: jqLiteRemoveClass,
  3155. toggleClass: function(element, selector, condition) {
  3156. if (selector) {
  3157. forEach(selector.split(' '), function(className) {
  3158. var classCondition = condition;
  3159. if (isUndefined(classCondition)) {
  3160. classCondition = !jqLiteHasClass(element, className);
  3161. }
  3162. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  3163. });
  3164. }
  3165. },
  3166. parent: function(element) {
  3167. var parent = element.parentNode;
  3168. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  3169. },
  3170. next: function(element) {
  3171. return element.nextElementSibling;
  3172. },
  3173. find: function(element, selector) {
  3174. if (element.getElementsByTagName) {
  3175. return element.getElementsByTagName(selector);
  3176. } else {
  3177. return [];
  3178. }
  3179. },
  3180. clone: jqLiteClone,
  3181. triggerHandler: function(element, event, extraParameters) {
  3182. var dummyEvent, eventFnsCopy, handlerArgs;
  3183. var eventName = event.type || event;
  3184. var expandoStore = jqLiteExpandoStore(element);
  3185. var events = expandoStore && expandoStore.events;
  3186. var eventFns = events && events[eventName];
  3187. if (eventFns) {
  3188. // Create a dummy event to pass to the handlers
  3189. dummyEvent = {
  3190. preventDefault: function() { this.defaultPrevented = true; },
  3191. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  3192. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  3193. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  3194. stopPropagation: noop,
  3195. type: eventName,
  3196. target: element
  3197. };
  3198. // If a custom event was provided then extend our dummy event with it
  3199. if (event.type) {
  3200. dummyEvent = extend(dummyEvent, event);
  3201. }
  3202. // Copy event handlers in case event handlers array is modified during execution.
  3203. eventFnsCopy = shallowCopy(eventFns);
  3204. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  3205. forEach(eventFnsCopy, function(fn) {
  3206. if (!dummyEvent.isImmediatePropagationStopped()) {
  3207. fn.apply(element, handlerArgs);
  3208. }
  3209. });
  3210. }
  3211. }
  3212. }, function(fn, name) {
  3213. /**
  3214. * chaining functions
  3215. */
  3216. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  3217. var value;
  3218. for (var i = 0, ii = this.length; i < ii; i++) {
  3219. if (isUndefined(value)) {
  3220. value = fn(this[i], arg1, arg2, arg3);
  3221. if (isDefined(value)) {
  3222. // any function which returns a value needs to be wrapped
  3223. value = jqLite(value);
  3224. }
  3225. } else {
  3226. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  3227. }
  3228. }
  3229. return isDefined(value) ? value : this;
  3230. };
  3231. // bind legacy bind/unbind to on/off
  3232. JQLite.prototype.bind = JQLite.prototype.on;
  3233. JQLite.prototype.unbind = JQLite.prototype.off;
  3234. });
  3235. // Provider for private $$jqLite service
  3236. function $$jqLiteProvider() {
  3237. this.$get = function $$jqLite() {
  3238. return extend(JQLite, {
  3239. hasClass: function(node, classes) {
  3240. if (node.attr) node = node[0];
  3241. return jqLiteHasClass(node, classes);
  3242. },
  3243. addClass: function(node, classes) {
  3244. if (node.attr) node = node[0];
  3245. return jqLiteAddClass(node, classes);
  3246. },
  3247. removeClass: function(node, classes) {
  3248. if (node.attr) node = node[0];
  3249. return jqLiteRemoveClass(node, classes);
  3250. }
  3251. });
  3252. };
  3253. }
  3254. /**
  3255. * Computes a hash of an 'obj'.
  3256. * Hash of a:
  3257. * string is string
  3258. * number is number as string
  3259. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  3260. * that is also assigned to the $$hashKey property of the object.
  3261. *
  3262. * @param obj
  3263. * @returns {string} hash string such that the same input will have the same hash string.
  3264. * The resulting string key is in 'type:hashKey' format.
  3265. */
  3266. function hashKey(obj, nextUidFn) {
  3267. var key = obj && obj.$$hashKey;
  3268. if (key) {
  3269. if (typeof key === 'function') {
  3270. key = obj.$$hashKey();
  3271. }
  3272. return key;
  3273. }
  3274. var objType = typeof obj;
  3275. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  3276. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  3277. } else {
  3278. key = objType + ':' + obj;
  3279. }
  3280. return key;
  3281. }
  3282. /**
  3283. * HashMap which can use objects as keys
  3284. */
  3285. function HashMap(array, isolatedUid) {
  3286. if (isolatedUid) {
  3287. var uid = 0;
  3288. this.nextUid = function() {
  3289. return ++uid;
  3290. };
  3291. }
  3292. forEach(array, this.put, this);
  3293. }
  3294. HashMap.prototype = {
  3295. /**
  3296. * Store key value pair
  3297. * @param key key to store can be any type
  3298. * @param value value to store can be any type
  3299. */
  3300. put: function(key, value) {
  3301. this[hashKey(key, this.nextUid)] = value;
  3302. },
  3303. /**
  3304. * @param key
  3305. * @returns {Object} the value for the key
  3306. */
  3307. get: function(key) {
  3308. return this[hashKey(key, this.nextUid)];
  3309. },
  3310. /**
  3311. * Remove the key/value pair
  3312. * @param key
  3313. */
  3314. remove: function(key) {
  3315. var value = this[key = hashKey(key, this.nextUid)];
  3316. delete this[key];
  3317. return value;
  3318. }
  3319. };
  3320. var $$HashMapProvider = [function() {
  3321. this.$get = [function() {
  3322. return HashMap;
  3323. }];
  3324. }];
  3325. /**
  3326. * @ngdoc function
  3327. * @module ng
  3328. * @name angular.injector
  3329. * @kind function
  3330. *
  3331. * @description
  3332. * Creates an injector object that can be used for retrieving services as well as for
  3333. * dependency injection (see {@link guide/di dependency injection}).
  3334. *
  3335. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3336. * {@link angular.module}. The `ng` module must be explicitly added.
  3337. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3338. * disallows argument name annotation inference.
  3339. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3340. *
  3341. * @example
  3342. * Typical usage
  3343. * ```js
  3344. * // create an injector
  3345. * var $injector = angular.injector(['ng']);
  3346. *
  3347. * // use the injector to kick off your application
  3348. * // use the type inference to auto inject arguments, or use implicit injection
  3349. * $injector.invoke(function($rootScope, $compile, $document) {
  3350. * $compile($document)($rootScope);
  3351. * $rootScope.$digest();
  3352. * });
  3353. * ```
  3354. *
  3355. * Sometimes you want to get access to the injector of a currently running Angular app
  3356. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  3357. * application has been bootstrapped. You can do this using the extra `injector()` added
  3358. * to JQuery/jqLite elements. See {@link angular.element}.
  3359. *
  3360. * *This is fairly rare but could be the case if a third party library is injecting the
  3361. * markup.*
  3362. *
  3363. * In the following example a new block of HTML containing a `ng-controller`
  3364. * directive is added to the end of the document body by JQuery. We then compile and link
  3365. * it into the current AngularJS scope.
  3366. *
  3367. * ```js
  3368. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3369. * $(document.body).append($div);
  3370. *
  3371. * angular.element(document).injector().invoke(function($compile) {
  3372. * var scope = angular.element($div).scope();
  3373. * $compile($div)(scope);
  3374. * });
  3375. * ```
  3376. */
  3377. /**
  3378. * @ngdoc module
  3379. * @name auto
  3380. * @description
  3381. *
  3382. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3383. */
  3384. var ARROW_ARG = /^([^\(]+?)=>/;
  3385. var FN_ARGS = /^[^\(]*\(\s*([^\)]*)\)/m;
  3386. var FN_ARG_SPLIT = /,/;
  3387. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3388. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3389. var $injectorMinErr = minErr('$injector');
  3390. function extractArgs(fn) {
  3391. var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
  3392. args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
  3393. return args;
  3394. }
  3395. function anonFn(fn) {
  3396. // For anonymous functions, showing at the very least the function signature can help in
  3397. // debugging.
  3398. var args = extractArgs(fn);
  3399. if (args) {
  3400. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3401. }
  3402. return 'fn';
  3403. }
  3404. function annotate(fn, strictDi, name) {
  3405. var $inject,
  3406. argDecl,
  3407. last;
  3408. if (typeof fn === 'function') {
  3409. if (!($inject = fn.$inject)) {
  3410. $inject = [];
  3411. if (fn.length) {
  3412. if (strictDi) {
  3413. if (!isString(name) || !name) {
  3414. name = fn.name || anonFn(fn);
  3415. }
  3416. throw $injectorMinErr('strictdi',
  3417. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3418. }
  3419. argDecl = extractArgs(fn);
  3420. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3421. arg.replace(FN_ARG, function(all, underscore, name) {
  3422. $inject.push(name);
  3423. });
  3424. });
  3425. }
  3426. fn.$inject = $inject;
  3427. }
  3428. } else if (isArray(fn)) {
  3429. last = fn.length - 1;
  3430. assertArgFn(fn[last], 'fn');
  3431. $inject = fn.slice(0, last);
  3432. } else {
  3433. assertArgFn(fn, 'fn', true);
  3434. }
  3435. return $inject;
  3436. }
  3437. ///////////////////////////////////////
  3438. /**
  3439. * @ngdoc service
  3440. * @name $injector
  3441. *
  3442. * @description
  3443. *
  3444. * `$injector` is used to retrieve object instances as defined by
  3445. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3446. * and load modules.
  3447. *
  3448. * The following always holds true:
  3449. *
  3450. * ```js
  3451. * var $injector = angular.injector();
  3452. * expect($injector.get('$injector')).toBe($injector);
  3453. * expect($injector.invoke(function($injector) {
  3454. * return $injector;
  3455. * })).toBe($injector);
  3456. * ```
  3457. *
  3458. * # Injection Function Annotation
  3459. *
  3460. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3461. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3462. *
  3463. * ```js
  3464. * // inferred (only works if code not minified/obfuscated)
  3465. * $injector.invoke(function(serviceA){});
  3466. *
  3467. * // annotated
  3468. * function explicit(serviceA) {};
  3469. * explicit.$inject = ['serviceA'];
  3470. * $injector.invoke(explicit);
  3471. *
  3472. * // inline
  3473. * $injector.invoke(['serviceA', function(serviceA){}]);
  3474. * ```
  3475. *
  3476. * ## Inference
  3477. *
  3478. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3479. * can then be parsed and the function arguments can be extracted. This method of discovering
  3480. * annotations is disallowed when the injector is in strict mode.
  3481. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3482. * argument names.
  3483. *
  3484. * ## `$inject` Annotation
  3485. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3486. *
  3487. * ## Inline
  3488. * As an array of injection names, where the last item in the array is the function to call.
  3489. */
  3490. /**
  3491. * @ngdoc method
  3492. * @name $injector#get
  3493. *
  3494. * @description
  3495. * Return an instance of the service.
  3496. *
  3497. * @param {string} name The name of the instance to retrieve.
  3498. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  3499. * @return {*} The instance.
  3500. */
  3501. /**
  3502. * @ngdoc method
  3503. * @name $injector#invoke
  3504. *
  3505. * @description
  3506. * Invoke the method and supply the method arguments from the `$injector`.
  3507. *
  3508. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  3509. * injected according to the {@link guide/di $inject Annotation} rules.
  3510. * @param {Object=} self The `this` for the invoked method.
  3511. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3512. * object first, before the `$injector` is consulted.
  3513. * @returns {*} the value returned by the invoked `fn` function.
  3514. */
  3515. /**
  3516. * @ngdoc method
  3517. * @name $injector#has
  3518. *
  3519. * @description
  3520. * Allows the user to query if the particular service exists.
  3521. *
  3522. * @param {string} name Name of the service to query.
  3523. * @returns {boolean} `true` if injector has given service.
  3524. */
  3525. /**
  3526. * @ngdoc method
  3527. * @name $injector#instantiate
  3528. * @description
  3529. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3530. * operator, and supplies all of the arguments to the constructor function as specified by the
  3531. * constructor annotation.
  3532. *
  3533. * @param {Function} Type Annotated constructor function.
  3534. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3535. * object first, before the `$injector` is consulted.
  3536. * @returns {Object} new instance of `Type`.
  3537. */
  3538. /**
  3539. * @ngdoc method
  3540. * @name $injector#annotate
  3541. *
  3542. * @description
  3543. * Returns an array of service names which the function is requesting for injection. This API is
  3544. * used by the injector to determine which services need to be injected into the function when the
  3545. * function is invoked. There are three ways in which the function can be annotated with the needed
  3546. * dependencies.
  3547. *
  3548. * # Argument names
  3549. *
  3550. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3551. * by converting the function into a string using `toString()` method and extracting the argument
  3552. * names.
  3553. * ```js
  3554. * // Given
  3555. * function MyController($scope, $route) {
  3556. * // ...
  3557. * }
  3558. *
  3559. * // Then
  3560. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3561. * ```
  3562. *
  3563. * You can disallow this method by using strict injection mode.
  3564. *
  3565. * This method does not work with code minification / obfuscation. For this reason the following
  3566. * annotation strategies are supported.
  3567. *
  3568. * # The `$inject` property
  3569. *
  3570. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3571. * represent names of services to be injected into the function.
  3572. * ```js
  3573. * // Given
  3574. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3575. * // ...
  3576. * }
  3577. * // Define function dependencies
  3578. * MyController['$inject'] = ['$scope', '$route'];
  3579. *
  3580. * // Then
  3581. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3582. * ```
  3583. *
  3584. * # The array notation
  3585. *
  3586. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3587. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3588. * a way that survives minification is a better choice:
  3589. *
  3590. * ```js
  3591. * // We wish to write this (not minification / obfuscation safe)
  3592. * injector.invoke(function($compile, $rootScope) {
  3593. * // ...
  3594. * });
  3595. *
  3596. * // We are forced to write break inlining
  3597. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3598. * // ...
  3599. * };
  3600. * tmpFn.$inject = ['$compile', '$rootScope'];
  3601. * injector.invoke(tmpFn);
  3602. *
  3603. * // To better support inline function the inline annotation is supported
  3604. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3605. * // ...
  3606. * }]);
  3607. *
  3608. * // Therefore
  3609. * expect(injector.annotate(
  3610. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3611. * ).toEqual(['$compile', '$rootScope']);
  3612. * ```
  3613. *
  3614. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3615. * be retrieved as described above.
  3616. *
  3617. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3618. *
  3619. * @returns {Array.<string>} The names of the services which the function requires.
  3620. */
  3621. /**
  3622. * @ngdoc service
  3623. * @name $provide
  3624. *
  3625. * @description
  3626. *
  3627. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3628. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3629. * {@link angular.Module}.
  3630. *
  3631. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3632. * factories** are functions which, in turn, are created by a **service provider**.
  3633. * The **service providers** are constructor functions. When instantiated they must contain a
  3634. * property called `$get`, which holds the **service factory** function.
  3635. *
  3636. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3637. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3638. * function to get the instance of the **service**.
  3639. *
  3640. * Often services have no configuration options and there is no need to add methods to the service
  3641. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3642. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3643. * services without specifying a provider.
  3644. *
  3645. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  3646. * {@link auto.$injector $injector}
  3647. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  3648. * providers and services.
  3649. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  3650. * services, not providers.
  3651. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  3652. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3653. * given factory function.
  3654. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  3655. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3656. * a new object using the given constructor function.
  3657. *
  3658. * See the individual methods for more information and examples.
  3659. */
  3660. /**
  3661. * @ngdoc method
  3662. * @name $provide#provider
  3663. * @description
  3664. *
  3665. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3666. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3667. * service.
  3668. *
  3669. * Service provider names start with the name of the service they provide followed by `Provider`.
  3670. * For example, the {@link ng.$log $log} service has a provider called
  3671. * {@link ng.$logProvider $logProvider}.
  3672. *
  3673. * Service provider objects can have additional methods which allow configuration of the provider
  3674. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3675. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3676. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3677. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3678. * console or not.
  3679. *
  3680. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3681. 'Provider'` key.
  3682. * @param {(Object|function())} provider If the provider is:
  3683. *
  3684. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3685. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3686. * - `Constructor`: a new instance of the provider will be created using
  3687. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3688. *
  3689. * @returns {Object} registered provider instance
  3690. * @example
  3691. *
  3692. * The following example shows how to create a simple event tracking service and register it using
  3693. * {@link auto.$provide#provider $provide.provider()}.
  3694. *
  3695. * ```js
  3696. * // Define the eventTracker provider
  3697. * function EventTrackerProvider() {
  3698. * var trackingUrl = '/track';
  3699. *
  3700. * // A provider method for configuring where the tracked events should been saved
  3701. * this.setTrackingUrl = function(url) {
  3702. * trackingUrl = url;
  3703. * };
  3704. *
  3705. * // The service factory function
  3706. * this.$get = ['$http', function($http) {
  3707. * var trackedEvents = {};
  3708. * return {
  3709. * // Call this to track an event
  3710. * event: function(event) {
  3711. * var count = trackedEvents[event] || 0;
  3712. * count += 1;
  3713. * trackedEvents[event] = count;
  3714. * return count;
  3715. * },
  3716. * // Call this to save the tracked events to the trackingUrl
  3717. * save: function() {
  3718. * $http.post(trackingUrl, trackedEvents);
  3719. * }
  3720. * };
  3721. * }];
  3722. * }
  3723. *
  3724. * describe('eventTracker', function() {
  3725. * var postSpy;
  3726. *
  3727. * beforeEach(module(function($provide) {
  3728. * // Register the eventTracker provider
  3729. * $provide.provider('eventTracker', EventTrackerProvider);
  3730. * }));
  3731. *
  3732. * beforeEach(module(function(eventTrackerProvider) {
  3733. * // Configure eventTracker provider
  3734. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3735. * }));
  3736. *
  3737. * it('tracks events', inject(function(eventTracker) {
  3738. * expect(eventTracker.event('login')).toEqual(1);
  3739. * expect(eventTracker.event('login')).toEqual(2);
  3740. * }));
  3741. *
  3742. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3743. * postSpy = spyOn($http, 'post');
  3744. * eventTracker.event('login');
  3745. * eventTracker.save();
  3746. * expect(postSpy).toHaveBeenCalled();
  3747. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3748. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3749. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3750. * }));
  3751. * });
  3752. * ```
  3753. */
  3754. /**
  3755. * @ngdoc method
  3756. * @name $provide#factory
  3757. * @description
  3758. *
  3759. * Register a **service factory**, which will be called to return the service instance.
  3760. * This is short for registering a service where its provider consists of only a `$get` property,
  3761. * which is the given service factory function.
  3762. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3763. * configure your service in a provider.
  3764. *
  3765. * @param {string} name The name of the instance.
  3766. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  3767. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  3768. * @returns {Object} registered provider instance
  3769. *
  3770. * @example
  3771. * Here is an example of registering a service
  3772. * ```js
  3773. * $provide.factory('ping', ['$http', function($http) {
  3774. * return function ping() {
  3775. * return $http.send('/ping');
  3776. * };
  3777. * }]);
  3778. * ```
  3779. * You would then inject and use this service like this:
  3780. * ```js
  3781. * someModule.controller('Ctrl', ['ping', function(ping) {
  3782. * ping();
  3783. * }]);
  3784. * ```
  3785. */
  3786. /**
  3787. * @ngdoc method
  3788. * @name $provide#service
  3789. * @description
  3790. *
  3791. * Register a **service constructor**, which will be invoked with `new` to create the service
  3792. * instance.
  3793. * This is short for registering a service where its provider's `$get` property is a factory
  3794. * function that returns an instance instantiated by the injector from the service constructor
  3795. * function.
  3796. *
  3797. * Internally it looks a bit like this:
  3798. *
  3799. * ```
  3800. * {
  3801. * $get: function() {
  3802. * return $injector.instantiate(constructor);
  3803. * }
  3804. * }
  3805. * ```
  3806. *
  3807. *
  3808. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3809. * as a type/class.
  3810. *
  3811. * @param {string} name The name of the instance.
  3812. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  3813. * that will be instantiated.
  3814. * @returns {Object} registered provider instance
  3815. *
  3816. * @example
  3817. * Here is an example of registering a service using
  3818. * {@link auto.$provide#service $provide.service(class)}.
  3819. * ```js
  3820. * var Ping = function($http) {
  3821. * this.$http = $http;
  3822. * };
  3823. *
  3824. * Ping.$inject = ['$http'];
  3825. *
  3826. * Ping.prototype.send = function() {
  3827. * return this.$http.get('/ping');
  3828. * };
  3829. * $provide.service('ping', Ping);
  3830. * ```
  3831. * You would then inject and use this service like this:
  3832. * ```js
  3833. * someModule.controller('Ctrl', ['ping', function(ping) {
  3834. * ping.send();
  3835. * }]);
  3836. * ```
  3837. */
  3838. /**
  3839. * @ngdoc method
  3840. * @name $provide#value
  3841. * @description
  3842. *
  3843. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3844. * number, an array, an object or a function. This is short for registering a service where its
  3845. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3846. * service**.
  3847. *
  3848. * Value services are similar to constant services, except that they cannot be injected into a
  3849. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3850. * an Angular
  3851. * {@link auto.$provide#decorator decorator}.
  3852. *
  3853. * @param {string} name The name of the instance.
  3854. * @param {*} value The value.
  3855. * @returns {Object} registered provider instance
  3856. *
  3857. * @example
  3858. * Here are some examples of creating value services.
  3859. * ```js
  3860. * $provide.value('ADMIN_USER', 'admin');
  3861. *
  3862. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3863. *
  3864. * $provide.value('halfOf', function(value) {
  3865. * return value / 2;
  3866. * });
  3867. * ```
  3868. */
  3869. /**
  3870. * @ngdoc method
  3871. * @name $provide#constant
  3872. * @description
  3873. *
  3874. * Register a **constant service**, such as a string, a number, an array, an object or a function,
  3875. * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
  3876. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3877. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3878. *
  3879. * @param {string} name The name of the constant.
  3880. * @param {*} value The constant value.
  3881. * @returns {Object} registered instance
  3882. *
  3883. * @example
  3884. * Here a some examples of creating constants:
  3885. * ```js
  3886. * $provide.constant('SHARD_HEIGHT', 306);
  3887. *
  3888. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3889. *
  3890. * $provide.constant('double', function(value) {
  3891. * return value * 2;
  3892. * });
  3893. * ```
  3894. */
  3895. /**
  3896. * @ngdoc method
  3897. * @name $provide#decorator
  3898. * @description
  3899. *
  3900. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  3901. * intercepts the creation of a service, allowing it to override or modify the behavior of the
  3902. * service. The object returned by the decorator may be the original service, or a new service
  3903. * object which replaces or wraps and delegates to the original service.
  3904. *
  3905. * @param {string} name The name of the service to decorate.
  3906. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  3907. * instantiated and should return the decorated service instance. The function is called using
  3908. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3909. * Local injection arguments:
  3910. *
  3911. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3912. * decorated or delegated to.
  3913. *
  3914. * @example
  3915. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3916. * calls to {@link ng.$log#error $log.warn()}.
  3917. * ```js
  3918. * $provide.decorator('$log', ['$delegate', function($delegate) {
  3919. * $delegate.warn = $delegate.error;
  3920. * return $delegate;
  3921. * }]);
  3922. * ```
  3923. */
  3924. function createInjector(modulesToLoad, strictDi) {
  3925. strictDi = (strictDi === true);
  3926. var INSTANTIATING = {},
  3927. providerSuffix = 'Provider',
  3928. path = [],
  3929. loadedModules = new HashMap([], true),
  3930. providerCache = {
  3931. $provide: {
  3932. provider: supportObject(provider),
  3933. factory: supportObject(factory),
  3934. service: supportObject(service),
  3935. value: supportObject(value),
  3936. constant: supportObject(constant),
  3937. decorator: decorator
  3938. }
  3939. },
  3940. providerInjector = (providerCache.$injector =
  3941. createInternalInjector(providerCache, function(serviceName, caller) {
  3942. if (angular.isString(caller)) {
  3943. path.push(caller);
  3944. }
  3945. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  3946. })),
  3947. instanceCache = {},
  3948. protoInstanceInjector =
  3949. createInternalInjector(instanceCache, function(serviceName, caller) {
  3950. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  3951. return instanceInjector.invoke(
  3952. provider.$get, provider, undefined, serviceName);
  3953. }),
  3954. instanceInjector = protoInstanceInjector;
  3955. providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
  3956. var runBlocks = loadModules(modulesToLoad);
  3957. instanceInjector = protoInstanceInjector.get('$injector');
  3958. instanceInjector.strictDi = strictDi;
  3959. forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
  3960. return instanceInjector;
  3961. ////////////////////////////////////
  3962. // $provider
  3963. ////////////////////////////////////
  3964. function supportObject(delegate) {
  3965. return function(key, value) {
  3966. if (isObject(key)) {
  3967. forEach(key, reverseParams(delegate));
  3968. } else {
  3969. return delegate(key, value);
  3970. }
  3971. };
  3972. }
  3973. function provider(name, provider_) {
  3974. assertNotHasOwnProperty(name, 'service');
  3975. if (isFunction(provider_) || isArray(provider_)) {
  3976. provider_ = providerInjector.instantiate(provider_);
  3977. }
  3978. if (!provider_.$get) {
  3979. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  3980. }
  3981. return providerCache[name + providerSuffix] = provider_;
  3982. }
  3983. function enforceReturnValue(name, factory) {
  3984. return function enforcedReturnValue() {
  3985. var result = instanceInjector.invoke(factory, this);
  3986. if (isUndefined(result)) {
  3987. throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
  3988. }
  3989. return result;
  3990. };
  3991. }
  3992. function factory(name, factoryFn, enforce) {
  3993. return provider(name, {
  3994. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  3995. });
  3996. }
  3997. function service(name, constructor) {
  3998. return factory(name, ['$injector', function($injector) {
  3999. return $injector.instantiate(constructor);
  4000. }]);
  4001. }
  4002. function value(name, val) { return factory(name, valueFn(val), false); }
  4003. function constant(name, value) {
  4004. assertNotHasOwnProperty(name, 'constant');
  4005. providerCache[name] = value;
  4006. instanceCache[name] = value;
  4007. }
  4008. function decorator(serviceName, decorFn) {
  4009. var origProvider = providerInjector.get(serviceName + providerSuffix),
  4010. orig$get = origProvider.$get;
  4011. origProvider.$get = function() {
  4012. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  4013. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  4014. };
  4015. }
  4016. ////////////////////////////////////
  4017. // Module Loading
  4018. ////////////////////////////////////
  4019. function loadModules(modulesToLoad) {
  4020. assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
  4021. var runBlocks = [], moduleFn;
  4022. forEach(modulesToLoad, function(module) {
  4023. if (loadedModules.get(module)) return;
  4024. loadedModules.put(module, true);
  4025. function runInvokeQueue(queue) {
  4026. var i, ii;
  4027. for (i = 0, ii = queue.length; i < ii; i++) {
  4028. var invokeArgs = queue[i],
  4029. provider = providerInjector.get(invokeArgs[0]);
  4030. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  4031. }
  4032. }
  4033. try {
  4034. if (isString(module)) {
  4035. moduleFn = angularModule(module);
  4036. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  4037. runInvokeQueue(moduleFn._invokeQueue);
  4038. runInvokeQueue(moduleFn._configBlocks);
  4039. } else if (isFunction(module)) {
  4040. runBlocks.push(providerInjector.invoke(module));
  4041. } else if (isArray(module)) {
  4042. runBlocks.push(providerInjector.invoke(module));
  4043. } else {
  4044. assertArgFn(module, 'module');
  4045. }
  4046. } catch (e) {
  4047. if (isArray(module)) {
  4048. module = module[module.length - 1];
  4049. }
  4050. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  4051. // Safari & FF's stack traces don't contain error.message content
  4052. // unlike those of Chrome and IE
  4053. // So if stack doesn't contain message, we create a new string that contains both.
  4054. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  4055. /* jshint -W022 */
  4056. e = e.message + '\n' + e.stack;
  4057. }
  4058. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  4059. module, e.stack || e.message || e);
  4060. }
  4061. });
  4062. return runBlocks;
  4063. }
  4064. ////////////////////////////////////
  4065. // internal Injector
  4066. ////////////////////////////////////
  4067. function createInternalInjector(cache, factory) {
  4068. function getService(serviceName, caller) {
  4069. if (cache.hasOwnProperty(serviceName)) {
  4070. if (cache[serviceName] === INSTANTIATING) {
  4071. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  4072. serviceName + ' <- ' + path.join(' <- '));
  4073. }
  4074. return cache[serviceName];
  4075. } else {
  4076. try {
  4077. path.unshift(serviceName);
  4078. cache[serviceName] = INSTANTIATING;
  4079. return cache[serviceName] = factory(serviceName, caller);
  4080. } catch (err) {
  4081. if (cache[serviceName] === INSTANTIATING) {
  4082. delete cache[serviceName];
  4083. }
  4084. throw err;
  4085. } finally {
  4086. path.shift();
  4087. }
  4088. }
  4089. }
  4090. function injectionArgs(fn, locals, serviceName) {
  4091. var args = [],
  4092. $inject = createInjector.$$annotate(fn, strictDi, serviceName);
  4093. for (var i = 0, length = $inject.length; i < length; i++) {
  4094. var key = $inject[i];
  4095. if (typeof key !== 'string') {
  4096. throw $injectorMinErr('itkn',
  4097. 'Incorrect injection token! Expected service name as string, got {0}', key);
  4098. }
  4099. args.push(locals && locals.hasOwnProperty(key) ? locals[key] :
  4100. getService(key, serviceName));
  4101. }
  4102. return args;
  4103. }
  4104. function isClass(func) {
  4105. // IE 9-11 do not support classes and IE9 leaks with the code below.
  4106. if (msie <= 11) {
  4107. return false;
  4108. }
  4109. // Workaround for MS Edge.
  4110. // Check https://connect.microsoft.com/IE/Feedback/Details/2211653
  4111. return typeof func === 'function'
  4112. && /^(?:class\s|constructor\()/.test(Function.prototype.toString.call(func));
  4113. }
  4114. function invoke(fn, self, locals, serviceName) {
  4115. if (typeof locals === 'string') {
  4116. serviceName = locals;
  4117. locals = null;
  4118. }
  4119. var args = injectionArgs(fn, locals, serviceName);
  4120. if (isArray(fn)) {
  4121. fn = fn[fn.length - 1];
  4122. }
  4123. if (!isClass(fn)) {
  4124. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  4125. // #5388
  4126. return fn.apply(self, args);
  4127. } else {
  4128. args.unshift(null);
  4129. return new (Function.prototype.bind.apply(fn, args))();
  4130. }
  4131. }
  4132. function instantiate(Type, locals, serviceName) {
  4133. // Check if Type is annotated and use just the given function at n-1 as parameter
  4134. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  4135. var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
  4136. var args = injectionArgs(Type, locals, serviceName);
  4137. // Empty object at position 0 is ignored for invocation with `new`, but required.
  4138. args.unshift(null);
  4139. return new (Function.prototype.bind.apply(ctor, args))();
  4140. }
  4141. return {
  4142. invoke: invoke,
  4143. instantiate: instantiate,
  4144. get: getService,
  4145. annotate: createInjector.$$annotate,
  4146. has: function(name) {
  4147. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  4148. }
  4149. };
  4150. }
  4151. }
  4152. createInjector.$$annotate = annotate;
  4153. /**
  4154. * @ngdoc provider
  4155. * @name $anchorScrollProvider
  4156. *
  4157. * @description
  4158. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  4159. * {@link ng.$location#hash $location.hash()} changes.
  4160. */
  4161. function $AnchorScrollProvider() {
  4162. var autoScrollingEnabled = true;
  4163. /**
  4164. * @ngdoc method
  4165. * @name $anchorScrollProvider#disableAutoScrolling
  4166. *
  4167. * @description
  4168. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  4169. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  4170. * Use this method to disable automatic scrolling.
  4171. *
  4172. * If automatic scrolling is disabled, one must explicitly call
  4173. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  4174. * current hash.
  4175. */
  4176. this.disableAutoScrolling = function() {
  4177. autoScrollingEnabled = false;
  4178. };
  4179. /**
  4180. * @ngdoc service
  4181. * @name $anchorScroll
  4182. * @kind function
  4183. * @requires $window
  4184. * @requires $location
  4185. * @requires $rootScope
  4186. *
  4187. * @description
  4188. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  4189. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  4190. * in the
  4191. * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#the-indicated-part-of-the-document).
  4192. *
  4193. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  4194. * match any anchor whenever it changes. This can be disabled by calling
  4195. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  4196. *
  4197. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  4198. * vertical scroll-offset (either fixed or dynamic).
  4199. *
  4200. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  4201. * {@link ng.$location#hash $location.hash()} will be used.
  4202. *
  4203. * @property {(number|function|jqLite)} yOffset
  4204. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  4205. * positioned elements at the top of the page, such as navbars, headers etc.
  4206. *
  4207. * `yOffset` can be specified in various ways:
  4208. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  4209. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  4210. * a number representing the offset (in pixels).<br /><br />
  4211. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  4212. * the top of the page to the element's bottom will be used as offset.<br />
  4213. * **Note**: The element will be taken into account only as long as its `position` is set to
  4214. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  4215. * their height and/or positioning according to the viewport's size.
  4216. *
  4217. * <br />
  4218. * <div class="alert alert-warning">
  4219. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  4220. * not some child element.
  4221. * </div>
  4222. *
  4223. * @example
  4224. <example module="anchorScrollExample">
  4225. <file name="index.html">
  4226. <div id="scrollArea" ng-controller="ScrollController">
  4227. <a ng-click="gotoBottom()">Go to bottom</a>
  4228. <a id="bottom"></a> You're at the bottom!
  4229. </div>
  4230. </file>
  4231. <file name="script.js">
  4232. angular.module('anchorScrollExample', [])
  4233. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  4234. function ($scope, $location, $anchorScroll) {
  4235. $scope.gotoBottom = function() {
  4236. // set the location.hash to the id of
  4237. // the element you wish to scroll to.
  4238. $location.hash('bottom');
  4239. // call $anchorScroll()
  4240. $anchorScroll();
  4241. };
  4242. }]);
  4243. </file>
  4244. <file name="style.css">
  4245. #scrollArea {
  4246. height: 280px;
  4247. overflow: auto;
  4248. }
  4249. #bottom {
  4250. display: block;
  4251. margin-top: 2000px;
  4252. }
  4253. </file>
  4254. </example>
  4255. *
  4256. * <hr />
  4257. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  4258. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  4259. *
  4260. * @example
  4261. <example module="anchorScrollOffsetExample">
  4262. <file name="index.html">
  4263. <div class="fixed-header" ng-controller="headerCtrl">
  4264. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  4265. Go to anchor {{x}}
  4266. </a>
  4267. </div>
  4268. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  4269. Anchor {{x}} of 5
  4270. </div>
  4271. </file>
  4272. <file name="script.js">
  4273. angular.module('anchorScrollOffsetExample', [])
  4274. .run(['$anchorScroll', function($anchorScroll) {
  4275. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  4276. }])
  4277. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  4278. function ($anchorScroll, $location, $scope) {
  4279. $scope.gotoAnchor = function(x) {
  4280. var newHash = 'anchor' + x;
  4281. if ($location.hash() !== newHash) {
  4282. // set the $location.hash to `newHash` and
  4283. // $anchorScroll will automatically scroll to it
  4284. $location.hash('anchor' + x);
  4285. } else {
  4286. // call $anchorScroll() explicitly,
  4287. // since $location.hash hasn't changed
  4288. $anchorScroll();
  4289. }
  4290. };
  4291. }
  4292. ]);
  4293. </file>
  4294. <file name="style.css">
  4295. body {
  4296. padding-top: 50px;
  4297. }
  4298. .anchor {
  4299. border: 2px dashed DarkOrchid;
  4300. padding: 10px 10px 200px 10px;
  4301. }
  4302. .fixed-header {
  4303. background-color: rgba(0, 0, 0, 0.2);
  4304. height: 50px;
  4305. position: fixed;
  4306. top: 0; left: 0; right: 0;
  4307. }
  4308. .fixed-header > a {
  4309. display: inline-block;
  4310. margin: 5px 15px;
  4311. }
  4312. </file>
  4313. </example>
  4314. */
  4315. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  4316. var document = $window.document;
  4317. // Helper function to get first anchor from a NodeList
  4318. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  4319. // and working in all supported browsers.)
  4320. function getFirstAnchor(list) {
  4321. var result = null;
  4322. Array.prototype.some.call(list, function(element) {
  4323. if (nodeName_(element) === 'a') {
  4324. result = element;
  4325. return true;
  4326. }
  4327. });
  4328. return result;
  4329. }
  4330. function getYOffset() {
  4331. var offset = scroll.yOffset;
  4332. if (isFunction(offset)) {
  4333. offset = offset();
  4334. } else if (isElement(offset)) {
  4335. var elem = offset[0];
  4336. var style = $window.getComputedStyle(elem);
  4337. if (style.position !== 'fixed') {
  4338. offset = 0;
  4339. } else {
  4340. offset = elem.getBoundingClientRect().bottom;
  4341. }
  4342. } else if (!isNumber(offset)) {
  4343. offset = 0;
  4344. }
  4345. return offset;
  4346. }
  4347. function scrollTo(elem) {
  4348. if (elem) {
  4349. elem.scrollIntoView();
  4350. var offset = getYOffset();
  4351. if (offset) {
  4352. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  4353. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  4354. // top of the viewport.
  4355. //
  4356. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  4357. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  4358. // way down the page.
  4359. //
  4360. // This is often the case for elements near the bottom of the page.
  4361. //
  4362. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  4363. // the top of the element and the offset, which is enough to align the top of `elem` at the
  4364. // desired position.
  4365. var elemTop = elem.getBoundingClientRect().top;
  4366. $window.scrollBy(0, elemTop - offset);
  4367. }
  4368. } else {
  4369. $window.scrollTo(0, 0);
  4370. }
  4371. }
  4372. function scroll(hash) {
  4373. hash = isString(hash) ? hash : $location.hash();
  4374. var elm;
  4375. // empty hash, scroll to the top of the page
  4376. if (!hash) scrollTo(null);
  4377. // element with given id
  4378. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4379. // first anchor with given name :-D
  4380. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4381. // no element and hash == 'top', scroll to the top of the page
  4382. else if (hash === 'top') scrollTo(null);
  4383. }
  4384. // does not scroll when user clicks on anchor link that is currently on
  4385. // (no url change, no $location.hash() change), browser native does scroll
  4386. if (autoScrollingEnabled) {
  4387. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4388. function autoScrollWatchAction(newVal, oldVal) {
  4389. // skip the initial scroll if $location.hash is empty
  4390. if (newVal === oldVal && newVal === '') return;
  4391. jqLiteDocumentLoaded(function() {
  4392. $rootScope.$evalAsync(scroll);
  4393. });
  4394. });
  4395. }
  4396. return scroll;
  4397. }];
  4398. }
  4399. var $animateMinErr = minErr('$animate');
  4400. var ELEMENT_NODE = 1;
  4401. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  4402. function mergeClasses(a,b) {
  4403. if (!a && !b) return '';
  4404. if (!a) return b;
  4405. if (!b) return a;
  4406. if (isArray(a)) a = a.join(' ');
  4407. if (isArray(b)) b = b.join(' ');
  4408. return a + ' ' + b;
  4409. }
  4410. function extractElementNode(element) {
  4411. for (var i = 0; i < element.length; i++) {
  4412. var elm = element[i];
  4413. if (elm.nodeType === ELEMENT_NODE) {
  4414. return elm;
  4415. }
  4416. }
  4417. }
  4418. function splitClasses(classes) {
  4419. if (isString(classes)) {
  4420. classes = classes.split(' ');
  4421. }
  4422. // Use createMap() to prevent class assumptions involving property names in
  4423. // Object.prototype
  4424. var obj = createMap();
  4425. forEach(classes, function(klass) {
  4426. // sometimes the split leaves empty string values
  4427. // incase extra spaces were applied to the options
  4428. if (klass.length) {
  4429. obj[klass] = true;
  4430. }
  4431. });
  4432. return obj;
  4433. }
  4434. // if any other type of options value besides an Object value is
  4435. // passed into the $animate.method() animation then this helper code
  4436. // will be run which will ignore it. While this patch is not the
  4437. // greatest solution to this, a lot of existing plugins depend on
  4438. // $animate to either call the callback (< 1.2) or return a promise
  4439. // that can be changed. This helper function ensures that the options
  4440. // are wiped clean incase a callback function is provided.
  4441. function prepareAnimateOptions(options) {
  4442. return isObject(options)
  4443. ? options
  4444. : {};
  4445. }
  4446. var $$CoreAnimateJsProvider = function() {
  4447. this.$get = function() {};
  4448. };
  4449. // this is prefixed with Core since it conflicts with
  4450. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  4451. var $$CoreAnimateQueueProvider = function() {
  4452. var postDigestQueue = new HashMap();
  4453. var postDigestElements = [];
  4454. this.$get = ['$$AnimateRunner', '$rootScope',
  4455. function($$AnimateRunner, $rootScope) {
  4456. return {
  4457. enabled: noop,
  4458. on: noop,
  4459. off: noop,
  4460. pin: noop,
  4461. push: function(element, event, options, domOperation) {
  4462. domOperation && domOperation();
  4463. options = options || {};
  4464. options.from && element.css(options.from);
  4465. options.to && element.css(options.to);
  4466. if (options.addClass || options.removeClass) {
  4467. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  4468. }
  4469. var runner = new $$AnimateRunner(); // jshint ignore:line
  4470. // since there are no animations to run the runner needs to be
  4471. // notified that the animation call is complete.
  4472. runner.complete();
  4473. return runner;
  4474. }
  4475. };
  4476. function updateData(data, classes, value) {
  4477. var changed = false;
  4478. if (classes) {
  4479. classes = isString(classes) ? classes.split(' ') :
  4480. isArray(classes) ? classes : [];
  4481. forEach(classes, function(className) {
  4482. if (className) {
  4483. changed = true;
  4484. data[className] = value;
  4485. }
  4486. });
  4487. }
  4488. return changed;
  4489. }
  4490. function handleCSSClassChanges() {
  4491. forEach(postDigestElements, function(element) {
  4492. var data = postDigestQueue.get(element);
  4493. if (data) {
  4494. var existing = splitClasses(element.attr('class'));
  4495. var toAdd = '';
  4496. var toRemove = '';
  4497. forEach(data, function(status, className) {
  4498. var hasClass = !!existing[className];
  4499. if (status !== hasClass) {
  4500. if (status) {
  4501. toAdd += (toAdd.length ? ' ' : '') + className;
  4502. } else {
  4503. toRemove += (toRemove.length ? ' ' : '') + className;
  4504. }
  4505. }
  4506. });
  4507. forEach(element, function(elm) {
  4508. toAdd && jqLiteAddClass(elm, toAdd);
  4509. toRemove && jqLiteRemoveClass(elm, toRemove);
  4510. });
  4511. postDigestQueue.remove(element);
  4512. }
  4513. });
  4514. postDigestElements.length = 0;
  4515. }
  4516. function addRemoveClassesPostDigest(element, add, remove) {
  4517. var data = postDigestQueue.get(element) || {};
  4518. var classesAdded = updateData(data, add, true);
  4519. var classesRemoved = updateData(data, remove, false);
  4520. if (classesAdded || classesRemoved) {
  4521. postDigestQueue.put(element, data);
  4522. postDigestElements.push(element);
  4523. if (postDigestElements.length === 1) {
  4524. $rootScope.$$postDigest(handleCSSClassChanges);
  4525. }
  4526. }
  4527. }
  4528. }];
  4529. };
  4530. /**
  4531. * @ngdoc provider
  4532. * @name $animateProvider
  4533. *
  4534. * @description
  4535. * Default implementation of $animate that doesn't perform any animations, instead just
  4536. * synchronously performs DOM updates and resolves the returned runner promise.
  4537. *
  4538. * In order to enable animations the `ngAnimate` module has to be loaded.
  4539. *
  4540. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  4541. */
  4542. var $AnimateProvider = ['$provide', function($provide) {
  4543. var provider = this;
  4544. this.$$registeredAnimations = Object.create(null);
  4545. /**
  4546. * @ngdoc method
  4547. * @name $animateProvider#register
  4548. *
  4549. * @description
  4550. * Registers a new injectable animation factory function. The factory function produces the
  4551. * animation object which contains callback functions for each event that is expected to be
  4552. * animated.
  4553. *
  4554. * * `eventFn`: `function(element, ... , doneFunction, options)`
  4555. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  4556. * on the type of animation additional arguments will be injected into the animation function. The
  4557. * list below explains the function signatures for the different animation methods:
  4558. *
  4559. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  4560. * - addClass: function(element, addedClasses, doneFunction, options)
  4561. * - removeClass: function(element, removedClasses, doneFunction, options)
  4562. * - enter, leave, move: function(element, doneFunction, options)
  4563. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  4564. *
  4565. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  4566. *
  4567. * ```js
  4568. * return {
  4569. * //enter, leave, move signature
  4570. * eventFn : function(element, done, options) {
  4571. * //code to run the animation
  4572. * //once complete, then run done()
  4573. * return function endFunction(wasCancelled) {
  4574. * //code to cancel the animation
  4575. * }
  4576. * }
  4577. * }
  4578. * ```
  4579. *
  4580. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  4581. * @param {Function} factory The factory function that will be executed to return the animation
  4582. * object.
  4583. */
  4584. this.register = function(name, factory) {
  4585. if (name && name.charAt(0) !== '.') {
  4586. throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name);
  4587. }
  4588. var key = name + '-animation';
  4589. provider.$$registeredAnimations[name.substr(1)] = key;
  4590. $provide.factory(key, factory);
  4591. };
  4592. /**
  4593. * @ngdoc method
  4594. * @name $animateProvider#classNameFilter
  4595. *
  4596. * @description
  4597. * Sets and/or returns the CSS class regular expression that is checked when performing
  4598. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4599. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  4600. * When setting the `classNameFilter` value, animations will only be performed on elements
  4601. * that successfully match the filter expression. This in turn can boost performance
  4602. * for low-powered devices as well as applications containing a lot of structural operations.
  4603. * @param {RegExp=} expression The className expression which will be checked against all animations
  4604. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4605. */
  4606. this.classNameFilter = function(expression) {
  4607. if (arguments.length === 1) {
  4608. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  4609. if (this.$$classNameFilter) {
  4610. var reservedRegex = new RegExp("(\\s+|\\/)" + NG_ANIMATE_CLASSNAME + "(\\s+|\\/)");
  4611. if (reservedRegex.test(this.$$classNameFilter.toString())) {
  4612. throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  4613. }
  4614. }
  4615. }
  4616. return this.$$classNameFilter;
  4617. };
  4618. this.$get = ['$$animateQueue', function($$animateQueue) {
  4619. function domInsert(element, parentElement, afterElement) {
  4620. // if for some reason the previous element was removed
  4621. // from the dom sometime before this code runs then let's
  4622. // just stick to using the parent element as the anchor
  4623. if (afterElement) {
  4624. var afterNode = extractElementNode(afterElement);
  4625. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  4626. afterElement = null;
  4627. }
  4628. }
  4629. afterElement ? afterElement.after(element) : parentElement.prepend(element);
  4630. }
  4631. /**
  4632. * @ngdoc service
  4633. * @name $animate
  4634. * @description The $animate service exposes a series of DOM utility methods that provide support
  4635. * for animation hooks. The default behavior is the application of DOM operations, however,
  4636. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  4637. * to ensure that animation runs with the triggered DOM operation.
  4638. *
  4639. * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
  4640. * included and only when it is active then the animation hooks that `$animate` triggers will be
  4641. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  4642. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  4643. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  4644. *
  4645. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  4646. *
  4647. * To learn more about enabling animation support, click here to visit the
  4648. * {@link ngAnimate ngAnimate module page}.
  4649. */
  4650. return {
  4651. // we don't call it directly since non-existant arguments may
  4652. // be interpreted as null within the sub enabled function
  4653. /**
  4654. *
  4655. * @ngdoc method
  4656. * @name $animate#on
  4657. * @kind function
  4658. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  4659. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  4660. * is fired with the following params:
  4661. *
  4662. * ```js
  4663. * $animate.on('enter', container,
  4664. * function callback(element, phase) {
  4665. * // cool we detected an enter animation within the container
  4666. * }
  4667. * );
  4668. * ```
  4669. *
  4670. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  4671. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  4672. * as well as among its children
  4673. * @param {Function} callback the callback function that will be fired when the listener is triggered
  4674. *
  4675. * The arguments present in the callback function are:
  4676. * * `element` - The captured DOM element that the animation was fired on.
  4677. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  4678. */
  4679. on: $$animateQueue.on,
  4680. /**
  4681. *
  4682. * @ngdoc method
  4683. * @name $animate#off
  4684. * @kind function
  4685. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  4686. * can be used in three different ways depending on the arguments:
  4687. *
  4688. * ```js
  4689. * // remove all the animation event listeners listening for `enter`
  4690. * $animate.off('enter');
  4691. *
  4692. * // remove all the animation event listeners listening for `enter` on the given element and its children
  4693. * $animate.off('enter', container);
  4694. *
  4695. * // remove the event listener function provided by `callback` that is set
  4696. * // to listen for `enter` on the given `container` as well as its children
  4697. * $animate.off('enter', container, callback);
  4698. * ```
  4699. *
  4700. * @param {string} event the animation event (e.g. enter, leave, move, addClass, removeClass, etc...)
  4701. * @param {DOMElement=} container the container element the event listener was placed on
  4702. * @param {Function=} callback the callback function that was registered as the listener
  4703. */
  4704. off: $$animateQueue.off,
  4705. /**
  4706. * @ngdoc method
  4707. * @name $animate#pin
  4708. * @kind function
  4709. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  4710. * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
  4711. * element despite being outside the realm of the application or within another application. Say for example if the application
  4712. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  4713. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  4714. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  4715. *
  4716. * Note that this feature is only active when the `ngAnimate` module is used.
  4717. *
  4718. * @param {DOMElement} element the external element that will be pinned
  4719. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  4720. */
  4721. pin: $$animateQueue.pin,
  4722. /**
  4723. *
  4724. * @ngdoc method
  4725. * @name $animate#enabled
  4726. * @kind function
  4727. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  4728. * function can be called in four ways:
  4729. *
  4730. * ```js
  4731. * // returns true or false
  4732. * $animate.enabled();
  4733. *
  4734. * // changes the enabled state for all animations
  4735. * $animate.enabled(false);
  4736. * $animate.enabled(true);
  4737. *
  4738. * // returns true or false if animations are enabled for an element
  4739. * $animate.enabled(element);
  4740. *
  4741. * // changes the enabled state for an element and its children
  4742. * $animate.enabled(element, true);
  4743. * $animate.enabled(element, false);
  4744. * ```
  4745. *
  4746. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  4747. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  4748. *
  4749. * @return {boolean} whether or not animations are enabled
  4750. */
  4751. enabled: $$animateQueue.enabled,
  4752. /**
  4753. * @ngdoc method
  4754. * @name $animate#cancel
  4755. * @kind function
  4756. * @description Cancels the provided animation.
  4757. *
  4758. * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
  4759. */
  4760. cancel: function(runner) {
  4761. runner.end && runner.end();
  4762. },
  4763. /**
  4764. *
  4765. * @ngdoc method
  4766. * @name $animate#enter
  4767. * @kind function
  4768. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  4769. * as the first child within the `parent` element and then triggers an animation.
  4770. * A promise is returned that will be resolved during the next digest once the animation
  4771. * has completed.
  4772. *
  4773. * @param {DOMElement} element the element which will be inserted into the DOM
  4774. * @param {DOMElement} parent the parent element which will append the element as
  4775. * a child (so long as the after element is not present)
  4776. * @param {DOMElement=} after the sibling element after which the element will be appended
  4777. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4778. *
  4779. * @return {Promise} the animation callback promise
  4780. */
  4781. enter: function(element, parent, after, options) {
  4782. parent = parent && jqLite(parent);
  4783. after = after && jqLite(after);
  4784. parent = parent || after.parent();
  4785. domInsert(element, parent, after);
  4786. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  4787. },
  4788. /**
  4789. *
  4790. * @ngdoc method
  4791. * @name $animate#move
  4792. * @kind function
  4793. * @description Inserts (moves) the element into its new position in the DOM either after
  4794. * the `after` element (if provided) or as the first child within the `parent` element
  4795. * and then triggers an animation. A promise is returned that will be resolved
  4796. * during the next digest once the animation has completed.
  4797. *
  4798. * @param {DOMElement} element the element which will be moved into the new DOM position
  4799. * @param {DOMElement} parent the parent element which will append the element as
  4800. * a child (so long as the after element is not present)
  4801. * @param {DOMElement=} after the sibling element after which the element will be appended
  4802. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4803. *
  4804. * @return {Promise} the animation callback promise
  4805. */
  4806. move: function(element, parent, after, options) {
  4807. parent = parent && jqLite(parent);
  4808. after = after && jqLite(after);
  4809. parent = parent || after.parent();
  4810. domInsert(element, parent, after);
  4811. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  4812. },
  4813. /**
  4814. * @ngdoc method
  4815. * @name $animate#leave
  4816. * @kind function
  4817. * @description Triggers an animation and then removes the element from the DOM.
  4818. * When the function is called a promise is returned that will be resolved during the next
  4819. * digest once the animation has completed.
  4820. *
  4821. * @param {DOMElement} element the element which will be removed from the DOM
  4822. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4823. *
  4824. * @return {Promise} the animation callback promise
  4825. */
  4826. leave: function(element, options) {
  4827. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  4828. element.remove();
  4829. });
  4830. },
  4831. /**
  4832. * @ngdoc method
  4833. * @name $animate#addClass
  4834. * @kind function
  4835. *
  4836. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  4837. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  4838. * animation if element already contains the CSS class or if the class is removed at a later step.
  4839. * Note that class-based animations are treated differently compared to structural animations
  4840. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4841. * depending if CSS or JavaScript animations are used.
  4842. *
  4843. * @param {DOMElement} element the element which the CSS classes will be applied to
  4844. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  4845. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4846. *
  4847. * @return {Promise} the animation callback promise
  4848. */
  4849. addClass: function(element, className, options) {
  4850. options = prepareAnimateOptions(options);
  4851. options.addClass = mergeClasses(options.addclass, className);
  4852. return $$animateQueue.push(element, 'addClass', options);
  4853. },
  4854. /**
  4855. * @ngdoc method
  4856. * @name $animate#removeClass
  4857. * @kind function
  4858. *
  4859. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  4860. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  4861. * animation if element does not contain the CSS class or if the class is added at a later step.
  4862. * Note that class-based animations are treated differently compared to structural animations
  4863. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4864. * depending if CSS or JavaScript animations are used.
  4865. *
  4866. * @param {DOMElement} element the element which the CSS classes will be applied to
  4867. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  4868. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4869. *
  4870. * @return {Promise} the animation callback promise
  4871. */
  4872. removeClass: function(element, className, options) {
  4873. options = prepareAnimateOptions(options);
  4874. options.removeClass = mergeClasses(options.removeClass, className);
  4875. return $$animateQueue.push(element, 'removeClass', options);
  4876. },
  4877. /**
  4878. * @ngdoc method
  4879. * @name $animate#setClass
  4880. * @kind function
  4881. *
  4882. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  4883. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  4884. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  4885. * passed. Note that class-based animations are treated differently compared to structural animations
  4886. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4887. * depending if CSS or JavaScript animations are used.
  4888. *
  4889. * @param {DOMElement} element the element which the CSS classes will be applied to
  4890. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  4891. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  4892. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4893. *
  4894. * @return {Promise} the animation callback promise
  4895. */
  4896. setClass: function(element, add, remove, options) {
  4897. options = prepareAnimateOptions(options);
  4898. options.addClass = mergeClasses(options.addClass, add);
  4899. options.removeClass = mergeClasses(options.removeClass, remove);
  4900. return $$animateQueue.push(element, 'setClass', options);
  4901. },
  4902. /**
  4903. * @ngdoc method
  4904. * @name $animate#animate
  4905. * @kind function
  4906. *
  4907. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  4908. * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take
  4909. * on the provided styles. For example, if a transition animation is set for the given classNamem, then the provided `from` and
  4910. * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding
  4911. * style in `to`, the style in `from` is applied immediately, and no animation is run.
  4912. * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`
  4913. * method (or as part of the `options` parameter):
  4914. *
  4915. * ```js
  4916. * ngModule.animation('.my-inline-animation', function() {
  4917. * return {
  4918. * animate : function(element, from, to, done, options) {
  4919. * //animation
  4920. * done();
  4921. * }
  4922. * }
  4923. * });
  4924. * ```
  4925. *
  4926. * @param {DOMElement} element the element which the CSS styles will be applied to
  4927. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  4928. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  4929. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  4930. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  4931. * (Note that if no animation is detected then this value will not be applied to the element.)
  4932. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4933. *
  4934. * @return {Promise} the animation callback promise
  4935. */
  4936. animate: function(element, from, to, className, options) {
  4937. options = prepareAnimateOptions(options);
  4938. options.from = options.from ? extend(options.from, from) : from;
  4939. options.to = options.to ? extend(options.to, to) : to;
  4940. className = className || 'ng-inline-animate';
  4941. options.tempClasses = mergeClasses(options.tempClasses, className);
  4942. return $$animateQueue.push(element, 'animate', options);
  4943. }
  4944. };
  4945. }];
  4946. }];
  4947. var $$AnimateAsyncRunFactoryProvider = function() {
  4948. this.$get = ['$$rAF', function($$rAF) {
  4949. var waitQueue = [];
  4950. function waitForTick(fn) {
  4951. waitQueue.push(fn);
  4952. if (waitQueue.length > 1) return;
  4953. $$rAF(function() {
  4954. for (var i = 0; i < waitQueue.length; i++) {
  4955. waitQueue[i]();
  4956. }
  4957. waitQueue = [];
  4958. });
  4959. }
  4960. return function() {
  4961. var passed = false;
  4962. waitForTick(function() {
  4963. passed = true;
  4964. });
  4965. return function(callback) {
  4966. passed ? callback() : waitForTick(callback);
  4967. };
  4968. };
  4969. }];
  4970. };
  4971. var $$AnimateRunnerFactoryProvider = function() {
  4972. this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$document', '$timeout',
  4973. function($q, $sniffer, $$animateAsyncRun, $document, $timeout) {
  4974. var INITIAL_STATE = 0;
  4975. var DONE_PENDING_STATE = 1;
  4976. var DONE_COMPLETE_STATE = 2;
  4977. AnimateRunner.chain = function(chain, callback) {
  4978. var index = 0;
  4979. next();
  4980. function next() {
  4981. if (index === chain.length) {
  4982. callback(true);
  4983. return;
  4984. }
  4985. chain[index](function(response) {
  4986. if (response === false) {
  4987. callback(false);
  4988. return;
  4989. }
  4990. index++;
  4991. next();
  4992. });
  4993. }
  4994. };
  4995. AnimateRunner.all = function(runners, callback) {
  4996. var count = 0;
  4997. var status = true;
  4998. forEach(runners, function(runner) {
  4999. runner.done(onProgress);
  5000. });
  5001. function onProgress(response) {
  5002. status = status && response;
  5003. if (++count === runners.length) {
  5004. callback(status);
  5005. }
  5006. }
  5007. };
  5008. function AnimateRunner(host) {
  5009. this.setHost(host);
  5010. var rafTick = $$animateAsyncRun();
  5011. var timeoutTick = function(fn) {
  5012. $timeout(fn, 0, false);
  5013. };
  5014. this._doneCallbacks = [];
  5015. this._tick = function(fn) {
  5016. var doc = $document[0];
  5017. // the document may not be ready or attached
  5018. // to the module for some internal tests
  5019. if (doc && doc.hidden) {
  5020. timeoutTick(fn);
  5021. } else {
  5022. rafTick(fn);
  5023. }
  5024. };
  5025. this._state = 0;
  5026. }
  5027. AnimateRunner.prototype = {
  5028. setHost: function(host) {
  5029. this.host = host || {};
  5030. },
  5031. done: function(fn) {
  5032. if (this._state === DONE_COMPLETE_STATE) {
  5033. fn();
  5034. } else {
  5035. this._doneCallbacks.push(fn);
  5036. }
  5037. },
  5038. progress: noop,
  5039. getPromise: function() {
  5040. if (!this.promise) {
  5041. var self = this;
  5042. this.promise = $q(function(resolve, reject) {
  5043. self.done(function(status) {
  5044. status === false ? reject() : resolve();
  5045. });
  5046. });
  5047. }
  5048. return this.promise;
  5049. },
  5050. then: function(resolveHandler, rejectHandler) {
  5051. return this.getPromise().then(resolveHandler, rejectHandler);
  5052. },
  5053. 'catch': function(handler) {
  5054. return this.getPromise()['catch'](handler);
  5055. },
  5056. 'finally': function(handler) {
  5057. return this.getPromise()['finally'](handler);
  5058. },
  5059. pause: function() {
  5060. if (this.host.pause) {
  5061. this.host.pause();
  5062. }
  5063. },
  5064. resume: function() {
  5065. if (this.host.resume) {
  5066. this.host.resume();
  5067. }
  5068. },
  5069. end: function() {
  5070. if (this.host.end) {
  5071. this.host.end();
  5072. }
  5073. this._resolve(true);
  5074. },
  5075. cancel: function() {
  5076. if (this.host.cancel) {
  5077. this.host.cancel();
  5078. }
  5079. this._resolve(false);
  5080. },
  5081. complete: function(response) {
  5082. var self = this;
  5083. if (self._state === INITIAL_STATE) {
  5084. self._state = DONE_PENDING_STATE;
  5085. self._tick(function() {
  5086. self._resolve(response);
  5087. });
  5088. }
  5089. },
  5090. _resolve: function(response) {
  5091. if (this._state !== DONE_COMPLETE_STATE) {
  5092. forEach(this._doneCallbacks, function(fn) {
  5093. fn(response);
  5094. });
  5095. this._doneCallbacks.length = 0;
  5096. this._state = DONE_COMPLETE_STATE;
  5097. }
  5098. }
  5099. };
  5100. return AnimateRunner;
  5101. }];
  5102. };
  5103. /**
  5104. * @ngdoc service
  5105. * @name $animateCss
  5106. * @kind object
  5107. *
  5108. * @description
  5109. * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
  5110. * then the `$animateCss` service will actually perform animations.
  5111. *
  5112. * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
  5113. */
  5114. var $CoreAnimateCssProvider = function() {
  5115. this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
  5116. return function(element, initialOptions) {
  5117. // all of the animation functions should create
  5118. // a copy of the options data, however, if a
  5119. // parent service has already created a copy then
  5120. // we should stick to using that
  5121. var options = initialOptions || {};
  5122. if (!options.$$prepared) {
  5123. options = copy(options);
  5124. }
  5125. // there is no point in applying the styles since
  5126. // there is no animation that goes on at all in
  5127. // this version of $animateCss.
  5128. if (options.cleanupStyles) {
  5129. options.from = options.to = null;
  5130. }
  5131. if (options.from) {
  5132. element.css(options.from);
  5133. options.from = null;
  5134. }
  5135. /* jshint newcap: false */
  5136. var closed, runner = new $$AnimateRunner();
  5137. return {
  5138. start: run,
  5139. end: run
  5140. };
  5141. function run() {
  5142. $$rAF(function() {
  5143. applyAnimationContents();
  5144. if (!closed) {
  5145. runner.complete();
  5146. }
  5147. closed = true;
  5148. });
  5149. return runner;
  5150. }
  5151. function applyAnimationContents() {
  5152. if (options.addClass) {
  5153. element.addClass(options.addClass);
  5154. options.addClass = null;
  5155. }
  5156. if (options.removeClass) {
  5157. element.removeClass(options.removeClass);
  5158. options.removeClass = null;
  5159. }
  5160. if (options.to) {
  5161. element.css(options.to);
  5162. options.to = null;
  5163. }
  5164. }
  5165. };
  5166. }];
  5167. };
  5168. /* global stripHash: true */
  5169. /**
  5170. * ! This is a private undocumented service !
  5171. *
  5172. * @name $browser
  5173. * @requires $log
  5174. * @description
  5175. * This object has two goals:
  5176. *
  5177. * - hide all the global state in the browser caused by the window object
  5178. * - abstract away all the browser specific features and inconsistencies
  5179. *
  5180. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  5181. * service, which can be used for convenient testing of the application without the interaction with
  5182. * the real browser apis.
  5183. */
  5184. /**
  5185. * @param {object} window The global window object.
  5186. * @param {object} document jQuery wrapped document.
  5187. * @param {object} $log window.console or an object with the same interface.
  5188. * @param {object} $sniffer $sniffer service
  5189. */
  5190. function Browser(window, document, $log, $sniffer) {
  5191. var self = this,
  5192. rawDocument = document[0],
  5193. location = window.location,
  5194. history = window.history,
  5195. setTimeout = window.setTimeout,
  5196. clearTimeout = window.clearTimeout,
  5197. pendingDeferIds = {};
  5198. self.isMock = false;
  5199. var outstandingRequestCount = 0;
  5200. var outstandingRequestCallbacks = [];
  5201. // TODO(vojta): remove this temporary api
  5202. self.$$completeOutstandingRequest = completeOutstandingRequest;
  5203. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  5204. /**
  5205. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  5206. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  5207. */
  5208. function completeOutstandingRequest(fn) {
  5209. try {
  5210. fn.apply(null, sliceArgs(arguments, 1));
  5211. } finally {
  5212. outstandingRequestCount--;
  5213. if (outstandingRequestCount === 0) {
  5214. while (outstandingRequestCallbacks.length) {
  5215. try {
  5216. outstandingRequestCallbacks.pop()();
  5217. } catch (e) {
  5218. $log.error(e);
  5219. }
  5220. }
  5221. }
  5222. }
  5223. }
  5224. function getHash(url) {
  5225. var index = url.indexOf('#');
  5226. return index === -1 ? '' : url.substr(index);
  5227. }
  5228. /**
  5229. * @private
  5230. * Note: this method is used only by scenario runner
  5231. * TODO(vojta): prefix this method with $$ ?
  5232. * @param {function()} callback Function that will be called when no outstanding request
  5233. */
  5234. self.notifyWhenNoOutstandingRequests = function(callback) {
  5235. if (outstandingRequestCount === 0) {
  5236. callback();
  5237. } else {
  5238. outstandingRequestCallbacks.push(callback);
  5239. }
  5240. };
  5241. //////////////////////////////////////////////////////////////
  5242. // URL API
  5243. //////////////////////////////////////////////////////////////
  5244. var cachedState, lastHistoryState,
  5245. lastBrowserUrl = location.href,
  5246. baseElement = document.find('base'),
  5247. pendingLocation = null;
  5248. cacheState();
  5249. lastHistoryState = cachedState;
  5250. /**
  5251. * @name $browser#url
  5252. *
  5253. * @description
  5254. * GETTER:
  5255. * Without any argument, this method just returns current value of location.href.
  5256. *
  5257. * SETTER:
  5258. * With at least one argument, this method sets url to new value.
  5259. * If html5 history api supported, pushState/replaceState is used, otherwise
  5260. * location.href/location.replace is used.
  5261. * Returns its own instance to allow chaining
  5262. *
  5263. * NOTE: this api is intended for use only by the $location service. Please use the
  5264. * {@link ng.$location $location service} to change url.
  5265. *
  5266. * @param {string} url New url (when used as setter)
  5267. * @param {boolean=} replace Should new url replace current history record?
  5268. * @param {object=} state object to use with pushState/replaceState
  5269. */
  5270. self.url = function(url, replace, state) {
  5271. // In modern browsers `history.state` is `null` by default; treating it separately
  5272. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  5273. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  5274. if (isUndefined(state)) {
  5275. state = null;
  5276. }
  5277. // Android Browser BFCache causes location, history reference to become stale.
  5278. if (location !== window.location) location = window.location;
  5279. if (history !== window.history) history = window.history;
  5280. // setter
  5281. if (url) {
  5282. var sameState = lastHistoryState === state;
  5283. // Don't change anything if previous and current URLs and states match. This also prevents
  5284. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  5285. // See https://github.com/angular/angular.js/commit/ffb2701
  5286. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  5287. return self;
  5288. }
  5289. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  5290. lastBrowserUrl = url;
  5291. lastHistoryState = state;
  5292. // Don't use history API if only the hash changed
  5293. // due to a bug in IE10/IE11 which leads
  5294. // to not firing a `hashchange` nor `popstate` event
  5295. // in some cases (see #9143).
  5296. if ($sniffer.history && (!sameBase || !sameState)) {
  5297. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  5298. cacheState();
  5299. // Do the assignment again so that those two variables are referentially identical.
  5300. lastHistoryState = cachedState;
  5301. } else {
  5302. if (!sameBase || pendingLocation) {
  5303. pendingLocation = url;
  5304. }
  5305. if (replace) {
  5306. location.replace(url);
  5307. } else if (!sameBase) {
  5308. location.href = url;
  5309. } else {
  5310. location.hash = getHash(url);
  5311. }
  5312. if (location.href !== url) {
  5313. pendingLocation = url;
  5314. }
  5315. }
  5316. return self;
  5317. // getter
  5318. } else {
  5319. // - pendingLocation is needed as browsers don't allow to read out
  5320. // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
  5321. // https://openradar.appspot.com/22186109).
  5322. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  5323. return pendingLocation || location.href.replace(/%27/g,"'");
  5324. }
  5325. };
  5326. /**
  5327. * @name $browser#state
  5328. *
  5329. * @description
  5330. * This method is a getter.
  5331. *
  5332. * Return history.state or null if history.state is undefined.
  5333. *
  5334. * @returns {object} state
  5335. */
  5336. self.state = function() {
  5337. return cachedState;
  5338. };
  5339. var urlChangeListeners = [],
  5340. urlChangeInit = false;
  5341. function cacheStateAndFireUrlChange() {
  5342. pendingLocation = null;
  5343. cacheState();
  5344. fireUrlChange();
  5345. }
  5346. function getCurrentState() {
  5347. try {
  5348. return history.state;
  5349. } catch (e) {
  5350. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  5351. }
  5352. }
  5353. // This variable should be used *only* inside the cacheState function.
  5354. var lastCachedState = null;
  5355. function cacheState() {
  5356. // This should be the only place in $browser where `history.state` is read.
  5357. cachedState = getCurrentState();
  5358. cachedState = isUndefined(cachedState) ? null : cachedState;
  5359. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  5360. if (equals(cachedState, lastCachedState)) {
  5361. cachedState = lastCachedState;
  5362. }
  5363. lastCachedState = cachedState;
  5364. }
  5365. function fireUrlChange() {
  5366. if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
  5367. return;
  5368. }
  5369. lastBrowserUrl = self.url();
  5370. lastHistoryState = cachedState;
  5371. forEach(urlChangeListeners, function(listener) {
  5372. listener(self.url(), cachedState);
  5373. });
  5374. }
  5375. /**
  5376. * @name $browser#onUrlChange
  5377. *
  5378. * @description
  5379. * Register callback function that will be called, when url changes.
  5380. *
  5381. * It's only called when the url is changed from outside of angular:
  5382. * - user types different url into address bar
  5383. * - user clicks on history (forward/back) button
  5384. * - user clicks on a link
  5385. *
  5386. * It's not called when url is changed by $browser.url() method
  5387. *
  5388. * The listener gets called with new url as parameter.
  5389. *
  5390. * NOTE: this api is intended for use only by the $location service. Please use the
  5391. * {@link ng.$location $location service} to monitor url changes in angular apps.
  5392. *
  5393. * @param {function(string)} listener Listener function to be called when url changes.
  5394. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  5395. */
  5396. self.onUrlChange = function(callback) {
  5397. // TODO(vojta): refactor to use node's syntax for events
  5398. if (!urlChangeInit) {
  5399. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  5400. // don't fire popstate when user change the address bar and don't fire hashchange when url
  5401. // changed by push/replaceState
  5402. // html5 history api - popstate event
  5403. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  5404. // hashchange event
  5405. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  5406. urlChangeInit = true;
  5407. }
  5408. urlChangeListeners.push(callback);
  5409. return callback;
  5410. };
  5411. /**
  5412. * @private
  5413. * Remove popstate and hashchange handler from window.
  5414. *
  5415. * NOTE: this api is intended for use only by $rootScope.
  5416. */
  5417. self.$$applicationDestroyed = function() {
  5418. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  5419. };
  5420. /**
  5421. * Checks whether the url has changed outside of Angular.
  5422. * Needs to be exported to be able to check for changes that have been done in sync,
  5423. * as hashchange/popstate events fire in async.
  5424. */
  5425. self.$$checkUrlChange = fireUrlChange;
  5426. //////////////////////////////////////////////////////////////
  5427. // Misc API
  5428. //////////////////////////////////////////////////////////////
  5429. /**
  5430. * @name $browser#baseHref
  5431. *
  5432. * @description
  5433. * Returns current <base href>
  5434. * (always relative - without domain)
  5435. *
  5436. * @returns {string} The current base href
  5437. */
  5438. self.baseHref = function() {
  5439. var href = baseElement.attr('href');
  5440. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  5441. };
  5442. /**
  5443. * @name $browser#defer
  5444. * @param {function()} fn A function, who's execution should be deferred.
  5445. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  5446. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  5447. *
  5448. * @description
  5449. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  5450. *
  5451. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  5452. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  5453. * via `$browser.defer.flush()`.
  5454. *
  5455. */
  5456. self.defer = function(fn, delay) {
  5457. var timeoutId;
  5458. outstandingRequestCount++;
  5459. timeoutId = setTimeout(function() {
  5460. delete pendingDeferIds[timeoutId];
  5461. completeOutstandingRequest(fn);
  5462. }, delay || 0);
  5463. pendingDeferIds[timeoutId] = true;
  5464. return timeoutId;
  5465. };
  5466. /**
  5467. * @name $browser#defer.cancel
  5468. *
  5469. * @description
  5470. * Cancels a deferred task identified with `deferId`.
  5471. *
  5472. * @param {*} deferId Token returned by the `$browser.defer` function.
  5473. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  5474. * canceled.
  5475. */
  5476. self.defer.cancel = function(deferId) {
  5477. if (pendingDeferIds[deferId]) {
  5478. delete pendingDeferIds[deferId];
  5479. clearTimeout(deferId);
  5480. completeOutstandingRequest(noop);
  5481. return true;
  5482. }
  5483. return false;
  5484. };
  5485. }
  5486. function $BrowserProvider() {
  5487. this.$get = ['$window', '$log', '$sniffer', '$document',
  5488. function($window, $log, $sniffer, $document) {
  5489. return new Browser($window, $document, $log, $sniffer);
  5490. }];
  5491. }
  5492. /**
  5493. * @ngdoc service
  5494. * @name $cacheFactory
  5495. *
  5496. * @description
  5497. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  5498. * them.
  5499. *
  5500. * ```js
  5501. *
  5502. * var cache = $cacheFactory('cacheId');
  5503. * expect($cacheFactory.get('cacheId')).toBe(cache);
  5504. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  5505. *
  5506. * cache.put("key", "value");
  5507. * cache.put("another key", "another value");
  5508. *
  5509. * // We've specified no options on creation
  5510. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  5511. *
  5512. * ```
  5513. *
  5514. *
  5515. * @param {string} cacheId Name or id of the newly created cache.
  5516. * @param {object=} options Options object that specifies the cache behavior. Properties:
  5517. *
  5518. * - `{number=}` `capacity` — turns the cache into LRU cache.
  5519. *
  5520. * @returns {object} Newly created cache object with the following set of methods:
  5521. *
  5522. * - `{object}` `info()` — Returns id, size, and options of cache.
  5523. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  5524. * it.
  5525. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  5526. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  5527. * - `{void}` `removeAll()` — Removes all cached values.
  5528. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  5529. *
  5530. * @example
  5531. <example module="cacheExampleApp">
  5532. <file name="index.html">
  5533. <div ng-controller="CacheController">
  5534. <input ng-model="newCacheKey" placeholder="Key">
  5535. <input ng-model="newCacheValue" placeholder="Value">
  5536. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  5537. <p ng-if="keys.length">Cached Values</p>
  5538. <div ng-repeat="key in keys">
  5539. <span ng-bind="key"></span>
  5540. <span>: </span>
  5541. <b ng-bind="cache.get(key)"></b>
  5542. </div>
  5543. <p>Cache Info</p>
  5544. <div ng-repeat="(key, value) in cache.info()">
  5545. <span ng-bind="key"></span>
  5546. <span>: </span>
  5547. <b ng-bind="value"></b>
  5548. </div>
  5549. </div>
  5550. </file>
  5551. <file name="script.js">
  5552. angular.module('cacheExampleApp', []).
  5553. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  5554. $scope.keys = [];
  5555. $scope.cache = $cacheFactory('cacheId');
  5556. $scope.put = function(key, value) {
  5557. if (angular.isUndefined($scope.cache.get(key))) {
  5558. $scope.keys.push(key);
  5559. }
  5560. $scope.cache.put(key, angular.isUndefined(value) ? null : value);
  5561. };
  5562. }]);
  5563. </file>
  5564. <file name="style.css">
  5565. p {
  5566. margin: 10px 0 3px;
  5567. }
  5568. </file>
  5569. </example>
  5570. */
  5571. function $CacheFactoryProvider() {
  5572. this.$get = function() {
  5573. var caches = {};
  5574. function cacheFactory(cacheId, options) {
  5575. if (cacheId in caches) {
  5576. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  5577. }
  5578. var size = 0,
  5579. stats = extend({}, options, {id: cacheId}),
  5580. data = createMap(),
  5581. capacity = (options && options.capacity) || Number.MAX_VALUE,
  5582. lruHash = createMap(),
  5583. freshEnd = null,
  5584. staleEnd = null;
  5585. /**
  5586. * @ngdoc type
  5587. * @name $cacheFactory.Cache
  5588. *
  5589. * @description
  5590. * A cache object used to store and retrieve data, primarily used by
  5591. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  5592. * templates and other data.
  5593. *
  5594. * ```js
  5595. * angular.module('superCache')
  5596. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  5597. * return $cacheFactory('super-cache');
  5598. * }]);
  5599. * ```
  5600. *
  5601. * Example test:
  5602. *
  5603. * ```js
  5604. * it('should behave like a cache', inject(function(superCache) {
  5605. * superCache.put('key', 'value');
  5606. * superCache.put('another key', 'another value');
  5607. *
  5608. * expect(superCache.info()).toEqual({
  5609. * id: 'super-cache',
  5610. * size: 2
  5611. * });
  5612. *
  5613. * superCache.remove('another key');
  5614. * expect(superCache.get('another key')).toBeUndefined();
  5615. *
  5616. * superCache.removeAll();
  5617. * expect(superCache.info()).toEqual({
  5618. * id: 'super-cache',
  5619. * size: 0
  5620. * });
  5621. * }));
  5622. * ```
  5623. */
  5624. return caches[cacheId] = {
  5625. /**
  5626. * @ngdoc method
  5627. * @name $cacheFactory.Cache#put
  5628. * @kind function
  5629. *
  5630. * @description
  5631. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  5632. * retrieved later, and incrementing the size of the cache if the key was not already
  5633. * present in the cache. If behaving like an LRU cache, it will also remove stale
  5634. * entries from the set.
  5635. *
  5636. * It will not insert undefined values into the cache.
  5637. *
  5638. * @param {string} key the key under which the cached data is stored.
  5639. * @param {*} value the value to store alongside the key. If it is undefined, the key
  5640. * will not be stored.
  5641. * @returns {*} the value stored.
  5642. */
  5643. put: function(key, value) {
  5644. if (isUndefined(value)) return;
  5645. if (capacity < Number.MAX_VALUE) {
  5646. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  5647. refresh(lruEntry);
  5648. }
  5649. if (!(key in data)) size++;
  5650. data[key] = value;
  5651. if (size > capacity) {
  5652. this.remove(staleEnd.key);
  5653. }
  5654. return value;
  5655. },
  5656. /**
  5657. * @ngdoc method
  5658. * @name $cacheFactory.Cache#get
  5659. * @kind function
  5660. *
  5661. * @description
  5662. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  5663. *
  5664. * @param {string} key the key of the data to be retrieved
  5665. * @returns {*} the value stored.
  5666. */
  5667. get: function(key) {
  5668. if (capacity < Number.MAX_VALUE) {
  5669. var lruEntry = lruHash[key];
  5670. if (!lruEntry) return;
  5671. refresh(lruEntry);
  5672. }
  5673. return data[key];
  5674. },
  5675. /**
  5676. * @ngdoc method
  5677. * @name $cacheFactory.Cache#remove
  5678. * @kind function
  5679. *
  5680. * @description
  5681. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  5682. *
  5683. * @param {string} key the key of the entry to be removed
  5684. */
  5685. remove: function(key) {
  5686. if (capacity < Number.MAX_VALUE) {
  5687. var lruEntry = lruHash[key];
  5688. if (!lruEntry) return;
  5689. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  5690. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  5691. link(lruEntry.n,lruEntry.p);
  5692. delete lruHash[key];
  5693. }
  5694. if (!(key in data)) return;
  5695. delete data[key];
  5696. size--;
  5697. },
  5698. /**
  5699. * @ngdoc method
  5700. * @name $cacheFactory.Cache#removeAll
  5701. * @kind function
  5702. *
  5703. * @description
  5704. * Clears the cache object of any entries.
  5705. */
  5706. removeAll: function() {
  5707. data = createMap();
  5708. size = 0;
  5709. lruHash = createMap();
  5710. freshEnd = staleEnd = null;
  5711. },
  5712. /**
  5713. * @ngdoc method
  5714. * @name $cacheFactory.Cache#destroy
  5715. * @kind function
  5716. *
  5717. * @description
  5718. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  5719. * removing it from the {@link $cacheFactory $cacheFactory} set.
  5720. */
  5721. destroy: function() {
  5722. data = null;
  5723. stats = null;
  5724. lruHash = null;
  5725. delete caches[cacheId];
  5726. },
  5727. /**
  5728. * @ngdoc method
  5729. * @name $cacheFactory.Cache#info
  5730. * @kind function
  5731. *
  5732. * @description
  5733. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  5734. *
  5735. * @returns {object} an object with the following properties:
  5736. * <ul>
  5737. * <li>**id**: the id of the cache instance</li>
  5738. * <li>**size**: the number of entries kept in the cache instance</li>
  5739. * <li>**...**: any additional properties from the options object when creating the
  5740. * cache.</li>
  5741. * </ul>
  5742. */
  5743. info: function() {
  5744. return extend({}, stats, {size: size});
  5745. }
  5746. };
  5747. /**
  5748. * makes the `entry` the freshEnd of the LRU linked list
  5749. */
  5750. function refresh(entry) {
  5751. if (entry != freshEnd) {
  5752. if (!staleEnd) {
  5753. staleEnd = entry;
  5754. } else if (staleEnd == entry) {
  5755. staleEnd = entry.n;
  5756. }
  5757. link(entry.n, entry.p);
  5758. link(entry, freshEnd);
  5759. freshEnd = entry;
  5760. freshEnd.n = null;
  5761. }
  5762. }
  5763. /**
  5764. * bidirectionally links two entries of the LRU linked list
  5765. */
  5766. function link(nextEntry, prevEntry) {
  5767. if (nextEntry != prevEntry) {
  5768. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  5769. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  5770. }
  5771. }
  5772. }
  5773. /**
  5774. * @ngdoc method
  5775. * @name $cacheFactory#info
  5776. *
  5777. * @description
  5778. * Get information about all the caches that have been created
  5779. *
  5780. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  5781. */
  5782. cacheFactory.info = function() {
  5783. var info = {};
  5784. forEach(caches, function(cache, cacheId) {
  5785. info[cacheId] = cache.info();
  5786. });
  5787. return info;
  5788. };
  5789. /**
  5790. * @ngdoc method
  5791. * @name $cacheFactory#get
  5792. *
  5793. * @description
  5794. * Get access to a cache object by the `cacheId` used when it was created.
  5795. *
  5796. * @param {string} cacheId Name or id of a cache to access.
  5797. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  5798. */
  5799. cacheFactory.get = function(cacheId) {
  5800. return caches[cacheId];
  5801. };
  5802. return cacheFactory;
  5803. };
  5804. }
  5805. /**
  5806. * @ngdoc service
  5807. * @name $templateCache
  5808. *
  5809. * @description
  5810. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  5811. * can load templates directly into the cache in a `script` tag, or by consuming the
  5812. * `$templateCache` service directly.
  5813. *
  5814. * Adding via the `script` tag:
  5815. *
  5816. * ```html
  5817. * <script type="text/ng-template" id="templateId.html">
  5818. * <p>This is the content of the template</p>
  5819. * </script>
  5820. * ```
  5821. *
  5822. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  5823. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  5824. * element with ng-app attribute), otherwise the template will be ignored.
  5825. *
  5826. * Adding via the `$templateCache` service:
  5827. *
  5828. * ```js
  5829. * var myApp = angular.module('myApp', []);
  5830. * myApp.run(function($templateCache) {
  5831. * $templateCache.put('templateId.html', 'This is the content of the template');
  5832. * });
  5833. * ```
  5834. *
  5835. * To retrieve the template later, simply use it in your HTML:
  5836. * ```html
  5837. * <div ng-include=" 'templateId.html' "></div>
  5838. * ```
  5839. *
  5840. * or get it via Javascript:
  5841. * ```js
  5842. * $templateCache.get('templateId.html')
  5843. * ```
  5844. *
  5845. * See {@link ng.$cacheFactory $cacheFactory}.
  5846. *
  5847. */
  5848. function $TemplateCacheProvider() {
  5849. this.$get = ['$cacheFactory', function($cacheFactory) {
  5850. return $cacheFactory('templates');
  5851. }];
  5852. }
  5853. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  5854. * Any commits to this file should be reviewed with security in mind. *
  5855. * Changes to this file can potentially create security vulnerabilities. *
  5856. * An approval from 2 Core members with history of modifying *
  5857. * this file is required. *
  5858. * *
  5859. * Does the change somehow allow for arbitrary javascript to be executed? *
  5860. * Or allows for someone to change the prototype of built-in objects? *
  5861. * Or gives undesired access to variables likes document or window? *
  5862. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  5863. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  5864. *
  5865. * DOM-related variables:
  5866. *
  5867. * - "node" - DOM Node
  5868. * - "element" - DOM Element or Node
  5869. * - "$node" or "$element" - jqLite-wrapped node or element
  5870. *
  5871. *
  5872. * Compiler related stuff:
  5873. *
  5874. * - "linkFn" - linking fn of a single directive
  5875. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  5876. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  5877. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  5878. */
  5879. /**
  5880. * @ngdoc service
  5881. * @name $compile
  5882. * @kind function
  5883. *
  5884. * @description
  5885. * Compiles an HTML string or DOM into a template and produces a template function, which
  5886. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  5887. *
  5888. * The compilation is a process of walking the DOM tree and matching DOM elements to
  5889. * {@link ng.$compileProvider#directive directives}.
  5890. *
  5891. * <div class="alert alert-warning">
  5892. * **Note:** This document is an in-depth reference of all directive options.
  5893. * For a gentle introduction to directives with examples of common use cases,
  5894. * see the {@link guide/directive directive guide}.
  5895. * </div>
  5896. *
  5897. * ## Comprehensive Directive API
  5898. *
  5899. * There are many different options for a directive.
  5900. *
  5901. * The difference resides in the return value of the factory function.
  5902. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  5903. * or just the `postLink` function (all other properties will have the default values).
  5904. *
  5905. * <div class="alert alert-success">
  5906. * **Best Practice:** It's recommended to use the "directive definition object" form.
  5907. * </div>
  5908. *
  5909. * Here's an example directive declared with a Directive Definition Object:
  5910. *
  5911. * ```js
  5912. * var myModule = angular.module(...);
  5913. *
  5914. * myModule.directive('directiveName', function factory(injectables) {
  5915. * var directiveDefinitionObject = {
  5916. * priority: 0,
  5917. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  5918. * // or
  5919. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  5920. * transclude: false,
  5921. * restrict: 'A',
  5922. * templateNamespace: 'html',
  5923. * scope: false,
  5924. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  5925. * controllerAs: 'stringIdentifier',
  5926. * bindToController: false,
  5927. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  5928. * compile: function compile(tElement, tAttrs, transclude) {
  5929. * return {
  5930. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5931. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5932. * }
  5933. * // or
  5934. * // return function postLink( ... ) { ... }
  5935. * },
  5936. * // or
  5937. * // link: {
  5938. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5939. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5940. * // }
  5941. * // or
  5942. * // link: function postLink( ... ) { ... }
  5943. * };
  5944. * return directiveDefinitionObject;
  5945. * });
  5946. * ```
  5947. *
  5948. * <div class="alert alert-warning">
  5949. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  5950. * </div>
  5951. *
  5952. * Therefore the above can be simplified as:
  5953. *
  5954. * ```js
  5955. * var myModule = angular.module(...);
  5956. *
  5957. * myModule.directive('directiveName', function factory(injectables) {
  5958. * var directiveDefinitionObject = {
  5959. * link: function postLink(scope, iElement, iAttrs) { ... }
  5960. * };
  5961. * return directiveDefinitionObject;
  5962. * // or
  5963. * // return function postLink(scope, iElement, iAttrs) { ... }
  5964. * });
  5965. * ```
  5966. *
  5967. *
  5968. *
  5969. * ### Directive Definition Object
  5970. *
  5971. * The directive definition object provides instructions to the {@link ng.$compile
  5972. * compiler}. The attributes are:
  5973. *
  5974. * #### `multiElement`
  5975. * When this property is set to true, the HTML compiler will collect DOM nodes between
  5976. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  5977. * together as the directive elements. It is recommended that this feature be used on directives
  5978. * which are not strictly behavioral (such as {@link ngClick}), and which
  5979. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  5980. *
  5981. * #### `priority`
  5982. * When there are multiple directives defined on a single DOM element, sometimes it
  5983. * is necessary to specify the order in which the directives are applied. The `priority` is used
  5984. * to sort the directives before their `compile` functions get called. Priority is defined as a
  5985. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  5986. * are also run in priority order, but post-link functions are run in reverse order. The order
  5987. * of directives with the same priority is undefined. The default priority is `0`.
  5988. *
  5989. * #### `terminal`
  5990. * If set to true then the current `priority` will be the last set of directives
  5991. * which will execute (any directives at the current priority will still execute
  5992. * as the order of execution on same `priority` is undefined). Note that expressions
  5993. * and other directives used in the directive's template will also be excluded from execution.
  5994. *
  5995. * #### `scope`
  5996. * The scope property can be `true`, an object or a falsy value:
  5997. *
  5998. * * **falsy:** No scope will be created for the directive. The directive will use its parent's scope.
  5999. *
  6000. * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
  6001. * the directive's element. If multiple directives on the same element request a new scope,
  6002. * only one new scope is created. The new scope rule does not apply for the root of the template
  6003. * since the root of the template always gets a new scope.
  6004. *
  6005. * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's element. The
  6006. * 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent
  6007. * scope. This is useful when creating reusable components, which should not accidentally read or modify
  6008. * data in the parent scope.
  6009. *
  6010. * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
  6011. * directive's element. These local properties are useful for aliasing values for templates. The keys in
  6012. * the object hash map to the name of the property on the isolate scope; the values define how the property
  6013. * is bound to the parent scope, via matching attributes on the directive's element:
  6014. *
  6015. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  6016. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  6017. * attribute name is assumed to be the same as the local name. Given `<my-component
  6018. * my-attr="hello {{name}}">` and the isolate scope definition `scope: { localName:'@myAttr' }`,
  6019. * the directive's scope property `localName` will reflect the interpolated value of `hello
  6020. * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's
  6021. * scope. The `name` is read from the parent scope (not the directive's scope).
  6022. *
  6023. * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression
  6024. * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.
  6025. * If no `attr` name is specified then the attribute name is assumed to be the same as the local
  6026. * name. Given `<my-component my-attr="parentModel">` and the isolate scope definition `scope: {
  6027. * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the
  6028. * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in
  6029. * `localModel` and vice versa. Optional attributes should be marked as such with a question mark:
  6030. * `=?` or `=?attr`. If the binding expression is non-assignable, or if the attribute isn't
  6031. * optional and doesn't exist, an exception ({@link error/$compile/nonassign `$compile:nonassign`})
  6032. * will be thrown upon discovering changes to the local value, since it will be impossible to sync
  6033. * them back to the parent scope. By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
  6034. * method is used for tracking changes, and the equality check is based on object identity.
  6035. * However, if an object literal or an array literal is passed as the binding expression, the
  6036. * equality check is done by value (using the {@link angular.equals} function). It's also possible
  6037. * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection
  6038. * `$watchCollection`}: use `=*` or `=*attr` (`=*?` or `=*?attr` if the attribute is optional).
  6039. *
  6040. * * `<` or `<attr` - set up a one-way (one-directional) binding between a local scope property and an
  6041. * expression passed via the attribute `attr`. The expression is evaluated in the context of the
  6042. * parent scope. If no `attr` name is specified then the attribute name is assumed to be the same as the
  6043. * local name. You can also make the binding optional by adding `?`: `<?` or `<?attr`.
  6044. *
  6045. * For example, given `<my-component my-attr="parentModel">` and directive definition of
  6046. * `scope: { localModel:'<myAttr' }`, then the isolated scope property `localModel` will reflect the
  6047. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  6048. * in `localModel`, but changes in `localModel` will not reflect in `parentModel`. There are however
  6049. * two caveats:
  6050. * 1. one-way binding does not copy the value from the parent to the isolate scope, it simply
  6051. * sets the same value. That means if your bound value is an object, changes to its properties
  6052. * in the isolated scope will be reflected in the parent scope (because both reference the same object).
  6053. * 2. one-way binding watches changes to the **identity** of the parent value. That means the
  6054. * {@link ng.$rootScope.Scope#$watch `$watch`} on the parent value only fires if the reference
  6055. * to the value has changed. In most cases, this should not be of concern, but can be important
  6056. * to know if you one-way bind to an object, and then replace that object in the isolated scope.
  6057. * If you now change a property of the object in your parent scope, the change will not be
  6058. * propagated to the isolated scope, because the identity of the object on the parent scope
  6059. * has not changed. Instead you must assign a new object.
  6060. *
  6061. * One-way binding is useful if you do not plan to propagate changes to your isolated scope bindings
  6062. * back to the parent. However, it does not make this completely impossible.
  6063. *
  6064. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. If
  6065. * no `attr` name is specified then the attribute name is assumed to be the same as the local name.
  6066. * Given `<my-component my-attr="count = count + value">` and the isolate scope definition `scope: {
  6067. * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for
  6068. * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope
  6069. * via an expression to the parent scope. This can be done by passing a map of local variable names
  6070. * and values into the expression wrapper fn. For example, if the expression is `increment(amount)`
  6071. * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.
  6072. *
  6073. * In general it's possible to apply more than one directive to one element, but there might be limitations
  6074. * depending on the type of scope required by the directives. The following points will help explain these limitations.
  6075. * For simplicity only two directives are taken into account, but it is also applicable for several directives:
  6076. *
  6077. * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
  6078. * * **child scope** + **no scope** => Both directives will share one single child scope
  6079. * * **child scope** + **child scope** => Both directives will share one single child scope
  6080. * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
  6081. * its parent's scope
  6082. * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
  6083. * be applied to the same element.
  6084. * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
  6085. * cannot be applied to the same element.
  6086. *
  6087. *
  6088. * #### `bindToController`
  6089. * This property is used to bind scope properties directly to the controller. It can be either
  6090. * `true` or an object hash with the same format as the `scope` property. Additionally, a controller
  6091. * alias must be set, either by using `controllerAs: 'myAlias'` or by specifying the alias in the controller
  6092. * definition: `controller: 'myCtrl as myAlias'`.
  6093. *
  6094. * When an isolate scope is used for a directive (see above), `bindToController: true` will
  6095. * allow a component to have its properties bound to the controller, rather than to scope.
  6096. *
  6097. * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller
  6098. * properties. You can access these bindings once they have been initialized by providing a controller method called
  6099. * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings
  6100. * initialized.
  6101. *
  6102. * <div class="alert alert-warning">
  6103. * **Deprecation warning:** although bindings for non-ES6 class controllers are currently
  6104. * bound to `this` before the controller constructor is called, this use is now deprecated. Please place initialization
  6105. * code that relies upon bindings inside a `$onInit` method on the controller, instead.
  6106. * </div>
  6107. *
  6108. * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.
  6109. * This will set up the scope bindings to the controller directly. Note that `scope` can still be used
  6110. * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate
  6111. * scope (useful for component directives).
  6112. *
  6113. * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.
  6114. *
  6115. *
  6116. * #### `controller`
  6117. * Controller constructor function. The controller is instantiated before the
  6118. * pre-linking phase and can be accessed by other directives (see
  6119. * `require` attribute). This allows the directives to communicate with each other and augment
  6120. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  6121. *
  6122. * * `$scope` - Current scope associated with the element
  6123. * * `$element` - Current element
  6124. * * `$attrs` - Current attributes object for the element
  6125. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  6126. * `function([scope], cloneLinkingFn, futureParentElement, slotName)`:
  6127. * * `scope`: (optional) override the scope.
  6128. * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.
  6129. * * `futureParentElement` (optional):
  6130. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  6131. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  6132. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  6133. * and when the `cloneLinkinFn` is passed,
  6134. * as those elements need to created and cloned in a special way when they are defined outside their
  6135. * usual containers (e.g. like `<svg>`).
  6136. * * See also the `directive.templateNamespace` property.
  6137. * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`)
  6138. * then the default translusion is provided.
  6139. * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns
  6140. * `true` if the specified slot contains content (i.e. one or more DOM nodes).
  6141. *
  6142. * The controller can provide the following methods that act as life-cycle hooks:
  6143. * * `$onInit` - Called on each controller after all the controllers on an element have been constructed and
  6144. * had their bindings initialized (and before the pre &amp; post linking functions for the directives on
  6145. * this element). This is a good place to put initialization code for your controller.
  6146. *
  6147. * #### `require`
  6148. * Require another directive and inject its controller as the fourth argument to the linking function. The
  6149. * `require` property can be a string, an array or an object:
  6150. * * a **string** containing the name of the directive to pass to the linking function
  6151. * * an **array** containing the names of directives to pass to the linking function. The argument passed to the
  6152. * linking function will be an array of controllers in the same order as the names in the `require` property
  6153. * * an **object** whose property values are the names of the directives to pass to the linking function. The argument
  6154. * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding
  6155. * controllers.
  6156. *
  6157. * If the `require` property is an object and `bindToController` is truthy, then the required controllers are
  6158. * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers
  6159. * have been constructed but before `$onInit` is called.
  6160. * See the {@link $compileProvider#component} helper for an example of how this can be used.
  6161. *
  6162. * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is
  6163. * raised (unless no link function is specified and the required controllers are not being bound to the directive
  6164. * controller, in which case error checking is skipped). The name can be prefixed with:
  6165. *
  6166. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  6167. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  6168. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  6169. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  6170. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  6171. * `null` to the `link` fn if not found.
  6172. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  6173. * `null` to the `link` fn if not found.
  6174. *
  6175. *
  6176. * #### `controllerAs`
  6177. * Identifier name for a reference to the controller in the directive's scope.
  6178. * This allows the controller to be referenced from the directive template. This is especially
  6179. * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
  6180. * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
  6181. * `controllerAs` reference might overwrite a property that already exists on the parent scope.
  6182. *
  6183. *
  6184. * #### `restrict`
  6185. * String of subset of `EACM` which restricts the directive to a specific directive
  6186. * declaration style. If omitted, the defaults (elements and attributes) are used.
  6187. *
  6188. * * `E` - Element name (default): `<my-directive></my-directive>`
  6189. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  6190. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  6191. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  6192. *
  6193. *
  6194. * #### `templateNamespace`
  6195. * String representing the document type used by the markup in the template.
  6196. * AngularJS needs this information as those elements need to be created and cloned
  6197. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  6198. *
  6199. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  6200. * top-level elements such as `<svg>` or `<math>`.
  6201. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  6202. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  6203. *
  6204. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  6205. *
  6206. * #### `template`
  6207. * HTML markup that may:
  6208. * * Replace the contents of the directive's element (default).
  6209. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  6210. * * Wrap the contents of the directive's element (if `transclude` is true).
  6211. *
  6212. * Value may be:
  6213. *
  6214. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  6215. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  6216. * function api below) and returns a string value.
  6217. *
  6218. *
  6219. * #### `templateUrl`
  6220. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  6221. *
  6222. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  6223. * for later when the template has been resolved. In the meantime it will continue to compile and link
  6224. * sibling and parent elements as though this element had not contained any directives.
  6225. *
  6226. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  6227. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  6228. * case when only one deeply nested directive has `templateUrl`.
  6229. *
  6230. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  6231. *
  6232. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  6233. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  6234. * a string value representing the url. In either case, the template URL is passed through {@link
  6235. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  6236. *
  6237. *
  6238. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  6239. * specify what the template should replace. Defaults to `false`.
  6240. *
  6241. * * `true` - the template will replace the directive's element.
  6242. * * `false` - the template will replace the contents of the directive's element.
  6243. *
  6244. * The replacement process migrates all of the attributes / classes from the old element to the new
  6245. * one. See the {@link guide/directive#template-expanding-directive
  6246. * Directives Guide} for an example.
  6247. *
  6248. * There are very few scenarios where element replacement is required for the application function,
  6249. * the main one being reusable custom components that are used within SVG contexts
  6250. * (because SVG doesn't work with custom elements in the DOM tree).
  6251. *
  6252. * #### `transclude`
  6253. * Extract the contents of the element where the directive appears and make it available to the directive.
  6254. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  6255. * {@link $compile#transclusion Transclusion} section below.
  6256. *
  6257. *
  6258. * #### `compile`
  6259. *
  6260. * ```js
  6261. * function compile(tElement, tAttrs, transclude) { ... }
  6262. * ```
  6263. *
  6264. * The compile function deals with transforming the template DOM. Since most directives do not do
  6265. * template transformation, it is not used often. The compile function takes the following arguments:
  6266. *
  6267. * * `tElement` - template element - The element where the directive has been declared. It is
  6268. * safe to do template transformation on the element and child elements only.
  6269. *
  6270. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  6271. * between all directive compile functions.
  6272. *
  6273. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  6274. *
  6275. * <div class="alert alert-warning">
  6276. * **Note:** The template instance and the link instance may be different objects if the template has
  6277. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  6278. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  6279. * should be done in a linking function rather than in a compile function.
  6280. * </div>
  6281. * <div class="alert alert-warning">
  6282. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  6283. * own templates or compile functions. Compiling these directives results in an infinite loop and
  6284. * stack overflow errors.
  6285. *
  6286. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  6287. * a directive's template instead of relying on automatic template compilation via `template` or
  6288. * `templateUrl` declaration or manual compilation inside the compile function.
  6289. * </div>
  6290. *
  6291. * <div class="alert alert-danger">
  6292. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  6293. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  6294. * to the link function instead.
  6295. * </div>
  6296. * A compile function can have a return value which can be either a function or an object.
  6297. *
  6298. * * returning a (post-link) function - is equivalent to registering the linking function via the
  6299. * `link` property of the config object when the compile function is empty.
  6300. *
  6301. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  6302. * control when a linking function should be called during the linking phase. See info about
  6303. * pre-linking and post-linking functions below.
  6304. *
  6305. *
  6306. * #### `link`
  6307. * This property is used only if the `compile` property is not defined.
  6308. *
  6309. * ```js
  6310. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  6311. * ```
  6312. *
  6313. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  6314. * executed after the template has been cloned. This is where most of the directive logic will be
  6315. * put.
  6316. *
  6317. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  6318. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  6319. *
  6320. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  6321. * manipulate the children of the element only in `postLink` function since the children have
  6322. * already been linked.
  6323. *
  6324. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  6325. * between all directive linking functions.
  6326. *
  6327. * * `controller` - the directive's required controller instance(s) - Instances are shared
  6328. * among all directives, which allows the directives to use the controllers as a communication
  6329. * channel. The exact value depends on the directive's `require` property:
  6330. * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
  6331. * * `string`: the controller instance
  6332. * * `array`: array of controller instances
  6333. *
  6334. * If a required controller cannot be found, and it is optional, the instance is `null`,
  6335. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  6336. *
  6337. * Note that you can also require the directive's own controller - it will be made available like
  6338. * any other controller.
  6339. *
  6340. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  6341. * This is the same as the `$transclude`
  6342. * parameter of directive controllers, see there for details.
  6343. * `function([scope], cloneLinkingFn, futureParentElement)`.
  6344. *
  6345. * #### Pre-linking function
  6346. *
  6347. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  6348. * compiler linking function will fail to locate the correct elements for linking.
  6349. *
  6350. * #### Post-linking function
  6351. *
  6352. * Executed after the child elements are linked.
  6353. *
  6354. * Note that child elements that contain `templateUrl` directives will not have been compiled
  6355. * and linked since they are waiting for their template to load asynchronously and their own
  6356. * compilation and linking has been suspended until that occurs.
  6357. *
  6358. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  6359. * for their async templates to be resolved.
  6360. *
  6361. *
  6362. * ### Transclusion
  6363. *
  6364. * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
  6365. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  6366. * scope from where they were taken.
  6367. *
  6368. * Transclusion is used (often with {@link ngTransclude}) to insert the
  6369. * original contents of a directive's element into a specified place in the template of the directive.
  6370. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  6371. * content has access to the properties on the scope from which it was taken, even if the directive
  6372. * has isolated scope.
  6373. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  6374. *
  6375. * This makes it possible for the widget to have private state for its template, while the transcluded
  6376. * content has access to its originating scope.
  6377. *
  6378. * <div class="alert alert-warning">
  6379. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  6380. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  6381. * Testing Transclusion Directives}.
  6382. * </div>
  6383. *
  6384. * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the
  6385. * directive's element, the entire element or multiple parts of the element contents:
  6386. *
  6387. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  6388. * * `'element'` - transclude the whole of the directive's element including any directives on this
  6389. * element that defined at a lower priority than this directive. When used, the `template`
  6390. * property is ignored.
  6391. * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template.
  6392. *
  6393. * **Mult-slot transclusion** is declared by providing an object for the `transclude` property.
  6394. *
  6395. * This object is a map where the keys are the name of the slot to fill and the value is an element selector
  6396. * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`)
  6397. * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc).
  6398. *
  6399. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  6400. *
  6401. * If the element selector is prefixed with a `?` then that slot is optional.
  6402. *
  6403. * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `<my-custom-element>` elements to
  6404. * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive.
  6405. *
  6406. * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements
  6407. * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call
  6408. * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and
  6409. * injectable into the directive's controller.
  6410. *
  6411. *
  6412. * #### Transclusion Functions
  6413. *
  6414. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  6415. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  6416. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  6417. *
  6418. * <div class="alert alert-info">
  6419. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  6420. * ngTransclude will deal with it for us.
  6421. * </div>
  6422. *
  6423. * If you want to manually control the insertion and removal of the transcluded content in your directive
  6424. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  6425. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  6426. *
  6427. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  6428. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  6429. * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
  6430. *
  6431. * <div class="alert alert-info">
  6432. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function
  6433. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  6434. * </div>
  6435. *
  6436. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  6437. * attach function**:
  6438. *
  6439. * ```js
  6440. * var transcludedContent, transclusionScope;
  6441. *
  6442. * $transclude(function(clone, scope) {
  6443. * element.append(clone);
  6444. * transcludedContent = clone;
  6445. * transclusionScope = scope;
  6446. * });
  6447. * ```
  6448. *
  6449. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  6450. * associated transclusion scope:
  6451. *
  6452. * ```js
  6453. * transcludedContent.remove();
  6454. * transclusionScope.$destroy();
  6455. * ```
  6456. *
  6457. * <div class="alert alert-info">
  6458. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  6459. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  6460. * then you are also responsible for calling `$destroy` on the transclusion scope.
  6461. * </div>
  6462. *
  6463. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  6464. * automatically destroy their transcluded clones as necessary so you do not need to worry about this if
  6465. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  6466. *
  6467. *
  6468. * #### Transclusion Scopes
  6469. *
  6470. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  6471. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  6472. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  6473. * was taken.
  6474. *
  6475. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  6476. * like this:
  6477. *
  6478. * ```html
  6479. * <div ng-app>
  6480. * <div isolate>
  6481. * <div transclusion>
  6482. * </div>
  6483. * </div>
  6484. * </div>
  6485. * ```
  6486. *
  6487. * The `$parent` scope hierarchy will look like this:
  6488. *
  6489. ```
  6490. - $rootScope
  6491. - isolate
  6492. - transclusion
  6493. ```
  6494. *
  6495. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  6496. *
  6497. ```
  6498. - $rootScope
  6499. - transclusion
  6500. - isolate
  6501. ```
  6502. *
  6503. *
  6504. * ### Attributes
  6505. *
  6506. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  6507. * `link()` or `compile()` functions. It has a variety of uses.
  6508. *
  6509. * * *Accessing normalized attribute names:* Directives like 'ngBind' can be expressed in many ways:
  6510. * 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. The attributes object allows for normalized access
  6511. * to the attributes.
  6512. *
  6513. * * *Directive inter-communication:* All directives share the same instance of the attributes
  6514. * object which allows the directives to use the attributes object as inter directive
  6515. * communication.
  6516. *
  6517. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  6518. * allowing other directives to read the interpolated value.
  6519. *
  6520. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  6521. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  6522. * the only way to easily get the actual value because during the linking phase the interpolation
  6523. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  6524. *
  6525. * ```js
  6526. * function linkingFn(scope, elm, attrs, ctrl) {
  6527. * // get the attribute value
  6528. * console.log(attrs.ngModel);
  6529. *
  6530. * // change the attribute
  6531. * attrs.$set('ngModel', 'new value');
  6532. *
  6533. * // observe changes to interpolated attribute
  6534. * attrs.$observe('ngModel', function(value) {
  6535. * console.log('ngModel has changed value to ' + value);
  6536. * });
  6537. * }
  6538. * ```
  6539. *
  6540. * ## Example
  6541. *
  6542. * <div class="alert alert-warning">
  6543. * **Note**: Typically directives are registered with `module.directive`. The example below is
  6544. * to illustrate how `$compile` works.
  6545. * </div>
  6546. *
  6547. <example module="compileExample">
  6548. <file name="index.html">
  6549. <script>
  6550. angular.module('compileExample', [], function($compileProvider) {
  6551. // configure new 'compile' directive by passing a directive
  6552. // factory function. The factory function injects the '$compile'
  6553. $compileProvider.directive('compile', function($compile) {
  6554. // directive factory creates a link function
  6555. return function(scope, element, attrs) {
  6556. scope.$watch(
  6557. function(scope) {
  6558. // watch the 'compile' expression for changes
  6559. return scope.$eval(attrs.compile);
  6560. },
  6561. function(value) {
  6562. // when the 'compile' expression changes
  6563. // assign it into the current DOM
  6564. element.html(value);
  6565. // compile the new DOM and link it to the current
  6566. // scope.
  6567. // NOTE: we only compile .childNodes so that
  6568. // we don't get into infinite loop compiling ourselves
  6569. $compile(element.contents())(scope);
  6570. }
  6571. );
  6572. };
  6573. });
  6574. })
  6575. .controller('GreeterController', ['$scope', function($scope) {
  6576. $scope.name = 'Angular';
  6577. $scope.html = 'Hello {{name}}';
  6578. }]);
  6579. </script>
  6580. <div ng-controller="GreeterController">
  6581. <input ng-model="name"> <br/>
  6582. <textarea ng-model="html"></textarea> <br/>
  6583. <div compile="html"></div>
  6584. </div>
  6585. </file>
  6586. <file name="protractor.js" type="protractor">
  6587. it('should auto compile', function() {
  6588. var textarea = $('textarea');
  6589. var output = $('div[compile]');
  6590. // The initial state reads 'Hello Angular'.
  6591. expect(output.getText()).toBe('Hello Angular');
  6592. textarea.clear();
  6593. textarea.sendKeys('{{name}}!');
  6594. expect(output.getText()).toBe('Angular!');
  6595. });
  6596. </file>
  6597. </example>
  6598. *
  6599. *
  6600. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  6601. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  6602. *
  6603. * <div class="alert alert-danger">
  6604. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  6605. * e.g. will not use the right outer scope. Please pass the transclude function as a
  6606. * `parentBoundTranscludeFn` to the link function instead.
  6607. * </div>
  6608. *
  6609. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  6610. * root element(s), not their children)
  6611. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  6612. * (a DOM element/tree) to a scope. Where:
  6613. *
  6614. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  6615. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  6616. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  6617. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  6618. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  6619. *
  6620. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  6621. * * `scope` - is the current scope with which the linking function is working with.
  6622. *
  6623. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  6624. * keys may be used to control linking behavior:
  6625. *
  6626. * * `parentBoundTranscludeFn` - the transclude function made available to
  6627. * directives; if given, it will be passed through to the link functions of
  6628. * directives found in `element` during compilation.
  6629. * * `transcludeControllers` - an object hash with keys that map controller names
  6630. * to a hash with the key `instance`, which maps to the controller instance;
  6631. * if given, it will make the controllers available to directives on the compileNode:
  6632. * ```
  6633. * {
  6634. * parent: {
  6635. * instance: parentControllerInstance
  6636. * }
  6637. * }
  6638. * ```
  6639. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  6640. * the cloned elements; only needed for transcludes that are allowed to contain non html
  6641. * elements (e.g. SVG elements). See also the directive.controller property.
  6642. *
  6643. * Calling the linking function returns the element of the template. It is either the original
  6644. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  6645. *
  6646. * After linking the view is not updated until after a call to $digest which typically is done by
  6647. * Angular automatically.
  6648. *
  6649. * If you need access to the bound view, there are two ways to do it:
  6650. *
  6651. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  6652. * before you send them to the compiler and keep this reference around.
  6653. * ```js
  6654. * var element = $compile('<p>{{total}}</p>')(scope);
  6655. * ```
  6656. *
  6657. * - if on the other hand, you need the element to be cloned, the view reference from the original
  6658. * example would not point to the clone, but rather to the original template that was cloned. In
  6659. * this case, you can access the clone via the cloneAttachFn:
  6660. * ```js
  6661. * var templateElement = angular.element('<p>{{total}}</p>'),
  6662. * scope = ....;
  6663. *
  6664. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  6665. * //attach the clone to DOM document at the right place
  6666. * });
  6667. *
  6668. * //now we have reference to the cloned DOM via `clonedElement`
  6669. * ```
  6670. *
  6671. *
  6672. * For information on how the compiler works, see the
  6673. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  6674. */
  6675. var $compileMinErr = minErr('$compile');
  6676. /**
  6677. * @ngdoc provider
  6678. * @name $compileProvider
  6679. *
  6680. * @description
  6681. */
  6682. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  6683. function $CompileProvider($provide, $$sanitizeUriProvider) {
  6684. var hasDirectives = {},
  6685. Suffix = 'Directive',
  6686. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
  6687. CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
  6688. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  6689. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  6690. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  6691. // The assumption is that future DOM event attribute names will begin with
  6692. // 'on' and be composed of only English letters.
  6693. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  6694. function parseIsolateBindings(scope, directiveName, isController) {
  6695. var LOCAL_REGEXP = /^\s*([@&<]|=(\*?))(\??)\s*(\w*)\s*$/;
  6696. var bindings = {};
  6697. forEach(scope, function(definition, scopeName) {
  6698. var match = definition.match(LOCAL_REGEXP);
  6699. if (!match) {
  6700. throw $compileMinErr('iscp',
  6701. "Invalid {3} for directive '{0}'." +
  6702. " Definition: {... {1}: '{2}' ...}",
  6703. directiveName, scopeName, definition,
  6704. (isController ? "controller bindings definition" :
  6705. "isolate scope definition"));
  6706. }
  6707. bindings[scopeName] = {
  6708. mode: match[1][0],
  6709. collection: match[2] === '*',
  6710. optional: match[3] === '?',
  6711. attrName: match[4] || scopeName
  6712. };
  6713. });
  6714. return bindings;
  6715. }
  6716. function parseDirectiveBindings(directive, directiveName) {
  6717. var bindings = {
  6718. isolateScope: null,
  6719. bindToController: null
  6720. };
  6721. if (isObject(directive.scope)) {
  6722. if (directive.bindToController === true) {
  6723. bindings.bindToController = parseIsolateBindings(directive.scope,
  6724. directiveName, true);
  6725. bindings.isolateScope = {};
  6726. } else {
  6727. bindings.isolateScope = parseIsolateBindings(directive.scope,
  6728. directiveName, false);
  6729. }
  6730. }
  6731. if (isObject(directive.bindToController)) {
  6732. bindings.bindToController =
  6733. parseIsolateBindings(directive.bindToController, directiveName, true);
  6734. }
  6735. if (isObject(bindings.bindToController)) {
  6736. var controller = directive.controller;
  6737. var controllerAs = directive.controllerAs;
  6738. if (!controller) {
  6739. // There is no controller, there may or may not be a controllerAs property
  6740. throw $compileMinErr('noctrl',
  6741. "Cannot bind to controller without directive '{0}'s controller.",
  6742. directiveName);
  6743. } else if (!identifierForController(controller, controllerAs)) {
  6744. // There is a controller, but no identifier or controllerAs property
  6745. throw $compileMinErr('noident',
  6746. "Cannot bind to controller without identifier for directive '{0}'.",
  6747. directiveName);
  6748. }
  6749. }
  6750. return bindings;
  6751. }
  6752. function assertValidDirectiveName(name) {
  6753. var letter = name.charAt(0);
  6754. if (!letter || letter !== lowercase(letter)) {
  6755. throw $compileMinErr('baddir', "Directive name '{0}' is invalid. The first character must be a lowercase letter", name);
  6756. }
  6757. if (name !== name.trim()) {
  6758. throw $compileMinErr('baddir',
  6759. "Directive name '{0}' is invalid. The name should not contain leading or trailing whitespaces",
  6760. name);
  6761. }
  6762. }
  6763. /**
  6764. * @ngdoc method
  6765. * @name $compileProvider#directive
  6766. * @kind function
  6767. *
  6768. * @description
  6769. * Register a new directive with the compiler.
  6770. *
  6771. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  6772. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  6773. * names and the values are the factories.
  6774. * @param {Function|Array} directiveFactory An injectable directive factory function. See the
  6775. * {@link guide/directive directive guide} and the {@link $compile compile API} for more info.
  6776. * @returns {ng.$compileProvider} Self for chaining.
  6777. */
  6778. this.directive = function registerDirective(name, directiveFactory) {
  6779. assertNotHasOwnProperty(name, 'directive');
  6780. if (isString(name)) {
  6781. assertValidDirectiveName(name);
  6782. assertArg(directiveFactory, 'directiveFactory');
  6783. if (!hasDirectives.hasOwnProperty(name)) {
  6784. hasDirectives[name] = [];
  6785. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  6786. function($injector, $exceptionHandler) {
  6787. var directives = [];
  6788. forEach(hasDirectives[name], function(directiveFactory, index) {
  6789. try {
  6790. var directive = $injector.invoke(directiveFactory);
  6791. if (isFunction(directive)) {
  6792. directive = { compile: valueFn(directive) };
  6793. } else if (!directive.compile && directive.link) {
  6794. directive.compile = valueFn(directive.link);
  6795. }
  6796. directive.priority = directive.priority || 0;
  6797. directive.index = index;
  6798. directive.name = directive.name || name;
  6799. directive.require = directive.require || (directive.controller && directive.name);
  6800. directive.restrict = directive.restrict || 'EA';
  6801. var bindings = directive.$$bindings =
  6802. parseDirectiveBindings(directive, directive.name);
  6803. if (isObject(bindings.isolateScope)) {
  6804. directive.$$isolateBindings = bindings.isolateScope;
  6805. }
  6806. directive.$$moduleName = directiveFactory.$$moduleName;
  6807. directives.push(directive);
  6808. } catch (e) {
  6809. $exceptionHandler(e);
  6810. }
  6811. });
  6812. return directives;
  6813. }]);
  6814. }
  6815. hasDirectives[name].push(directiveFactory);
  6816. } else {
  6817. forEach(name, reverseParams(registerDirective));
  6818. }
  6819. return this;
  6820. };
  6821. /**
  6822. * @ngdoc method
  6823. * @name $compileProvider#component
  6824. * @module ng
  6825. * @param {string} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`)
  6826. * @param {Object} options Component definition object (a simplified
  6827. * {@link ng.$compile#directive-definition-object directive definition object}),
  6828. * with the following properties (all optional):
  6829. *
  6830. * - `controller` – `{(string|function()=}` – controller constructor function that should be
  6831. * associated with newly created scope or the name of a {@link ng.$compile#-controller-
  6832. * registered controller} if passed as a string. An empty `noop` function by default.
  6833. * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope.
  6834. * If present, the controller will be published to scope under the `controllerAs` name.
  6835. * If not present, this will default to be `$ctrl`.
  6836. * - `template` – `{string=|function()=}` – html template as a string or a function that
  6837. * returns an html template as a string which should be used as the contents of this component.
  6838. * Empty string by default.
  6839. *
  6840. * If `template` is a function, then it is {@link auto.$injector#invoke injected} with
  6841. * the following locals:
  6842. *
  6843. * - `$element` - Current element
  6844. * - `$attrs` - Current attributes object for the element
  6845. *
  6846. * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
  6847. * template that should be used as the contents of this component.
  6848. *
  6849. * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
  6850. * the following locals:
  6851. *
  6852. * - `$element` - Current element
  6853. * - `$attrs` - Current attributes object for the element
  6854. *
  6855. * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties.
  6856. * Component properties are always bound to the component controller and not to the scope.
  6857. * See {@link ng.$compile#-bindtocontroller- `bindToController`}.
  6858. * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled.
  6859. * Disabled by default.
  6860. * - `$...` – `{function()=}` – additional annotations to provide to the directive factory function.
  6861. *
  6862. * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls.
  6863. * @description
  6864. * Register a **component definition** with the compiler. This is a shorthand for registering a special
  6865. * type of directive, which represents a self-contained UI component in your application. Such components
  6866. * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`).
  6867. *
  6868. * Component definitions are very simple and do not require as much configuration as defining general
  6869. * directives. Component definitions usually consist only of a template and a controller backing it.
  6870. *
  6871. * In order to make the definition easier, components enforce best practices like use of `controllerAs`,
  6872. * `bindToController`. They always have **isolate scope** and are restricted to elements.
  6873. *
  6874. * Here are a few examples of how you would usually define components:
  6875. *
  6876. * ```js
  6877. * var myMod = angular.module(...);
  6878. * myMod.component('myComp', {
  6879. * template: '<div>My name is {{$ctrl.name}}</div>',
  6880. * controller: function() {
  6881. * this.name = 'shahar';
  6882. * }
  6883. * });
  6884. *
  6885. * myMod.component('myComp', {
  6886. * template: '<div>My name is {{$ctrl.name}}</div>',
  6887. * bindings: {name: '@'}
  6888. * });
  6889. *
  6890. * myMod.component('myComp', {
  6891. * templateUrl: 'views/my-comp.html',
  6892. * controller: 'MyCtrl as ctrl',
  6893. * bindings: {name: '@'}
  6894. * });
  6895. *
  6896. * ```
  6897. * For more examples, and an in-depth guide, see the {@link guide/component component guide}.
  6898. *
  6899. * <br />
  6900. * See also {@link ng.$compileProvider#directive $compileProvider.directive()}.
  6901. */
  6902. this.component = function registerComponent(name, options) {
  6903. var controller = options.controller || function() {};
  6904. function factory($injector) {
  6905. function makeInjectable(fn) {
  6906. if (isFunction(fn) || isArray(fn)) {
  6907. return function(tElement, tAttrs) {
  6908. return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
  6909. };
  6910. } else {
  6911. return fn;
  6912. }
  6913. }
  6914. var template = (!options.template && !options.templateUrl ? '' : options.template);
  6915. return {
  6916. controller: controller,
  6917. controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',
  6918. template: makeInjectable(template),
  6919. templateUrl: makeInjectable(options.templateUrl),
  6920. transclude: options.transclude,
  6921. scope: {},
  6922. bindToController: options.bindings || {},
  6923. restrict: 'E',
  6924. require: options.require
  6925. };
  6926. }
  6927. // Copy any annotation properties (starting with $) over to the factory function
  6928. // These could be used by libraries such as the new component router
  6929. forEach(options, function(val, key) {
  6930. if (key.charAt(0) === '$') {
  6931. factory[key] = val;
  6932. }
  6933. });
  6934. factory.$inject = ['$injector'];
  6935. return this.directive(name, factory);
  6936. };
  6937. /**
  6938. * @ngdoc method
  6939. * @name $compileProvider#aHrefSanitizationWhitelist
  6940. * @kind function
  6941. *
  6942. * @description
  6943. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  6944. * urls during a[href] sanitization.
  6945. *
  6946. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  6947. *
  6948. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  6949. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  6950. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  6951. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  6952. *
  6953. * @param {RegExp=} regexp New regexp to whitelist urls with.
  6954. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  6955. * chaining otherwise.
  6956. */
  6957. this.aHrefSanitizationWhitelist = function(regexp) {
  6958. if (isDefined(regexp)) {
  6959. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  6960. return this;
  6961. } else {
  6962. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  6963. }
  6964. };
  6965. /**
  6966. * @ngdoc method
  6967. * @name $compileProvider#imgSrcSanitizationWhitelist
  6968. * @kind function
  6969. *
  6970. * @description
  6971. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  6972. * urls during img[src] sanitization.
  6973. *
  6974. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  6975. *
  6976. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  6977. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  6978. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  6979. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  6980. *
  6981. * @param {RegExp=} regexp New regexp to whitelist urls with.
  6982. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  6983. * chaining otherwise.
  6984. */
  6985. this.imgSrcSanitizationWhitelist = function(regexp) {
  6986. if (isDefined(regexp)) {
  6987. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  6988. return this;
  6989. } else {
  6990. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  6991. }
  6992. };
  6993. /**
  6994. * @ngdoc method
  6995. * @name $compileProvider#debugInfoEnabled
  6996. *
  6997. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  6998. * current debugInfoEnabled state
  6999. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  7000. *
  7001. * @kind function
  7002. *
  7003. * @description
  7004. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  7005. * binding information and a reference to the current scope on to DOM elements.
  7006. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  7007. * * `ng-binding` CSS class
  7008. * * `$binding` data property containing an array of the binding expressions
  7009. *
  7010. * You may want to disable this in production for a significant performance boost. See
  7011. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  7012. *
  7013. * The default value is true.
  7014. */
  7015. var debugInfoEnabled = true;
  7016. this.debugInfoEnabled = function(enabled) {
  7017. if (isDefined(enabled)) {
  7018. debugInfoEnabled = enabled;
  7019. return this;
  7020. }
  7021. return debugInfoEnabled;
  7022. };
  7023. this.$get = [
  7024. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  7025. '$controller', '$rootScope', '$sce', '$animate', '$$sanitizeUri',
  7026. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  7027. $controller, $rootScope, $sce, $animate, $$sanitizeUri) {
  7028. var SIMPLE_ATTR_NAME = /^\w/;
  7029. var specialAttrHolder = document.createElement('div');
  7030. var Attributes = function(element, attributesToCopy) {
  7031. if (attributesToCopy) {
  7032. var keys = Object.keys(attributesToCopy);
  7033. var i, l, key;
  7034. for (i = 0, l = keys.length; i < l; i++) {
  7035. key = keys[i];
  7036. this[key] = attributesToCopy[key];
  7037. }
  7038. } else {
  7039. this.$attr = {};
  7040. }
  7041. this.$$element = element;
  7042. };
  7043. Attributes.prototype = {
  7044. /**
  7045. * @ngdoc method
  7046. * @name $compile.directive.Attributes#$normalize
  7047. * @kind function
  7048. *
  7049. * @description
  7050. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  7051. * `data-`) to its normalized, camelCase form.
  7052. *
  7053. * Also there is special case for Moz prefix starting with upper case letter.
  7054. *
  7055. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  7056. *
  7057. * @param {string} name Name to normalize
  7058. */
  7059. $normalize: directiveNormalize,
  7060. /**
  7061. * @ngdoc method
  7062. * @name $compile.directive.Attributes#$addClass
  7063. * @kind function
  7064. *
  7065. * @description
  7066. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  7067. * are enabled then an animation will be triggered for the class addition.
  7068. *
  7069. * @param {string} classVal The className value that will be added to the element
  7070. */
  7071. $addClass: function(classVal) {
  7072. if (classVal && classVal.length > 0) {
  7073. $animate.addClass(this.$$element, classVal);
  7074. }
  7075. },
  7076. /**
  7077. * @ngdoc method
  7078. * @name $compile.directive.Attributes#$removeClass
  7079. * @kind function
  7080. *
  7081. * @description
  7082. * Removes the CSS class value specified by the classVal parameter from the element. If
  7083. * animations are enabled then an animation will be triggered for the class removal.
  7084. *
  7085. * @param {string} classVal The className value that will be removed from the element
  7086. */
  7087. $removeClass: function(classVal) {
  7088. if (classVal && classVal.length > 0) {
  7089. $animate.removeClass(this.$$element, classVal);
  7090. }
  7091. },
  7092. /**
  7093. * @ngdoc method
  7094. * @name $compile.directive.Attributes#$updateClass
  7095. * @kind function
  7096. *
  7097. * @description
  7098. * Adds and removes the appropriate CSS class values to the element based on the difference
  7099. * between the new and old CSS class values (specified as newClasses and oldClasses).
  7100. *
  7101. * @param {string} newClasses The current CSS className value
  7102. * @param {string} oldClasses The former CSS className value
  7103. */
  7104. $updateClass: function(newClasses, oldClasses) {
  7105. var toAdd = tokenDifference(newClasses, oldClasses);
  7106. if (toAdd && toAdd.length) {
  7107. $animate.addClass(this.$$element, toAdd);
  7108. }
  7109. var toRemove = tokenDifference(oldClasses, newClasses);
  7110. if (toRemove && toRemove.length) {
  7111. $animate.removeClass(this.$$element, toRemove);
  7112. }
  7113. },
  7114. /**
  7115. * Set a normalized attribute on the element in a way such that all directives
  7116. * can share the attribute. This function properly handles boolean attributes.
  7117. * @param {string} key Normalized key. (ie ngAttribute)
  7118. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  7119. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  7120. * Defaults to true.
  7121. * @param {string=} attrName Optional none normalized name. Defaults to key.
  7122. */
  7123. $set: function(key, value, writeAttr, attrName) {
  7124. // TODO: decide whether or not to throw an error if "class"
  7125. //is set through this function since it may cause $updateClass to
  7126. //become unstable.
  7127. var node = this.$$element[0],
  7128. booleanKey = getBooleanAttrName(node, key),
  7129. aliasedKey = getAliasedAttrName(key),
  7130. observer = key,
  7131. nodeName;
  7132. if (booleanKey) {
  7133. this.$$element.prop(key, value);
  7134. attrName = booleanKey;
  7135. } else if (aliasedKey) {
  7136. this[aliasedKey] = value;
  7137. observer = aliasedKey;
  7138. }
  7139. this[key] = value;
  7140. // translate normalized key to actual key
  7141. if (attrName) {
  7142. this.$attr[key] = attrName;
  7143. } else {
  7144. attrName = this.$attr[key];
  7145. if (!attrName) {
  7146. this.$attr[key] = attrName = snake_case(key, '-');
  7147. }
  7148. }
  7149. nodeName = nodeName_(this.$$element);
  7150. if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) ||
  7151. (nodeName === 'img' && key === 'src')) {
  7152. // sanitize a[href] and img[src] values
  7153. this[key] = value = $$sanitizeUri(value, key === 'src');
  7154. } else if (nodeName === 'img' && key === 'srcset') {
  7155. // sanitize img[srcset] values
  7156. var result = "";
  7157. // first check if there are spaces because it's not the same pattern
  7158. var trimmedSrcset = trim(value);
  7159. // ( 999x ,| 999w ,| ,|, )
  7160. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  7161. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  7162. // split srcset into tuple of uri and descriptor except for the last item
  7163. var rawUris = trimmedSrcset.split(pattern);
  7164. // for each tuples
  7165. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  7166. for (var i = 0; i < nbrUrisWith2parts; i++) {
  7167. var innerIdx = i * 2;
  7168. // sanitize the uri
  7169. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  7170. // add the descriptor
  7171. result += (" " + trim(rawUris[innerIdx + 1]));
  7172. }
  7173. // split the last item into uri and descriptor
  7174. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  7175. // sanitize the last uri
  7176. result += $$sanitizeUri(trim(lastTuple[0]), true);
  7177. // and add the last descriptor if any
  7178. if (lastTuple.length === 2) {
  7179. result += (" " + trim(lastTuple[1]));
  7180. }
  7181. this[key] = value = result;
  7182. }
  7183. if (writeAttr !== false) {
  7184. if (value === null || isUndefined(value)) {
  7185. this.$$element.removeAttr(attrName);
  7186. } else {
  7187. if (SIMPLE_ATTR_NAME.test(attrName)) {
  7188. this.$$element.attr(attrName, value);
  7189. } else {
  7190. setSpecialAttr(this.$$element[0], attrName, value);
  7191. }
  7192. }
  7193. }
  7194. // fire observers
  7195. var $$observers = this.$$observers;
  7196. $$observers && forEach($$observers[observer], function(fn) {
  7197. try {
  7198. fn(value);
  7199. } catch (e) {
  7200. $exceptionHandler(e);
  7201. }
  7202. });
  7203. },
  7204. /**
  7205. * @ngdoc method
  7206. * @name $compile.directive.Attributes#$observe
  7207. * @kind function
  7208. *
  7209. * @description
  7210. * Observes an interpolated attribute.
  7211. *
  7212. * The observer function will be invoked once during the next `$digest` following
  7213. * compilation. The observer is then invoked whenever the interpolated value
  7214. * changes.
  7215. *
  7216. * @param {string} key Normalized key. (ie ngAttribute) .
  7217. * @param {function(interpolatedValue)} fn Function that will be called whenever
  7218. the interpolated value of the attribute changes.
  7219. * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation
  7220. * guide} for more info.
  7221. * @returns {function()} Returns a deregistration function for this observer.
  7222. */
  7223. $observe: function(key, fn) {
  7224. var attrs = this,
  7225. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  7226. listeners = ($$observers[key] || ($$observers[key] = []));
  7227. listeners.push(fn);
  7228. $rootScope.$evalAsync(function() {
  7229. if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
  7230. // no one registered attribute interpolation function, so lets call it manually
  7231. fn(attrs[key]);
  7232. }
  7233. });
  7234. return function() {
  7235. arrayRemove(listeners, fn);
  7236. };
  7237. }
  7238. };
  7239. function setSpecialAttr(element, attrName, value) {
  7240. // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute`
  7241. // so we have to jump through some hoops to get such an attribute
  7242. // https://github.com/angular/angular.js/pull/13318
  7243. specialAttrHolder.innerHTML = "<span " + attrName + ">";
  7244. var attributes = specialAttrHolder.firstChild.attributes;
  7245. var attribute = attributes[0];
  7246. // We have to remove the attribute from its container element before we can add it to the destination element
  7247. attributes.removeNamedItem(attribute.name);
  7248. attribute.value = value;
  7249. element.attributes.setNamedItem(attribute);
  7250. }
  7251. function safeAddClass($element, className) {
  7252. try {
  7253. $element.addClass(className);
  7254. } catch (e) {
  7255. // ignore, since it means that we are trying to set class on
  7256. // SVG element, where class name is read-only.
  7257. }
  7258. }
  7259. var startSymbol = $interpolate.startSymbol(),
  7260. endSymbol = $interpolate.endSymbol(),
  7261. denormalizeTemplate = (startSymbol == '{{' && endSymbol == '}}')
  7262. ? identity
  7263. : function denormalizeTemplate(template) {
  7264. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  7265. },
  7266. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  7267. var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
  7268. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  7269. var bindings = $element.data('$binding') || [];
  7270. if (isArray(binding)) {
  7271. bindings = bindings.concat(binding);
  7272. } else {
  7273. bindings.push(binding);
  7274. }
  7275. $element.data('$binding', bindings);
  7276. } : noop;
  7277. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  7278. safeAddClass($element, 'ng-binding');
  7279. } : noop;
  7280. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  7281. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  7282. $element.data(dataName, scope);
  7283. } : noop;
  7284. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  7285. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  7286. } : noop;
  7287. return compile;
  7288. //================================
  7289. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  7290. previousCompileContext) {
  7291. if (!($compileNodes instanceof jqLite)) {
  7292. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  7293. // modify it.
  7294. $compileNodes = jqLite($compileNodes);
  7295. }
  7296. var NOT_EMPTY = /\S+/;
  7297. // We can not compile top level text elements since text nodes can be merged and we will
  7298. // not be able to attach scope data to them, so we will wrap them in <span>
  7299. for (var i = 0, len = $compileNodes.length; i < len; i++) {
  7300. var domNode = $compileNodes[i];
  7301. if (domNode.nodeType === NODE_TYPE_TEXT && domNode.nodeValue.match(NOT_EMPTY) /* non-empty */) {
  7302. jqLiteWrapNode(domNode, $compileNodes[i] = document.createElement('span'));
  7303. }
  7304. }
  7305. var compositeLinkFn =
  7306. compileNodes($compileNodes, transcludeFn, $compileNodes,
  7307. maxPriority, ignoreDirective, previousCompileContext);
  7308. compile.$$addScopeClass($compileNodes);
  7309. var namespace = null;
  7310. return function publicLinkFn(scope, cloneConnectFn, options) {
  7311. assertArg(scope, 'scope');
  7312. if (previousCompileContext && previousCompileContext.needsNewScope) {
  7313. // A parent directive did a replace and a directive on this element asked
  7314. // for transclusion, which caused us to lose a layer of element on which
  7315. // we could hold the new transclusion scope, so we will create it manually
  7316. // here.
  7317. scope = scope.$parent.$new();
  7318. }
  7319. options = options || {};
  7320. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  7321. transcludeControllers = options.transcludeControllers,
  7322. futureParentElement = options.futureParentElement;
  7323. // When `parentBoundTranscludeFn` is passed, it is a
  7324. // `controllersBoundTransclude` function (it was previously passed
  7325. // as `transclude` to directive.link) so we must unwrap it to get
  7326. // its `boundTranscludeFn`
  7327. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  7328. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  7329. }
  7330. if (!namespace) {
  7331. namespace = detectNamespaceForChildElements(futureParentElement);
  7332. }
  7333. var $linkNode;
  7334. if (namespace !== 'html') {
  7335. // When using a directive with replace:true and templateUrl the $compileNodes
  7336. // (or a child element inside of them)
  7337. // might change, so we need to recreate the namespace adapted compileNodes
  7338. // for call to the link function.
  7339. // Note: This will already clone the nodes...
  7340. $linkNode = jqLite(
  7341. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  7342. );
  7343. } else if (cloneConnectFn) {
  7344. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  7345. // and sometimes changes the structure of the DOM.
  7346. $linkNode = JQLitePrototype.clone.call($compileNodes);
  7347. } else {
  7348. $linkNode = $compileNodes;
  7349. }
  7350. if (transcludeControllers) {
  7351. for (var controllerName in transcludeControllers) {
  7352. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  7353. }
  7354. }
  7355. compile.$$addScopeInfo($linkNode, scope);
  7356. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  7357. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  7358. return $linkNode;
  7359. };
  7360. }
  7361. function detectNamespaceForChildElements(parentElement) {
  7362. // TODO: Make this detect MathML as well...
  7363. var node = parentElement && parentElement[0];
  7364. if (!node) {
  7365. return 'html';
  7366. } else {
  7367. return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html';
  7368. }
  7369. }
  7370. /**
  7371. * Compile function matches each node in nodeList against the directives. Once all directives
  7372. * for a particular node are collected their compile functions are executed. The compile
  7373. * functions return values - the linking functions - are combined into a composite linking
  7374. * function, which is the a linking function for the node.
  7375. *
  7376. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  7377. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  7378. * scope argument is auto-generated to the new child of the transcluded parent scope.
  7379. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  7380. * the rootElement must be set the jqLite collection of the compile root. This is
  7381. * needed so that the jqLite collection items can be replaced with widgets.
  7382. * @param {number=} maxPriority Max directive priority.
  7383. * @returns {Function} A composite linking function of all of the matched directives or null.
  7384. */
  7385. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  7386. previousCompileContext) {
  7387. var linkFns = [],
  7388. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  7389. for (var i = 0; i < nodeList.length; i++) {
  7390. attrs = new Attributes();
  7391. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  7392. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  7393. ignoreDirective);
  7394. nodeLinkFn = (directives.length)
  7395. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  7396. null, [], [], previousCompileContext)
  7397. : null;
  7398. if (nodeLinkFn && nodeLinkFn.scope) {
  7399. compile.$$addScopeClass(attrs.$$element);
  7400. }
  7401. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  7402. !(childNodes = nodeList[i].childNodes) ||
  7403. !childNodes.length)
  7404. ? null
  7405. : compileNodes(childNodes,
  7406. nodeLinkFn ? (
  7407. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  7408. && nodeLinkFn.transclude) : transcludeFn);
  7409. if (nodeLinkFn || childLinkFn) {
  7410. linkFns.push(i, nodeLinkFn, childLinkFn);
  7411. linkFnFound = true;
  7412. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  7413. }
  7414. //use the previous context only for the first element in the virtual group
  7415. previousCompileContext = null;
  7416. }
  7417. // return a linking function if we have found anything, null otherwise
  7418. return linkFnFound ? compositeLinkFn : null;
  7419. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  7420. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  7421. var stableNodeList;
  7422. if (nodeLinkFnFound) {
  7423. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  7424. // offsets don't get screwed up
  7425. var nodeListLength = nodeList.length;
  7426. stableNodeList = new Array(nodeListLength);
  7427. // create a sparse array by only copying the elements which have a linkFn
  7428. for (i = 0; i < linkFns.length; i+=3) {
  7429. idx = linkFns[i];
  7430. stableNodeList[idx] = nodeList[idx];
  7431. }
  7432. } else {
  7433. stableNodeList = nodeList;
  7434. }
  7435. for (i = 0, ii = linkFns.length; i < ii;) {
  7436. node = stableNodeList[linkFns[i++]];
  7437. nodeLinkFn = linkFns[i++];
  7438. childLinkFn = linkFns[i++];
  7439. if (nodeLinkFn) {
  7440. if (nodeLinkFn.scope) {
  7441. childScope = scope.$new();
  7442. compile.$$addScopeInfo(jqLite(node), childScope);
  7443. } else {
  7444. childScope = scope;
  7445. }
  7446. if (nodeLinkFn.transcludeOnThisElement) {
  7447. childBoundTranscludeFn = createBoundTranscludeFn(
  7448. scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  7449. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  7450. childBoundTranscludeFn = parentBoundTranscludeFn;
  7451. } else if (!parentBoundTranscludeFn && transcludeFn) {
  7452. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  7453. } else {
  7454. childBoundTranscludeFn = null;
  7455. }
  7456. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  7457. } else if (childLinkFn) {
  7458. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  7459. }
  7460. }
  7461. }
  7462. }
  7463. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  7464. var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  7465. if (!transcludedScope) {
  7466. transcludedScope = scope.$new(false, containingScope);
  7467. transcludedScope.$$transcluded = true;
  7468. }
  7469. return transcludeFn(transcludedScope, cloneFn, {
  7470. parentBoundTranscludeFn: previousBoundTranscludeFn,
  7471. transcludeControllers: controllers,
  7472. futureParentElement: futureParentElement
  7473. });
  7474. };
  7475. // We need to attach the transclusion slots onto the `boundTranscludeFn`
  7476. // so that they are available inside the `controllersBoundTransclude` function
  7477. var boundSlots = boundTranscludeFn.$$slots = createMap();
  7478. for (var slotName in transcludeFn.$$slots) {
  7479. if (transcludeFn.$$slots[slotName]) {
  7480. boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);
  7481. } else {
  7482. boundSlots[slotName] = null;
  7483. }
  7484. }
  7485. return boundTranscludeFn;
  7486. }
  7487. /**
  7488. * Looks for directives on the given node and adds them to the directive collection which is
  7489. * sorted.
  7490. *
  7491. * @param node Node to search.
  7492. * @param directives An array to which the directives are added to. This array is sorted before
  7493. * the function returns.
  7494. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  7495. * @param {number=} maxPriority Max directive priority.
  7496. */
  7497. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  7498. var nodeType = node.nodeType,
  7499. attrsMap = attrs.$attr,
  7500. match,
  7501. className;
  7502. switch (nodeType) {
  7503. case NODE_TYPE_ELEMENT: /* Element */
  7504. // use the node name: <directive>
  7505. addDirective(directives,
  7506. directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
  7507. // iterate over the attributes
  7508. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  7509. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  7510. var attrStartName = false;
  7511. var attrEndName = false;
  7512. attr = nAttrs[j];
  7513. name = attr.name;
  7514. value = trim(attr.value);
  7515. // support ngAttr attribute binding
  7516. ngAttrName = directiveNormalize(name);
  7517. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  7518. name = name.replace(PREFIX_REGEXP, '')
  7519. .substr(8).replace(/_(.)/g, function(match, letter) {
  7520. return letter.toUpperCase();
  7521. });
  7522. }
  7523. var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);
  7524. if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {
  7525. attrStartName = name;
  7526. attrEndName = name.substr(0, name.length - 5) + 'end';
  7527. name = name.substr(0, name.length - 6);
  7528. }
  7529. nName = directiveNormalize(name.toLowerCase());
  7530. attrsMap[nName] = name;
  7531. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  7532. attrs[nName] = value;
  7533. if (getBooleanAttrName(node, nName)) {
  7534. attrs[nName] = true; // presence means true
  7535. }
  7536. }
  7537. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  7538. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  7539. attrEndName);
  7540. }
  7541. // use class as directive
  7542. className = node.className;
  7543. if (isObject(className)) {
  7544. // Maybe SVGAnimatedString
  7545. className = className.animVal;
  7546. }
  7547. if (isString(className) && className !== '') {
  7548. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  7549. nName = directiveNormalize(match[2]);
  7550. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  7551. attrs[nName] = trim(match[3]);
  7552. }
  7553. className = className.substr(match.index + match[0].length);
  7554. }
  7555. }
  7556. break;
  7557. case NODE_TYPE_TEXT: /* Text Node */
  7558. if (msie === 11) {
  7559. // Workaround for #11781
  7560. while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {
  7561. node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
  7562. node.parentNode.removeChild(node.nextSibling);
  7563. }
  7564. }
  7565. addTextInterpolateDirective(directives, node.nodeValue);
  7566. break;
  7567. case NODE_TYPE_COMMENT: /* Comment */
  7568. try {
  7569. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  7570. if (match) {
  7571. nName = directiveNormalize(match[1]);
  7572. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  7573. attrs[nName] = trim(match[2]);
  7574. }
  7575. }
  7576. } catch (e) {
  7577. // turns out that under some circumstances IE9 throws errors when one attempts to read
  7578. // comment's node value.
  7579. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  7580. }
  7581. break;
  7582. }
  7583. directives.sort(byPriority);
  7584. return directives;
  7585. }
  7586. /**
  7587. * Given a node with an directive-start it collects all of the siblings until it finds
  7588. * directive-end.
  7589. * @param node
  7590. * @param attrStart
  7591. * @param attrEnd
  7592. * @returns {*}
  7593. */
  7594. function groupScan(node, attrStart, attrEnd) {
  7595. var nodes = [];
  7596. var depth = 0;
  7597. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  7598. do {
  7599. if (!node) {
  7600. throw $compileMinErr('uterdir',
  7601. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  7602. attrStart, attrEnd);
  7603. }
  7604. if (node.nodeType == NODE_TYPE_ELEMENT) {
  7605. if (node.hasAttribute(attrStart)) depth++;
  7606. if (node.hasAttribute(attrEnd)) depth--;
  7607. }
  7608. nodes.push(node);
  7609. node = node.nextSibling;
  7610. } while (depth > 0);
  7611. } else {
  7612. nodes.push(node);
  7613. }
  7614. return jqLite(nodes);
  7615. }
  7616. /**
  7617. * Wrapper for linking function which converts normal linking function into a grouped
  7618. * linking function.
  7619. * @param linkFn
  7620. * @param attrStart
  7621. * @param attrEnd
  7622. * @returns {Function}
  7623. */
  7624. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  7625. return function(scope, element, attrs, controllers, transcludeFn) {
  7626. element = groupScan(element[0], attrStart, attrEnd);
  7627. return linkFn(scope, element, attrs, controllers, transcludeFn);
  7628. };
  7629. }
  7630. /**
  7631. * A function generator that is used to support both eager and lazy compilation
  7632. * linking function.
  7633. * @param eager
  7634. * @param $compileNodes
  7635. * @param transcludeFn
  7636. * @param maxPriority
  7637. * @param ignoreDirective
  7638. * @param previousCompileContext
  7639. * @returns {Function}
  7640. */
  7641. function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
  7642. if (eager) {
  7643. return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  7644. }
  7645. var compiled;
  7646. return function() {
  7647. if (!compiled) {
  7648. compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  7649. // Null out all of these references in order to make them eligible for garbage collection
  7650. // since this is a potentially long lived closure
  7651. $compileNodes = transcludeFn = previousCompileContext = null;
  7652. }
  7653. return compiled.apply(this, arguments);
  7654. };
  7655. }
  7656. /**
  7657. * Once the directives have been collected, their compile functions are executed. This method
  7658. * is responsible for inlining directive templates as well as terminating the application
  7659. * of the directives if the terminal directive has been reached.
  7660. *
  7661. * @param {Array} directives Array of collected directives to execute their compile function.
  7662. * this needs to be pre-sorted by priority order.
  7663. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  7664. * @param {Object} templateAttrs The shared attribute function
  7665. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  7666. * scope argument is auto-generated to the new
  7667. * child of the transcluded parent scope.
  7668. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  7669. * argument has the root jqLite array so that we can replace nodes
  7670. * on it.
  7671. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  7672. * compiling the transclusion.
  7673. * @param {Array.<Function>} preLinkFns
  7674. * @param {Array.<Function>} postLinkFns
  7675. * @param {Object} previousCompileContext Context used for previous compilation of the current
  7676. * node
  7677. * @returns {Function} linkFn
  7678. */
  7679. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  7680. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  7681. previousCompileContext) {
  7682. previousCompileContext = previousCompileContext || {};
  7683. var terminalPriority = -Number.MAX_VALUE,
  7684. newScopeDirective = previousCompileContext.newScopeDirective,
  7685. controllerDirectives = previousCompileContext.controllerDirectives,
  7686. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  7687. templateDirective = previousCompileContext.templateDirective,
  7688. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  7689. hasTranscludeDirective = false,
  7690. hasTemplate = false,
  7691. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  7692. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  7693. directive,
  7694. directiveName,
  7695. $template,
  7696. replaceDirective = originalReplaceDirective,
  7697. childTranscludeFn = transcludeFn,
  7698. linkFn,
  7699. didScanForMultipleTransclusion = false,
  7700. mightHaveMultipleTransclusionError = false,
  7701. directiveValue;
  7702. // executes all directives on the current element
  7703. for (var i = 0, ii = directives.length; i < ii; i++) {
  7704. directive = directives[i];
  7705. var attrStart = directive.$$start;
  7706. var attrEnd = directive.$$end;
  7707. // collect multiblock sections
  7708. if (attrStart) {
  7709. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  7710. }
  7711. $template = undefined;
  7712. if (terminalPriority > directive.priority) {
  7713. break; // prevent further processing of directives
  7714. }
  7715. if (directiveValue = directive.scope) {
  7716. // skip the check for directives with async templates, we'll check the derived sync
  7717. // directive when the template arrives
  7718. if (!directive.templateUrl) {
  7719. if (isObject(directiveValue)) {
  7720. // This directive is trying to add an isolated scope.
  7721. // Check that there is no scope of any kind already
  7722. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  7723. directive, $compileNode);
  7724. newIsolateScopeDirective = directive;
  7725. } else {
  7726. // This directive is trying to add a child scope.
  7727. // Check that there is no isolated scope already
  7728. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  7729. $compileNode);
  7730. }
  7731. }
  7732. newScopeDirective = newScopeDirective || directive;
  7733. }
  7734. directiveName = directive.name;
  7735. // If we encounter a condition that can result in transclusion on the directive,
  7736. // then scan ahead in the remaining directives for others that may cause a multiple
  7737. // transclusion error to be thrown during the compilation process. If a matching directive
  7738. // is found, then we know that when we encounter a transcluded directive, we need to eagerly
  7739. // compile the `transclude` function rather than doing it lazily in order to throw
  7740. // exceptions at the correct time
  7741. if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))
  7742. || (directive.transclude && !directive.$$tlb))) {
  7743. var candidateDirective;
  7744. for (var scanningIndex = i + 1; candidateDirective = directives[scanningIndex++];) {
  7745. if ((candidateDirective.transclude && !candidateDirective.$$tlb)
  7746. || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {
  7747. mightHaveMultipleTransclusionError = true;
  7748. break;
  7749. }
  7750. }
  7751. didScanForMultipleTransclusion = true;
  7752. }
  7753. if (!directive.templateUrl && directive.controller) {
  7754. directiveValue = directive.controller;
  7755. controllerDirectives = controllerDirectives || createMap();
  7756. assertNoDuplicate("'" + directiveName + "' controller",
  7757. controllerDirectives[directiveName], directive, $compileNode);
  7758. controllerDirectives[directiveName] = directive;
  7759. }
  7760. if (directiveValue = directive.transclude) {
  7761. hasTranscludeDirective = true;
  7762. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  7763. // This option should only be used by directives that know how to safely handle element transclusion,
  7764. // where the transcluded nodes are added or replaced after linking.
  7765. if (!directive.$$tlb) {
  7766. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  7767. nonTlbTranscludeDirective = directive;
  7768. }
  7769. if (directiveValue == 'element') {
  7770. hasElementTranscludeDirective = true;
  7771. terminalPriority = directive.priority;
  7772. $template = $compileNode;
  7773. $compileNode = templateAttrs.$$element =
  7774. jqLite(document.createComment(' ' + directiveName + ': ' +
  7775. templateAttrs[directiveName] + ' '));
  7776. compileNode = $compileNode[0];
  7777. replaceWith(jqCollection, sliceArgs($template), compileNode);
  7778. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
  7779. replaceDirective && replaceDirective.name, {
  7780. // Don't pass in:
  7781. // - controllerDirectives - otherwise we'll create duplicates controllers
  7782. // - newIsolateScopeDirective or templateDirective - combining templates with
  7783. // element transclusion doesn't make sense.
  7784. //
  7785. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  7786. // on the same element more than once.
  7787. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  7788. });
  7789. } else {
  7790. var slots = createMap();
  7791. $template = jqLite(jqLiteClone(compileNode)).contents();
  7792. if (isObject(directiveValue)) {
  7793. // We have transclusion slots,
  7794. // collect them up, compile them and store their transclusion functions
  7795. $template = [];
  7796. var slotMap = createMap();
  7797. var filledSlots = createMap();
  7798. // Parse the element selectors
  7799. forEach(directiveValue, function(elementSelector, slotName) {
  7800. // If an element selector starts with a ? then it is optional
  7801. var optional = (elementSelector.charAt(0) === '?');
  7802. elementSelector = optional ? elementSelector.substring(1) : elementSelector;
  7803. slotMap[elementSelector] = slotName;
  7804. // We explicitly assign `null` since this implies that a slot was defined but not filled.
  7805. // Later when calling boundTransclusion functions with a slot name we only error if the
  7806. // slot is `undefined`
  7807. slots[slotName] = null;
  7808. // filledSlots contains `true` for all slots that are either optional or have been
  7809. // filled. This is used to check that we have not missed any required slots
  7810. filledSlots[slotName] = optional;
  7811. });
  7812. // Add the matching elements into their slot
  7813. forEach($compileNode.contents(), function(node) {
  7814. var slotName = slotMap[directiveNormalize(nodeName_(node))];
  7815. if (slotName) {
  7816. filledSlots[slotName] = true;
  7817. slots[slotName] = slots[slotName] || [];
  7818. slots[slotName].push(node);
  7819. } else {
  7820. $template.push(node);
  7821. }
  7822. });
  7823. // Check for required slots that were not filled
  7824. forEach(filledSlots, function(filled, slotName) {
  7825. if (!filled) {
  7826. throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
  7827. }
  7828. });
  7829. for (var slotName in slots) {
  7830. if (slots[slotName]) {
  7831. // Only define a transclusion function if the slot was filled
  7832. slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn);
  7833. }
  7834. }
  7835. }
  7836. $compileNode.empty(); // clear contents
  7837. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
  7838. undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
  7839. childTranscludeFn.$$slots = slots;
  7840. }
  7841. }
  7842. if (directive.template) {
  7843. hasTemplate = true;
  7844. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  7845. templateDirective = directive;
  7846. directiveValue = (isFunction(directive.template))
  7847. ? directive.template($compileNode, templateAttrs)
  7848. : directive.template;
  7849. directiveValue = denormalizeTemplate(directiveValue);
  7850. if (directive.replace) {
  7851. replaceDirective = directive;
  7852. if (jqLiteIsTextNode(directiveValue)) {
  7853. $template = [];
  7854. } else {
  7855. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  7856. }
  7857. compileNode = $template[0];
  7858. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7859. throw $compileMinErr('tplrt',
  7860. "Template for directive '{0}' must have exactly one root element. {1}",
  7861. directiveName, '');
  7862. }
  7863. replaceWith(jqCollection, $compileNode, compileNode);
  7864. var newTemplateAttrs = {$attr: {}};
  7865. // combine directives from the original node and from the template:
  7866. // - take the array of directives for this element
  7867. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  7868. // - collect directives from the template and sort them by priority
  7869. // - combine directives as: processed + template + unprocessed
  7870. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  7871. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  7872. if (newIsolateScopeDirective || newScopeDirective) {
  7873. // The original directive caused the current element to be replaced but this element
  7874. // also needs to have a new scope, so we need to tell the template directives
  7875. // that they would need to get their scope from further up, if they require transclusion
  7876. markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
  7877. }
  7878. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  7879. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  7880. ii = directives.length;
  7881. } else {
  7882. $compileNode.html(directiveValue);
  7883. }
  7884. }
  7885. if (directive.templateUrl) {
  7886. hasTemplate = true;
  7887. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  7888. templateDirective = directive;
  7889. if (directive.replace) {
  7890. replaceDirective = directive;
  7891. }
  7892. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  7893. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  7894. controllerDirectives: controllerDirectives,
  7895. newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
  7896. newIsolateScopeDirective: newIsolateScopeDirective,
  7897. templateDirective: templateDirective,
  7898. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  7899. });
  7900. ii = directives.length;
  7901. } else if (directive.compile) {
  7902. try {
  7903. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  7904. if (isFunction(linkFn)) {
  7905. addLinkFns(null, linkFn, attrStart, attrEnd);
  7906. } else if (linkFn) {
  7907. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  7908. }
  7909. } catch (e) {
  7910. $exceptionHandler(e, startingTag($compileNode));
  7911. }
  7912. }
  7913. if (directive.terminal) {
  7914. nodeLinkFn.terminal = true;
  7915. terminalPriority = Math.max(terminalPriority, directive.priority);
  7916. }
  7917. }
  7918. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  7919. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  7920. nodeLinkFn.templateOnThisElement = hasTemplate;
  7921. nodeLinkFn.transclude = childTranscludeFn;
  7922. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  7923. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  7924. return nodeLinkFn;
  7925. ////////////////////
  7926. function addLinkFns(pre, post, attrStart, attrEnd) {
  7927. if (pre) {
  7928. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  7929. pre.require = directive.require;
  7930. pre.directiveName = directiveName;
  7931. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  7932. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  7933. }
  7934. preLinkFns.push(pre);
  7935. }
  7936. if (post) {
  7937. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  7938. post.require = directive.require;
  7939. post.directiveName = directiveName;
  7940. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  7941. post = cloneAndAnnotateFn(post, {isolateScope: true});
  7942. }
  7943. postLinkFns.push(post);
  7944. }
  7945. }
  7946. function getControllers(directiveName, require, $element, elementControllers) {
  7947. var value;
  7948. if (isString(require)) {
  7949. var match = require.match(REQUIRE_PREFIX_REGEXP);
  7950. var name = require.substring(match[0].length);
  7951. var inheritType = match[1] || match[3];
  7952. var optional = match[2] === '?';
  7953. //If only parents then start at the parent element
  7954. if (inheritType === '^^') {
  7955. $element = $element.parent();
  7956. //Otherwise attempt getting the controller from elementControllers in case
  7957. //the element is transcluded (and has no data) and to avoid .data if possible
  7958. } else {
  7959. value = elementControllers && elementControllers[name];
  7960. value = value && value.instance;
  7961. }
  7962. if (!value) {
  7963. var dataName = '$' + name + 'Controller';
  7964. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  7965. }
  7966. if (!value && !optional) {
  7967. throw $compileMinErr('ctreq',
  7968. "Controller '{0}', required by directive '{1}', can't be found!",
  7969. name, directiveName);
  7970. }
  7971. } else if (isArray(require)) {
  7972. value = [];
  7973. for (var i = 0, ii = require.length; i < ii; i++) {
  7974. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  7975. }
  7976. } else if (isObject(require)) {
  7977. value = {};
  7978. forEach(require, function(controller, property) {
  7979. value[property] = getControllers(directiveName, controller, $element, elementControllers);
  7980. });
  7981. }
  7982. return value || null;
  7983. }
  7984. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
  7985. var elementControllers = createMap();
  7986. for (var controllerKey in controllerDirectives) {
  7987. var directive = controllerDirectives[controllerKey];
  7988. var locals = {
  7989. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  7990. $element: $element,
  7991. $attrs: attrs,
  7992. $transclude: transcludeFn
  7993. };
  7994. var controller = directive.controller;
  7995. if (controller == '@') {
  7996. controller = attrs[directive.name];
  7997. }
  7998. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  7999. // For directives with element transclusion the element is a comment,
  8000. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  8001. // clean up (http://bugs.jquery.com/ticket/8335).
  8002. // Instead, we save the controllers for the element in a local hash and attach to .data
  8003. // later, once we have the actual element.
  8004. elementControllers[directive.name] = controllerInstance;
  8005. if (!hasElementTranscludeDirective) {
  8006. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  8007. }
  8008. }
  8009. return elementControllers;
  8010. }
  8011. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  8012. var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
  8013. attrs, removeScopeBindingWatches, removeControllerBindingWatches;
  8014. if (compileNode === linkNode) {
  8015. attrs = templateAttrs;
  8016. $element = templateAttrs.$$element;
  8017. } else {
  8018. $element = jqLite(linkNode);
  8019. attrs = new Attributes($element, templateAttrs);
  8020. }
  8021. controllerScope = scope;
  8022. if (newIsolateScopeDirective) {
  8023. isolateScope = scope.$new(true);
  8024. } else if (newScopeDirective) {
  8025. controllerScope = scope.$parent;
  8026. }
  8027. if (boundTranscludeFn) {
  8028. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  8029. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  8030. transcludeFn = controllersBoundTransclude;
  8031. transcludeFn.$$boundTransclude = boundTranscludeFn;
  8032. // expose the slots on the `$transclude` function
  8033. transcludeFn.isSlotFilled = function(slotName) {
  8034. return !!boundTranscludeFn.$$slots[slotName];
  8035. };
  8036. }
  8037. if (controllerDirectives) {
  8038. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope);
  8039. }
  8040. if (newIsolateScopeDirective) {
  8041. // Initialize isolate scope bindings for new isolate scope directive.
  8042. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  8043. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  8044. compile.$$addScopeClass($element, true);
  8045. isolateScope.$$isolateBindings =
  8046. newIsolateScopeDirective.$$isolateBindings;
  8047. removeScopeBindingWatches = initializeDirectiveBindings(scope, attrs, isolateScope,
  8048. isolateScope.$$isolateBindings,
  8049. newIsolateScopeDirective);
  8050. if (removeScopeBindingWatches) {
  8051. isolateScope.$on('$destroy', removeScopeBindingWatches);
  8052. }
  8053. }
  8054. // Initialize bindToController bindings
  8055. for (var name in elementControllers) {
  8056. var controllerDirective = controllerDirectives[name];
  8057. var controller = elementControllers[name];
  8058. var bindings = controllerDirective.$$bindings.bindToController;
  8059. if (controller.identifier && bindings) {
  8060. removeControllerBindingWatches =
  8061. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8062. }
  8063. var controllerResult = controller();
  8064. if (controllerResult !== controller.instance) {
  8065. // If the controller constructor has a return value, overwrite the instance
  8066. // from setupControllers
  8067. controller.instance = controllerResult;
  8068. $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
  8069. removeControllerBindingWatches && removeControllerBindingWatches();
  8070. removeControllerBindingWatches =
  8071. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8072. }
  8073. }
  8074. // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy
  8075. forEach(controllerDirectives, function(controllerDirective, name) {
  8076. var require = controllerDirective.require;
  8077. if (controllerDirective.bindToController && !isArray(require) && isObject(require)) {
  8078. extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers));
  8079. }
  8080. });
  8081. // Trigger the `$onInit` method on all controllers that have one
  8082. forEach(elementControllers, function(controller) {
  8083. if (isFunction(controller.instance.$onInit)) {
  8084. controller.instance.$onInit();
  8085. }
  8086. });
  8087. // PRELINKING
  8088. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  8089. linkFn = preLinkFns[i];
  8090. invokeLinkFn(linkFn,
  8091. linkFn.isolateScope ? isolateScope : scope,
  8092. $element,
  8093. attrs,
  8094. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  8095. transcludeFn
  8096. );
  8097. }
  8098. // RECURSION
  8099. // We only pass the isolate scope, if the isolate directive has a template,
  8100. // otherwise the child elements do not belong to the isolate directive.
  8101. var scopeToChild = scope;
  8102. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  8103. scopeToChild = isolateScope;
  8104. }
  8105. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  8106. // POSTLINKING
  8107. for (i = postLinkFns.length - 1; i >= 0; i--) {
  8108. linkFn = postLinkFns[i];
  8109. invokeLinkFn(linkFn,
  8110. linkFn.isolateScope ? isolateScope : scope,
  8111. $element,
  8112. attrs,
  8113. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  8114. transcludeFn
  8115. );
  8116. }
  8117. // This is the function that is injected as `$transclude`.
  8118. // Note: all arguments are optional!
  8119. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
  8120. var transcludeControllers;
  8121. // No scope passed in:
  8122. if (!isScope(scope)) {
  8123. slotName = futureParentElement;
  8124. futureParentElement = cloneAttachFn;
  8125. cloneAttachFn = scope;
  8126. scope = undefined;
  8127. }
  8128. if (hasElementTranscludeDirective) {
  8129. transcludeControllers = elementControllers;
  8130. }
  8131. if (!futureParentElement) {
  8132. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  8133. }
  8134. if (slotName) {
  8135. // slotTranscludeFn can be one of three things:
  8136. // * a transclude function - a filled slot
  8137. // * `null` - an optional slot that was not filled
  8138. // * `undefined` - a slot that was not declared (i.e. invalid)
  8139. var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];
  8140. if (slotTranscludeFn) {
  8141. return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  8142. } else if (isUndefined(slotTranscludeFn)) {
  8143. throw $compileMinErr('noslot',
  8144. 'No parent directive that requires a transclusion with slot name "{0}". ' +
  8145. 'Element: {1}',
  8146. slotName, startingTag($element));
  8147. }
  8148. } else {
  8149. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  8150. }
  8151. }
  8152. }
  8153. }
  8154. // Depending upon the context in which a directive finds itself it might need to have a new isolated
  8155. // or child scope created. For instance:
  8156. // * if the directive has been pulled into a template because another directive with a higher priority
  8157. // asked for element transclusion
  8158. // * if the directive itself asks for transclusion but it is at the root of a template and the original
  8159. // element was replaced. See https://github.com/angular/angular.js/issues/12936
  8160. function markDirectiveScope(directives, isolateScope, newScope) {
  8161. for (var j = 0, jj = directives.length; j < jj; j++) {
  8162. directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
  8163. }
  8164. }
  8165. /**
  8166. * looks up the directive and decorates it with exception handling and proper parameters. We
  8167. * call this the boundDirective.
  8168. *
  8169. * @param {string} name name of the directive to look up.
  8170. * @param {string} location The directive must be found in specific format.
  8171. * String containing any of theses characters:
  8172. *
  8173. * * `E`: element name
  8174. * * `A': attribute
  8175. * * `C`: class
  8176. * * `M`: comment
  8177. * @returns {boolean} true if directive was added.
  8178. */
  8179. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  8180. endAttrName) {
  8181. if (name === ignoreDirective) return null;
  8182. var match = null;
  8183. if (hasDirectives.hasOwnProperty(name)) {
  8184. for (var directive, directives = $injector.get(name + Suffix),
  8185. i = 0, ii = directives.length; i < ii; i++) {
  8186. try {
  8187. directive = directives[i];
  8188. if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
  8189. directive.restrict.indexOf(location) != -1) {
  8190. if (startAttrName) {
  8191. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  8192. }
  8193. tDirectives.push(directive);
  8194. match = directive;
  8195. }
  8196. } catch (e) { $exceptionHandler(e); }
  8197. }
  8198. }
  8199. return match;
  8200. }
  8201. /**
  8202. * looks up the directive and returns true if it is a multi-element directive,
  8203. * and therefore requires DOM nodes between -start and -end markers to be grouped
  8204. * together.
  8205. *
  8206. * @param {string} name name of the directive to look up.
  8207. * @returns true if directive was registered as multi-element.
  8208. */
  8209. function directiveIsMultiElement(name) {
  8210. if (hasDirectives.hasOwnProperty(name)) {
  8211. for (var directive, directives = $injector.get(name + Suffix),
  8212. i = 0, ii = directives.length; i < ii; i++) {
  8213. directive = directives[i];
  8214. if (directive.multiElement) {
  8215. return true;
  8216. }
  8217. }
  8218. }
  8219. return false;
  8220. }
  8221. /**
  8222. * When the element is replaced with HTML template then the new attributes
  8223. * on the template need to be merged with the existing attributes in the DOM.
  8224. * The desired effect is to have both of the attributes present.
  8225. *
  8226. * @param {object} dst destination attributes (original DOM)
  8227. * @param {object} src source attributes (from the directive template)
  8228. */
  8229. function mergeTemplateAttributes(dst, src) {
  8230. var srcAttr = src.$attr,
  8231. dstAttr = dst.$attr,
  8232. $element = dst.$$element;
  8233. // reapply the old attributes to the new element
  8234. forEach(dst, function(value, key) {
  8235. if (key.charAt(0) != '$') {
  8236. if (src[key] && src[key] !== value) {
  8237. value += (key === 'style' ? ';' : ' ') + src[key];
  8238. }
  8239. dst.$set(key, value, true, srcAttr[key]);
  8240. }
  8241. });
  8242. // copy the new attributes on the old attrs object
  8243. forEach(src, function(value, key) {
  8244. if (key == 'class') {
  8245. safeAddClass($element, value);
  8246. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  8247. } else if (key == 'style') {
  8248. $element.attr('style', $element.attr('style') + ';' + value);
  8249. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  8250. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  8251. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  8252. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  8253. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  8254. dst[key] = value;
  8255. dstAttr[key] = srcAttr[key];
  8256. }
  8257. });
  8258. }
  8259. function compileTemplateUrl(directives, $compileNode, tAttrs,
  8260. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  8261. var linkQueue = [],
  8262. afterTemplateNodeLinkFn,
  8263. afterTemplateChildLinkFn,
  8264. beforeTemplateCompileNode = $compileNode[0],
  8265. origAsyncDirective = directives.shift(),
  8266. derivedSyncDirective = inherit(origAsyncDirective, {
  8267. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  8268. }),
  8269. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  8270. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  8271. : origAsyncDirective.templateUrl,
  8272. templateNamespace = origAsyncDirective.templateNamespace;
  8273. $compileNode.empty();
  8274. $templateRequest(templateUrl)
  8275. .then(function(content) {
  8276. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  8277. content = denormalizeTemplate(content);
  8278. if (origAsyncDirective.replace) {
  8279. if (jqLiteIsTextNode(content)) {
  8280. $template = [];
  8281. } else {
  8282. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  8283. }
  8284. compileNode = $template[0];
  8285. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  8286. throw $compileMinErr('tplrt',
  8287. "Template for directive '{0}' must have exactly one root element. {1}",
  8288. origAsyncDirective.name, templateUrl);
  8289. }
  8290. tempTemplateAttrs = {$attr: {}};
  8291. replaceWith($rootElement, $compileNode, compileNode);
  8292. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  8293. if (isObject(origAsyncDirective.scope)) {
  8294. // the original directive that caused the template to be loaded async required
  8295. // an isolate scope
  8296. markDirectiveScope(templateDirectives, true);
  8297. }
  8298. directives = templateDirectives.concat(directives);
  8299. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  8300. } else {
  8301. compileNode = beforeTemplateCompileNode;
  8302. $compileNode.html(content);
  8303. }
  8304. directives.unshift(derivedSyncDirective);
  8305. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  8306. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  8307. previousCompileContext);
  8308. forEach($rootElement, function(node, i) {
  8309. if (node == compileNode) {
  8310. $rootElement[i] = $compileNode[0];
  8311. }
  8312. });
  8313. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  8314. while (linkQueue.length) {
  8315. var scope = linkQueue.shift(),
  8316. beforeTemplateLinkNode = linkQueue.shift(),
  8317. linkRootElement = linkQueue.shift(),
  8318. boundTranscludeFn = linkQueue.shift(),
  8319. linkNode = $compileNode[0];
  8320. if (scope.$$destroyed) continue;
  8321. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  8322. var oldClasses = beforeTemplateLinkNode.className;
  8323. if (!(previousCompileContext.hasElementTranscludeDirective &&
  8324. origAsyncDirective.replace)) {
  8325. // it was cloned therefore we have to clone as well.
  8326. linkNode = jqLiteClone(compileNode);
  8327. }
  8328. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  8329. // Copy in CSS classes from original node
  8330. safeAddClass(jqLite(linkNode), oldClasses);
  8331. }
  8332. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  8333. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  8334. } else {
  8335. childBoundTranscludeFn = boundTranscludeFn;
  8336. }
  8337. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  8338. childBoundTranscludeFn);
  8339. }
  8340. linkQueue = null;
  8341. });
  8342. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  8343. var childBoundTranscludeFn = boundTranscludeFn;
  8344. if (scope.$$destroyed) return;
  8345. if (linkQueue) {
  8346. linkQueue.push(scope,
  8347. node,
  8348. rootElement,
  8349. childBoundTranscludeFn);
  8350. } else {
  8351. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  8352. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  8353. }
  8354. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  8355. }
  8356. };
  8357. }
  8358. /**
  8359. * Sorting function for bound directives.
  8360. */
  8361. function byPriority(a, b) {
  8362. var diff = b.priority - a.priority;
  8363. if (diff !== 0) return diff;
  8364. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  8365. return a.index - b.index;
  8366. }
  8367. function assertNoDuplicate(what, previousDirective, directive, element) {
  8368. function wrapModuleNameIfDefined(moduleName) {
  8369. return moduleName ?
  8370. (' (module: ' + moduleName + ')') :
  8371. '';
  8372. }
  8373. if (previousDirective) {
  8374. throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
  8375. previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
  8376. directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
  8377. }
  8378. }
  8379. function addTextInterpolateDirective(directives, text) {
  8380. var interpolateFn = $interpolate(text, true);
  8381. if (interpolateFn) {
  8382. directives.push({
  8383. priority: 0,
  8384. compile: function textInterpolateCompileFn(templateNode) {
  8385. var templateNodeParent = templateNode.parent(),
  8386. hasCompileParent = !!templateNodeParent.length;
  8387. // When transcluding a template that has bindings in the root
  8388. // we don't have a parent and thus need to add the class during linking fn.
  8389. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  8390. return function textInterpolateLinkFn(scope, node) {
  8391. var parent = node.parent();
  8392. if (!hasCompileParent) compile.$$addBindingClass(parent);
  8393. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  8394. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  8395. node[0].nodeValue = value;
  8396. });
  8397. };
  8398. }
  8399. });
  8400. }
  8401. }
  8402. function wrapTemplate(type, template) {
  8403. type = lowercase(type || 'html');
  8404. switch (type) {
  8405. case 'svg':
  8406. case 'math':
  8407. var wrapper = document.createElement('div');
  8408. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  8409. return wrapper.childNodes[0].childNodes;
  8410. default:
  8411. return template;
  8412. }
  8413. }
  8414. function getTrustedContext(node, attrNormalizedName) {
  8415. if (attrNormalizedName == "srcdoc") {
  8416. return $sce.HTML;
  8417. }
  8418. var tag = nodeName_(node);
  8419. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  8420. if (attrNormalizedName == "xlinkHref" ||
  8421. (tag == "form" && attrNormalizedName == "action") ||
  8422. (tag != "img" && (attrNormalizedName == "src" ||
  8423. attrNormalizedName == "ngSrc"))) {
  8424. return $sce.RESOURCE_URL;
  8425. }
  8426. }
  8427. function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  8428. var trustedContext = getTrustedContext(node, name);
  8429. allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
  8430. var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
  8431. // no interpolation found -> ignore
  8432. if (!interpolateFn) return;
  8433. if (name === "multiple" && nodeName_(node) === "select") {
  8434. throw $compileMinErr("selmulti",
  8435. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  8436. startingTag(node));
  8437. }
  8438. directives.push({
  8439. priority: 100,
  8440. compile: function() {
  8441. return {
  8442. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  8443. var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
  8444. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  8445. throw $compileMinErr('nodomevents',
  8446. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  8447. "ng- versions (such as ng-click instead of onclick) instead.");
  8448. }
  8449. // If the attribute has changed since last $interpolate()ed
  8450. var newValue = attr[name];
  8451. if (newValue !== value) {
  8452. // we need to interpolate again since the attribute value has been updated
  8453. // (e.g. by another directive's compile function)
  8454. // ensure unset/empty values make interpolateFn falsy
  8455. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  8456. value = newValue;
  8457. }
  8458. // if attribute was updated so that there is no interpolation going on we don't want to
  8459. // register any observers
  8460. if (!interpolateFn) return;
  8461. // initialize attr object so that it's ready in case we need the value for isolate
  8462. // scope initialization, otherwise the value would not be available from isolate
  8463. // directive's linking fn during linking phase
  8464. attr[name] = interpolateFn(scope);
  8465. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  8466. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  8467. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  8468. //special case for class attribute addition + removal
  8469. //so that class changes can tap into the animation
  8470. //hooks provided by the $animate service. Be sure to
  8471. //skip animations when the first digest occurs (when
  8472. //both the new and the old values are the same) since
  8473. //the CSS classes are the non-interpolated values
  8474. if (name === 'class' && newValue != oldValue) {
  8475. attr.$updateClass(newValue, oldValue);
  8476. } else {
  8477. attr.$set(name, newValue);
  8478. }
  8479. });
  8480. }
  8481. };
  8482. }
  8483. });
  8484. }
  8485. /**
  8486. * This is a special jqLite.replaceWith, which can replace items which
  8487. * have no parents, provided that the containing jqLite collection is provided.
  8488. *
  8489. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  8490. * in the root of the tree.
  8491. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  8492. * the shell, but replace its DOM node reference.
  8493. * @param {Node} newNode The new DOM node.
  8494. */
  8495. function replaceWith($rootElement, elementsToRemove, newNode) {
  8496. var firstElementToRemove = elementsToRemove[0],
  8497. removeCount = elementsToRemove.length,
  8498. parent = firstElementToRemove.parentNode,
  8499. i, ii;
  8500. if ($rootElement) {
  8501. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  8502. if ($rootElement[i] == firstElementToRemove) {
  8503. $rootElement[i++] = newNode;
  8504. for (var j = i, j2 = j + removeCount - 1,
  8505. jj = $rootElement.length;
  8506. j < jj; j++, j2++) {
  8507. if (j2 < jj) {
  8508. $rootElement[j] = $rootElement[j2];
  8509. } else {
  8510. delete $rootElement[j];
  8511. }
  8512. }
  8513. $rootElement.length -= removeCount - 1;
  8514. // If the replaced element is also the jQuery .context then replace it
  8515. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  8516. // http://api.jquery.com/context/
  8517. if ($rootElement.context === firstElementToRemove) {
  8518. $rootElement.context = newNode;
  8519. }
  8520. break;
  8521. }
  8522. }
  8523. }
  8524. if (parent) {
  8525. parent.replaceChild(newNode, firstElementToRemove);
  8526. }
  8527. // Append all the `elementsToRemove` to a fragment. This will...
  8528. // - remove them from the DOM
  8529. // - allow them to still be traversed with .nextSibling
  8530. // - allow a single fragment.qSA to fetch all elements being removed
  8531. var fragment = document.createDocumentFragment();
  8532. for (i = 0; i < removeCount; i++) {
  8533. fragment.appendChild(elementsToRemove[i]);
  8534. }
  8535. if (jqLite.hasData(firstElementToRemove)) {
  8536. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  8537. // data here because there's no public interface in jQuery to do that and copying over
  8538. // event listeners (which is the main use of private data) wouldn't work anyway.
  8539. jqLite.data(newNode, jqLite.data(firstElementToRemove));
  8540. // Remove $destroy event listeners from `firstElementToRemove`
  8541. jqLite(firstElementToRemove).off('$destroy');
  8542. }
  8543. // Cleanup any data/listeners on the elements and children.
  8544. // This includes invoking the $destroy event on any elements with listeners.
  8545. jqLite.cleanData(fragment.querySelectorAll('*'));
  8546. // Update the jqLite collection to only contain the `newNode`
  8547. for (i = 1; i < removeCount; i++) {
  8548. delete elementsToRemove[i];
  8549. }
  8550. elementsToRemove[0] = newNode;
  8551. elementsToRemove.length = 1;
  8552. }
  8553. function cloneAndAnnotateFn(fn, annotation) {
  8554. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  8555. }
  8556. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  8557. try {
  8558. linkFn(scope, $element, attrs, controllers, transcludeFn);
  8559. } catch (e) {
  8560. $exceptionHandler(e, startingTag($element));
  8561. }
  8562. }
  8563. // Set up $watches for isolate scope and controller bindings. This process
  8564. // only occurs for isolate scopes and new scopes with controllerAs.
  8565. function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
  8566. var removeWatchCollection = [];
  8567. forEach(bindings, function(definition, scopeName) {
  8568. var attrName = definition.attrName,
  8569. optional = definition.optional,
  8570. mode = definition.mode, // @, =, or &
  8571. lastValue,
  8572. parentGet, parentSet, compare, removeWatch;
  8573. switch (mode) {
  8574. case '@':
  8575. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  8576. destination[scopeName] = attrs[attrName] = void 0;
  8577. }
  8578. attrs.$observe(attrName, function(value) {
  8579. if (isString(value)) {
  8580. destination[scopeName] = value;
  8581. }
  8582. });
  8583. attrs.$$observers[attrName].$$scope = scope;
  8584. lastValue = attrs[attrName];
  8585. if (isString(lastValue)) {
  8586. // If the attribute has been provided then we trigger an interpolation to ensure
  8587. // the value is there for use in the link fn
  8588. destination[scopeName] = $interpolate(lastValue)(scope);
  8589. } else if (isBoolean(lastValue)) {
  8590. // If the attributes is one of the BOOLEAN_ATTR then Angular will have converted
  8591. // the value to boolean rather than a string, so we special case this situation
  8592. destination[scopeName] = lastValue;
  8593. }
  8594. break;
  8595. case '=':
  8596. if (!hasOwnProperty.call(attrs, attrName)) {
  8597. if (optional) break;
  8598. attrs[attrName] = void 0;
  8599. }
  8600. if (optional && !attrs[attrName]) break;
  8601. parentGet = $parse(attrs[attrName]);
  8602. if (parentGet.literal) {
  8603. compare = equals;
  8604. } else {
  8605. compare = function(a, b) { return a === b || (a !== a && b !== b); };
  8606. }
  8607. parentSet = parentGet.assign || function() {
  8608. // reset the change, or we will throw this exception on every $digest
  8609. lastValue = destination[scopeName] = parentGet(scope);
  8610. throw $compileMinErr('nonassign',
  8611. "Expression '{0}' in attribute '{1}' used with directive '{2}' is non-assignable!",
  8612. attrs[attrName], attrName, directive.name);
  8613. };
  8614. lastValue = destination[scopeName] = parentGet(scope);
  8615. var parentValueWatch = function parentValueWatch(parentValue) {
  8616. if (!compare(parentValue, destination[scopeName])) {
  8617. // we are out of sync and need to copy
  8618. if (!compare(parentValue, lastValue)) {
  8619. // parent changed and it has precedence
  8620. destination[scopeName] = parentValue;
  8621. } else {
  8622. // if the parent can be assigned then do so
  8623. parentSet(scope, parentValue = destination[scopeName]);
  8624. }
  8625. }
  8626. return lastValue = parentValue;
  8627. };
  8628. parentValueWatch.$stateful = true;
  8629. if (definition.collection) {
  8630. removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  8631. } else {
  8632. removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  8633. }
  8634. removeWatchCollection.push(removeWatch);
  8635. break;
  8636. case '<':
  8637. if (!hasOwnProperty.call(attrs, attrName)) {
  8638. if (optional) break;
  8639. attrs[attrName] = void 0;
  8640. }
  8641. if (optional && !attrs[attrName]) break;
  8642. parentGet = $parse(attrs[attrName]);
  8643. destination[scopeName] = parentGet(scope);
  8644. removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newParentValue) {
  8645. destination[scopeName] = newParentValue;
  8646. }, parentGet.literal);
  8647. removeWatchCollection.push(removeWatch);
  8648. break;
  8649. case '&':
  8650. // Don't assign Object.prototype method to scope
  8651. parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
  8652. // Don't assign noop to destination if expression is not valid
  8653. if (parentGet === noop && optional) break;
  8654. destination[scopeName] = function(locals) {
  8655. return parentGet(scope, locals);
  8656. };
  8657. break;
  8658. }
  8659. });
  8660. return removeWatchCollection.length && function removeWatches() {
  8661. for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
  8662. removeWatchCollection[i]();
  8663. }
  8664. };
  8665. }
  8666. }];
  8667. }
  8668. var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
  8669. /**
  8670. * Converts all accepted directives format into proper directive name.
  8671. * @param name Name to normalize
  8672. */
  8673. function directiveNormalize(name) {
  8674. return camelCase(name.replace(PREFIX_REGEXP, ''));
  8675. }
  8676. /**
  8677. * @ngdoc type
  8678. * @name $compile.directive.Attributes
  8679. *
  8680. * @description
  8681. * A shared object between directive compile / linking functions which contains normalized DOM
  8682. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  8683. * needed since all of these are treated as equivalent in Angular:
  8684. *
  8685. * ```
  8686. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  8687. * ```
  8688. */
  8689. /**
  8690. * @ngdoc property
  8691. * @name $compile.directive.Attributes#$attr
  8692. *
  8693. * @description
  8694. * A map of DOM element attribute names to the normalized name. This is
  8695. * needed to do reverse lookup from normalized name back to actual name.
  8696. */
  8697. /**
  8698. * @ngdoc method
  8699. * @name $compile.directive.Attributes#$set
  8700. * @kind function
  8701. *
  8702. * @description
  8703. * Set DOM element attribute value.
  8704. *
  8705. *
  8706. * @param {string} name Normalized element attribute name of the property to modify. The name is
  8707. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  8708. * property to the original name.
  8709. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  8710. */
  8711. /**
  8712. * Closure compiler type information
  8713. */
  8714. function nodesetLinkingFn(
  8715. /* angular.Scope */ scope,
  8716. /* NodeList */ nodeList,
  8717. /* Element */ rootElement,
  8718. /* function(Function) */ boundTranscludeFn
  8719. ) {}
  8720. function directiveLinkingFn(
  8721. /* nodesetLinkingFn */ nodesetLinkingFn,
  8722. /* angular.Scope */ scope,
  8723. /* Node */ node,
  8724. /* Element */ rootElement,
  8725. /* function(Function) */ boundTranscludeFn
  8726. ) {}
  8727. function tokenDifference(str1, str2) {
  8728. var values = '',
  8729. tokens1 = str1.split(/\s+/),
  8730. tokens2 = str2.split(/\s+/);
  8731. outer:
  8732. for (var i = 0; i < tokens1.length; i++) {
  8733. var token = tokens1[i];
  8734. for (var j = 0; j < tokens2.length; j++) {
  8735. if (token == tokens2[j]) continue outer;
  8736. }
  8737. values += (values.length > 0 ? ' ' : '') + token;
  8738. }
  8739. return values;
  8740. }
  8741. function removeComments(jqNodes) {
  8742. jqNodes = jqLite(jqNodes);
  8743. var i = jqNodes.length;
  8744. if (i <= 1) {
  8745. return jqNodes;
  8746. }
  8747. while (i--) {
  8748. var node = jqNodes[i];
  8749. if (node.nodeType === NODE_TYPE_COMMENT) {
  8750. splice.call(jqNodes, i, 1);
  8751. }
  8752. }
  8753. return jqNodes;
  8754. }
  8755. var $controllerMinErr = minErr('$controller');
  8756. var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/;
  8757. function identifierForController(controller, ident) {
  8758. if (ident && isString(ident)) return ident;
  8759. if (isString(controller)) {
  8760. var match = CNTRL_REG.exec(controller);
  8761. if (match) return match[3];
  8762. }
  8763. }
  8764. /**
  8765. * @ngdoc provider
  8766. * @name $controllerProvider
  8767. * @description
  8768. * The {@link ng.$controller $controller service} is used by Angular to create new
  8769. * controllers.
  8770. *
  8771. * This provider allows controller registration via the
  8772. * {@link ng.$controllerProvider#register register} method.
  8773. */
  8774. function $ControllerProvider() {
  8775. var controllers = {},
  8776. globals = false;
  8777. /**
  8778. * @ngdoc method
  8779. * @name $controllerProvider#register
  8780. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  8781. * the names and the values are the constructors.
  8782. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  8783. * annotations in the array notation).
  8784. */
  8785. this.register = function(name, constructor) {
  8786. assertNotHasOwnProperty(name, 'controller');
  8787. if (isObject(name)) {
  8788. extend(controllers, name);
  8789. } else {
  8790. controllers[name] = constructor;
  8791. }
  8792. };
  8793. /**
  8794. * @ngdoc method
  8795. * @name $controllerProvider#allowGlobals
  8796. * @description If called, allows `$controller` to find controller constructors on `window`
  8797. */
  8798. this.allowGlobals = function() {
  8799. globals = true;
  8800. };
  8801. this.$get = ['$injector', '$window', function($injector, $window) {
  8802. /**
  8803. * @ngdoc service
  8804. * @name $controller
  8805. * @requires $injector
  8806. *
  8807. * @param {Function|string} constructor If called with a function then it's considered to be the
  8808. * controller constructor function. Otherwise it's considered to be a string which is used
  8809. * to retrieve the controller constructor using the following steps:
  8810. *
  8811. * * check if a controller with given name is registered via `$controllerProvider`
  8812. * * check if evaluating the string on the current scope returns a constructor
  8813. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  8814. * `window` object (not recommended)
  8815. *
  8816. * The string can use the `controller as property` syntax, where the controller instance is published
  8817. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  8818. * to work correctly.
  8819. *
  8820. * @param {Object} locals Injection locals for Controller.
  8821. * @return {Object} Instance of given controller.
  8822. *
  8823. * @description
  8824. * `$controller` service is responsible for instantiating controllers.
  8825. *
  8826. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  8827. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  8828. */
  8829. return function(expression, locals, later, ident) {
  8830. // PRIVATE API:
  8831. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  8832. // If true, $controller will allocate the object with the correct
  8833. // prototype chain, but will not invoke the controller until a returned
  8834. // callback is invoked.
  8835. // param `ident` --- An optional label which overrides the label parsed from the controller
  8836. // expression, if any.
  8837. var instance, match, constructor, identifier;
  8838. later = later === true;
  8839. if (ident && isString(ident)) {
  8840. identifier = ident;
  8841. }
  8842. if (isString(expression)) {
  8843. match = expression.match(CNTRL_REG);
  8844. if (!match) {
  8845. throw $controllerMinErr('ctrlfmt',
  8846. "Badly formed controller string '{0}'. " +
  8847. "Must match `__name__ as __id__` or `__name__`.", expression);
  8848. }
  8849. constructor = match[1],
  8850. identifier = identifier || match[3];
  8851. expression = controllers.hasOwnProperty(constructor)
  8852. ? controllers[constructor]
  8853. : getter(locals.$scope, constructor, true) ||
  8854. (globals ? getter($window, constructor, true) : undefined);
  8855. assertArgFn(expression, constructor, true);
  8856. }
  8857. if (later) {
  8858. // Instantiate controller later:
  8859. // This machinery is used to create an instance of the object before calling the
  8860. // controller's constructor itself.
  8861. //
  8862. // This allows properties to be added to the controller before the constructor is
  8863. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  8864. //
  8865. // This feature is not intended for use by applications, and is thus not documented
  8866. // publicly.
  8867. // Object creation: http://jsperf.com/create-constructor/2
  8868. var controllerPrototype = (isArray(expression) ?
  8869. expression[expression.length - 1] : expression).prototype;
  8870. instance = Object.create(controllerPrototype || null);
  8871. if (identifier) {
  8872. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8873. }
  8874. var instantiate;
  8875. return instantiate = extend(function() {
  8876. var result = $injector.invoke(expression, instance, locals, constructor);
  8877. if (result !== instance && (isObject(result) || isFunction(result))) {
  8878. instance = result;
  8879. if (identifier) {
  8880. // If result changed, re-assign controllerAs value to scope.
  8881. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8882. }
  8883. }
  8884. return instance;
  8885. }, {
  8886. instance: instance,
  8887. identifier: identifier
  8888. });
  8889. }
  8890. instance = $injector.instantiate(expression, locals, constructor);
  8891. if (identifier) {
  8892. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8893. }
  8894. return instance;
  8895. };
  8896. function addIdentifier(locals, identifier, instance, name) {
  8897. if (!(locals && isObject(locals.$scope))) {
  8898. throw minErr('$controller')('noscp',
  8899. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  8900. name, identifier);
  8901. }
  8902. locals.$scope[identifier] = instance;
  8903. }
  8904. }];
  8905. }
  8906. /**
  8907. * @ngdoc service
  8908. * @name $document
  8909. * @requires $window
  8910. *
  8911. * @description
  8912. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  8913. *
  8914. * @example
  8915. <example module="documentExample">
  8916. <file name="index.html">
  8917. <div ng-controller="ExampleController">
  8918. <p>$document title: <b ng-bind="title"></b></p>
  8919. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  8920. </div>
  8921. </file>
  8922. <file name="script.js">
  8923. angular.module('documentExample', [])
  8924. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  8925. $scope.title = $document[0].title;
  8926. $scope.windowTitle = angular.element(window.document)[0].title;
  8927. }]);
  8928. </file>
  8929. </example>
  8930. */
  8931. function $DocumentProvider() {
  8932. this.$get = ['$window', function(window) {
  8933. return jqLite(window.document);
  8934. }];
  8935. }
  8936. /**
  8937. * @ngdoc service
  8938. * @name $exceptionHandler
  8939. * @requires ng.$log
  8940. *
  8941. * @description
  8942. * Any uncaught exception in angular expressions is delegated to this service.
  8943. * The default implementation simply delegates to `$log.error` which logs it into
  8944. * the browser console.
  8945. *
  8946. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  8947. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  8948. *
  8949. * ## Example:
  8950. *
  8951. * ```js
  8952. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
  8953. * return function(exception, cause) {
  8954. * exception.message += ' (caused by "' + cause + '")';
  8955. * throw exception;
  8956. * };
  8957. * });
  8958. * ```
  8959. *
  8960. * This example will override the normal action of `$exceptionHandler`, to make angular
  8961. * exceptions fail hard when they happen, instead of just logging to the console.
  8962. *
  8963. * <hr />
  8964. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  8965. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  8966. * (unless executed during a digest).
  8967. *
  8968. * If you wish, you can manually delegate exceptions, e.g.
  8969. * `try { ... } catch(e) { $exceptionHandler(e); }`
  8970. *
  8971. * @param {Error} exception Exception associated with the error.
  8972. * @param {string=} cause optional information about the context in which
  8973. * the error was thrown.
  8974. *
  8975. */
  8976. function $ExceptionHandlerProvider() {
  8977. this.$get = ['$log', function($log) {
  8978. return function(exception, cause) {
  8979. $log.error.apply($log, arguments);
  8980. };
  8981. }];
  8982. }
  8983. var $$ForceReflowProvider = function() {
  8984. this.$get = ['$document', function($document) {
  8985. return function(domNode) {
  8986. //the line below will force the browser to perform a repaint so
  8987. //that all the animated elements within the animation frame will
  8988. //be properly updated and drawn on screen. This is required to
  8989. //ensure that the preparation animation is properly flushed so that
  8990. //the active state picks up from there. DO NOT REMOVE THIS LINE.
  8991. //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
  8992. //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
  8993. //WILL TAKE YEARS AWAY FROM YOUR LIFE.
  8994. if (domNode) {
  8995. if (!domNode.nodeType && domNode instanceof jqLite) {
  8996. domNode = domNode[0];
  8997. }
  8998. } else {
  8999. domNode = $document[0].body;
  9000. }
  9001. return domNode.offsetWidth + 1;
  9002. };
  9003. }];
  9004. };
  9005. var APPLICATION_JSON = 'application/json';
  9006. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  9007. var JSON_START = /^\[|^\{(?!\{)/;
  9008. var JSON_ENDS = {
  9009. '[': /]$/,
  9010. '{': /}$/
  9011. };
  9012. var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
  9013. var $httpMinErr = minErr('$http');
  9014. var $httpMinErrLegacyFn = function(method) {
  9015. return function() {
  9016. throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method);
  9017. };
  9018. };
  9019. function serializeValue(v) {
  9020. if (isObject(v)) {
  9021. return isDate(v) ? v.toISOString() : toJson(v);
  9022. }
  9023. return v;
  9024. }
  9025. function $HttpParamSerializerProvider() {
  9026. /**
  9027. * @ngdoc service
  9028. * @name $httpParamSerializer
  9029. * @description
  9030. *
  9031. * Default {@link $http `$http`} params serializer that converts objects to strings
  9032. * according to the following rules:
  9033. *
  9034. * * `{'foo': 'bar'}` results in `foo=bar`
  9035. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  9036. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  9037. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
  9038. *
  9039. * Note that serializer will sort the request parameters alphabetically.
  9040. * */
  9041. this.$get = function() {
  9042. return function ngParamSerializer(params) {
  9043. if (!params) return '';
  9044. var parts = [];
  9045. forEachSorted(params, function(value, key) {
  9046. if (value === null || isUndefined(value)) return;
  9047. if (isArray(value)) {
  9048. forEach(value, function(v, k) {
  9049. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  9050. });
  9051. } else {
  9052. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  9053. }
  9054. });
  9055. return parts.join('&');
  9056. };
  9057. };
  9058. }
  9059. function $HttpParamSerializerJQLikeProvider() {
  9060. /**
  9061. * @ngdoc service
  9062. * @name $httpParamSerializerJQLike
  9063. * @description
  9064. *
  9065. * Alternative {@link $http `$http`} params serializer that follows
  9066. * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  9067. * The serializer will also sort the params alphabetically.
  9068. *
  9069. * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
  9070. *
  9071. * ```js
  9072. * $http({
  9073. * url: myUrl,
  9074. * method: 'GET',
  9075. * params: myParams,
  9076. * paramSerializer: '$httpParamSerializerJQLike'
  9077. * });
  9078. * ```
  9079. *
  9080. * It is also possible to set it as the default `paramSerializer` in the
  9081. * {@link $httpProvider#defaults `$httpProvider`}.
  9082. *
  9083. * Additionally, you can inject the serializer and use it explicitly, for example to serialize
  9084. * form data for submission:
  9085. *
  9086. * ```js
  9087. * .controller(function($http, $httpParamSerializerJQLike) {
  9088. * //...
  9089. *
  9090. * $http({
  9091. * url: myUrl,
  9092. * method: 'POST',
  9093. * data: $httpParamSerializerJQLike(myData),
  9094. * headers: {
  9095. * 'Content-Type': 'application/x-www-form-urlencoded'
  9096. * }
  9097. * });
  9098. *
  9099. * });
  9100. * ```
  9101. *
  9102. * */
  9103. this.$get = function() {
  9104. return function jQueryLikeParamSerializer(params) {
  9105. if (!params) return '';
  9106. var parts = [];
  9107. serialize(params, '', true);
  9108. return parts.join('&');
  9109. function serialize(toSerialize, prefix, topLevel) {
  9110. if (toSerialize === null || isUndefined(toSerialize)) return;
  9111. if (isArray(toSerialize)) {
  9112. forEach(toSerialize, function(value, index) {
  9113. serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
  9114. });
  9115. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  9116. forEachSorted(toSerialize, function(value, key) {
  9117. serialize(value, prefix +
  9118. (topLevel ? '' : '[') +
  9119. key +
  9120. (topLevel ? '' : ']'));
  9121. });
  9122. } else {
  9123. parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
  9124. }
  9125. }
  9126. };
  9127. };
  9128. }
  9129. function defaultHttpResponseTransform(data, headers) {
  9130. if (isString(data)) {
  9131. // Strip json vulnerability protection prefix and trim whitespace
  9132. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  9133. if (tempData) {
  9134. var contentType = headers('Content-Type');
  9135. if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
  9136. data = fromJson(tempData);
  9137. }
  9138. }
  9139. }
  9140. return data;
  9141. }
  9142. function isJsonLike(str) {
  9143. var jsonStart = str.match(JSON_START);
  9144. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  9145. }
  9146. /**
  9147. * Parse headers into key value object
  9148. *
  9149. * @param {string} headers Raw headers as a string
  9150. * @returns {Object} Parsed headers as key value object
  9151. */
  9152. function parseHeaders(headers) {
  9153. var parsed = createMap(), i;
  9154. function fillInParsed(key, val) {
  9155. if (key) {
  9156. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  9157. }
  9158. }
  9159. if (isString(headers)) {
  9160. forEach(headers.split('\n'), function(line) {
  9161. i = line.indexOf(':');
  9162. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  9163. });
  9164. } else if (isObject(headers)) {
  9165. forEach(headers, function(headerVal, headerKey) {
  9166. fillInParsed(lowercase(headerKey), trim(headerVal));
  9167. });
  9168. }
  9169. return parsed;
  9170. }
  9171. /**
  9172. * Returns a function that provides access to parsed headers.
  9173. *
  9174. * Headers are lazy parsed when first requested.
  9175. * @see parseHeaders
  9176. *
  9177. * @param {(string|Object)} headers Headers to provide access to.
  9178. * @returns {function(string=)} Returns a getter function which if called with:
  9179. *
  9180. * - if called with single an argument returns a single header value or null
  9181. * - if called with no arguments returns an object containing all headers.
  9182. */
  9183. function headersGetter(headers) {
  9184. var headersObj;
  9185. return function(name) {
  9186. if (!headersObj) headersObj = parseHeaders(headers);
  9187. if (name) {
  9188. var value = headersObj[lowercase(name)];
  9189. if (value === void 0) {
  9190. value = null;
  9191. }
  9192. return value;
  9193. }
  9194. return headersObj;
  9195. };
  9196. }
  9197. /**
  9198. * Chain all given functions
  9199. *
  9200. * This function is used for both request and response transforming
  9201. *
  9202. * @param {*} data Data to transform.
  9203. * @param {function(string=)} headers HTTP headers getter fn.
  9204. * @param {number} status HTTP status code of the response.
  9205. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  9206. * @returns {*} Transformed data.
  9207. */
  9208. function transformData(data, headers, status, fns) {
  9209. if (isFunction(fns)) {
  9210. return fns(data, headers, status);
  9211. }
  9212. forEach(fns, function(fn) {
  9213. data = fn(data, headers, status);
  9214. });
  9215. return data;
  9216. }
  9217. function isSuccess(status) {
  9218. return 200 <= status && status < 300;
  9219. }
  9220. /**
  9221. * @ngdoc provider
  9222. * @name $httpProvider
  9223. * @description
  9224. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  9225. * */
  9226. function $HttpProvider() {
  9227. /**
  9228. * @ngdoc property
  9229. * @name $httpProvider#defaults
  9230. * @description
  9231. *
  9232. * Object containing default values for all {@link ng.$http $http} requests.
  9233. *
  9234. * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
  9235. * that will provide the cache for all requests who set their `cache` property to `true`.
  9236. * If you set the `defaults.cache = false` then only requests that specify their own custom
  9237. * cache object will be cached. See {@link $http#caching $http Caching} for more information.
  9238. *
  9239. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  9240. * Defaults value is `'XSRF-TOKEN'`.
  9241. *
  9242. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  9243. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  9244. *
  9245. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  9246. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  9247. * setting default headers.
  9248. * - **`defaults.headers.common`**
  9249. * - **`defaults.headers.post`**
  9250. * - **`defaults.headers.put`**
  9251. * - **`defaults.headers.patch`**
  9252. *
  9253. *
  9254. * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
  9255. * used to the prepare string representation of request parameters (specified as an object).
  9256. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  9257. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  9258. *
  9259. **/
  9260. var defaults = this.defaults = {
  9261. // transform incoming response data
  9262. transformResponse: [defaultHttpResponseTransform],
  9263. // transform outgoing request data
  9264. transformRequest: [function(d) {
  9265. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  9266. }],
  9267. // default headers
  9268. headers: {
  9269. common: {
  9270. 'Accept': 'application/json, text/plain, */*'
  9271. },
  9272. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  9273. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  9274. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  9275. },
  9276. xsrfCookieName: 'XSRF-TOKEN',
  9277. xsrfHeaderName: 'X-XSRF-TOKEN',
  9278. paramSerializer: '$httpParamSerializer'
  9279. };
  9280. var useApplyAsync = false;
  9281. /**
  9282. * @ngdoc method
  9283. * @name $httpProvider#useApplyAsync
  9284. * @description
  9285. *
  9286. * Configure $http service to combine processing of multiple http responses received at around
  9287. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  9288. * significant performance improvement for bigger applications that make many HTTP requests
  9289. * concurrently (common during application bootstrap).
  9290. *
  9291. * Defaults to false. If no value is specified, returns the current configured value.
  9292. *
  9293. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  9294. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  9295. * to load and share the same digest cycle.
  9296. *
  9297. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  9298. * otherwise, returns the current configured value.
  9299. **/
  9300. this.useApplyAsync = function(value) {
  9301. if (isDefined(value)) {
  9302. useApplyAsync = !!value;
  9303. return this;
  9304. }
  9305. return useApplyAsync;
  9306. };
  9307. var useLegacyPromise = true;
  9308. /**
  9309. * @ngdoc method
  9310. * @name $httpProvider#useLegacyPromiseExtensions
  9311. * @description
  9312. *
  9313. * Configure `$http` service to return promises without the shorthand methods `success` and `error`.
  9314. * This should be used to make sure that applications work without these methods.
  9315. *
  9316. * Defaults to true. If no value is specified, returns the current configured value.
  9317. *
  9318. * @param {boolean=} value If true, `$http` will return a promise with the deprecated legacy `success` and `error` methods.
  9319. *
  9320. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  9321. * otherwise, returns the current configured value.
  9322. **/
  9323. this.useLegacyPromiseExtensions = function(value) {
  9324. if (isDefined(value)) {
  9325. useLegacyPromise = !!value;
  9326. return this;
  9327. }
  9328. return useLegacyPromise;
  9329. };
  9330. /**
  9331. * @ngdoc property
  9332. * @name $httpProvider#interceptors
  9333. * @description
  9334. *
  9335. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  9336. * pre-processing of request or postprocessing of responses.
  9337. *
  9338. * These service factories are ordered by request, i.e. they are applied in the same order as the
  9339. * array, on request, but reverse order, on response.
  9340. *
  9341. * {@link ng.$http#interceptors Interceptors detailed info}
  9342. **/
  9343. var interceptorFactories = this.interceptors = [];
  9344. this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
  9345. function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
  9346. var defaultCache = $cacheFactory('$http');
  9347. /**
  9348. * Make sure that default param serializer is exposed as a function
  9349. */
  9350. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  9351. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  9352. /**
  9353. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  9354. * The reversal is needed so that we can build up the interception chain around the
  9355. * server request.
  9356. */
  9357. var reversedInterceptors = [];
  9358. forEach(interceptorFactories, function(interceptorFactory) {
  9359. reversedInterceptors.unshift(isString(interceptorFactory)
  9360. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  9361. });
  9362. /**
  9363. * @ngdoc service
  9364. * @kind function
  9365. * @name $http
  9366. * @requires ng.$httpBackend
  9367. * @requires $cacheFactory
  9368. * @requires $rootScope
  9369. * @requires $q
  9370. * @requires $injector
  9371. *
  9372. * @description
  9373. * The `$http` service is a core Angular service that facilitates communication with the remote
  9374. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  9375. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  9376. *
  9377. * For unit testing applications that use `$http` service, see
  9378. * {@link ngMock.$httpBackend $httpBackend mock}.
  9379. *
  9380. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  9381. * $resource} service.
  9382. *
  9383. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  9384. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  9385. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  9386. *
  9387. *
  9388. * ## General usage
  9389. * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
  9390. * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
  9391. *
  9392. * ```js
  9393. * // Simple GET request example:
  9394. * $http({
  9395. * method: 'GET',
  9396. * url: '/someUrl'
  9397. * }).then(function successCallback(response) {
  9398. * // this callback will be called asynchronously
  9399. * // when the response is available
  9400. * }, function errorCallback(response) {
  9401. * // called asynchronously if an error occurs
  9402. * // or server returns response with an error status.
  9403. * });
  9404. * ```
  9405. *
  9406. * The response object has these properties:
  9407. *
  9408. * - **data** – `{string|Object}` – The response body transformed with the transform
  9409. * functions.
  9410. * - **status** – `{number}` – HTTP status code of the response.
  9411. * - **headers** – `{function([headerName])}` – Header getter function.
  9412. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  9413. * - **statusText** – `{string}` – HTTP status text of the response.
  9414. *
  9415. * A response status code between 200 and 299 is considered a success status and
  9416. * will result in the success callback being called. Note that if the response is a redirect,
  9417. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  9418. * called for such responses.
  9419. *
  9420. *
  9421. * ## Shortcut methods
  9422. *
  9423. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  9424. * request data must be passed in for POST/PUT requests. An optional config can be passed as the
  9425. * last argument.
  9426. *
  9427. * ```js
  9428. * $http.get('/someUrl', config).then(successCallback, errorCallback);
  9429. * $http.post('/someUrl', data, config).then(successCallback, errorCallback);
  9430. * ```
  9431. *
  9432. * Complete list of shortcut methods:
  9433. *
  9434. * - {@link ng.$http#get $http.get}
  9435. * - {@link ng.$http#head $http.head}
  9436. * - {@link ng.$http#post $http.post}
  9437. * - {@link ng.$http#put $http.put}
  9438. * - {@link ng.$http#delete $http.delete}
  9439. * - {@link ng.$http#jsonp $http.jsonp}
  9440. * - {@link ng.$http#patch $http.patch}
  9441. *
  9442. *
  9443. * ## Writing Unit Tests that use $http
  9444. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  9445. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  9446. * request using trained responses.
  9447. *
  9448. * ```
  9449. * $httpBackend.expectGET(...);
  9450. * $http.get(...);
  9451. * $httpBackend.flush();
  9452. * ```
  9453. *
  9454. * ## Deprecation Notice
  9455. * <div class="alert alert-danger">
  9456. * The `$http` legacy promise methods `success` and `error` have been deprecated.
  9457. * Use the standard `then` method instead.
  9458. * If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to
  9459. * `false` then these methods will throw {@link $http:legacy `$http/legacy`} error.
  9460. * </div>
  9461. *
  9462. * ## Setting HTTP Headers
  9463. *
  9464. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  9465. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  9466. * object, which currently contains this default configuration:
  9467. *
  9468. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  9469. * - `Accept: application/json, text/plain, * / *`
  9470. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  9471. * - `Content-Type: application/json`
  9472. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  9473. * - `Content-Type: application/json`
  9474. *
  9475. * To add or overwrite these defaults, simply add or remove a property from these configuration
  9476. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  9477. * with the lowercased HTTP method name as the key, e.g.
  9478. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  9479. *
  9480. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  9481. * fashion. For example:
  9482. *
  9483. * ```
  9484. * module.run(function($http) {
  9485. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
  9486. * });
  9487. * ```
  9488. *
  9489. * In addition, you can supply a `headers` property in the config object passed when
  9490. * calling `$http(config)`, which overrides the defaults without changing them globally.
  9491. *
  9492. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  9493. * Use the `headers` property, setting the desired header to `undefined`. For example:
  9494. *
  9495. * ```js
  9496. * var req = {
  9497. * method: 'POST',
  9498. * url: 'http://example.com',
  9499. * headers: {
  9500. * 'Content-Type': undefined
  9501. * },
  9502. * data: { test: 'test' }
  9503. * }
  9504. *
  9505. * $http(req).then(function(){...}, function(){...});
  9506. * ```
  9507. *
  9508. * ## Transforming Requests and Responses
  9509. *
  9510. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  9511. * and `transformResponse`. These properties can be a single function that returns
  9512. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  9513. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  9514. *
  9515. * ### Default Transformations
  9516. *
  9517. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  9518. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  9519. * then these will be applied.
  9520. *
  9521. * You can augment or replace the default transformations by modifying these properties by adding to or
  9522. * replacing the array.
  9523. *
  9524. * Angular provides the following default transformations:
  9525. *
  9526. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  9527. *
  9528. * - If the `data` property of the request configuration object contains an object, serialize it
  9529. * into JSON format.
  9530. *
  9531. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  9532. *
  9533. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  9534. * - If JSON response is detected, deserialize it using a JSON parser.
  9535. *
  9536. *
  9537. * ### Overriding the Default Transformations Per Request
  9538. *
  9539. * If you wish override the request/response transformations only for a single request then provide
  9540. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  9541. * into `$http`.
  9542. *
  9543. * Note that if you provide these properties on the config object the default transformations will be
  9544. * overwritten. If you wish to augment the default transformations then you must include them in your
  9545. * local transformation array.
  9546. *
  9547. * The following code demonstrates adding a new response transformation to be run after the default response
  9548. * transformations have been run.
  9549. *
  9550. * ```js
  9551. * function appendTransform(defaults, transform) {
  9552. *
  9553. * // We can't guarantee that the default transformation is an array
  9554. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  9555. *
  9556. * // Append the new transformation to the defaults
  9557. * return defaults.concat(transform);
  9558. * }
  9559. *
  9560. * $http({
  9561. * url: '...',
  9562. * method: 'GET',
  9563. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  9564. * return doTransform(value);
  9565. * })
  9566. * });
  9567. * ```
  9568. *
  9569. *
  9570. * ## Caching
  9571. *
  9572. * To enable caching, set the request configuration `cache` property to `true` (to use default
  9573. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  9574. * When the cache is enabled, `$http` stores the response from the server in the specified
  9575. * cache. The next time the same request is made, the response is served from the cache without
  9576. * sending a request to the server.
  9577. *
  9578. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  9579. * the same way that real requests are.
  9580. *
  9581. * If there are multiple GET requests for the same URL that should be cached using the same
  9582. * cache, but the cache is not populated yet, only one request to the server will be made and
  9583. * the remaining requests will be fulfilled using the response from the first request.
  9584. *
  9585. * You can change the default cache to a new object (built with
  9586. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  9587. * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
  9588. * their `cache` property to `true` will now use this cache object.
  9589. *
  9590. * If you set the default cache to `false` then only requests that specify their own custom
  9591. * cache object will be cached.
  9592. *
  9593. * ## Interceptors
  9594. *
  9595. * Before you start creating interceptors, be sure to understand the
  9596. * {@link ng.$q $q and deferred/promise APIs}.
  9597. *
  9598. * For purposes of global error handling, authentication, or any kind of synchronous or
  9599. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  9600. * able to intercept requests before they are handed to the server and
  9601. * responses before they are handed over to the application code that
  9602. * initiated these requests. The interceptors leverage the {@link ng.$q
  9603. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  9604. *
  9605. * The interceptors are service factories that are registered with the `$httpProvider` by
  9606. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  9607. * injected with dependencies (if specified) and returns the interceptor.
  9608. *
  9609. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  9610. *
  9611. * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
  9612. * modify the `config` object or create a new one. The function needs to return the `config`
  9613. * object directly, or a promise containing the `config` or a new `config` object.
  9614. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  9615. * resolved with a rejection.
  9616. * * `response`: interceptors get called with http `response` object. The function is free to
  9617. * modify the `response` object or create a new one. The function needs to return the `response`
  9618. * object directly, or as a promise containing the `response` or a new `response` object.
  9619. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  9620. * resolved with a rejection.
  9621. *
  9622. *
  9623. * ```js
  9624. * // register the interceptor as a service
  9625. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  9626. * return {
  9627. * // optional method
  9628. * 'request': function(config) {
  9629. * // do something on success
  9630. * return config;
  9631. * },
  9632. *
  9633. * // optional method
  9634. * 'requestError': function(rejection) {
  9635. * // do something on error
  9636. * if (canRecover(rejection)) {
  9637. * return responseOrNewPromise
  9638. * }
  9639. * return $q.reject(rejection);
  9640. * },
  9641. *
  9642. *
  9643. *
  9644. * // optional method
  9645. * 'response': function(response) {
  9646. * // do something on success
  9647. * return response;
  9648. * },
  9649. *
  9650. * // optional method
  9651. * 'responseError': function(rejection) {
  9652. * // do something on error
  9653. * if (canRecover(rejection)) {
  9654. * return responseOrNewPromise
  9655. * }
  9656. * return $q.reject(rejection);
  9657. * }
  9658. * };
  9659. * });
  9660. *
  9661. * $httpProvider.interceptors.push('myHttpInterceptor');
  9662. *
  9663. *
  9664. * // alternatively, register the interceptor via an anonymous factory
  9665. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  9666. * return {
  9667. * 'request': function(config) {
  9668. * // same as above
  9669. * },
  9670. *
  9671. * 'response': function(response) {
  9672. * // same as above
  9673. * }
  9674. * };
  9675. * });
  9676. * ```
  9677. *
  9678. * ## Security Considerations
  9679. *
  9680. * When designing web applications, consider security threats from:
  9681. *
  9682. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  9683. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  9684. *
  9685. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  9686. * pre-configured with strategies that address these issues, but for this to work backend server
  9687. * cooperation is required.
  9688. *
  9689. * ### JSON Vulnerability Protection
  9690. *
  9691. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  9692. * allows third party website to turn your JSON resource URL into
  9693. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  9694. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  9695. * Angular will automatically strip the prefix before processing it as JSON.
  9696. *
  9697. * For example if your server needs to return:
  9698. * ```js
  9699. * ['one','two']
  9700. * ```
  9701. *
  9702. * which is vulnerable to attack, your server can return:
  9703. * ```js
  9704. * )]}',
  9705. * ['one','two']
  9706. * ```
  9707. *
  9708. * Angular will strip the prefix, before processing the JSON.
  9709. *
  9710. *
  9711. * ### Cross Site Request Forgery (XSRF) Protection
  9712. *
  9713. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by
  9714. * which the attacker can trick an authenticated user into unknowingly executing actions on your
  9715. * website. Angular provides a mechanism to counter XSRF. When performing XHR requests, the
  9716. * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP
  9717. * header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the
  9718. * cookie, your server can be assured that the XHR came from JavaScript running on your domain.
  9719. * The header will not be set for cross-domain requests.
  9720. *
  9721. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  9722. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  9723. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  9724. * that only JavaScript running on your domain could have sent the request. The token must be
  9725. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  9726. * making up its own tokens). We recommend that the token is a digest of your site's
  9727. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  9728. * for added security.
  9729. *
  9730. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  9731. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  9732. * or the per-request config object.
  9733. *
  9734. * In order to prevent collisions in environments where multiple Angular apps share the
  9735. * same domain or subdomain, we recommend that each application uses unique cookie name.
  9736. *
  9737. * @param {object} config Object describing the request to be made and how it should be
  9738. * processed. The object has following properties:
  9739. *
  9740. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  9741. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  9742. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
  9743. * with the `paramSerializer` and appended as GET parameters.
  9744. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  9745. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  9746. * HTTP headers to send to the server. If the return value of a function is null, the
  9747. * header will not be sent. Functions accept a config object as an argument.
  9748. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  9749. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  9750. * - **transformRequest** –
  9751. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  9752. * transform function or an array of such functions. The transform function takes the http
  9753. * request body and headers and returns its transformed (typically serialized) version.
  9754. * See {@link ng.$http#overriding-the-default-transformations-per-request
  9755. * Overriding the Default Transformations}
  9756. * - **transformResponse** –
  9757. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  9758. * transform function or an array of such functions. The transform function takes the http
  9759. * response body, headers and status and returns its transformed (typically deserialized) version.
  9760. * See {@link ng.$http#overriding-the-default-transformations-per-request
  9761. * Overriding the Default TransformationjqLiks}
  9762. * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
  9763. * prepare the string representation of request parameters (specified as an object).
  9764. * If specified as string, it is interpreted as function registered with the
  9765. * {@link $injector $injector}, which means you can create your own serializer
  9766. * by registering it as a {@link auto.$provide#service service}.
  9767. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
  9768. * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
  9769. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  9770. * GET request, otherwise if a cache instance built with
  9771. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  9772. * caching.
  9773. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  9774. * that should abort the request when resolved.
  9775. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  9776. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  9777. * for more information.
  9778. * - **responseType** - `{string}` - see
  9779. * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
  9780. *
  9781. * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
  9782. * when the request succeeds or fails.
  9783. *
  9784. *
  9785. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  9786. * requests. This is primarily meant to be used for debugging purposes.
  9787. *
  9788. *
  9789. * @example
  9790. <example module="httpExample">
  9791. <file name="index.html">
  9792. <div ng-controller="FetchController">
  9793. <select ng-model="method" aria-label="Request method">
  9794. <option>GET</option>
  9795. <option>JSONP</option>
  9796. </select>
  9797. <input type="text" ng-model="url" size="80" aria-label="URL" />
  9798. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  9799. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  9800. <button id="samplejsonpbtn"
  9801. ng-click="updateModel('JSONP',
  9802. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  9803. Sample JSONP
  9804. </button>
  9805. <button id="invalidjsonpbtn"
  9806. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  9807. Invalid JSONP
  9808. </button>
  9809. <pre>http status code: {{status}}</pre>
  9810. <pre>http response data: {{data}}</pre>
  9811. </div>
  9812. </file>
  9813. <file name="script.js">
  9814. angular.module('httpExample', [])
  9815. .controller('FetchController', ['$scope', '$http', '$templateCache',
  9816. function($scope, $http, $templateCache) {
  9817. $scope.method = 'GET';
  9818. $scope.url = 'http-hello.html';
  9819. $scope.fetch = function() {
  9820. $scope.code = null;
  9821. $scope.response = null;
  9822. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  9823. then(function(response) {
  9824. $scope.status = response.status;
  9825. $scope.data = response.data;
  9826. }, function(response) {
  9827. $scope.data = response.data || "Request failed";
  9828. $scope.status = response.status;
  9829. });
  9830. };
  9831. $scope.updateModel = function(method, url) {
  9832. $scope.method = method;
  9833. $scope.url = url;
  9834. };
  9835. }]);
  9836. </file>
  9837. <file name="http-hello.html">
  9838. Hello, $http!
  9839. </file>
  9840. <file name="protractor.js" type="protractor">
  9841. var status = element(by.binding('status'));
  9842. var data = element(by.binding('data'));
  9843. var fetchBtn = element(by.id('fetchbtn'));
  9844. var sampleGetBtn = element(by.id('samplegetbtn'));
  9845. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  9846. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  9847. it('should make an xhr GET request', function() {
  9848. sampleGetBtn.click();
  9849. fetchBtn.click();
  9850. expect(status.getText()).toMatch('200');
  9851. expect(data.getText()).toMatch(/Hello, \$http!/);
  9852. });
  9853. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  9854. // it('should make a JSONP request to angularjs.org', function() {
  9855. // sampleJsonpBtn.click();
  9856. // fetchBtn.click();
  9857. // expect(status.getText()).toMatch('200');
  9858. // expect(data.getText()).toMatch(/Super Hero!/);
  9859. // });
  9860. it('should make JSONP request to invalid URL and invoke the error handler',
  9861. function() {
  9862. invalidJsonpBtn.click();
  9863. fetchBtn.click();
  9864. expect(status.getText()).toMatch('0');
  9865. expect(data.getText()).toMatch('Request failed');
  9866. });
  9867. </file>
  9868. </example>
  9869. */
  9870. function $http(requestConfig) {
  9871. if (!isObject(requestConfig)) {
  9872. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  9873. }
  9874. if (!isString(requestConfig.url)) {
  9875. throw minErr('$http')('badreq', 'Http request configuration url must be a string. Received: {0}', requestConfig.url);
  9876. }
  9877. var config = extend({
  9878. method: 'get',
  9879. transformRequest: defaults.transformRequest,
  9880. transformResponse: defaults.transformResponse,
  9881. paramSerializer: defaults.paramSerializer
  9882. }, requestConfig);
  9883. config.headers = mergeHeaders(requestConfig);
  9884. config.method = uppercase(config.method);
  9885. config.paramSerializer = isString(config.paramSerializer) ?
  9886. $injector.get(config.paramSerializer) : config.paramSerializer;
  9887. var serverRequest = function(config) {
  9888. var headers = config.headers;
  9889. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  9890. // strip content-type if data is undefined
  9891. if (isUndefined(reqData)) {
  9892. forEach(headers, function(value, header) {
  9893. if (lowercase(header) === 'content-type') {
  9894. delete headers[header];
  9895. }
  9896. });
  9897. }
  9898. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  9899. config.withCredentials = defaults.withCredentials;
  9900. }
  9901. // send request
  9902. return sendReq(config, reqData).then(transformResponse, transformResponse);
  9903. };
  9904. var chain = [serverRequest, undefined];
  9905. var promise = $q.when(config);
  9906. // apply interceptors
  9907. forEach(reversedInterceptors, function(interceptor) {
  9908. if (interceptor.request || interceptor.requestError) {
  9909. chain.unshift(interceptor.request, interceptor.requestError);
  9910. }
  9911. if (interceptor.response || interceptor.responseError) {
  9912. chain.push(interceptor.response, interceptor.responseError);
  9913. }
  9914. });
  9915. while (chain.length) {
  9916. var thenFn = chain.shift();
  9917. var rejectFn = chain.shift();
  9918. promise = promise.then(thenFn, rejectFn);
  9919. }
  9920. if (useLegacyPromise) {
  9921. promise.success = function(fn) {
  9922. assertArgFn(fn, 'fn');
  9923. promise.then(function(response) {
  9924. fn(response.data, response.status, response.headers, config);
  9925. });
  9926. return promise;
  9927. };
  9928. promise.error = function(fn) {
  9929. assertArgFn(fn, 'fn');
  9930. promise.then(null, function(response) {
  9931. fn(response.data, response.status, response.headers, config);
  9932. });
  9933. return promise;
  9934. };
  9935. } else {
  9936. promise.success = $httpMinErrLegacyFn('success');
  9937. promise.error = $httpMinErrLegacyFn('error');
  9938. }
  9939. return promise;
  9940. function transformResponse(response) {
  9941. // make a copy since the response must be cacheable
  9942. var resp = extend({}, response);
  9943. resp.data = transformData(response.data, response.headers, response.status,
  9944. config.transformResponse);
  9945. return (isSuccess(response.status))
  9946. ? resp
  9947. : $q.reject(resp);
  9948. }
  9949. function executeHeaderFns(headers, config) {
  9950. var headerContent, processedHeaders = {};
  9951. forEach(headers, function(headerFn, header) {
  9952. if (isFunction(headerFn)) {
  9953. headerContent = headerFn(config);
  9954. if (headerContent != null) {
  9955. processedHeaders[header] = headerContent;
  9956. }
  9957. } else {
  9958. processedHeaders[header] = headerFn;
  9959. }
  9960. });
  9961. return processedHeaders;
  9962. }
  9963. function mergeHeaders(config) {
  9964. var defHeaders = defaults.headers,
  9965. reqHeaders = extend({}, config.headers),
  9966. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  9967. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  9968. // using for-in instead of forEach to avoid unnecessary iteration after header has been found
  9969. defaultHeadersIteration:
  9970. for (defHeaderName in defHeaders) {
  9971. lowercaseDefHeaderName = lowercase(defHeaderName);
  9972. for (reqHeaderName in reqHeaders) {
  9973. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  9974. continue defaultHeadersIteration;
  9975. }
  9976. }
  9977. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  9978. }
  9979. // execute if header value is a function for merged headers
  9980. return executeHeaderFns(reqHeaders, shallowCopy(config));
  9981. }
  9982. }
  9983. $http.pendingRequests = [];
  9984. /**
  9985. * @ngdoc method
  9986. * @name $http#get
  9987. *
  9988. * @description
  9989. * Shortcut method to perform `GET` request.
  9990. *
  9991. * @param {string} url Relative or absolute URL specifying the destination of the request
  9992. * @param {Object=} config Optional configuration object
  9993. * @returns {HttpPromise} Future object
  9994. */
  9995. /**
  9996. * @ngdoc method
  9997. * @name $http#delete
  9998. *
  9999. * @description
  10000. * Shortcut method to perform `DELETE` request.
  10001. *
  10002. * @param {string} url Relative or absolute URL specifying the destination of the request
  10003. * @param {Object=} config Optional configuration object
  10004. * @returns {HttpPromise} Future object
  10005. */
  10006. /**
  10007. * @ngdoc method
  10008. * @name $http#head
  10009. *
  10010. * @description
  10011. * Shortcut method to perform `HEAD` request.
  10012. *
  10013. * @param {string} url Relative or absolute URL specifying the destination of the request
  10014. * @param {Object=} config Optional configuration object
  10015. * @returns {HttpPromise} Future object
  10016. */
  10017. /**
  10018. * @ngdoc method
  10019. * @name $http#jsonp
  10020. *
  10021. * @description
  10022. * Shortcut method to perform `JSONP` request.
  10023. *
  10024. * @param {string} url Relative or absolute URL specifying the destination of the request.
  10025. * The name of the callback should be the string `JSON_CALLBACK`.
  10026. * @param {Object=} config Optional configuration object
  10027. * @returns {HttpPromise} Future object
  10028. */
  10029. createShortMethods('get', 'delete', 'head', 'jsonp');
  10030. /**
  10031. * @ngdoc method
  10032. * @name $http#post
  10033. *
  10034. * @description
  10035. * Shortcut method to perform `POST` request.
  10036. *
  10037. * @param {string} url Relative or absolute URL specifying the destination of the request
  10038. * @param {*} data Request content
  10039. * @param {Object=} config Optional configuration object
  10040. * @returns {HttpPromise} Future object
  10041. */
  10042. /**
  10043. * @ngdoc method
  10044. * @name $http#put
  10045. *
  10046. * @description
  10047. * Shortcut method to perform `PUT` request.
  10048. *
  10049. * @param {string} url Relative or absolute URL specifying the destination of the request
  10050. * @param {*} data Request content
  10051. * @param {Object=} config Optional configuration object
  10052. * @returns {HttpPromise} Future object
  10053. */
  10054. /**
  10055. * @ngdoc method
  10056. * @name $http#patch
  10057. *
  10058. * @description
  10059. * Shortcut method to perform `PATCH` request.
  10060. *
  10061. * @param {string} url Relative or absolute URL specifying the destination of the request
  10062. * @param {*} data Request content
  10063. * @param {Object=} config Optional configuration object
  10064. * @returns {HttpPromise} Future object
  10065. */
  10066. createShortMethodsWithData('post', 'put', 'patch');
  10067. /**
  10068. * @ngdoc property
  10069. * @name $http#defaults
  10070. *
  10071. * @description
  10072. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  10073. * default headers, withCredentials as well as request and response transformations.
  10074. *
  10075. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  10076. */
  10077. $http.defaults = defaults;
  10078. return $http;
  10079. function createShortMethods(names) {
  10080. forEach(arguments, function(name) {
  10081. $http[name] = function(url, config) {
  10082. return $http(extend({}, config || {}, {
  10083. method: name,
  10084. url: url
  10085. }));
  10086. };
  10087. });
  10088. }
  10089. function createShortMethodsWithData(name) {
  10090. forEach(arguments, function(name) {
  10091. $http[name] = function(url, data, config) {
  10092. return $http(extend({}, config || {}, {
  10093. method: name,
  10094. url: url,
  10095. data: data
  10096. }));
  10097. };
  10098. });
  10099. }
  10100. /**
  10101. * Makes the request.
  10102. *
  10103. * !!! ACCESSES CLOSURE VARS:
  10104. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  10105. */
  10106. function sendReq(config, reqData) {
  10107. var deferred = $q.defer(),
  10108. promise = deferred.promise,
  10109. cache,
  10110. cachedResp,
  10111. reqHeaders = config.headers,
  10112. url = buildUrl(config.url, config.paramSerializer(config.params));
  10113. $http.pendingRequests.push(config);
  10114. promise.then(removePendingReq, removePendingReq);
  10115. if ((config.cache || defaults.cache) && config.cache !== false &&
  10116. (config.method === 'GET' || config.method === 'JSONP')) {
  10117. cache = isObject(config.cache) ? config.cache
  10118. : isObject(defaults.cache) ? defaults.cache
  10119. : defaultCache;
  10120. }
  10121. if (cache) {
  10122. cachedResp = cache.get(url);
  10123. if (isDefined(cachedResp)) {
  10124. if (isPromiseLike(cachedResp)) {
  10125. // cached request has already been sent, but there is no response yet
  10126. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  10127. } else {
  10128. // serving from cache
  10129. if (isArray(cachedResp)) {
  10130. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  10131. } else {
  10132. resolvePromise(cachedResp, 200, {}, 'OK');
  10133. }
  10134. }
  10135. } else {
  10136. // put the promise for the non-transformed response into cache as a placeholder
  10137. cache.put(url, promise);
  10138. }
  10139. }
  10140. // if we won't have the response in cache, set the xsrf headers and
  10141. // send the request to the backend
  10142. if (isUndefined(cachedResp)) {
  10143. var xsrfValue = urlIsSameOrigin(config.url)
  10144. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  10145. : undefined;
  10146. if (xsrfValue) {
  10147. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  10148. }
  10149. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  10150. config.withCredentials, config.responseType);
  10151. }
  10152. return promise;
  10153. /**
  10154. * Callback registered to $httpBackend():
  10155. * - caches the response if desired
  10156. * - resolves the raw $http promise
  10157. * - calls $apply
  10158. */
  10159. function done(status, response, headersString, statusText) {
  10160. if (cache) {
  10161. if (isSuccess(status)) {
  10162. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  10163. } else {
  10164. // remove promise from the cache
  10165. cache.remove(url);
  10166. }
  10167. }
  10168. function resolveHttpPromise() {
  10169. resolvePromise(response, status, headersString, statusText);
  10170. }
  10171. if (useApplyAsync) {
  10172. $rootScope.$applyAsync(resolveHttpPromise);
  10173. } else {
  10174. resolveHttpPromise();
  10175. if (!$rootScope.$$phase) $rootScope.$apply();
  10176. }
  10177. }
  10178. /**
  10179. * Resolves the raw $http promise.
  10180. */
  10181. function resolvePromise(response, status, headers, statusText) {
  10182. //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
  10183. status = status >= -1 ? status : 0;
  10184. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  10185. data: response,
  10186. status: status,
  10187. headers: headersGetter(headers),
  10188. config: config,
  10189. statusText: statusText
  10190. });
  10191. }
  10192. function resolvePromiseWithResult(result) {
  10193. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
  10194. }
  10195. function removePendingReq() {
  10196. var idx = $http.pendingRequests.indexOf(config);
  10197. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  10198. }
  10199. }
  10200. function buildUrl(url, serializedParams) {
  10201. if (serializedParams.length > 0) {
  10202. url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
  10203. }
  10204. return url;
  10205. }
  10206. }];
  10207. }
  10208. /**
  10209. * @ngdoc service
  10210. * @name $xhrFactory
  10211. *
  10212. * @description
  10213. * Factory function used to create XMLHttpRequest objects.
  10214. *
  10215. * Replace or decorate this service to create your own custom XMLHttpRequest objects.
  10216. *
  10217. * ```
  10218. * angular.module('myApp', [])
  10219. * .factory('$xhrFactory', function() {
  10220. * return function createXhr(method, url) {
  10221. * return new window.XMLHttpRequest({mozSystem: true});
  10222. * };
  10223. * });
  10224. * ```
  10225. *
  10226. * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
  10227. * @param {string} url URL of the request.
  10228. */
  10229. function $xhrFactoryProvider() {
  10230. this.$get = function() {
  10231. return function createXhr() {
  10232. return new window.XMLHttpRequest();
  10233. };
  10234. };
  10235. }
  10236. /**
  10237. * @ngdoc service
  10238. * @name $httpBackend
  10239. * @requires $window
  10240. * @requires $document
  10241. * @requires $xhrFactory
  10242. *
  10243. * @description
  10244. * HTTP backend used by the {@link ng.$http service} that delegates to
  10245. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  10246. *
  10247. * You should never need to use this service directly, instead use the higher-level abstractions:
  10248. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  10249. *
  10250. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  10251. * $httpBackend} which can be trained with responses.
  10252. */
  10253. function $HttpBackendProvider() {
  10254. this.$get = ['$browser', '$window', '$document', '$xhrFactory', function($browser, $window, $document, $xhrFactory) {
  10255. return createHttpBackend($browser, $xhrFactory, $browser.defer, $window.angular.callbacks, $document[0]);
  10256. }];
  10257. }
  10258. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  10259. // TODO(vojta): fix the signature
  10260. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  10261. $browser.$$incOutstandingRequestCount();
  10262. url = url || $browser.url();
  10263. if (lowercase(method) == 'jsonp') {
  10264. var callbackId = '_' + (callbacks.counter++).toString(36);
  10265. callbacks[callbackId] = function(data) {
  10266. callbacks[callbackId].data = data;
  10267. callbacks[callbackId].called = true;
  10268. };
  10269. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  10270. callbackId, function(status, text) {
  10271. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  10272. callbacks[callbackId] = noop;
  10273. });
  10274. } else {
  10275. var xhr = createXhr(method, url);
  10276. xhr.open(method, url, true);
  10277. forEach(headers, function(value, key) {
  10278. if (isDefined(value)) {
  10279. xhr.setRequestHeader(key, value);
  10280. }
  10281. });
  10282. xhr.onload = function requestLoaded() {
  10283. var statusText = xhr.statusText || '';
  10284. // responseText is the old-school way of retrieving response (supported by IE9)
  10285. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  10286. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  10287. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  10288. var status = xhr.status === 1223 ? 204 : xhr.status;
  10289. // fix status code when it is 0 (0 status is undocumented).
  10290. // Occurs when accessing file resources or on Android 4.1 stock browser
  10291. // while retrieving files from application cache.
  10292. if (status === 0) {
  10293. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  10294. }
  10295. completeRequest(callback,
  10296. status,
  10297. response,
  10298. xhr.getAllResponseHeaders(),
  10299. statusText);
  10300. };
  10301. var requestError = function() {
  10302. // The response is always empty
  10303. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  10304. completeRequest(callback, -1, null, null, '');
  10305. };
  10306. xhr.onerror = requestError;
  10307. xhr.onabort = requestError;
  10308. if (withCredentials) {
  10309. xhr.withCredentials = true;
  10310. }
  10311. if (responseType) {
  10312. try {
  10313. xhr.responseType = responseType;
  10314. } catch (e) {
  10315. // WebKit added support for the json responseType value on 09/03/2013
  10316. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  10317. // known to throw when setting the value "json" as the response type. Other older
  10318. // browsers implementing the responseType
  10319. //
  10320. // The json response type can be ignored if not supported, because JSON payloads are
  10321. // parsed on the client-side regardless.
  10322. if (responseType !== 'json') {
  10323. throw e;
  10324. }
  10325. }
  10326. }
  10327. xhr.send(isUndefined(post) ? null : post);
  10328. }
  10329. if (timeout > 0) {
  10330. var timeoutId = $browserDefer(timeoutRequest, timeout);
  10331. } else if (isPromiseLike(timeout)) {
  10332. timeout.then(timeoutRequest);
  10333. }
  10334. function timeoutRequest() {
  10335. jsonpDone && jsonpDone();
  10336. xhr && xhr.abort();
  10337. }
  10338. function completeRequest(callback, status, response, headersString, statusText) {
  10339. // cancel timeout and subsequent timeout promise resolution
  10340. if (isDefined(timeoutId)) {
  10341. $browserDefer.cancel(timeoutId);
  10342. }
  10343. jsonpDone = xhr = null;
  10344. callback(status, response, headersString, statusText);
  10345. $browser.$$completeOutstandingRequest(noop);
  10346. }
  10347. };
  10348. function jsonpReq(url, callbackId, done) {
  10349. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  10350. // - fetches local scripts via XHR and evals them
  10351. // - adds and immediately removes script elements from the document
  10352. var script = rawDocument.createElement('script'), callback = null;
  10353. script.type = "text/javascript";
  10354. script.src = url;
  10355. script.async = true;
  10356. callback = function(event) {
  10357. removeEventListenerFn(script, "load", callback);
  10358. removeEventListenerFn(script, "error", callback);
  10359. rawDocument.body.removeChild(script);
  10360. script = null;
  10361. var status = -1;
  10362. var text = "unknown";
  10363. if (event) {
  10364. if (event.type === "load" && !callbacks[callbackId].called) {
  10365. event = { type: "error" };
  10366. }
  10367. text = event.type;
  10368. status = event.type === "error" ? 404 : 200;
  10369. }
  10370. if (done) {
  10371. done(status, text);
  10372. }
  10373. };
  10374. addEventListenerFn(script, "load", callback);
  10375. addEventListenerFn(script, "error", callback);
  10376. rawDocument.body.appendChild(script);
  10377. return callback;
  10378. }
  10379. }
  10380. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  10381. $interpolateMinErr.throwNoconcat = function(text) {
  10382. throw $interpolateMinErr('noconcat',
  10383. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  10384. "interpolations that concatenate multiple expressions when a trusted value is " +
  10385. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  10386. };
  10387. $interpolateMinErr.interr = function(text, err) {
  10388. return $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
  10389. };
  10390. /**
  10391. * @ngdoc provider
  10392. * @name $interpolateProvider
  10393. *
  10394. * @description
  10395. *
  10396. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  10397. *
  10398. * <div class="alert alert-danger">
  10399. * This feature is sometimes used to mix different markup languages, e.g. to wrap an Angular
  10400. * template within a Python Jinja template (or any other template language). Mixing templating
  10401. * languages is **very dangerous**. The embedding template language will not safely escape Angular
  10402. * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)
  10403. * security bugs!
  10404. * </div>
  10405. *
  10406. * @example
  10407. <example name="custom-interpolation-markup" module="customInterpolationApp">
  10408. <file name="index.html">
  10409. <script>
  10410. var customInterpolationApp = angular.module('customInterpolationApp', []);
  10411. customInterpolationApp.config(function($interpolateProvider) {
  10412. $interpolateProvider.startSymbol('//');
  10413. $interpolateProvider.endSymbol('//');
  10414. });
  10415. customInterpolationApp.controller('DemoController', function() {
  10416. this.label = "This binding is brought you by // interpolation symbols.";
  10417. });
  10418. </script>
  10419. <div ng-controller="DemoController as demo">
  10420. //demo.label//
  10421. </div>
  10422. </file>
  10423. <file name="protractor.js" type="protractor">
  10424. it('should interpolate binding with custom symbols', function() {
  10425. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  10426. });
  10427. </file>
  10428. </example>
  10429. */
  10430. function $InterpolateProvider() {
  10431. var startSymbol = '{{';
  10432. var endSymbol = '}}';
  10433. /**
  10434. * @ngdoc method
  10435. * @name $interpolateProvider#startSymbol
  10436. * @description
  10437. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  10438. *
  10439. * @param {string=} value new value to set the starting symbol to.
  10440. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  10441. */
  10442. this.startSymbol = function(value) {
  10443. if (value) {
  10444. startSymbol = value;
  10445. return this;
  10446. } else {
  10447. return startSymbol;
  10448. }
  10449. };
  10450. /**
  10451. * @ngdoc method
  10452. * @name $interpolateProvider#endSymbol
  10453. * @description
  10454. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  10455. *
  10456. * @param {string=} value new value to set the ending symbol to.
  10457. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  10458. */
  10459. this.endSymbol = function(value) {
  10460. if (value) {
  10461. endSymbol = value;
  10462. return this;
  10463. } else {
  10464. return endSymbol;
  10465. }
  10466. };
  10467. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  10468. var startSymbolLength = startSymbol.length,
  10469. endSymbolLength = endSymbol.length,
  10470. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  10471. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  10472. function escape(ch) {
  10473. return '\\\\\\' + ch;
  10474. }
  10475. function unescapeText(text) {
  10476. return text.replace(escapedStartRegexp, startSymbol).
  10477. replace(escapedEndRegexp, endSymbol);
  10478. }
  10479. function stringify(value) {
  10480. if (value == null) { // null || undefined
  10481. return '';
  10482. }
  10483. switch (typeof value) {
  10484. case 'string':
  10485. break;
  10486. case 'number':
  10487. value = '' + value;
  10488. break;
  10489. default:
  10490. value = toJson(value);
  10491. }
  10492. return value;
  10493. }
  10494. //TODO: this is the same as the constantWatchDelegate in parse.js
  10495. function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {
  10496. var unwatch;
  10497. return unwatch = scope.$watch(function constantInterpolateWatch(scope) {
  10498. unwatch();
  10499. return constantInterp(scope);
  10500. }, listener, objectEquality);
  10501. }
  10502. /**
  10503. * @ngdoc service
  10504. * @name $interpolate
  10505. * @kind function
  10506. *
  10507. * @requires $parse
  10508. * @requires $sce
  10509. *
  10510. * @description
  10511. *
  10512. * Compiles a string with markup into an interpolation function. This service is used by the
  10513. * HTML {@link ng.$compile $compile} service for data binding. See
  10514. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  10515. * interpolation markup.
  10516. *
  10517. *
  10518. * ```js
  10519. * var $interpolate = ...; // injected
  10520. * var exp = $interpolate('Hello {{name | uppercase}}!');
  10521. * expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
  10522. * ```
  10523. *
  10524. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  10525. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  10526. * evaluate to a value other than `undefined`.
  10527. *
  10528. * ```js
  10529. * var $interpolate = ...; // injected
  10530. * var context = {greeting: 'Hello', name: undefined };
  10531. *
  10532. * // default "forgiving" mode
  10533. * var exp = $interpolate('{{greeting}} {{name}}!');
  10534. * expect(exp(context)).toEqual('Hello !');
  10535. *
  10536. * // "allOrNothing" mode
  10537. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  10538. * expect(exp(context)).toBeUndefined();
  10539. * context.name = 'Angular';
  10540. * expect(exp(context)).toEqual('Hello Angular!');
  10541. * ```
  10542. *
  10543. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  10544. *
  10545. * ####Escaped Interpolation
  10546. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  10547. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  10548. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  10549. * or binding.
  10550. *
  10551. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  10552. * degree, while also enabling code examples to work without relying on the
  10553. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  10554. *
  10555. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  10556. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  10557. * interpolation start/end markers with their escaped counterparts.**
  10558. *
  10559. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  10560. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  10561. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  10562. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  10563. * this is typically useful only when user-data is used in rendering a template from the server, or
  10564. * when otherwise untrusted data is used by a directive.
  10565. *
  10566. * <example>
  10567. * <file name="index.html">
  10568. * <div ng-init="username='A user'">
  10569. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  10570. * </p>
  10571. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  10572. * application, but fails to accomplish their task, because the server has correctly
  10573. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  10574. * characters.</p>
  10575. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  10576. * from the database by an administrator.</p>
  10577. * </div>
  10578. * </file>
  10579. * </example>
  10580. *
  10581. * @param {string} text The text with markup to interpolate.
  10582. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  10583. * embedded expression in order to return an interpolation function. Strings with no
  10584. * embedded expression will return null for the interpolation function.
  10585. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  10586. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  10587. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  10588. * provides Strict Contextual Escaping for details.
  10589. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  10590. * unless all embedded expressions evaluate to a value other than `undefined`.
  10591. * @returns {function(context)} an interpolation function which is used to compute the
  10592. * interpolated string. The function has these parameters:
  10593. *
  10594. * - `context`: evaluation context for all expressions embedded in the interpolated text
  10595. */
  10596. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  10597. // Provide a quick exit and simplified result function for text with no interpolation
  10598. if (!text.length || text.indexOf(startSymbol) === -1) {
  10599. var constantInterp;
  10600. if (!mustHaveExpression) {
  10601. var unescapedText = unescapeText(text);
  10602. constantInterp = valueFn(unescapedText);
  10603. constantInterp.exp = text;
  10604. constantInterp.expressions = [];
  10605. constantInterp.$$watchDelegate = constantWatchDelegate;
  10606. }
  10607. return constantInterp;
  10608. }
  10609. allOrNothing = !!allOrNothing;
  10610. var startIndex,
  10611. endIndex,
  10612. index = 0,
  10613. expressions = [],
  10614. parseFns = [],
  10615. textLength = text.length,
  10616. exp,
  10617. concat = [],
  10618. expressionPositions = [];
  10619. while (index < textLength) {
  10620. if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  10621. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
  10622. if (index !== startIndex) {
  10623. concat.push(unescapeText(text.substring(index, startIndex)));
  10624. }
  10625. exp = text.substring(startIndex + startSymbolLength, endIndex);
  10626. expressions.push(exp);
  10627. parseFns.push($parse(exp, parseStringifyInterceptor));
  10628. index = endIndex + endSymbolLength;
  10629. expressionPositions.push(concat.length);
  10630. concat.push('');
  10631. } else {
  10632. // we did not find an interpolation, so we have to add the remainder to the separators array
  10633. if (index !== textLength) {
  10634. concat.push(unescapeText(text.substring(index)));
  10635. }
  10636. break;
  10637. }
  10638. }
  10639. // Concatenating expressions makes it hard to reason about whether some combination of
  10640. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  10641. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  10642. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  10643. // make it obvious that you bound the value to some user controlled value. This helps reduce
  10644. // the load when auditing for XSS issues.
  10645. if (trustedContext && concat.length > 1) {
  10646. $interpolateMinErr.throwNoconcat(text);
  10647. }
  10648. if (!mustHaveExpression || expressions.length) {
  10649. var compute = function(values) {
  10650. for (var i = 0, ii = expressions.length; i < ii; i++) {
  10651. if (allOrNothing && isUndefined(values[i])) return;
  10652. concat[expressionPositions[i]] = values[i];
  10653. }
  10654. return concat.join('');
  10655. };
  10656. var getValue = function(value) {
  10657. return trustedContext ?
  10658. $sce.getTrusted(trustedContext, value) :
  10659. $sce.valueOf(value);
  10660. };
  10661. return extend(function interpolationFn(context) {
  10662. var i = 0;
  10663. var ii = expressions.length;
  10664. var values = new Array(ii);
  10665. try {
  10666. for (; i < ii; i++) {
  10667. values[i] = parseFns[i](context);
  10668. }
  10669. return compute(values);
  10670. } catch (err) {
  10671. $exceptionHandler($interpolateMinErr.interr(text, err));
  10672. }
  10673. }, {
  10674. // all of these properties are undocumented for now
  10675. exp: text, //just for compatibility with regular watchers created via $watch
  10676. expressions: expressions,
  10677. $$watchDelegate: function(scope, listener) {
  10678. var lastValue;
  10679. return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
  10680. var currValue = compute(values);
  10681. if (isFunction(listener)) {
  10682. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  10683. }
  10684. lastValue = currValue;
  10685. });
  10686. }
  10687. });
  10688. }
  10689. function parseStringifyInterceptor(value) {
  10690. try {
  10691. value = getValue(value);
  10692. return allOrNothing && !isDefined(value) ? value : stringify(value);
  10693. } catch (err) {
  10694. $exceptionHandler($interpolateMinErr.interr(text, err));
  10695. }
  10696. }
  10697. }
  10698. /**
  10699. * @ngdoc method
  10700. * @name $interpolate#startSymbol
  10701. * @description
  10702. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  10703. *
  10704. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  10705. * the symbol.
  10706. *
  10707. * @returns {string} start symbol.
  10708. */
  10709. $interpolate.startSymbol = function() {
  10710. return startSymbol;
  10711. };
  10712. /**
  10713. * @ngdoc method
  10714. * @name $interpolate#endSymbol
  10715. * @description
  10716. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  10717. *
  10718. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  10719. * the symbol.
  10720. *
  10721. * @returns {string} end symbol.
  10722. */
  10723. $interpolate.endSymbol = function() {
  10724. return endSymbol;
  10725. };
  10726. return $interpolate;
  10727. }];
  10728. }
  10729. function $IntervalProvider() {
  10730. this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',
  10731. function($rootScope, $window, $q, $$q, $browser) {
  10732. var intervals = {};
  10733. /**
  10734. * @ngdoc service
  10735. * @name $interval
  10736. *
  10737. * @description
  10738. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  10739. * milliseconds.
  10740. *
  10741. * The return value of registering an interval function is a promise. This promise will be
  10742. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  10743. * run indefinitely if `count` is not defined. The value of the notification will be the
  10744. * number of iterations that have run.
  10745. * To cancel an interval, call `$interval.cancel(promise)`.
  10746. *
  10747. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  10748. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  10749. * time.
  10750. *
  10751. * <div class="alert alert-warning">
  10752. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  10753. * with them. In particular they are not automatically destroyed when a controller's scope or a
  10754. * directive's element are destroyed.
  10755. * You should take this into consideration and make sure to always cancel the interval at the
  10756. * appropriate moment. See the example below for more details on how and when to do this.
  10757. * </div>
  10758. *
  10759. * @param {function()} fn A function that should be called repeatedly.
  10760. * @param {number} delay Number of milliseconds between each function call.
  10761. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  10762. * indefinitely.
  10763. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  10764. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  10765. * @param {...*=} Pass additional parameters to the executed function.
  10766. * @returns {promise} A promise which will be notified on each iteration.
  10767. *
  10768. * @example
  10769. * <example module="intervalExample">
  10770. * <file name="index.html">
  10771. * <script>
  10772. * angular.module('intervalExample', [])
  10773. * .controller('ExampleController', ['$scope', '$interval',
  10774. * function($scope, $interval) {
  10775. * $scope.format = 'M/d/yy h:mm:ss a';
  10776. * $scope.blood_1 = 100;
  10777. * $scope.blood_2 = 120;
  10778. *
  10779. * var stop;
  10780. * $scope.fight = function() {
  10781. * // Don't start a new fight if we are already fighting
  10782. * if ( angular.isDefined(stop) ) return;
  10783. *
  10784. * stop = $interval(function() {
  10785. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  10786. * $scope.blood_1 = $scope.blood_1 - 3;
  10787. * $scope.blood_2 = $scope.blood_2 - 4;
  10788. * } else {
  10789. * $scope.stopFight();
  10790. * }
  10791. * }, 100);
  10792. * };
  10793. *
  10794. * $scope.stopFight = function() {
  10795. * if (angular.isDefined(stop)) {
  10796. * $interval.cancel(stop);
  10797. * stop = undefined;
  10798. * }
  10799. * };
  10800. *
  10801. * $scope.resetFight = function() {
  10802. * $scope.blood_1 = 100;
  10803. * $scope.blood_2 = 120;
  10804. * };
  10805. *
  10806. * $scope.$on('$destroy', function() {
  10807. * // Make sure that the interval is destroyed too
  10808. * $scope.stopFight();
  10809. * });
  10810. * }])
  10811. * // Register the 'myCurrentTime' directive factory method.
  10812. * // We inject $interval and dateFilter service since the factory method is DI.
  10813. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  10814. * function($interval, dateFilter) {
  10815. * // return the directive link function. (compile function not needed)
  10816. * return function(scope, element, attrs) {
  10817. * var format, // date format
  10818. * stopTime; // so that we can cancel the time updates
  10819. *
  10820. * // used to update the UI
  10821. * function updateTime() {
  10822. * element.text(dateFilter(new Date(), format));
  10823. * }
  10824. *
  10825. * // watch the expression, and update the UI on change.
  10826. * scope.$watch(attrs.myCurrentTime, function(value) {
  10827. * format = value;
  10828. * updateTime();
  10829. * });
  10830. *
  10831. * stopTime = $interval(updateTime, 1000);
  10832. *
  10833. * // listen on DOM destroy (removal) event, and cancel the next UI update
  10834. * // to prevent updating time after the DOM element was removed.
  10835. * element.on('$destroy', function() {
  10836. * $interval.cancel(stopTime);
  10837. * });
  10838. * }
  10839. * }]);
  10840. * </script>
  10841. *
  10842. * <div>
  10843. * <div ng-controller="ExampleController">
  10844. * <label>Date format: <input ng-model="format"></label> <hr/>
  10845. * Current time is: <span my-current-time="format"></span>
  10846. * <hr/>
  10847. * Blood 1 : <font color='red'>{{blood_1}}</font>
  10848. * Blood 2 : <font color='red'>{{blood_2}}</font>
  10849. * <button type="button" data-ng-click="fight()">Fight</button>
  10850. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  10851. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  10852. * </div>
  10853. * </div>
  10854. *
  10855. * </file>
  10856. * </example>
  10857. */
  10858. function interval(fn, delay, count, invokeApply) {
  10859. var hasParams = arguments.length > 4,
  10860. args = hasParams ? sliceArgs(arguments, 4) : [],
  10861. setInterval = $window.setInterval,
  10862. clearInterval = $window.clearInterval,
  10863. iteration = 0,
  10864. skipApply = (isDefined(invokeApply) && !invokeApply),
  10865. deferred = (skipApply ? $$q : $q).defer(),
  10866. promise = deferred.promise;
  10867. count = isDefined(count) ? count : 0;
  10868. promise.$$intervalId = setInterval(function tick() {
  10869. if (skipApply) {
  10870. $browser.defer(callback);
  10871. } else {
  10872. $rootScope.$evalAsync(callback);
  10873. }
  10874. deferred.notify(iteration++);
  10875. if (count > 0 && iteration >= count) {
  10876. deferred.resolve(iteration);
  10877. clearInterval(promise.$$intervalId);
  10878. delete intervals[promise.$$intervalId];
  10879. }
  10880. if (!skipApply) $rootScope.$apply();
  10881. }, delay);
  10882. intervals[promise.$$intervalId] = deferred;
  10883. return promise;
  10884. function callback() {
  10885. if (!hasParams) {
  10886. fn(iteration);
  10887. } else {
  10888. fn.apply(null, args);
  10889. }
  10890. }
  10891. }
  10892. /**
  10893. * @ngdoc method
  10894. * @name $interval#cancel
  10895. *
  10896. * @description
  10897. * Cancels a task associated with the `promise`.
  10898. *
  10899. * @param {Promise=} promise returned by the `$interval` function.
  10900. * @returns {boolean} Returns `true` if the task was successfully canceled.
  10901. */
  10902. interval.cancel = function(promise) {
  10903. if (promise && promise.$$intervalId in intervals) {
  10904. intervals[promise.$$intervalId].reject('canceled');
  10905. $window.clearInterval(promise.$$intervalId);
  10906. delete intervals[promise.$$intervalId];
  10907. return true;
  10908. }
  10909. return false;
  10910. };
  10911. return interval;
  10912. }];
  10913. }
  10914. /**
  10915. * @ngdoc service
  10916. * @name $locale
  10917. *
  10918. * @description
  10919. * $locale service provides localization rules for various Angular components. As of right now the
  10920. * only public api is:
  10921. *
  10922. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  10923. */
  10924. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  10925. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  10926. var $locationMinErr = minErr('$location');
  10927. /**
  10928. * Encode path using encodeUriSegment, ignoring forward slashes
  10929. *
  10930. * @param {string} path Path to encode
  10931. * @returns {string}
  10932. */
  10933. function encodePath(path) {
  10934. var segments = path.split('/'),
  10935. i = segments.length;
  10936. while (i--) {
  10937. segments[i] = encodeUriSegment(segments[i]);
  10938. }
  10939. return segments.join('/');
  10940. }
  10941. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  10942. var parsedUrl = urlResolve(absoluteUrl);
  10943. locationObj.$$protocol = parsedUrl.protocol;
  10944. locationObj.$$host = parsedUrl.hostname;
  10945. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  10946. }
  10947. function parseAppUrl(relativeUrl, locationObj) {
  10948. var prefixed = (relativeUrl.charAt(0) !== '/');
  10949. if (prefixed) {
  10950. relativeUrl = '/' + relativeUrl;
  10951. }
  10952. var match = urlResolve(relativeUrl);
  10953. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  10954. match.pathname.substring(1) : match.pathname);
  10955. locationObj.$$search = parseKeyValue(match.search);
  10956. locationObj.$$hash = decodeURIComponent(match.hash);
  10957. // make sure path starts with '/';
  10958. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  10959. locationObj.$$path = '/' + locationObj.$$path;
  10960. }
  10961. }
  10962. /**
  10963. *
  10964. * @param {string} begin
  10965. * @param {string} whole
  10966. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  10967. * expected string.
  10968. */
  10969. function beginsWith(begin, whole) {
  10970. if (whole.indexOf(begin) === 0) {
  10971. return whole.substr(begin.length);
  10972. }
  10973. }
  10974. function stripHash(url) {
  10975. var index = url.indexOf('#');
  10976. return index == -1 ? url : url.substr(0, index);
  10977. }
  10978. function trimEmptyHash(url) {
  10979. return url.replace(/(#.+)|#$/, '$1');
  10980. }
  10981. function stripFile(url) {
  10982. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  10983. }
  10984. /* return the server only (scheme://host:port) */
  10985. function serverBase(url) {
  10986. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  10987. }
  10988. /**
  10989. * LocationHtml5Url represents an url
  10990. * This object is exposed as $location service when HTML5 mode is enabled and supported
  10991. *
  10992. * @constructor
  10993. * @param {string} appBase application base URL
  10994. * @param {string} appBaseNoFile application base URL stripped of any filename
  10995. * @param {string} basePrefix url path prefix
  10996. */
  10997. function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
  10998. this.$$html5 = true;
  10999. basePrefix = basePrefix || '';
  11000. parseAbsoluteUrl(appBase, this);
  11001. /**
  11002. * Parse given html5 (regular) url string into properties
  11003. * @param {string} url HTML5 url
  11004. * @private
  11005. */
  11006. this.$$parse = function(url) {
  11007. var pathUrl = beginsWith(appBaseNoFile, url);
  11008. if (!isString(pathUrl)) {
  11009. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  11010. appBaseNoFile);
  11011. }
  11012. parseAppUrl(pathUrl, this);
  11013. if (!this.$$path) {
  11014. this.$$path = '/';
  11015. }
  11016. this.$$compose();
  11017. };
  11018. /**
  11019. * Compose url and update `absUrl` property
  11020. * @private
  11021. */
  11022. this.$$compose = function() {
  11023. var search = toKeyValue(this.$$search),
  11024. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  11025. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  11026. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  11027. };
  11028. this.$$parseLinkUrl = function(url, relHref) {
  11029. if (relHref && relHref[0] === '#') {
  11030. // special case for links to hash fragments:
  11031. // keep the old url and only replace the hash fragment
  11032. this.hash(relHref.slice(1));
  11033. return true;
  11034. }
  11035. var appUrl, prevAppUrl;
  11036. var rewrittenUrl;
  11037. if (isDefined(appUrl = beginsWith(appBase, url))) {
  11038. prevAppUrl = appUrl;
  11039. if (isDefined(appUrl = beginsWith(basePrefix, appUrl))) {
  11040. rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  11041. } else {
  11042. rewrittenUrl = appBase + prevAppUrl;
  11043. }
  11044. } else if (isDefined(appUrl = beginsWith(appBaseNoFile, url))) {
  11045. rewrittenUrl = appBaseNoFile + appUrl;
  11046. } else if (appBaseNoFile == url + '/') {
  11047. rewrittenUrl = appBaseNoFile;
  11048. }
  11049. if (rewrittenUrl) {
  11050. this.$$parse(rewrittenUrl);
  11051. }
  11052. return !!rewrittenUrl;
  11053. };
  11054. }
  11055. /**
  11056. * LocationHashbangUrl represents url
  11057. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  11058. * It also serves as the base class for html5 mode fallback on legacy browsers.
  11059. *
  11060. * @constructor
  11061. * @param {string} appBase application base URL
  11062. * @param {string} appBaseNoFile application base URL stripped of any filename
  11063. * @param {string} hashPrefix hashbang prefix
  11064. */
  11065. function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
  11066. parseAbsoluteUrl(appBase, this);
  11067. /**
  11068. * Parse given hashbang url into properties
  11069. * @param {string} url Hashbang url
  11070. * @private
  11071. */
  11072. this.$$parse = function(url) {
  11073. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  11074. var withoutHashUrl;
  11075. if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
  11076. // The rest of the url starts with a hash so we have
  11077. // got either a hashbang path or a plain hash fragment
  11078. withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
  11079. if (isUndefined(withoutHashUrl)) {
  11080. // There was no hashbang prefix so we just have a hash fragment
  11081. withoutHashUrl = withoutBaseUrl;
  11082. }
  11083. } else {
  11084. // There was no hashbang path nor hash fragment:
  11085. // If we are in HTML5 mode we use what is left as the path;
  11086. // Otherwise we ignore what is left
  11087. if (this.$$html5) {
  11088. withoutHashUrl = withoutBaseUrl;
  11089. } else {
  11090. withoutHashUrl = '';
  11091. if (isUndefined(withoutBaseUrl)) {
  11092. appBase = url;
  11093. this.replace();
  11094. }
  11095. }
  11096. }
  11097. parseAppUrl(withoutHashUrl, this);
  11098. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  11099. this.$$compose();
  11100. /*
  11101. * In Windows, on an anchor node on documents loaded from
  11102. * the filesystem, the browser will return a pathname
  11103. * prefixed with the drive name ('/C:/path') when a
  11104. * pathname without a drive is set:
  11105. * * a.setAttribute('href', '/foo')
  11106. * * a.pathname === '/C:/foo' //true
  11107. *
  11108. * Inside of Angular, we're always using pathnames that
  11109. * do not include drive names for routing.
  11110. */
  11111. function removeWindowsDriveName(path, url, base) {
  11112. /*
  11113. Matches paths for file protocol on windows,
  11114. such as /C:/foo/bar, and captures only /foo/bar.
  11115. */
  11116. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  11117. var firstPathSegmentMatch;
  11118. //Get the relative path from the input URL.
  11119. if (url.indexOf(base) === 0) {
  11120. url = url.replace(base, '');
  11121. }
  11122. // The input URL intentionally contains a first path segment that ends with a colon.
  11123. if (windowsFilePathExp.exec(url)) {
  11124. return path;
  11125. }
  11126. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  11127. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  11128. }
  11129. };
  11130. /**
  11131. * Compose hashbang url and update `absUrl` property
  11132. * @private
  11133. */
  11134. this.$$compose = function() {
  11135. var search = toKeyValue(this.$$search),
  11136. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  11137. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  11138. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  11139. };
  11140. this.$$parseLinkUrl = function(url, relHref) {
  11141. if (stripHash(appBase) == stripHash(url)) {
  11142. this.$$parse(url);
  11143. return true;
  11144. }
  11145. return false;
  11146. };
  11147. }
  11148. /**
  11149. * LocationHashbangUrl represents url
  11150. * This object is exposed as $location service when html5 history api is enabled but the browser
  11151. * does not support it.
  11152. *
  11153. * @constructor
  11154. * @param {string} appBase application base URL
  11155. * @param {string} appBaseNoFile application base URL stripped of any filename
  11156. * @param {string} hashPrefix hashbang prefix
  11157. */
  11158. function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
  11159. this.$$html5 = true;
  11160. LocationHashbangUrl.apply(this, arguments);
  11161. this.$$parseLinkUrl = function(url, relHref) {
  11162. if (relHref && relHref[0] === '#') {
  11163. // special case for links to hash fragments:
  11164. // keep the old url and only replace the hash fragment
  11165. this.hash(relHref.slice(1));
  11166. return true;
  11167. }
  11168. var rewrittenUrl;
  11169. var appUrl;
  11170. if (appBase == stripHash(url)) {
  11171. rewrittenUrl = url;
  11172. } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
  11173. rewrittenUrl = appBase + hashPrefix + appUrl;
  11174. } else if (appBaseNoFile === url + '/') {
  11175. rewrittenUrl = appBaseNoFile;
  11176. }
  11177. if (rewrittenUrl) {
  11178. this.$$parse(rewrittenUrl);
  11179. }
  11180. return !!rewrittenUrl;
  11181. };
  11182. this.$$compose = function() {
  11183. var search = toKeyValue(this.$$search),
  11184. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  11185. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  11186. // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
  11187. this.$$absUrl = appBase + hashPrefix + this.$$url;
  11188. };
  11189. }
  11190. var locationPrototype = {
  11191. /**
  11192. * Are we in html5 mode?
  11193. * @private
  11194. */
  11195. $$html5: false,
  11196. /**
  11197. * Has any change been replacing?
  11198. * @private
  11199. */
  11200. $$replace: false,
  11201. /**
  11202. * @ngdoc method
  11203. * @name $location#absUrl
  11204. *
  11205. * @description
  11206. * This method is getter only.
  11207. *
  11208. * Return full url representation with all segments encoded according to rules specified in
  11209. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  11210. *
  11211. *
  11212. * ```js
  11213. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11214. * var absUrl = $location.absUrl();
  11215. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  11216. * ```
  11217. *
  11218. * @return {string} full url
  11219. */
  11220. absUrl: locationGetter('$$absUrl'),
  11221. /**
  11222. * @ngdoc method
  11223. * @name $location#url
  11224. *
  11225. * @description
  11226. * This method is getter / setter.
  11227. *
  11228. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  11229. *
  11230. * Change path, search and hash, when called with parameter and return `$location`.
  11231. *
  11232. *
  11233. * ```js
  11234. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11235. * var url = $location.url();
  11236. * // => "/some/path?foo=bar&baz=xoxo"
  11237. * ```
  11238. *
  11239. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  11240. * @return {string} url
  11241. */
  11242. url: function(url) {
  11243. if (isUndefined(url)) {
  11244. return this.$$url;
  11245. }
  11246. var match = PATH_MATCH.exec(url);
  11247. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  11248. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  11249. this.hash(match[5] || '');
  11250. return this;
  11251. },
  11252. /**
  11253. * @ngdoc method
  11254. * @name $location#protocol
  11255. *
  11256. * @description
  11257. * This method is getter only.
  11258. *
  11259. * Return protocol of current url.
  11260. *
  11261. *
  11262. * ```js
  11263. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11264. * var protocol = $location.protocol();
  11265. * // => "http"
  11266. * ```
  11267. *
  11268. * @return {string} protocol of current url
  11269. */
  11270. protocol: locationGetter('$$protocol'),
  11271. /**
  11272. * @ngdoc method
  11273. * @name $location#host
  11274. *
  11275. * @description
  11276. * This method is getter only.
  11277. *
  11278. * Return host of current url.
  11279. *
  11280. * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  11281. *
  11282. *
  11283. * ```js
  11284. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11285. * var host = $location.host();
  11286. * // => "example.com"
  11287. *
  11288. * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  11289. * host = $location.host();
  11290. * // => "example.com"
  11291. * host = location.host;
  11292. * // => "example.com:8080"
  11293. * ```
  11294. *
  11295. * @return {string} host of current url.
  11296. */
  11297. host: locationGetter('$$host'),
  11298. /**
  11299. * @ngdoc method
  11300. * @name $location#port
  11301. *
  11302. * @description
  11303. * This method is getter only.
  11304. *
  11305. * Return port of current url.
  11306. *
  11307. *
  11308. * ```js
  11309. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11310. * var port = $location.port();
  11311. * // => 80
  11312. * ```
  11313. *
  11314. * @return {Number} port
  11315. */
  11316. port: locationGetter('$$port'),
  11317. /**
  11318. * @ngdoc method
  11319. * @name $location#path
  11320. *
  11321. * @description
  11322. * This method is getter / setter.
  11323. *
  11324. * Return path of current url when called without any parameter.
  11325. *
  11326. * Change path when called with parameter and return `$location`.
  11327. *
  11328. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  11329. * if it is missing.
  11330. *
  11331. *
  11332. * ```js
  11333. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11334. * var path = $location.path();
  11335. * // => "/some/path"
  11336. * ```
  11337. *
  11338. * @param {(string|number)=} path New path
  11339. * @return {string} path
  11340. */
  11341. path: locationGetterSetter('$$path', function(path) {
  11342. path = path !== null ? path.toString() : '';
  11343. return path.charAt(0) == '/' ? path : '/' + path;
  11344. }),
  11345. /**
  11346. * @ngdoc method
  11347. * @name $location#search
  11348. *
  11349. * @description
  11350. * This method is getter / setter.
  11351. *
  11352. * Return search part (as object) of current url when called without any parameter.
  11353. *
  11354. * Change search part when called with parameter and return `$location`.
  11355. *
  11356. *
  11357. * ```js
  11358. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11359. * var searchObject = $location.search();
  11360. * // => {foo: 'bar', baz: 'xoxo'}
  11361. *
  11362. * // set foo to 'yipee'
  11363. * $location.search('foo', 'yipee');
  11364. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  11365. * ```
  11366. *
  11367. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  11368. * hash object.
  11369. *
  11370. * When called with a single argument the method acts as a setter, setting the `search` component
  11371. * of `$location` to the specified value.
  11372. *
  11373. * If the argument is a hash object containing an array of values, these values will be encoded
  11374. * as duplicate search parameters in the url.
  11375. *
  11376. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  11377. * will override only a single search property.
  11378. *
  11379. * If `paramValue` is an array, it will override the property of the `search` component of
  11380. * `$location` specified via the first argument.
  11381. *
  11382. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  11383. *
  11384. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  11385. * value nor trailing equal sign.
  11386. *
  11387. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  11388. * one or more arguments returns `$location` object itself.
  11389. */
  11390. search: function(search, paramValue) {
  11391. switch (arguments.length) {
  11392. case 0:
  11393. return this.$$search;
  11394. case 1:
  11395. if (isString(search) || isNumber(search)) {
  11396. search = search.toString();
  11397. this.$$search = parseKeyValue(search);
  11398. } else if (isObject(search)) {
  11399. search = copy(search, {});
  11400. // remove object undefined or null properties
  11401. forEach(search, function(value, key) {
  11402. if (value == null) delete search[key];
  11403. });
  11404. this.$$search = search;
  11405. } else {
  11406. throw $locationMinErr('isrcharg',
  11407. 'The first argument of the `$location#search()` call must be a string or an object.');
  11408. }
  11409. break;
  11410. default:
  11411. if (isUndefined(paramValue) || paramValue === null) {
  11412. delete this.$$search[search];
  11413. } else {
  11414. this.$$search[search] = paramValue;
  11415. }
  11416. }
  11417. this.$$compose();
  11418. return this;
  11419. },
  11420. /**
  11421. * @ngdoc method
  11422. * @name $location#hash
  11423. *
  11424. * @description
  11425. * This method is getter / setter.
  11426. *
  11427. * Returns the hash fragment when called without any parameters.
  11428. *
  11429. * Changes the hash fragment when called with a parameter and returns `$location`.
  11430. *
  11431. *
  11432. * ```js
  11433. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  11434. * var hash = $location.hash();
  11435. * // => "hashValue"
  11436. * ```
  11437. *
  11438. * @param {(string|number)=} hash New hash fragment
  11439. * @return {string} hash
  11440. */
  11441. hash: locationGetterSetter('$$hash', function(hash) {
  11442. return hash !== null ? hash.toString() : '';
  11443. }),
  11444. /**
  11445. * @ngdoc method
  11446. * @name $location#replace
  11447. *
  11448. * @description
  11449. * If called, all changes to $location during the current `$digest` will replace the current history
  11450. * record, instead of adding a new one.
  11451. */
  11452. replace: function() {
  11453. this.$$replace = true;
  11454. return this;
  11455. }
  11456. };
  11457. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  11458. Location.prototype = Object.create(locationPrototype);
  11459. /**
  11460. * @ngdoc method
  11461. * @name $location#state
  11462. *
  11463. * @description
  11464. * This method is getter / setter.
  11465. *
  11466. * Return the history state object when called without any parameter.
  11467. *
  11468. * Change the history state object when called with one parameter and return `$location`.
  11469. * The state object is later passed to `pushState` or `replaceState`.
  11470. *
  11471. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  11472. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  11473. * older browsers (like IE9 or Android < 4.0), don't use this method.
  11474. *
  11475. * @param {object=} state State object for pushState or replaceState
  11476. * @return {object} state
  11477. */
  11478. Location.prototype.state = function(state) {
  11479. if (!arguments.length) {
  11480. return this.$$state;
  11481. }
  11482. if (Location !== LocationHtml5Url || !this.$$html5) {
  11483. throw $locationMinErr('nostate', 'History API state support is available only ' +
  11484. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  11485. }
  11486. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  11487. // but we're changing the $$state reference to $browser.state() during the $digest
  11488. // so the modification window is narrow.
  11489. this.$$state = isUndefined(state) ? null : state;
  11490. return this;
  11491. };
  11492. });
  11493. function locationGetter(property) {
  11494. return function() {
  11495. return this[property];
  11496. };
  11497. }
  11498. function locationGetterSetter(property, preprocess) {
  11499. return function(value) {
  11500. if (isUndefined(value)) {
  11501. return this[property];
  11502. }
  11503. this[property] = preprocess(value);
  11504. this.$$compose();
  11505. return this;
  11506. };
  11507. }
  11508. /**
  11509. * @ngdoc service
  11510. * @name $location
  11511. *
  11512. * @requires $rootElement
  11513. *
  11514. * @description
  11515. * The $location service parses the URL in the browser address bar (based on the
  11516. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  11517. * available to your application. Changes to the URL in the address bar are reflected into
  11518. * $location service and changes to $location are reflected into the browser address bar.
  11519. *
  11520. * **The $location service:**
  11521. *
  11522. * - Exposes the current URL in the browser address bar, so you can
  11523. * - Watch and observe the URL.
  11524. * - Change the URL.
  11525. * - Synchronizes the URL with the browser when the user
  11526. * - Changes the address bar.
  11527. * - Clicks the back or forward button (or clicks a History link).
  11528. * - Clicks on a link.
  11529. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  11530. *
  11531. * For more information see {@link guide/$location Developer Guide: Using $location}
  11532. */
  11533. /**
  11534. * @ngdoc provider
  11535. * @name $locationProvider
  11536. * @description
  11537. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  11538. */
  11539. function $LocationProvider() {
  11540. var hashPrefix = '',
  11541. html5Mode = {
  11542. enabled: false,
  11543. requireBase: true,
  11544. rewriteLinks: true
  11545. };
  11546. /**
  11547. * @ngdoc method
  11548. * @name $locationProvider#hashPrefix
  11549. * @description
  11550. * @param {string=} prefix Prefix for hash part (containing path and search)
  11551. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  11552. */
  11553. this.hashPrefix = function(prefix) {
  11554. if (isDefined(prefix)) {
  11555. hashPrefix = prefix;
  11556. return this;
  11557. } else {
  11558. return hashPrefix;
  11559. }
  11560. };
  11561. /**
  11562. * @ngdoc method
  11563. * @name $locationProvider#html5Mode
  11564. * @description
  11565. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  11566. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  11567. * properties:
  11568. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  11569. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  11570. * support `pushState`.
  11571. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  11572. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  11573. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  11574. * See the {@link guide/$location $location guide for more information}
  11575. * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
  11576. * enables/disables url rewriting for relative links.
  11577. *
  11578. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  11579. */
  11580. this.html5Mode = function(mode) {
  11581. if (isBoolean(mode)) {
  11582. html5Mode.enabled = mode;
  11583. return this;
  11584. } else if (isObject(mode)) {
  11585. if (isBoolean(mode.enabled)) {
  11586. html5Mode.enabled = mode.enabled;
  11587. }
  11588. if (isBoolean(mode.requireBase)) {
  11589. html5Mode.requireBase = mode.requireBase;
  11590. }
  11591. if (isBoolean(mode.rewriteLinks)) {
  11592. html5Mode.rewriteLinks = mode.rewriteLinks;
  11593. }
  11594. return this;
  11595. } else {
  11596. return html5Mode;
  11597. }
  11598. };
  11599. /**
  11600. * @ngdoc event
  11601. * @name $location#$locationChangeStart
  11602. * @eventType broadcast on root scope
  11603. * @description
  11604. * Broadcasted before a URL will change.
  11605. *
  11606. * This change can be prevented by calling
  11607. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  11608. * details about event object. Upon successful change
  11609. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  11610. *
  11611. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  11612. * the browser supports the HTML5 History API.
  11613. *
  11614. * @param {Object} angularEvent Synthetic event object.
  11615. * @param {string} newUrl New URL
  11616. * @param {string=} oldUrl URL that was before it was changed.
  11617. * @param {string=} newState New history state object
  11618. * @param {string=} oldState History state object that was before it was changed.
  11619. */
  11620. /**
  11621. * @ngdoc event
  11622. * @name $location#$locationChangeSuccess
  11623. * @eventType broadcast on root scope
  11624. * @description
  11625. * Broadcasted after a URL was changed.
  11626. *
  11627. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  11628. * the browser supports the HTML5 History API.
  11629. *
  11630. * @param {Object} angularEvent Synthetic event object.
  11631. * @param {string} newUrl New URL
  11632. * @param {string=} oldUrl URL that was before it was changed.
  11633. * @param {string=} newState New history state object
  11634. * @param {string=} oldState History state object that was before it was changed.
  11635. */
  11636. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  11637. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  11638. var $location,
  11639. LocationMode,
  11640. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  11641. initialUrl = $browser.url(),
  11642. appBase;
  11643. if (html5Mode.enabled) {
  11644. if (!baseHref && html5Mode.requireBase) {
  11645. throw $locationMinErr('nobase',
  11646. "$location in HTML5 mode requires a <base> tag to be present!");
  11647. }
  11648. appBase = serverBase(initialUrl) + (baseHref || '/');
  11649. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  11650. } else {
  11651. appBase = stripHash(initialUrl);
  11652. LocationMode = LocationHashbangUrl;
  11653. }
  11654. var appBaseNoFile = stripFile(appBase);
  11655. $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
  11656. $location.$$parseLinkUrl(initialUrl, initialUrl);
  11657. $location.$$state = $browser.state();
  11658. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  11659. function setBrowserUrlWithFallback(url, replace, state) {
  11660. var oldUrl = $location.url();
  11661. var oldState = $location.$$state;
  11662. try {
  11663. $browser.url(url, replace, state);
  11664. // Make sure $location.state() returns referentially identical (not just deeply equal)
  11665. // state object; this makes possible quick checking if the state changed in the digest
  11666. // loop. Checking deep equality would be too expensive.
  11667. $location.$$state = $browser.state();
  11668. } catch (e) {
  11669. // Restore old values if pushState fails
  11670. $location.url(oldUrl);
  11671. $location.$$state = oldState;
  11672. throw e;
  11673. }
  11674. }
  11675. $rootElement.on('click', function(event) {
  11676. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  11677. // currently we open nice url link and redirect then
  11678. if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
  11679. var elm = jqLite(event.target);
  11680. // traverse the DOM up to find first A tag
  11681. while (nodeName_(elm[0]) !== 'a') {
  11682. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  11683. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  11684. }
  11685. var absHref = elm.prop('href');
  11686. // get the actual href attribute - see
  11687. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  11688. var relHref = elm.attr('href') || elm.attr('xlink:href');
  11689. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  11690. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  11691. // an animation.
  11692. absHref = urlResolve(absHref.animVal).href;
  11693. }
  11694. // Ignore when url is started with javascript: or mailto:
  11695. if (IGNORE_URI_REGEXP.test(absHref)) return;
  11696. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  11697. if ($location.$$parseLinkUrl(absHref, relHref)) {
  11698. // We do a preventDefault for all urls that are part of the angular application,
  11699. // in html5mode and also without, so that we are able to abort navigation without
  11700. // getting double entries in the location history.
  11701. event.preventDefault();
  11702. // update location manually
  11703. if ($location.absUrl() != $browser.url()) {
  11704. $rootScope.$apply();
  11705. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  11706. $window.angular['ff-684208-preventDefault'] = true;
  11707. }
  11708. }
  11709. }
  11710. });
  11711. // rewrite hashbang url <> html5 url
  11712. if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
  11713. $browser.url($location.absUrl(), true);
  11714. }
  11715. var initializing = true;
  11716. // update $location when $browser url changes
  11717. $browser.onUrlChange(function(newUrl, newState) {
  11718. if (isUndefined(beginsWith(appBaseNoFile, newUrl))) {
  11719. // If we are navigating outside of the app then force a reload
  11720. $window.location.href = newUrl;
  11721. return;
  11722. }
  11723. $rootScope.$evalAsync(function() {
  11724. var oldUrl = $location.absUrl();
  11725. var oldState = $location.$$state;
  11726. var defaultPrevented;
  11727. newUrl = trimEmptyHash(newUrl);
  11728. $location.$$parse(newUrl);
  11729. $location.$$state = newState;
  11730. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  11731. newState, oldState).defaultPrevented;
  11732. // if the location was changed by a `$locationChangeStart` handler then stop
  11733. // processing this location change
  11734. if ($location.absUrl() !== newUrl) return;
  11735. if (defaultPrevented) {
  11736. $location.$$parse(oldUrl);
  11737. $location.$$state = oldState;
  11738. setBrowserUrlWithFallback(oldUrl, false, oldState);
  11739. } else {
  11740. initializing = false;
  11741. afterLocationChange(oldUrl, oldState);
  11742. }
  11743. });
  11744. if (!$rootScope.$$phase) $rootScope.$digest();
  11745. });
  11746. // update browser
  11747. $rootScope.$watch(function $locationWatch() {
  11748. var oldUrl = trimEmptyHash($browser.url());
  11749. var newUrl = trimEmptyHash($location.absUrl());
  11750. var oldState = $browser.state();
  11751. var currentReplace = $location.$$replace;
  11752. var urlOrStateChanged = oldUrl !== newUrl ||
  11753. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  11754. if (initializing || urlOrStateChanged) {
  11755. initializing = false;
  11756. $rootScope.$evalAsync(function() {
  11757. var newUrl = $location.absUrl();
  11758. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  11759. $location.$$state, oldState).defaultPrevented;
  11760. // if the location was changed by a `$locationChangeStart` handler then stop
  11761. // processing this location change
  11762. if ($location.absUrl() !== newUrl) return;
  11763. if (defaultPrevented) {
  11764. $location.$$parse(oldUrl);
  11765. $location.$$state = oldState;
  11766. } else {
  11767. if (urlOrStateChanged) {
  11768. setBrowserUrlWithFallback(newUrl, currentReplace,
  11769. oldState === $location.$$state ? null : $location.$$state);
  11770. }
  11771. afterLocationChange(oldUrl, oldState);
  11772. }
  11773. });
  11774. }
  11775. $location.$$replace = false;
  11776. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  11777. // there is a change
  11778. });
  11779. return $location;
  11780. function afterLocationChange(oldUrl, oldState) {
  11781. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  11782. $location.$$state, oldState);
  11783. }
  11784. }];
  11785. }
  11786. /**
  11787. * @ngdoc service
  11788. * @name $log
  11789. * @requires $window
  11790. *
  11791. * @description
  11792. * Simple service for logging. Default implementation safely writes the message
  11793. * into the browser's console (if present).
  11794. *
  11795. * The main purpose of this service is to simplify debugging and troubleshooting.
  11796. *
  11797. * The default is to log `debug` messages. You can use
  11798. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  11799. *
  11800. * @example
  11801. <example module="logExample">
  11802. <file name="script.js">
  11803. angular.module('logExample', [])
  11804. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  11805. $scope.$log = $log;
  11806. $scope.message = 'Hello World!';
  11807. }]);
  11808. </file>
  11809. <file name="index.html">
  11810. <div ng-controller="LogController">
  11811. <p>Reload this page with open console, enter text and hit the log button...</p>
  11812. <label>Message:
  11813. <input type="text" ng-model="message" /></label>
  11814. <button ng-click="$log.log(message)">log</button>
  11815. <button ng-click="$log.warn(message)">warn</button>
  11816. <button ng-click="$log.info(message)">info</button>
  11817. <button ng-click="$log.error(message)">error</button>
  11818. <button ng-click="$log.debug(message)">debug</button>
  11819. </div>
  11820. </file>
  11821. </example>
  11822. */
  11823. /**
  11824. * @ngdoc provider
  11825. * @name $logProvider
  11826. * @description
  11827. * Use the `$logProvider` to configure how the application logs messages
  11828. */
  11829. function $LogProvider() {
  11830. var debug = true,
  11831. self = this;
  11832. /**
  11833. * @ngdoc method
  11834. * @name $logProvider#debugEnabled
  11835. * @description
  11836. * @param {boolean=} flag enable or disable debug level messages
  11837. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  11838. */
  11839. this.debugEnabled = function(flag) {
  11840. if (isDefined(flag)) {
  11841. debug = flag;
  11842. return this;
  11843. } else {
  11844. return debug;
  11845. }
  11846. };
  11847. this.$get = ['$window', function($window) {
  11848. return {
  11849. /**
  11850. * @ngdoc method
  11851. * @name $log#log
  11852. *
  11853. * @description
  11854. * Write a log message
  11855. */
  11856. log: consoleLog('log'),
  11857. /**
  11858. * @ngdoc method
  11859. * @name $log#info
  11860. *
  11861. * @description
  11862. * Write an information message
  11863. */
  11864. info: consoleLog('info'),
  11865. /**
  11866. * @ngdoc method
  11867. * @name $log#warn
  11868. *
  11869. * @description
  11870. * Write a warning message
  11871. */
  11872. warn: consoleLog('warn'),
  11873. /**
  11874. * @ngdoc method
  11875. * @name $log#error
  11876. *
  11877. * @description
  11878. * Write an error message
  11879. */
  11880. error: consoleLog('error'),
  11881. /**
  11882. * @ngdoc method
  11883. * @name $log#debug
  11884. *
  11885. * @description
  11886. * Write a debug message
  11887. */
  11888. debug: (function() {
  11889. var fn = consoleLog('debug');
  11890. return function() {
  11891. if (debug) {
  11892. fn.apply(self, arguments);
  11893. }
  11894. };
  11895. }())
  11896. };
  11897. function formatError(arg) {
  11898. if (arg instanceof Error) {
  11899. if (arg.stack) {
  11900. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  11901. ? 'Error: ' + arg.message + '\n' + arg.stack
  11902. : arg.stack;
  11903. } else if (arg.sourceURL) {
  11904. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  11905. }
  11906. }
  11907. return arg;
  11908. }
  11909. function consoleLog(type) {
  11910. var console = $window.console || {},
  11911. logFn = console[type] || console.log || noop,
  11912. hasApply = false;
  11913. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  11914. // The reason behind this is that console.log has type "object" in IE8...
  11915. try {
  11916. hasApply = !!logFn.apply;
  11917. } catch (e) {}
  11918. if (hasApply) {
  11919. return function() {
  11920. var args = [];
  11921. forEach(arguments, function(arg) {
  11922. args.push(formatError(arg));
  11923. });
  11924. return logFn.apply(console, args);
  11925. };
  11926. }
  11927. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  11928. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  11929. return function(arg1, arg2) {
  11930. logFn(arg1, arg2 == null ? '' : arg2);
  11931. };
  11932. }
  11933. }];
  11934. }
  11935. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  11936. * Any commits to this file should be reviewed with security in mind. *
  11937. * Changes to this file can potentially create security vulnerabilities. *
  11938. * An approval from 2 Core members with history of modifying *
  11939. * this file is required. *
  11940. * *
  11941. * Does the change somehow allow for arbitrary javascript to be executed? *
  11942. * Or allows for someone to change the prototype of built-in objects? *
  11943. * Or gives undesired access to variables likes document or window? *
  11944. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  11945. var $parseMinErr = minErr('$parse');
  11946. // Sandboxing Angular Expressions
  11947. // ------------------------------
  11948. // Angular expressions are generally considered safe because these expressions only have direct
  11949. // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
  11950. // obtaining a reference to native JS functions such as the Function constructor.
  11951. //
  11952. // As an example, consider the following Angular expression:
  11953. //
  11954. // {}.toString.constructor('alert("evil JS code")')
  11955. //
  11956. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  11957. // against the expression language, but not to prevent exploits that were enabled by exposing
  11958. // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
  11959. // practice and therefore we are not even trying to protect against interaction with an object
  11960. // explicitly exposed in this way.
  11961. //
  11962. // In general, it is not possible to access a Window object from an angular expression unless a
  11963. // window or some DOM object that has a reference to window is published onto a Scope.
  11964. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  11965. // native objects.
  11966. //
  11967. // See https://docs.angularjs.org/guide/security
  11968. function ensureSafeMemberName(name, fullExpression) {
  11969. if (name === "__defineGetter__" || name === "__defineSetter__"
  11970. || name === "__lookupGetter__" || name === "__lookupSetter__"
  11971. || name === "__proto__") {
  11972. throw $parseMinErr('isecfld',
  11973. 'Attempting to access a disallowed field in Angular expressions! '
  11974. + 'Expression: {0}', fullExpression);
  11975. }
  11976. return name;
  11977. }
  11978. function getStringValue(name) {
  11979. // Property names must be strings. This means that non-string objects cannot be used
  11980. // as keys in an object. Any non-string object, including a number, is typecasted
  11981. // into a string via the toString method.
  11982. // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names
  11983. //
  11984. // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it
  11985. // to a string. It's not always possible. If `name` is an object and its `toString` method is
  11986. // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:
  11987. //
  11988. // TypeError: Cannot convert object to primitive value
  11989. //
  11990. // For performance reasons, we don't catch this error here and allow it to propagate up the call
  11991. // stack. Note that you'll get the same error in JavaScript if you try to access a property using
  11992. // such a 'broken' object as a key.
  11993. return name + '';
  11994. }
  11995. function ensureSafeObject(obj, fullExpression) {
  11996. // nifty check if obj is Function that is fast and works across iframes and other contexts
  11997. if (obj) {
  11998. if (obj.constructor === obj) {
  11999. throw $parseMinErr('isecfn',
  12000. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  12001. fullExpression);
  12002. } else if (// isWindow(obj)
  12003. obj.window === obj) {
  12004. throw $parseMinErr('isecwindow',
  12005. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  12006. fullExpression);
  12007. } else if (// isElement(obj)
  12008. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  12009. throw $parseMinErr('isecdom',
  12010. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  12011. fullExpression);
  12012. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  12013. obj === Object) {
  12014. throw $parseMinErr('isecobj',
  12015. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  12016. fullExpression);
  12017. }
  12018. }
  12019. return obj;
  12020. }
  12021. var CALL = Function.prototype.call;
  12022. var APPLY = Function.prototype.apply;
  12023. var BIND = Function.prototype.bind;
  12024. function ensureSafeFunction(obj, fullExpression) {
  12025. if (obj) {
  12026. if (obj.constructor === obj) {
  12027. throw $parseMinErr('isecfn',
  12028. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  12029. fullExpression);
  12030. } else if (obj === CALL || obj === APPLY || obj === BIND) {
  12031. throw $parseMinErr('isecff',
  12032. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  12033. fullExpression);
  12034. }
  12035. }
  12036. }
  12037. function ensureSafeAssignContext(obj, fullExpression) {
  12038. if (obj) {
  12039. if (obj === (0).constructor || obj === (false).constructor || obj === ''.constructor ||
  12040. obj === {}.constructor || obj === [].constructor || obj === Function.constructor) {
  12041. throw $parseMinErr('isecaf',
  12042. 'Assigning to a constructor is disallowed! Expression: {0}', fullExpression);
  12043. }
  12044. }
  12045. }
  12046. var OPERATORS = createMap();
  12047. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  12048. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  12049. /////////////////////////////////////////
  12050. /**
  12051. * @constructor
  12052. */
  12053. var Lexer = function(options) {
  12054. this.options = options;
  12055. };
  12056. Lexer.prototype = {
  12057. constructor: Lexer,
  12058. lex: function(text) {
  12059. this.text = text;
  12060. this.index = 0;
  12061. this.tokens = [];
  12062. while (this.index < this.text.length) {
  12063. var ch = this.text.charAt(this.index);
  12064. if (ch === '"' || ch === "'") {
  12065. this.readString(ch);
  12066. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  12067. this.readNumber();
  12068. } else if (this.isIdent(ch)) {
  12069. this.readIdent();
  12070. } else if (this.is(ch, '(){}[].,;:?')) {
  12071. this.tokens.push({index: this.index, text: ch});
  12072. this.index++;
  12073. } else if (this.isWhitespace(ch)) {
  12074. this.index++;
  12075. } else {
  12076. var ch2 = ch + this.peek();
  12077. var ch3 = ch2 + this.peek(2);
  12078. var op1 = OPERATORS[ch];
  12079. var op2 = OPERATORS[ch2];
  12080. var op3 = OPERATORS[ch3];
  12081. if (op1 || op2 || op3) {
  12082. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  12083. this.tokens.push({index: this.index, text: token, operator: true});
  12084. this.index += token.length;
  12085. } else {
  12086. this.throwError('Unexpected next character ', this.index, this.index + 1);
  12087. }
  12088. }
  12089. }
  12090. return this.tokens;
  12091. },
  12092. is: function(ch, chars) {
  12093. return chars.indexOf(ch) !== -1;
  12094. },
  12095. peek: function(i) {
  12096. var num = i || 1;
  12097. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  12098. },
  12099. isNumber: function(ch) {
  12100. return ('0' <= ch && ch <= '9') && typeof ch === "string";
  12101. },
  12102. isWhitespace: function(ch) {
  12103. // IE treats non-breaking space as \u00A0
  12104. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  12105. ch === '\n' || ch === '\v' || ch === '\u00A0');
  12106. },
  12107. isIdent: function(ch) {
  12108. return ('a' <= ch && ch <= 'z' ||
  12109. 'A' <= ch && ch <= 'Z' ||
  12110. '_' === ch || ch === '$');
  12111. },
  12112. isExpOperator: function(ch) {
  12113. return (ch === '-' || ch === '+' || this.isNumber(ch));
  12114. },
  12115. throwError: function(error, start, end) {
  12116. end = end || this.index;
  12117. var colStr = (isDefined(start)
  12118. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  12119. : ' ' + end);
  12120. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  12121. error, colStr, this.text);
  12122. },
  12123. readNumber: function() {
  12124. var number = '';
  12125. var start = this.index;
  12126. while (this.index < this.text.length) {
  12127. var ch = lowercase(this.text.charAt(this.index));
  12128. if (ch == '.' || this.isNumber(ch)) {
  12129. number += ch;
  12130. } else {
  12131. var peekCh = this.peek();
  12132. if (ch == 'e' && this.isExpOperator(peekCh)) {
  12133. number += ch;
  12134. } else if (this.isExpOperator(ch) &&
  12135. peekCh && this.isNumber(peekCh) &&
  12136. number.charAt(number.length - 1) == 'e') {
  12137. number += ch;
  12138. } else if (this.isExpOperator(ch) &&
  12139. (!peekCh || !this.isNumber(peekCh)) &&
  12140. number.charAt(number.length - 1) == 'e') {
  12141. this.throwError('Invalid exponent');
  12142. } else {
  12143. break;
  12144. }
  12145. }
  12146. this.index++;
  12147. }
  12148. this.tokens.push({
  12149. index: start,
  12150. text: number,
  12151. constant: true,
  12152. value: Number(number)
  12153. });
  12154. },
  12155. readIdent: function() {
  12156. var start = this.index;
  12157. while (this.index < this.text.length) {
  12158. var ch = this.text.charAt(this.index);
  12159. if (!(this.isIdent(ch) || this.isNumber(ch))) {
  12160. break;
  12161. }
  12162. this.index++;
  12163. }
  12164. this.tokens.push({
  12165. index: start,
  12166. text: this.text.slice(start, this.index),
  12167. identifier: true
  12168. });
  12169. },
  12170. readString: function(quote) {
  12171. var start = this.index;
  12172. this.index++;
  12173. var string = '';
  12174. var rawString = quote;
  12175. var escape = false;
  12176. while (this.index < this.text.length) {
  12177. var ch = this.text.charAt(this.index);
  12178. rawString += ch;
  12179. if (escape) {
  12180. if (ch === 'u') {
  12181. var hex = this.text.substring(this.index + 1, this.index + 5);
  12182. if (!hex.match(/[\da-f]{4}/i)) {
  12183. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  12184. }
  12185. this.index += 4;
  12186. string += String.fromCharCode(parseInt(hex, 16));
  12187. } else {
  12188. var rep = ESCAPE[ch];
  12189. string = string + (rep || ch);
  12190. }
  12191. escape = false;
  12192. } else if (ch === '\\') {
  12193. escape = true;
  12194. } else if (ch === quote) {
  12195. this.index++;
  12196. this.tokens.push({
  12197. index: start,
  12198. text: rawString,
  12199. constant: true,
  12200. value: string
  12201. });
  12202. return;
  12203. } else {
  12204. string += ch;
  12205. }
  12206. this.index++;
  12207. }
  12208. this.throwError('Unterminated quote', start);
  12209. }
  12210. };
  12211. var AST = function(lexer, options) {
  12212. this.lexer = lexer;
  12213. this.options = options;
  12214. };
  12215. AST.Program = 'Program';
  12216. AST.ExpressionStatement = 'ExpressionStatement';
  12217. AST.AssignmentExpression = 'AssignmentExpression';
  12218. AST.ConditionalExpression = 'ConditionalExpression';
  12219. AST.LogicalExpression = 'LogicalExpression';
  12220. AST.BinaryExpression = 'BinaryExpression';
  12221. AST.UnaryExpression = 'UnaryExpression';
  12222. AST.CallExpression = 'CallExpression';
  12223. AST.MemberExpression = 'MemberExpression';
  12224. AST.Identifier = 'Identifier';
  12225. AST.Literal = 'Literal';
  12226. AST.ArrayExpression = 'ArrayExpression';
  12227. AST.Property = 'Property';
  12228. AST.ObjectExpression = 'ObjectExpression';
  12229. AST.ThisExpression = 'ThisExpression';
  12230. AST.LocalsExpression = 'LocalsExpression';
  12231. // Internal use only
  12232. AST.NGValueParameter = 'NGValueParameter';
  12233. AST.prototype = {
  12234. ast: function(text) {
  12235. this.text = text;
  12236. this.tokens = this.lexer.lex(text);
  12237. var value = this.program();
  12238. if (this.tokens.length !== 0) {
  12239. this.throwError('is an unexpected token', this.tokens[0]);
  12240. }
  12241. return value;
  12242. },
  12243. program: function() {
  12244. var body = [];
  12245. while (true) {
  12246. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  12247. body.push(this.expressionStatement());
  12248. if (!this.expect(';')) {
  12249. return { type: AST.Program, body: body};
  12250. }
  12251. }
  12252. },
  12253. expressionStatement: function() {
  12254. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  12255. },
  12256. filterChain: function() {
  12257. var left = this.expression();
  12258. var token;
  12259. while ((token = this.expect('|'))) {
  12260. left = this.filter(left);
  12261. }
  12262. return left;
  12263. },
  12264. expression: function() {
  12265. return this.assignment();
  12266. },
  12267. assignment: function() {
  12268. var result = this.ternary();
  12269. if (this.expect('=')) {
  12270. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  12271. }
  12272. return result;
  12273. },
  12274. ternary: function() {
  12275. var test = this.logicalOR();
  12276. var alternate;
  12277. var consequent;
  12278. if (this.expect('?')) {
  12279. alternate = this.expression();
  12280. if (this.consume(':')) {
  12281. consequent = this.expression();
  12282. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  12283. }
  12284. }
  12285. return test;
  12286. },
  12287. logicalOR: function() {
  12288. var left = this.logicalAND();
  12289. while (this.expect('||')) {
  12290. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  12291. }
  12292. return left;
  12293. },
  12294. logicalAND: function() {
  12295. var left = this.equality();
  12296. while (this.expect('&&')) {
  12297. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  12298. }
  12299. return left;
  12300. },
  12301. equality: function() {
  12302. var left = this.relational();
  12303. var token;
  12304. while ((token = this.expect('==','!=','===','!=='))) {
  12305. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  12306. }
  12307. return left;
  12308. },
  12309. relational: function() {
  12310. var left = this.additive();
  12311. var token;
  12312. while ((token = this.expect('<', '>', '<=', '>='))) {
  12313. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  12314. }
  12315. return left;
  12316. },
  12317. additive: function() {
  12318. var left = this.multiplicative();
  12319. var token;
  12320. while ((token = this.expect('+','-'))) {
  12321. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  12322. }
  12323. return left;
  12324. },
  12325. multiplicative: function() {
  12326. var left = this.unary();
  12327. var token;
  12328. while ((token = this.expect('*','/','%'))) {
  12329. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  12330. }
  12331. return left;
  12332. },
  12333. unary: function() {
  12334. var token;
  12335. if ((token = this.expect('+', '-', '!'))) {
  12336. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  12337. } else {
  12338. return this.primary();
  12339. }
  12340. },
  12341. primary: function() {
  12342. var primary;
  12343. if (this.expect('(')) {
  12344. primary = this.filterChain();
  12345. this.consume(')');
  12346. } else if (this.expect('[')) {
  12347. primary = this.arrayDeclaration();
  12348. } else if (this.expect('{')) {
  12349. primary = this.object();
  12350. } else if (this.constants.hasOwnProperty(this.peek().text)) {
  12351. primary = copy(this.constants[this.consume().text]);
  12352. } else if (this.peek().identifier) {
  12353. primary = this.identifier();
  12354. } else if (this.peek().constant) {
  12355. primary = this.constant();
  12356. } else {
  12357. this.throwError('not a primary expression', this.peek());
  12358. }
  12359. var next;
  12360. while ((next = this.expect('(', '[', '.'))) {
  12361. if (next.text === '(') {
  12362. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  12363. this.consume(')');
  12364. } else if (next.text === '[') {
  12365. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  12366. this.consume(']');
  12367. } else if (next.text === '.') {
  12368. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  12369. } else {
  12370. this.throwError('IMPOSSIBLE');
  12371. }
  12372. }
  12373. return primary;
  12374. },
  12375. filter: function(baseExpression) {
  12376. var args = [baseExpression];
  12377. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  12378. while (this.expect(':')) {
  12379. args.push(this.expression());
  12380. }
  12381. return result;
  12382. },
  12383. parseArguments: function() {
  12384. var args = [];
  12385. if (this.peekToken().text !== ')') {
  12386. do {
  12387. args.push(this.expression());
  12388. } while (this.expect(','));
  12389. }
  12390. return args;
  12391. },
  12392. identifier: function() {
  12393. var token = this.consume();
  12394. if (!token.identifier) {
  12395. this.throwError('is not a valid identifier', token);
  12396. }
  12397. return { type: AST.Identifier, name: token.text };
  12398. },
  12399. constant: function() {
  12400. // TODO check that it is a constant
  12401. return { type: AST.Literal, value: this.consume().value };
  12402. },
  12403. arrayDeclaration: function() {
  12404. var elements = [];
  12405. if (this.peekToken().text !== ']') {
  12406. do {
  12407. if (this.peek(']')) {
  12408. // Support trailing commas per ES5.1.
  12409. break;
  12410. }
  12411. elements.push(this.expression());
  12412. } while (this.expect(','));
  12413. }
  12414. this.consume(']');
  12415. return { type: AST.ArrayExpression, elements: elements };
  12416. },
  12417. object: function() {
  12418. var properties = [], property;
  12419. if (this.peekToken().text !== '}') {
  12420. do {
  12421. if (this.peek('}')) {
  12422. // Support trailing commas per ES5.1.
  12423. break;
  12424. }
  12425. property = {type: AST.Property, kind: 'init'};
  12426. if (this.peek().constant) {
  12427. property.key = this.constant();
  12428. } else if (this.peek().identifier) {
  12429. property.key = this.identifier();
  12430. } else {
  12431. this.throwError("invalid key", this.peek());
  12432. }
  12433. this.consume(':');
  12434. property.value = this.expression();
  12435. properties.push(property);
  12436. } while (this.expect(','));
  12437. }
  12438. this.consume('}');
  12439. return {type: AST.ObjectExpression, properties: properties };
  12440. },
  12441. throwError: function(msg, token) {
  12442. throw $parseMinErr('syntax',
  12443. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  12444. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  12445. },
  12446. consume: function(e1) {
  12447. if (this.tokens.length === 0) {
  12448. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  12449. }
  12450. var token = this.expect(e1);
  12451. if (!token) {
  12452. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  12453. }
  12454. return token;
  12455. },
  12456. peekToken: function() {
  12457. if (this.tokens.length === 0) {
  12458. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  12459. }
  12460. return this.tokens[0];
  12461. },
  12462. peek: function(e1, e2, e3, e4) {
  12463. return this.peekAhead(0, e1, e2, e3, e4);
  12464. },
  12465. peekAhead: function(i, e1, e2, e3, e4) {
  12466. if (this.tokens.length > i) {
  12467. var token = this.tokens[i];
  12468. var t = token.text;
  12469. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  12470. (!e1 && !e2 && !e3 && !e4)) {
  12471. return token;
  12472. }
  12473. }
  12474. return false;
  12475. },
  12476. expect: function(e1, e2, e3, e4) {
  12477. var token = this.peek(e1, e2, e3, e4);
  12478. if (token) {
  12479. this.tokens.shift();
  12480. return token;
  12481. }
  12482. return false;
  12483. },
  12484. /* `undefined` is not a constant, it is an identifier,
  12485. * but using it as an identifier is not supported
  12486. */
  12487. constants: {
  12488. 'true': { type: AST.Literal, value: true },
  12489. 'false': { type: AST.Literal, value: false },
  12490. 'null': { type: AST.Literal, value: null },
  12491. 'undefined': {type: AST.Literal, value: undefined },
  12492. 'this': {type: AST.ThisExpression },
  12493. '$locals': {type: AST.LocalsExpression }
  12494. }
  12495. };
  12496. function ifDefined(v, d) {
  12497. return typeof v !== 'undefined' ? v : d;
  12498. }
  12499. function plusFn(l, r) {
  12500. if (typeof l === 'undefined') return r;
  12501. if (typeof r === 'undefined') return l;
  12502. return l + r;
  12503. }
  12504. function isStateless($filter, filterName) {
  12505. var fn = $filter(filterName);
  12506. return !fn.$stateful;
  12507. }
  12508. function findConstantAndWatchExpressions(ast, $filter) {
  12509. var allConstants;
  12510. var argsToWatch;
  12511. switch (ast.type) {
  12512. case AST.Program:
  12513. allConstants = true;
  12514. forEach(ast.body, function(expr) {
  12515. findConstantAndWatchExpressions(expr.expression, $filter);
  12516. allConstants = allConstants && expr.expression.constant;
  12517. });
  12518. ast.constant = allConstants;
  12519. break;
  12520. case AST.Literal:
  12521. ast.constant = true;
  12522. ast.toWatch = [];
  12523. break;
  12524. case AST.UnaryExpression:
  12525. findConstantAndWatchExpressions(ast.argument, $filter);
  12526. ast.constant = ast.argument.constant;
  12527. ast.toWatch = ast.argument.toWatch;
  12528. break;
  12529. case AST.BinaryExpression:
  12530. findConstantAndWatchExpressions(ast.left, $filter);
  12531. findConstantAndWatchExpressions(ast.right, $filter);
  12532. ast.constant = ast.left.constant && ast.right.constant;
  12533. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  12534. break;
  12535. case AST.LogicalExpression:
  12536. findConstantAndWatchExpressions(ast.left, $filter);
  12537. findConstantAndWatchExpressions(ast.right, $filter);
  12538. ast.constant = ast.left.constant && ast.right.constant;
  12539. ast.toWatch = ast.constant ? [] : [ast];
  12540. break;
  12541. case AST.ConditionalExpression:
  12542. findConstantAndWatchExpressions(ast.test, $filter);
  12543. findConstantAndWatchExpressions(ast.alternate, $filter);
  12544. findConstantAndWatchExpressions(ast.consequent, $filter);
  12545. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  12546. ast.toWatch = ast.constant ? [] : [ast];
  12547. break;
  12548. case AST.Identifier:
  12549. ast.constant = false;
  12550. ast.toWatch = [ast];
  12551. break;
  12552. case AST.MemberExpression:
  12553. findConstantAndWatchExpressions(ast.object, $filter);
  12554. if (ast.computed) {
  12555. findConstantAndWatchExpressions(ast.property, $filter);
  12556. }
  12557. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  12558. ast.toWatch = [ast];
  12559. break;
  12560. case AST.CallExpression:
  12561. allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
  12562. argsToWatch = [];
  12563. forEach(ast.arguments, function(expr) {
  12564. findConstantAndWatchExpressions(expr, $filter);
  12565. allConstants = allConstants && expr.constant;
  12566. if (!expr.constant) {
  12567. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  12568. }
  12569. });
  12570. ast.constant = allConstants;
  12571. ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
  12572. break;
  12573. case AST.AssignmentExpression:
  12574. findConstantAndWatchExpressions(ast.left, $filter);
  12575. findConstantAndWatchExpressions(ast.right, $filter);
  12576. ast.constant = ast.left.constant && ast.right.constant;
  12577. ast.toWatch = [ast];
  12578. break;
  12579. case AST.ArrayExpression:
  12580. allConstants = true;
  12581. argsToWatch = [];
  12582. forEach(ast.elements, function(expr) {
  12583. findConstantAndWatchExpressions(expr, $filter);
  12584. allConstants = allConstants && expr.constant;
  12585. if (!expr.constant) {
  12586. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  12587. }
  12588. });
  12589. ast.constant = allConstants;
  12590. ast.toWatch = argsToWatch;
  12591. break;
  12592. case AST.ObjectExpression:
  12593. allConstants = true;
  12594. argsToWatch = [];
  12595. forEach(ast.properties, function(property) {
  12596. findConstantAndWatchExpressions(property.value, $filter);
  12597. allConstants = allConstants && property.value.constant;
  12598. if (!property.value.constant) {
  12599. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  12600. }
  12601. });
  12602. ast.constant = allConstants;
  12603. ast.toWatch = argsToWatch;
  12604. break;
  12605. case AST.ThisExpression:
  12606. ast.constant = false;
  12607. ast.toWatch = [];
  12608. break;
  12609. case AST.LocalsExpression:
  12610. ast.constant = false;
  12611. ast.toWatch = [];
  12612. break;
  12613. }
  12614. }
  12615. function getInputs(body) {
  12616. if (body.length != 1) return;
  12617. var lastExpression = body[0].expression;
  12618. var candidate = lastExpression.toWatch;
  12619. if (candidate.length !== 1) return candidate;
  12620. return candidate[0] !== lastExpression ? candidate : undefined;
  12621. }
  12622. function isAssignable(ast) {
  12623. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  12624. }
  12625. function assignableAST(ast) {
  12626. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  12627. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  12628. }
  12629. }
  12630. function isLiteral(ast) {
  12631. return ast.body.length === 0 ||
  12632. ast.body.length === 1 && (
  12633. ast.body[0].expression.type === AST.Literal ||
  12634. ast.body[0].expression.type === AST.ArrayExpression ||
  12635. ast.body[0].expression.type === AST.ObjectExpression);
  12636. }
  12637. function isConstant(ast) {
  12638. return ast.constant;
  12639. }
  12640. function ASTCompiler(astBuilder, $filter) {
  12641. this.astBuilder = astBuilder;
  12642. this.$filter = $filter;
  12643. }
  12644. ASTCompiler.prototype = {
  12645. compile: function(expression, expensiveChecks) {
  12646. var self = this;
  12647. var ast = this.astBuilder.ast(expression);
  12648. this.state = {
  12649. nextId: 0,
  12650. filters: {},
  12651. expensiveChecks: expensiveChecks,
  12652. fn: {vars: [], body: [], own: {}},
  12653. assign: {vars: [], body: [], own: {}},
  12654. inputs: []
  12655. };
  12656. findConstantAndWatchExpressions(ast, self.$filter);
  12657. var extra = '';
  12658. var assignable;
  12659. this.stage = 'assign';
  12660. if ((assignable = assignableAST(ast))) {
  12661. this.state.computing = 'assign';
  12662. var result = this.nextId();
  12663. this.recurse(assignable, result);
  12664. this.return_(result);
  12665. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  12666. }
  12667. var toWatch = getInputs(ast.body);
  12668. self.stage = 'inputs';
  12669. forEach(toWatch, function(watch, key) {
  12670. var fnKey = 'fn' + key;
  12671. self.state[fnKey] = {vars: [], body: [], own: {}};
  12672. self.state.computing = fnKey;
  12673. var intoId = self.nextId();
  12674. self.recurse(watch, intoId);
  12675. self.return_(intoId);
  12676. self.state.inputs.push(fnKey);
  12677. watch.watchId = key;
  12678. });
  12679. this.state.computing = 'fn';
  12680. this.stage = 'main';
  12681. this.recurse(ast);
  12682. var fnString =
  12683. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  12684. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  12685. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  12686. this.filterPrefix() +
  12687. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  12688. extra +
  12689. this.watchFns() +
  12690. 'return fn;';
  12691. /* jshint -W054 */
  12692. var fn = (new Function('$filter',
  12693. 'ensureSafeMemberName',
  12694. 'ensureSafeObject',
  12695. 'ensureSafeFunction',
  12696. 'getStringValue',
  12697. 'ensureSafeAssignContext',
  12698. 'ifDefined',
  12699. 'plus',
  12700. 'text',
  12701. fnString))(
  12702. this.$filter,
  12703. ensureSafeMemberName,
  12704. ensureSafeObject,
  12705. ensureSafeFunction,
  12706. getStringValue,
  12707. ensureSafeAssignContext,
  12708. ifDefined,
  12709. plusFn,
  12710. expression);
  12711. /* jshint +W054 */
  12712. this.state = this.stage = undefined;
  12713. fn.literal = isLiteral(ast);
  12714. fn.constant = isConstant(ast);
  12715. return fn;
  12716. },
  12717. USE: 'use',
  12718. STRICT: 'strict',
  12719. watchFns: function() {
  12720. var result = [];
  12721. var fns = this.state.inputs;
  12722. var self = this;
  12723. forEach(fns, function(name) {
  12724. result.push('var ' + name + '=' + self.generateFunction(name, 's'));
  12725. });
  12726. if (fns.length) {
  12727. result.push('fn.inputs=[' + fns.join(',') + '];');
  12728. }
  12729. return result.join('');
  12730. },
  12731. generateFunction: function(name, params) {
  12732. return 'function(' + params + '){' +
  12733. this.varsPrefix(name) +
  12734. this.body(name) +
  12735. '};';
  12736. },
  12737. filterPrefix: function() {
  12738. var parts = [];
  12739. var self = this;
  12740. forEach(this.state.filters, function(id, filter) {
  12741. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  12742. });
  12743. if (parts.length) return 'var ' + parts.join(',') + ';';
  12744. return '';
  12745. },
  12746. varsPrefix: function(section) {
  12747. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  12748. },
  12749. body: function(section) {
  12750. return this.state[section].body.join('');
  12751. },
  12752. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  12753. var left, right, self = this, args, expression;
  12754. recursionFn = recursionFn || noop;
  12755. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  12756. intoId = intoId || this.nextId();
  12757. this.if_('i',
  12758. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  12759. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  12760. );
  12761. return;
  12762. }
  12763. switch (ast.type) {
  12764. case AST.Program:
  12765. forEach(ast.body, function(expression, pos) {
  12766. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  12767. if (pos !== ast.body.length - 1) {
  12768. self.current().body.push(right, ';');
  12769. } else {
  12770. self.return_(right);
  12771. }
  12772. });
  12773. break;
  12774. case AST.Literal:
  12775. expression = this.escape(ast.value);
  12776. this.assign(intoId, expression);
  12777. recursionFn(expression);
  12778. break;
  12779. case AST.UnaryExpression:
  12780. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  12781. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  12782. this.assign(intoId, expression);
  12783. recursionFn(expression);
  12784. break;
  12785. case AST.BinaryExpression:
  12786. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  12787. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  12788. if (ast.operator === '+') {
  12789. expression = this.plus(left, right);
  12790. } else if (ast.operator === '-') {
  12791. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  12792. } else {
  12793. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  12794. }
  12795. this.assign(intoId, expression);
  12796. recursionFn(expression);
  12797. break;
  12798. case AST.LogicalExpression:
  12799. intoId = intoId || this.nextId();
  12800. self.recurse(ast.left, intoId);
  12801. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  12802. recursionFn(intoId);
  12803. break;
  12804. case AST.ConditionalExpression:
  12805. intoId = intoId || this.nextId();
  12806. self.recurse(ast.test, intoId);
  12807. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  12808. recursionFn(intoId);
  12809. break;
  12810. case AST.Identifier:
  12811. intoId = intoId || this.nextId();
  12812. if (nameId) {
  12813. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  12814. nameId.computed = false;
  12815. nameId.name = ast.name;
  12816. }
  12817. ensureSafeMemberName(ast.name);
  12818. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  12819. function() {
  12820. self.if_(self.stage === 'inputs' || 's', function() {
  12821. if (create && create !== 1) {
  12822. self.if_(
  12823. self.not(self.nonComputedMember('s', ast.name)),
  12824. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  12825. }
  12826. self.assign(intoId, self.nonComputedMember('s', ast.name));
  12827. });
  12828. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  12829. );
  12830. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
  12831. self.addEnsureSafeObject(intoId);
  12832. }
  12833. recursionFn(intoId);
  12834. break;
  12835. case AST.MemberExpression:
  12836. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  12837. intoId = intoId || this.nextId();
  12838. self.recurse(ast.object, left, undefined, function() {
  12839. self.if_(self.notNull(left), function() {
  12840. if (create && create !== 1) {
  12841. self.addEnsureSafeAssignContext(left);
  12842. }
  12843. if (ast.computed) {
  12844. right = self.nextId();
  12845. self.recurse(ast.property, right);
  12846. self.getStringValue(right);
  12847. self.addEnsureSafeMemberName(right);
  12848. if (create && create !== 1) {
  12849. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  12850. }
  12851. expression = self.ensureSafeObject(self.computedMember(left, right));
  12852. self.assign(intoId, expression);
  12853. if (nameId) {
  12854. nameId.computed = true;
  12855. nameId.name = right;
  12856. }
  12857. } else {
  12858. ensureSafeMemberName(ast.property.name);
  12859. if (create && create !== 1) {
  12860. self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  12861. }
  12862. expression = self.nonComputedMember(left, ast.property.name);
  12863. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
  12864. expression = self.ensureSafeObject(expression);
  12865. }
  12866. self.assign(intoId, expression);
  12867. if (nameId) {
  12868. nameId.computed = false;
  12869. nameId.name = ast.property.name;
  12870. }
  12871. }
  12872. }, function() {
  12873. self.assign(intoId, 'undefined');
  12874. });
  12875. recursionFn(intoId);
  12876. }, !!create);
  12877. break;
  12878. case AST.CallExpression:
  12879. intoId = intoId || this.nextId();
  12880. if (ast.filter) {
  12881. right = self.filter(ast.callee.name);
  12882. args = [];
  12883. forEach(ast.arguments, function(expr) {
  12884. var argument = self.nextId();
  12885. self.recurse(expr, argument);
  12886. args.push(argument);
  12887. });
  12888. expression = right + '(' + args.join(',') + ')';
  12889. self.assign(intoId, expression);
  12890. recursionFn(intoId);
  12891. } else {
  12892. right = self.nextId();
  12893. left = {};
  12894. args = [];
  12895. self.recurse(ast.callee, right, left, function() {
  12896. self.if_(self.notNull(right), function() {
  12897. self.addEnsureSafeFunction(right);
  12898. forEach(ast.arguments, function(expr) {
  12899. self.recurse(expr, self.nextId(), undefined, function(argument) {
  12900. args.push(self.ensureSafeObject(argument));
  12901. });
  12902. });
  12903. if (left.name) {
  12904. if (!self.state.expensiveChecks) {
  12905. self.addEnsureSafeObject(left.context);
  12906. }
  12907. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  12908. } else {
  12909. expression = right + '(' + args.join(',') + ')';
  12910. }
  12911. expression = self.ensureSafeObject(expression);
  12912. self.assign(intoId, expression);
  12913. }, function() {
  12914. self.assign(intoId, 'undefined');
  12915. });
  12916. recursionFn(intoId);
  12917. });
  12918. }
  12919. break;
  12920. case AST.AssignmentExpression:
  12921. right = this.nextId();
  12922. left = {};
  12923. if (!isAssignable(ast.left)) {
  12924. throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
  12925. }
  12926. this.recurse(ast.left, undefined, left, function() {
  12927. self.if_(self.notNull(left.context), function() {
  12928. self.recurse(ast.right, right);
  12929. self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
  12930. self.addEnsureSafeAssignContext(left.context);
  12931. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  12932. self.assign(intoId, expression);
  12933. recursionFn(intoId || expression);
  12934. });
  12935. }, 1);
  12936. break;
  12937. case AST.ArrayExpression:
  12938. args = [];
  12939. forEach(ast.elements, function(expr) {
  12940. self.recurse(expr, self.nextId(), undefined, function(argument) {
  12941. args.push(argument);
  12942. });
  12943. });
  12944. expression = '[' + args.join(',') + ']';
  12945. this.assign(intoId, expression);
  12946. recursionFn(expression);
  12947. break;
  12948. case AST.ObjectExpression:
  12949. args = [];
  12950. forEach(ast.properties, function(property) {
  12951. self.recurse(property.value, self.nextId(), undefined, function(expr) {
  12952. args.push(self.escape(
  12953. property.key.type === AST.Identifier ? property.key.name :
  12954. ('' + property.key.value)) +
  12955. ':' + expr);
  12956. });
  12957. });
  12958. expression = '{' + args.join(',') + '}';
  12959. this.assign(intoId, expression);
  12960. recursionFn(expression);
  12961. break;
  12962. case AST.ThisExpression:
  12963. this.assign(intoId, 's');
  12964. recursionFn('s');
  12965. break;
  12966. case AST.LocalsExpression:
  12967. this.assign(intoId, 'l');
  12968. recursionFn('l');
  12969. break;
  12970. case AST.NGValueParameter:
  12971. this.assign(intoId, 'v');
  12972. recursionFn('v');
  12973. break;
  12974. }
  12975. },
  12976. getHasOwnProperty: function(element, property) {
  12977. var key = element + '.' + property;
  12978. var own = this.current().own;
  12979. if (!own.hasOwnProperty(key)) {
  12980. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  12981. }
  12982. return own[key];
  12983. },
  12984. assign: function(id, value) {
  12985. if (!id) return;
  12986. this.current().body.push(id, '=', value, ';');
  12987. return id;
  12988. },
  12989. filter: function(filterName) {
  12990. if (!this.state.filters.hasOwnProperty(filterName)) {
  12991. this.state.filters[filterName] = this.nextId(true);
  12992. }
  12993. return this.state.filters[filterName];
  12994. },
  12995. ifDefined: function(id, defaultValue) {
  12996. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  12997. },
  12998. plus: function(left, right) {
  12999. return 'plus(' + left + ',' + right + ')';
  13000. },
  13001. return_: function(id) {
  13002. this.current().body.push('return ', id, ';');
  13003. },
  13004. if_: function(test, alternate, consequent) {
  13005. if (test === true) {
  13006. alternate();
  13007. } else {
  13008. var body = this.current().body;
  13009. body.push('if(', test, '){');
  13010. alternate();
  13011. body.push('}');
  13012. if (consequent) {
  13013. body.push('else{');
  13014. consequent();
  13015. body.push('}');
  13016. }
  13017. }
  13018. },
  13019. not: function(expression) {
  13020. return '!(' + expression + ')';
  13021. },
  13022. notNull: function(expression) {
  13023. return expression + '!=null';
  13024. },
  13025. nonComputedMember: function(left, right) {
  13026. return left + '.' + right;
  13027. },
  13028. computedMember: function(left, right) {
  13029. return left + '[' + right + ']';
  13030. },
  13031. member: function(left, right, computed) {
  13032. if (computed) return this.computedMember(left, right);
  13033. return this.nonComputedMember(left, right);
  13034. },
  13035. addEnsureSafeObject: function(item) {
  13036. this.current().body.push(this.ensureSafeObject(item), ';');
  13037. },
  13038. addEnsureSafeMemberName: function(item) {
  13039. this.current().body.push(this.ensureSafeMemberName(item), ';');
  13040. },
  13041. addEnsureSafeFunction: function(item) {
  13042. this.current().body.push(this.ensureSafeFunction(item), ';');
  13043. },
  13044. addEnsureSafeAssignContext: function(item) {
  13045. this.current().body.push(this.ensureSafeAssignContext(item), ';');
  13046. },
  13047. ensureSafeObject: function(item) {
  13048. return 'ensureSafeObject(' + item + ',text)';
  13049. },
  13050. ensureSafeMemberName: function(item) {
  13051. return 'ensureSafeMemberName(' + item + ',text)';
  13052. },
  13053. ensureSafeFunction: function(item) {
  13054. return 'ensureSafeFunction(' + item + ',text)';
  13055. },
  13056. getStringValue: function(item) {
  13057. this.assign(item, 'getStringValue(' + item + ')');
  13058. },
  13059. ensureSafeAssignContext: function(item) {
  13060. return 'ensureSafeAssignContext(' + item + ',text)';
  13061. },
  13062. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  13063. var self = this;
  13064. return function() {
  13065. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  13066. };
  13067. },
  13068. lazyAssign: function(id, value) {
  13069. var self = this;
  13070. return function() {
  13071. self.assign(id, value);
  13072. };
  13073. },
  13074. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  13075. stringEscapeFn: function(c) {
  13076. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  13077. },
  13078. escape: function(value) {
  13079. if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
  13080. if (isNumber(value)) return value.toString();
  13081. if (value === true) return 'true';
  13082. if (value === false) return 'false';
  13083. if (value === null) return 'null';
  13084. if (typeof value === 'undefined') return 'undefined';
  13085. throw $parseMinErr('esc', 'IMPOSSIBLE');
  13086. },
  13087. nextId: function(skip, init) {
  13088. var id = 'v' + (this.state.nextId++);
  13089. if (!skip) {
  13090. this.current().vars.push(id + (init ? '=' + init : ''));
  13091. }
  13092. return id;
  13093. },
  13094. current: function() {
  13095. return this.state[this.state.computing];
  13096. }
  13097. };
  13098. function ASTInterpreter(astBuilder, $filter) {
  13099. this.astBuilder = astBuilder;
  13100. this.$filter = $filter;
  13101. }
  13102. ASTInterpreter.prototype = {
  13103. compile: function(expression, expensiveChecks) {
  13104. var self = this;
  13105. var ast = this.astBuilder.ast(expression);
  13106. this.expression = expression;
  13107. this.expensiveChecks = expensiveChecks;
  13108. findConstantAndWatchExpressions(ast, self.$filter);
  13109. var assignable;
  13110. var assign;
  13111. if ((assignable = assignableAST(ast))) {
  13112. assign = this.recurse(assignable);
  13113. }
  13114. var toWatch = getInputs(ast.body);
  13115. var inputs;
  13116. if (toWatch) {
  13117. inputs = [];
  13118. forEach(toWatch, function(watch, key) {
  13119. var input = self.recurse(watch);
  13120. watch.input = input;
  13121. inputs.push(input);
  13122. watch.watchId = key;
  13123. });
  13124. }
  13125. var expressions = [];
  13126. forEach(ast.body, function(expression) {
  13127. expressions.push(self.recurse(expression.expression));
  13128. });
  13129. var fn = ast.body.length === 0 ? function() {} :
  13130. ast.body.length === 1 ? expressions[0] :
  13131. function(scope, locals) {
  13132. var lastValue;
  13133. forEach(expressions, function(exp) {
  13134. lastValue = exp(scope, locals);
  13135. });
  13136. return lastValue;
  13137. };
  13138. if (assign) {
  13139. fn.assign = function(scope, value, locals) {
  13140. return assign(scope, locals, value);
  13141. };
  13142. }
  13143. if (inputs) {
  13144. fn.inputs = inputs;
  13145. }
  13146. fn.literal = isLiteral(ast);
  13147. fn.constant = isConstant(ast);
  13148. return fn;
  13149. },
  13150. recurse: function(ast, context, create) {
  13151. var left, right, self = this, args, expression;
  13152. if (ast.input) {
  13153. return this.inputs(ast.input, ast.watchId);
  13154. }
  13155. switch (ast.type) {
  13156. case AST.Literal:
  13157. return this.value(ast.value, context);
  13158. case AST.UnaryExpression:
  13159. right = this.recurse(ast.argument);
  13160. return this['unary' + ast.operator](right, context);
  13161. case AST.BinaryExpression:
  13162. left = this.recurse(ast.left);
  13163. right = this.recurse(ast.right);
  13164. return this['binary' + ast.operator](left, right, context);
  13165. case AST.LogicalExpression:
  13166. left = this.recurse(ast.left);
  13167. right = this.recurse(ast.right);
  13168. return this['binary' + ast.operator](left, right, context);
  13169. case AST.ConditionalExpression:
  13170. return this['ternary?:'](
  13171. this.recurse(ast.test),
  13172. this.recurse(ast.alternate),
  13173. this.recurse(ast.consequent),
  13174. context
  13175. );
  13176. case AST.Identifier:
  13177. ensureSafeMemberName(ast.name, self.expression);
  13178. return self.identifier(ast.name,
  13179. self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
  13180. context, create, self.expression);
  13181. case AST.MemberExpression:
  13182. left = this.recurse(ast.object, false, !!create);
  13183. if (!ast.computed) {
  13184. ensureSafeMemberName(ast.property.name, self.expression);
  13185. right = ast.property.name;
  13186. }
  13187. if (ast.computed) right = this.recurse(ast.property);
  13188. return ast.computed ?
  13189. this.computedMember(left, right, context, create, self.expression) :
  13190. this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
  13191. case AST.CallExpression:
  13192. args = [];
  13193. forEach(ast.arguments, function(expr) {
  13194. args.push(self.recurse(expr));
  13195. });
  13196. if (ast.filter) right = this.$filter(ast.callee.name);
  13197. if (!ast.filter) right = this.recurse(ast.callee, true);
  13198. return ast.filter ?
  13199. function(scope, locals, assign, inputs) {
  13200. var values = [];
  13201. for (var i = 0; i < args.length; ++i) {
  13202. values.push(args[i](scope, locals, assign, inputs));
  13203. }
  13204. var value = right.apply(undefined, values, inputs);
  13205. return context ? {context: undefined, name: undefined, value: value} : value;
  13206. } :
  13207. function(scope, locals, assign, inputs) {
  13208. var rhs = right(scope, locals, assign, inputs);
  13209. var value;
  13210. if (rhs.value != null) {
  13211. ensureSafeObject(rhs.context, self.expression);
  13212. ensureSafeFunction(rhs.value, self.expression);
  13213. var values = [];
  13214. for (var i = 0; i < args.length; ++i) {
  13215. values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
  13216. }
  13217. value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
  13218. }
  13219. return context ? {value: value} : value;
  13220. };
  13221. case AST.AssignmentExpression:
  13222. left = this.recurse(ast.left, true, 1);
  13223. right = this.recurse(ast.right);
  13224. return function(scope, locals, assign, inputs) {
  13225. var lhs = left(scope, locals, assign, inputs);
  13226. var rhs = right(scope, locals, assign, inputs);
  13227. ensureSafeObject(lhs.value, self.expression);
  13228. ensureSafeAssignContext(lhs.context);
  13229. lhs.context[lhs.name] = rhs;
  13230. return context ? {value: rhs} : rhs;
  13231. };
  13232. case AST.ArrayExpression:
  13233. args = [];
  13234. forEach(ast.elements, function(expr) {
  13235. args.push(self.recurse(expr));
  13236. });
  13237. return function(scope, locals, assign, inputs) {
  13238. var value = [];
  13239. for (var i = 0; i < args.length; ++i) {
  13240. value.push(args[i](scope, locals, assign, inputs));
  13241. }
  13242. return context ? {value: value} : value;
  13243. };
  13244. case AST.ObjectExpression:
  13245. args = [];
  13246. forEach(ast.properties, function(property) {
  13247. args.push({key: property.key.type === AST.Identifier ?
  13248. property.key.name :
  13249. ('' + property.key.value),
  13250. value: self.recurse(property.value)
  13251. });
  13252. });
  13253. return function(scope, locals, assign, inputs) {
  13254. var value = {};
  13255. for (var i = 0; i < args.length; ++i) {
  13256. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  13257. }
  13258. return context ? {value: value} : value;
  13259. };
  13260. case AST.ThisExpression:
  13261. return function(scope) {
  13262. return context ? {value: scope} : scope;
  13263. };
  13264. case AST.LocalsExpression:
  13265. return function(scope, locals) {
  13266. return context ? {value: locals} : locals;
  13267. };
  13268. case AST.NGValueParameter:
  13269. return function(scope, locals, assign, inputs) {
  13270. return context ? {value: assign} : assign;
  13271. };
  13272. }
  13273. },
  13274. 'unary+': function(argument, context) {
  13275. return function(scope, locals, assign, inputs) {
  13276. var arg = argument(scope, locals, assign, inputs);
  13277. if (isDefined(arg)) {
  13278. arg = +arg;
  13279. } else {
  13280. arg = 0;
  13281. }
  13282. return context ? {value: arg} : arg;
  13283. };
  13284. },
  13285. 'unary-': function(argument, context) {
  13286. return function(scope, locals, assign, inputs) {
  13287. var arg = argument(scope, locals, assign, inputs);
  13288. if (isDefined(arg)) {
  13289. arg = -arg;
  13290. } else {
  13291. arg = 0;
  13292. }
  13293. return context ? {value: arg} : arg;
  13294. };
  13295. },
  13296. 'unary!': function(argument, context) {
  13297. return function(scope, locals, assign, inputs) {
  13298. var arg = !argument(scope, locals, assign, inputs);
  13299. return context ? {value: arg} : arg;
  13300. };
  13301. },
  13302. 'binary+': function(left, right, context) {
  13303. return function(scope, locals, assign, inputs) {
  13304. var lhs = left(scope, locals, assign, inputs);
  13305. var rhs = right(scope, locals, assign, inputs);
  13306. var arg = plusFn(lhs, rhs);
  13307. return context ? {value: arg} : arg;
  13308. };
  13309. },
  13310. 'binary-': function(left, right, context) {
  13311. return function(scope, locals, assign, inputs) {
  13312. var lhs = left(scope, locals, assign, inputs);
  13313. var rhs = right(scope, locals, assign, inputs);
  13314. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  13315. return context ? {value: arg} : arg;
  13316. };
  13317. },
  13318. 'binary*': function(left, right, context) {
  13319. return function(scope, locals, assign, inputs) {
  13320. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  13321. return context ? {value: arg} : arg;
  13322. };
  13323. },
  13324. 'binary/': function(left, right, context) {
  13325. return function(scope, locals, assign, inputs) {
  13326. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  13327. return context ? {value: arg} : arg;
  13328. };
  13329. },
  13330. 'binary%': function(left, right, context) {
  13331. return function(scope, locals, assign, inputs) {
  13332. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  13333. return context ? {value: arg} : arg;
  13334. };
  13335. },
  13336. 'binary===': function(left, right, context) {
  13337. return function(scope, locals, assign, inputs) {
  13338. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  13339. return context ? {value: arg} : arg;
  13340. };
  13341. },
  13342. 'binary!==': function(left, right, context) {
  13343. return function(scope, locals, assign, inputs) {
  13344. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  13345. return context ? {value: arg} : arg;
  13346. };
  13347. },
  13348. 'binary==': function(left, right, context) {
  13349. return function(scope, locals, assign, inputs) {
  13350. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  13351. return context ? {value: arg} : arg;
  13352. };
  13353. },
  13354. 'binary!=': function(left, right, context) {
  13355. return function(scope, locals, assign, inputs) {
  13356. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  13357. return context ? {value: arg} : arg;
  13358. };
  13359. },
  13360. 'binary<': function(left, right, context) {
  13361. return function(scope, locals, assign, inputs) {
  13362. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  13363. return context ? {value: arg} : arg;
  13364. };
  13365. },
  13366. 'binary>': function(left, right, context) {
  13367. return function(scope, locals, assign, inputs) {
  13368. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  13369. return context ? {value: arg} : arg;
  13370. };
  13371. },
  13372. 'binary<=': function(left, right, context) {
  13373. return function(scope, locals, assign, inputs) {
  13374. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  13375. return context ? {value: arg} : arg;
  13376. };
  13377. },
  13378. 'binary>=': function(left, right, context) {
  13379. return function(scope, locals, assign, inputs) {
  13380. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  13381. return context ? {value: arg} : arg;
  13382. };
  13383. },
  13384. 'binary&&': function(left, right, context) {
  13385. return function(scope, locals, assign, inputs) {
  13386. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  13387. return context ? {value: arg} : arg;
  13388. };
  13389. },
  13390. 'binary||': function(left, right, context) {
  13391. return function(scope, locals, assign, inputs) {
  13392. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  13393. return context ? {value: arg} : arg;
  13394. };
  13395. },
  13396. 'ternary?:': function(test, alternate, consequent, context) {
  13397. return function(scope, locals, assign, inputs) {
  13398. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  13399. return context ? {value: arg} : arg;
  13400. };
  13401. },
  13402. value: function(value, context) {
  13403. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  13404. },
  13405. identifier: function(name, expensiveChecks, context, create, expression) {
  13406. return function(scope, locals, assign, inputs) {
  13407. var base = locals && (name in locals) ? locals : scope;
  13408. if (create && create !== 1 && base && !(base[name])) {
  13409. base[name] = {};
  13410. }
  13411. var value = base ? base[name] : undefined;
  13412. if (expensiveChecks) {
  13413. ensureSafeObject(value, expression);
  13414. }
  13415. if (context) {
  13416. return {context: base, name: name, value: value};
  13417. } else {
  13418. return value;
  13419. }
  13420. };
  13421. },
  13422. computedMember: function(left, right, context, create, expression) {
  13423. return function(scope, locals, assign, inputs) {
  13424. var lhs = left(scope, locals, assign, inputs);
  13425. var rhs;
  13426. var value;
  13427. if (lhs != null) {
  13428. rhs = right(scope, locals, assign, inputs);
  13429. rhs = getStringValue(rhs);
  13430. ensureSafeMemberName(rhs, expression);
  13431. if (create && create !== 1) {
  13432. ensureSafeAssignContext(lhs);
  13433. if (lhs && !(lhs[rhs])) {
  13434. lhs[rhs] = {};
  13435. }
  13436. }
  13437. value = lhs[rhs];
  13438. ensureSafeObject(value, expression);
  13439. }
  13440. if (context) {
  13441. return {context: lhs, name: rhs, value: value};
  13442. } else {
  13443. return value;
  13444. }
  13445. };
  13446. },
  13447. nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
  13448. return function(scope, locals, assign, inputs) {
  13449. var lhs = left(scope, locals, assign, inputs);
  13450. if (create && create !== 1) {
  13451. ensureSafeAssignContext(lhs);
  13452. if (lhs && !(lhs[right])) {
  13453. lhs[right] = {};
  13454. }
  13455. }
  13456. var value = lhs != null ? lhs[right] : undefined;
  13457. if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
  13458. ensureSafeObject(value, expression);
  13459. }
  13460. if (context) {
  13461. return {context: lhs, name: right, value: value};
  13462. } else {
  13463. return value;
  13464. }
  13465. };
  13466. },
  13467. inputs: function(input, watchId) {
  13468. return function(scope, value, locals, inputs) {
  13469. if (inputs) return inputs[watchId];
  13470. return input(scope, value, locals);
  13471. };
  13472. }
  13473. };
  13474. /**
  13475. * @constructor
  13476. */
  13477. var Parser = function(lexer, $filter, options) {
  13478. this.lexer = lexer;
  13479. this.$filter = $filter;
  13480. this.options = options;
  13481. this.ast = new AST(this.lexer);
  13482. this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
  13483. new ASTCompiler(this.ast, $filter);
  13484. };
  13485. Parser.prototype = {
  13486. constructor: Parser,
  13487. parse: function(text) {
  13488. return this.astCompiler.compile(text, this.options.expensiveChecks);
  13489. }
  13490. };
  13491. function isPossiblyDangerousMemberName(name) {
  13492. return name == 'constructor';
  13493. }
  13494. var objectValueOf = Object.prototype.valueOf;
  13495. function getValueOf(value) {
  13496. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  13497. }
  13498. ///////////////////////////////////
  13499. /**
  13500. * @ngdoc service
  13501. * @name $parse
  13502. * @kind function
  13503. *
  13504. * @description
  13505. *
  13506. * Converts Angular {@link guide/expression expression} into a function.
  13507. *
  13508. * ```js
  13509. * var getter = $parse('user.name');
  13510. * var setter = getter.assign;
  13511. * var context = {user:{name:'angular'}};
  13512. * var locals = {user:{name:'local'}};
  13513. *
  13514. * expect(getter(context)).toEqual('angular');
  13515. * setter(context, 'newValue');
  13516. * expect(context.user.name).toEqual('newValue');
  13517. * expect(getter(context, locals)).toEqual('local');
  13518. * ```
  13519. *
  13520. *
  13521. * @param {string} expression String expression to compile.
  13522. * @returns {function(context, locals)} a function which represents the compiled expression:
  13523. *
  13524. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  13525. * are evaluated against (typically a scope object).
  13526. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  13527. * `context`.
  13528. *
  13529. * The returned function also has the following properties:
  13530. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  13531. * literal.
  13532. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  13533. * constant literals.
  13534. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  13535. * set to a function to change its value on the given context.
  13536. *
  13537. */
  13538. /**
  13539. * @ngdoc provider
  13540. * @name $parseProvider
  13541. *
  13542. * @description
  13543. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  13544. * service.
  13545. */
  13546. function $ParseProvider() {
  13547. var cacheDefault = createMap();
  13548. var cacheExpensive = createMap();
  13549. this.$get = ['$filter', function($filter) {
  13550. var noUnsafeEval = csp().noUnsafeEval;
  13551. var $parseOptions = {
  13552. csp: noUnsafeEval,
  13553. expensiveChecks: false
  13554. },
  13555. $parseOptionsExpensive = {
  13556. csp: noUnsafeEval,
  13557. expensiveChecks: true
  13558. };
  13559. var runningChecksEnabled = false;
  13560. $parse.$$runningExpensiveChecks = function() {
  13561. return runningChecksEnabled;
  13562. };
  13563. return $parse;
  13564. function $parse(exp, interceptorFn, expensiveChecks) {
  13565. var parsedExpression, oneTime, cacheKey;
  13566. expensiveChecks = expensiveChecks || runningChecksEnabled;
  13567. switch (typeof exp) {
  13568. case 'string':
  13569. exp = exp.trim();
  13570. cacheKey = exp;
  13571. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  13572. parsedExpression = cache[cacheKey];
  13573. if (!parsedExpression) {
  13574. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  13575. oneTime = true;
  13576. exp = exp.substring(2);
  13577. }
  13578. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  13579. var lexer = new Lexer(parseOptions);
  13580. var parser = new Parser(lexer, $filter, parseOptions);
  13581. parsedExpression = parser.parse(exp);
  13582. if (parsedExpression.constant) {
  13583. parsedExpression.$$watchDelegate = constantWatchDelegate;
  13584. } else if (oneTime) {
  13585. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  13586. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  13587. } else if (parsedExpression.inputs) {
  13588. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  13589. }
  13590. if (expensiveChecks) {
  13591. parsedExpression = expensiveChecksInterceptor(parsedExpression);
  13592. }
  13593. cache[cacheKey] = parsedExpression;
  13594. }
  13595. return addInterceptor(parsedExpression, interceptorFn);
  13596. case 'function':
  13597. return addInterceptor(exp, interceptorFn);
  13598. default:
  13599. return addInterceptor(noop, interceptorFn);
  13600. }
  13601. }
  13602. function expensiveChecksInterceptor(fn) {
  13603. if (!fn) return fn;
  13604. expensiveCheckFn.$$watchDelegate = fn.$$watchDelegate;
  13605. expensiveCheckFn.assign = expensiveChecksInterceptor(fn.assign);
  13606. expensiveCheckFn.constant = fn.constant;
  13607. expensiveCheckFn.literal = fn.literal;
  13608. for (var i = 0; fn.inputs && i < fn.inputs.length; ++i) {
  13609. fn.inputs[i] = expensiveChecksInterceptor(fn.inputs[i]);
  13610. }
  13611. expensiveCheckFn.inputs = fn.inputs;
  13612. return expensiveCheckFn;
  13613. function expensiveCheckFn(scope, locals, assign, inputs) {
  13614. var expensiveCheckOldValue = runningChecksEnabled;
  13615. runningChecksEnabled = true;
  13616. try {
  13617. return fn(scope, locals, assign, inputs);
  13618. } finally {
  13619. runningChecksEnabled = expensiveCheckOldValue;
  13620. }
  13621. }
  13622. }
  13623. function expressionInputDirtyCheck(newValue, oldValueOfValue) {
  13624. if (newValue == null || oldValueOfValue == null) { // null/undefined
  13625. return newValue === oldValueOfValue;
  13626. }
  13627. if (typeof newValue === 'object') {
  13628. // attempt to convert the value to a primitive type
  13629. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  13630. // be cheaply dirty-checked
  13631. newValue = getValueOf(newValue);
  13632. if (typeof newValue === 'object') {
  13633. // objects/arrays are not supported - deep-watching them would be too expensive
  13634. return false;
  13635. }
  13636. // fall-through to the primitive equality check
  13637. }
  13638. //Primitive or NaN
  13639. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  13640. }
  13641. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  13642. var inputExpressions = parsedExpression.inputs;
  13643. var lastResult;
  13644. if (inputExpressions.length === 1) {
  13645. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  13646. inputExpressions = inputExpressions[0];
  13647. return scope.$watch(function expressionInputWatch(scope) {
  13648. var newInputValue = inputExpressions(scope);
  13649. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
  13650. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  13651. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  13652. }
  13653. return lastResult;
  13654. }, listener, objectEquality, prettyPrintExpression);
  13655. }
  13656. var oldInputValueOfValues = [];
  13657. var oldInputValues = [];
  13658. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  13659. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  13660. oldInputValues[i] = null;
  13661. }
  13662. return scope.$watch(function expressionInputsWatch(scope) {
  13663. var changed = false;
  13664. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  13665. var newInputValue = inputExpressions[i](scope);
  13666. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
  13667. oldInputValues[i] = newInputValue;
  13668. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  13669. }
  13670. }
  13671. if (changed) {
  13672. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  13673. }
  13674. return lastResult;
  13675. }, listener, objectEquality, prettyPrintExpression);
  13676. }
  13677. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  13678. var unwatch, lastValue;
  13679. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  13680. return parsedExpression(scope);
  13681. }, function oneTimeListener(value, old, scope) {
  13682. lastValue = value;
  13683. if (isFunction(listener)) {
  13684. listener.apply(this, arguments);
  13685. }
  13686. if (isDefined(value)) {
  13687. scope.$$postDigest(function() {
  13688. if (isDefined(lastValue)) {
  13689. unwatch();
  13690. }
  13691. });
  13692. }
  13693. }, objectEquality);
  13694. }
  13695. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  13696. var unwatch, lastValue;
  13697. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  13698. return parsedExpression(scope);
  13699. }, function oneTimeListener(value, old, scope) {
  13700. lastValue = value;
  13701. if (isFunction(listener)) {
  13702. listener.call(this, value, old, scope);
  13703. }
  13704. if (isAllDefined(value)) {
  13705. scope.$$postDigest(function() {
  13706. if (isAllDefined(lastValue)) unwatch();
  13707. });
  13708. }
  13709. }, objectEquality);
  13710. function isAllDefined(value) {
  13711. var allDefined = true;
  13712. forEach(value, function(val) {
  13713. if (!isDefined(val)) allDefined = false;
  13714. });
  13715. return allDefined;
  13716. }
  13717. }
  13718. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  13719. var unwatch;
  13720. return unwatch = scope.$watch(function constantWatch(scope) {
  13721. unwatch();
  13722. return parsedExpression(scope);
  13723. }, listener, objectEquality);
  13724. }
  13725. function addInterceptor(parsedExpression, interceptorFn) {
  13726. if (!interceptorFn) return parsedExpression;
  13727. var watchDelegate = parsedExpression.$$watchDelegate;
  13728. var useInputs = false;
  13729. var regularWatch =
  13730. watchDelegate !== oneTimeLiteralWatchDelegate &&
  13731. watchDelegate !== oneTimeWatchDelegate;
  13732. var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
  13733. var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
  13734. return interceptorFn(value, scope, locals);
  13735. } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
  13736. var value = parsedExpression(scope, locals, assign, inputs);
  13737. var result = interceptorFn(value, scope, locals);
  13738. // we only return the interceptor's result if the
  13739. // initial value is defined (for bind-once)
  13740. return isDefined(value) ? result : value;
  13741. };
  13742. // Propagate $$watchDelegates other then inputsWatchDelegate
  13743. if (parsedExpression.$$watchDelegate &&
  13744. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  13745. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  13746. } else if (!interceptorFn.$stateful) {
  13747. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  13748. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  13749. fn.$$watchDelegate = inputsWatchDelegate;
  13750. useInputs = !parsedExpression.inputs;
  13751. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  13752. }
  13753. return fn;
  13754. }
  13755. }];
  13756. }
  13757. /**
  13758. * @ngdoc service
  13759. * @name $q
  13760. * @requires $rootScope
  13761. *
  13762. * @description
  13763. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  13764. * when they are done processing.
  13765. *
  13766. * This is an implementation of promises/deferred objects inspired by
  13767. * [Kris Kowal's Q](https://github.com/kriskowal/q).
  13768. *
  13769. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  13770. * implementations, and the other which resembles ES6 promises to some degree.
  13771. *
  13772. * # $q constructor
  13773. *
  13774. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  13775. * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
  13776. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  13777. *
  13778. * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
  13779. * available yet.
  13780. *
  13781. * It can be used like so:
  13782. *
  13783. * ```js
  13784. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  13785. * // are available in the current lexical scope (they could have been injected or passed in).
  13786. *
  13787. * function asyncGreet(name) {
  13788. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  13789. * return $q(function(resolve, reject) {
  13790. * setTimeout(function() {
  13791. * if (okToGreet(name)) {
  13792. * resolve('Hello, ' + name + '!');
  13793. * } else {
  13794. * reject('Greeting ' + name + ' is not allowed.');
  13795. * }
  13796. * }, 1000);
  13797. * });
  13798. * }
  13799. *
  13800. * var promise = asyncGreet('Robin Hood');
  13801. * promise.then(function(greeting) {
  13802. * alert('Success: ' + greeting);
  13803. * }, function(reason) {
  13804. * alert('Failed: ' + reason);
  13805. * });
  13806. * ```
  13807. *
  13808. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  13809. *
  13810. * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.
  13811. *
  13812. * However, the more traditional CommonJS-style usage is still available, and documented below.
  13813. *
  13814. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  13815. * interface for interacting with an object that represents the result of an action that is
  13816. * performed asynchronously, and may or may not be finished at any given point in time.
  13817. *
  13818. * From the perspective of dealing with error handling, deferred and promise APIs are to
  13819. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  13820. *
  13821. * ```js
  13822. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  13823. * // are available in the current lexical scope (they could have been injected or passed in).
  13824. *
  13825. * function asyncGreet(name) {
  13826. * var deferred = $q.defer();
  13827. *
  13828. * setTimeout(function() {
  13829. * deferred.notify('About to greet ' + name + '.');
  13830. *
  13831. * if (okToGreet(name)) {
  13832. * deferred.resolve('Hello, ' + name + '!');
  13833. * } else {
  13834. * deferred.reject('Greeting ' + name + ' is not allowed.');
  13835. * }
  13836. * }, 1000);
  13837. *
  13838. * return deferred.promise;
  13839. * }
  13840. *
  13841. * var promise = asyncGreet('Robin Hood');
  13842. * promise.then(function(greeting) {
  13843. * alert('Success: ' + greeting);
  13844. * }, function(reason) {
  13845. * alert('Failed: ' + reason);
  13846. * }, function(update) {
  13847. * alert('Got notification: ' + update);
  13848. * });
  13849. * ```
  13850. *
  13851. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  13852. * comes in the way of guarantees that promise and deferred APIs make, see
  13853. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  13854. *
  13855. * Additionally the promise api allows for composition that is very hard to do with the
  13856. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  13857. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  13858. * section on serial or parallel joining of promises.
  13859. *
  13860. * # The Deferred API
  13861. *
  13862. * A new instance of deferred is constructed by calling `$q.defer()`.
  13863. *
  13864. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  13865. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  13866. * of the task.
  13867. *
  13868. * **Methods**
  13869. *
  13870. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  13871. * constructed via `$q.reject`, the promise will be rejected instead.
  13872. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  13873. * resolving it with a rejection constructed via `$q.reject`.
  13874. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  13875. * multiple times before the promise is either resolved or rejected.
  13876. *
  13877. * **Properties**
  13878. *
  13879. * - promise – `{Promise}` – promise object associated with this deferred.
  13880. *
  13881. *
  13882. * # The Promise API
  13883. *
  13884. * A new promise instance is created when a deferred instance is created and can be retrieved by
  13885. * calling `deferred.promise`.
  13886. *
  13887. * The purpose of the promise object is to allow for interested parties to get access to the result
  13888. * of the deferred task when it completes.
  13889. *
  13890. * **Methods**
  13891. *
  13892. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  13893. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  13894. * as soon as the result is available. The callbacks are called with a single argument: the result
  13895. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  13896. * provide a progress indication, before the promise is resolved or rejected.
  13897. *
  13898. * This method *returns a new promise* which is resolved or rejected via the return value of the
  13899. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  13900. * with the value which is resolved in that promise using
  13901. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  13902. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  13903. * resolved or rejected from the notifyCallback method.
  13904. *
  13905. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  13906. *
  13907. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  13908. * but to do so without modifying the final value. This is useful to release resources or do some
  13909. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  13910. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  13911. * more information.
  13912. *
  13913. * # Chaining promises
  13914. *
  13915. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  13916. * possible to create a chain of promises:
  13917. *
  13918. * ```js
  13919. * promiseB = promiseA.then(function(result) {
  13920. * return result + 1;
  13921. * });
  13922. *
  13923. * // promiseB will be resolved immediately after promiseA is resolved and its value
  13924. * // will be the result of promiseA incremented by 1
  13925. * ```
  13926. *
  13927. * It is possible to create chains of any length and since a promise can be resolved with another
  13928. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  13929. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  13930. * $http's response interceptors.
  13931. *
  13932. *
  13933. * # Differences between Kris Kowal's Q and $q
  13934. *
  13935. * There are two main differences:
  13936. *
  13937. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  13938. * mechanism in angular, which means faster propagation of resolution or rejection into your
  13939. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  13940. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  13941. * all the important functionality needed for common async tasks.
  13942. *
  13943. * # Testing
  13944. *
  13945. * ```js
  13946. * it('should simulate promise', inject(function($q, $rootScope) {
  13947. * var deferred = $q.defer();
  13948. * var promise = deferred.promise;
  13949. * var resolvedValue;
  13950. *
  13951. * promise.then(function(value) { resolvedValue = value; });
  13952. * expect(resolvedValue).toBeUndefined();
  13953. *
  13954. * // Simulate resolving of promise
  13955. * deferred.resolve(123);
  13956. * // Note that the 'then' function does not get called synchronously.
  13957. * // This is because we want the promise API to always be async, whether or not
  13958. * // it got called synchronously or asynchronously.
  13959. * expect(resolvedValue).toBeUndefined();
  13960. *
  13961. * // Propagate promise resolution to 'then' functions using $apply().
  13962. * $rootScope.$apply();
  13963. * expect(resolvedValue).toEqual(123);
  13964. * }));
  13965. * ```
  13966. *
  13967. * @param {function(function, function)} resolver Function which is responsible for resolving or
  13968. * rejecting the newly created promise. The first parameter is a function which resolves the
  13969. * promise, the second parameter is a function which rejects the promise.
  13970. *
  13971. * @returns {Promise} The newly created promise.
  13972. */
  13973. function $QProvider() {
  13974. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  13975. return qFactory(function(callback) {
  13976. $rootScope.$evalAsync(callback);
  13977. }, $exceptionHandler);
  13978. }];
  13979. }
  13980. function $$QProvider() {
  13981. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  13982. return qFactory(function(callback) {
  13983. $browser.defer(callback);
  13984. }, $exceptionHandler);
  13985. }];
  13986. }
  13987. /**
  13988. * Constructs a promise manager.
  13989. *
  13990. * @param {function(function)} nextTick Function for executing functions in the next turn.
  13991. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  13992. * debugging purposes.
  13993. * @returns {object} Promise manager.
  13994. */
  13995. function qFactory(nextTick, exceptionHandler) {
  13996. var $qMinErr = minErr('$q', TypeError);
  13997. /**
  13998. * @ngdoc method
  13999. * @name ng.$q#defer
  14000. * @kind function
  14001. *
  14002. * @description
  14003. * Creates a `Deferred` object which represents a task which will finish in the future.
  14004. *
  14005. * @returns {Deferred} Returns a new instance of deferred.
  14006. */
  14007. var defer = function() {
  14008. var d = new Deferred();
  14009. //Necessary to support unbound execution :/
  14010. d.resolve = simpleBind(d, d.resolve);
  14011. d.reject = simpleBind(d, d.reject);
  14012. d.notify = simpleBind(d, d.notify);
  14013. return d;
  14014. };
  14015. function Promise() {
  14016. this.$$state = { status: 0 };
  14017. }
  14018. extend(Promise.prototype, {
  14019. then: function(onFulfilled, onRejected, progressBack) {
  14020. if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
  14021. return this;
  14022. }
  14023. var result = new Deferred();
  14024. this.$$state.pending = this.$$state.pending || [];
  14025. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  14026. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  14027. return result.promise;
  14028. },
  14029. "catch": function(callback) {
  14030. return this.then(null, callback);
  14031. },
  14032. "finally": function(callback, progressBack) {
  14033. return this.then(function(value) {
  14034. return handleCallback(value, true, callback);
  14035. }, function(error) {
  14036. return handleCallback(error, false, callback);
  14037. }, progressBack);
  14038. }
  14039. });
  14040. //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
  14041. function simpleBind(context, fn) {
  14042. return function(value) {
  14043. fn.call(context, value);
  14044. };
  14045. }
  14046. function processQueue(state) {
  14047. var fn, deferred, pending;
  14048. pending = state.pending;
  14049. state.processScheduled = false;
  14050. state.pending = undefined;
  14051. for (var i = 0, ii = pending.length; i < ii; ++i) {
  14052. deferred = pending[i][0];
  14053. fn = pending[i][state.status];
  14054. try {
  14055. if (isFunction(fn)) {
  14056. deferred.resolve(fn(state.value));
  14057. } else if (state.status === 1) {
  14058. deferred.resolve(state.value);
  14059. } else {
  14060. deferred.reject(state.value);
  14061. }
  14062. } catch (e) {
  14063. deferred.reject(e);
  14064. exceptionHandler(e);
  14065. }
  14066. }
  14067. }
  14068. function scheduleProcessQueue(state) {
  14069. if (state.processScheduled || !state.pending) return;
  14070. state.processScheduled = true;
  14071. nextTick(function() { processQueue(state); });
  14072. }
  14073. function Deferred() {
  14074. this.promise = new Promise();
  14075. }
  14076. extend(Deferred.prototype, {
  14077. resolve: function(val) {
  14078. if (this.promise.$$state.status) return;
  14079. if (val === this.promise) {
  14080. this.$$reject($qMinErr(
  14081. 'qcycle',
  14082. "Expected promise to be resolved with value other than itself '{0}'",
  14083. val));
  14084. } else {
  14085. this.$$resolve(val);
  14086. }
  14087. },
  14088. $$resolve: function(val) {
  14089. var then;
  14090. var that = this;
  14091. var done = false;
  14092. try {
  14093. if ((isObject(val) || isFunction(val))) then = val && val.then;
  14094. if (isFunction(then)) {
  14095. this.promise.$$state.status = -1;
  14096. then.call(val, resolvePromise, rejectPromise, simpleBind(this, this.notify));
  14097. } else {
  14098. this.promise.$$state.value = val;
  14099. this.promise.$$state.status = 1;
  14100. scheduleProcessQueue(this.promise.$$state);
  14101. }
  14102. } catch (e) {
  14103. rejectPromise(e);
  14104. exceptionHandler(e);
  14105. }
  14106. function resolvePromise(val) {
  14107. if (done) return;
  14108. done = true;
  14109. that.$$resolve(val);
  14110. }
  14111. function rejectPromise(val) {
  14112. if (done) return;
  14113. done = true;
  14114. that.$$reject(val);
  14115. }
  14116. },
  14117. reject: function(reason) {
  14118. if (this.promise.$$state.status) return;
  14119. this.$$reject(reason);
  14120. },
  14121. $$reject: function(reason) {
  14122. this.promise.$$state.value = reason;
  14123. this.promise.$$state.status = 2;
  14124. scheduleProcessQueue(this.promise.$$state);
  14125. },
  14126. notify: function(progress) {
  14127. var callbacks = this.promise.$$state.pending;
  14128. if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
  14129. nextTick(function() {
  14130. var callback, result;
  14131. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  14132. result = callbacks[i][0];
  14133. callback = callbacks[i][3];
  14134. try {
  14135. result.notify(isFunction(callback) ? callback(progress) : progress);
  14136. } catch (e) {
  14137. exceptionHandler(e);
  14138. }
  14139. }
  14140. });
  14141. }
  14142. }
  14143. });
  14144. /**
  14145. * @ngdoc method
  14146. * @name $q#reject
  14147. * @kind function
  14148. *
  14149. * @description
  14150. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  14151. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  14152. * a promise chain, you don't need to worry about it.
  14153. *
  14154. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  14155. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  14156. * a promise error callback and you want to forward the error to the promise derived from the
  14157. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  14158. * `reject`.
  14159. *
  14160. * ```js
  14161. * promiseB = promiseA.then(function(result) {
  14162. * // success: do something and resolve promiseB
  14163. * // with the old or a new result
  14164. * return result;
  14165. * }, function(reason) {
  14166. * // error: handle the error if possible and
  14167. * // resolve promiseB with newPromiseOrValue,
  14168. * // otherwise forward the rejection to promiseB
  14169. * if (canHandle(reason)) {
  14170. * // handle the error and recover
  14171. * return newPromiseOrValue;
  14172. * }
  14173. * return $q.reject(reason);
  14174. * });
  14175. * ```
  14176. *
  14177. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  14178. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  14179. */
  14180. var reject = function(reason) {
  14181. var result = new Deferred();
  14182. result.reject(reason);
  14183. return result.promise;
  14184. };
  14185. var makePromise = function makePromise(value, resolved) {
  14186. var result = new Deferred();
  14187. if (resolved) {
  14188. result.resolve(value);
  14189. } else {
  14190. result.reject(value);
  14191. }
  14192. return result.promise;
  14193. };
  14194. var handleCallback = function handleCallback(value, isResolved, callback) {
  14195. var callbackOutput = null;
  14196. try {
  14197. if (isFunction(callback)) callbackOutput = callback();
  14198. } catch (e) {
  14199. return makePromise(e, false);
  14200. }
  14201. if (isPromiseLike(callbackOutput)) {
  14202. return callbackOutput.then(function() {
  14203. return makePromise(value, isResolved);
  14204. }, function(error) {
  14205. return makePromise(error, false);
  14206. });
  14207. } else {
  14208. return makePromise(value, isResolved);
  14209. }
  14210. };
  14211. /**
  14212. * @ngdoc method
  14213. * @name $q#when
  14214. * @kind function
  14215. *
  14216. * @description
  14217. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  14218. * This is useful when you are dealing with an object that might or might not be a promise, or if
  14219. * the promise comes from a source that can't be trusted.
  14220. *
  14221. * @param {*} value Value or a promise
  14222. * @param {Function=} successCallback
  14223. * @param {Function=} errorCallback
  14224. * @param {Function=} progressCallback
  14225. * @returns {Promise} Returns a promise of the passed value or promise
  14226. */
  14227. var when = function(value, callback, errback, progressBack) {
  14228. var result = new Deferred();
  14229. result.resolve(value);
  14230. return result.promise.then(callback, errback, progressBack);
  14231. };
  14232. /**
  14233. * @ngdoc method
  14234. * @name $q#resolve
  14235. * @kind function
  14236. *
  14237. * @description
  14238. * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
  14239. *
  14240. * @param {*} value Value or a promise
  14241. * @param {Function=} successCallback
  14242. * @param {Function=} errorCallback
  14243. * @param {Function=} progressCallback
  14244. * @returns {Promise} Returns a promise of the passed value or promise
  14245. */
  14246. var resolve = when;
  14247. /**
  14248. * @ngdoc method
  14249. * @name $q#all
  14250. * @kind function
  14251. *
  14252. * @description
  14253. * Combines multiple promises into a single promise that is resolved when all of the input
  14254. * promises are resolved.
  14255. *
  14256. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  14257. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  14258. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  14259. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  14260. * with the same rejection value.
  14261. */
  14262. function all(promises) {
  14263. var deferred = new Deferred(),
  14264. counter = 0,
  14265. results = isArray(promises) ? [] : {};
  14266. forEach(promises, function(promise, key) {
  14267. counter++;
  14268. when(promise).then(function(value) {
  14269. if (results.hasOwnProperty(key)) return;
  14270. results[key] = value;
  14271. if (!(--counter)) deferred.resolve(results);
  14272. }, function(reason) {
  14273. if (results.hasOwnProperty(key)) return;
  14274. deferred.reject(reason);
  14275. });
  14276. });
  14277. if (counter === 0) {
  14278. deferred.resolve(results);
  14279. }
  14280. return deferred.promise;
  14281. }
  14282. var $Q = function Q(resolver) {
  14283. if (!isFunction(resolver)) {
  14284. throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
  14285. }
  14286. var deferred = new Deferred();
  14287. function resolveFn(value) {
  14288. deferred.resolve(value);
  14289. }
  14290. function rejectFn(reason) {
  14291. deferred.reject(reason);
  14292. }
  14293. resolver(resolveFn, rejectFn);
  14294. return deferred.promise;
  14295. };
  14296. // Let's make the instanceof operator work for promises, so that
  14297. // `new $q(fn) instanceof $q` would evaluate to true.
  14298. $Q.prototype = Promise.prototype;
  14299. $Q.defer = defer;
  14300. $Q.reject = reject;
  14301. $Q.when = when;
  14302. $Q.resolve = resolve;
  14303. $Q.all = all;
  14304. return $Q;
  14305. }
  14306. function $$RAFProvider() { //rAF
  14307. this.$get = ['$window', '$timeout', function($window, $timeout) {
  14308. var requestAnimationFrame = $window.requestAnimationFrame ||
  14309. $window.webkitRequestAnimationFrame;
  14310. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  14311. $window.webkitCancelAnimationFrame ||
  14312. $window.webkitCancelRequestAnimationFrame;
  14313. var rafSupported = !!requestAnimationFrame;
  14314. var raf = rafSupported
  14315. ? function(fn) {
  14316. var id = requestAnimationFrame(fn);
  14317. return function() {
  14318. cancelAnimationFrame(id);
  14319. };
  14320. }
  14321. : function(fn) {
  14322. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  14323. return function() {
  14324. $timeout.cancel(timer);
  14325. };
  14326. };
  14327. raf.supported = rafSupported;
  14328. return raf;
  14329. }];
  14330. }
  14331. /**
  14332. * DESIGN NOTES
  14333. *
  14334. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  14335. *
  14336. * The typical use of scope is to watch the expressions, which most of the time return the same
  14337. * value as last time so we optimize the operation.
  14338. *
  14339. * Closures construction is expensive in terms of speed as well as memory:
  14340. * - No closures, instead use prototypical inheritance for API
  14341. * - Internal state needs to be stored on scope directly, which means that private state is
  14342. * exposed as $$____ properties
  14343. *
  14344. * Loop operations are optimized by using while(count--) { ... }
  14345. * - This means that in order to keep the same order of execution as addition we have to add
  14346. * items to the array at the beginning (unshift) instead of at the end (push)
  14347. *
  14348. * Child scopes are created and removed often
  14349. * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
  14350. *
  14351. * There are fewer watches than observers. This is why you don't want the observer to be implemented
  14352. * in the same way as watch. Watch requires return of the initialization function which is expensive
  14353. * to construct.
  14354. */
  14355. /**
  14356. * @ngdoc provider
  14357. * @name $rootScopeProvider
  14358. * @description
  14359. *
  14360. * Provider for the $rootScope service.
  14361. */
  14362. /**
  14363. * @ngdoc method
  14364. * @name $rootScopeProvider#digestTtl
  14365. * @description
  14366. *
  14367. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  14368. * assuming that the model is unstable.
  14369. *
  14370. * The current default is 10 iterations.
  14371. *
  14372. * In complex applications it's possible that the dependencies between `$watch`s will result in
  14373. * several digest iterations. However if an application needs more than the default 10 digest
  14374. * iterations for its model to stabilize then you should investigate what is causing the model to
  14375. * continuously change during the digest.
  14376. *
  14377. * Increasing the TTL could have performance implications, so you should not change it without
  14378. * proper justification.
  14379. *
  14380. * @param {number} limit The number of digest iterations.
  14381. */
  14382. /**
  14383. * @ngdoc service
  14384. * @name $rootScope
  14385. * @description
  14386. *
  14387. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  14388. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  14389. * between the model and the view, via a mechanism for watching the model for changes.
  14390. * They also provide event emission/broadcast and subscription facility. See the
  14391. * {@link guide/scope developer guide on scopes}.
  14392. */
  14393. function $RootScopeProvider() {
  14394. var TTL = 10;
  14395. var $rootScopeMinErr = minErr('$rootScope');
  14396. var lastDirtyWatch = null;
  14397. var applyAsyncId = null;
  14398. this.digestTtl = function(value) {
  14399. if (arguments.length) {
  14400. TTL = value;
  14401. }
  14402. return TTL;
  14403. };
  14404. function createChildScopeClass(parent) {
  14405. function ChildScope() {
  14406. this.$$watchers = this.$$nextSibling =
  14407. this.$$childHead = this.$$childTail = null;
  14408. this.$$listeners = {};
  14409. this.$$listenerCount = {};
  14410. this.$$watchersCount = 0;
  14411. this.$id = nextUid();
  14412. this.$$ChildScope = null;
  14413. }
  14414. ChildScope.prototype = parent;
  14415. return ChildScope;
  14416. }
  14417. this.$get = ['$exceptionHandler', '$parse', '$browser',
  14418. function($exceptionHandler, $parse, $browser) {
  14419. function destroyChildScope($event) {
  14420. $event.currentScope.$$destroyed = true;
  14421. }
  14422. function cleanUpScope($scope) {
  14423. if (msie === 9) {
  14424. // There is a memory leak in IE9 if all child scopes are not disconnected
  14425. // completely when a scope is destroyed. So this code will recurse up through
  14426. // all this scopes children
  14427. //
  14428. // See issue https://github.com/angular/angular.js/issues/10706
  14429. $scope.$$childHead && cleanUpScope($scope.$$childHead);
  14430. $scope.$$nextSibling && cleanUpScope($scope.$$nextSibling);
  14431. }
  14432. // The code below works around IE9 and V8's memory leaks
  14433. //
  14434. // See:
  14435. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  14436. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  14437. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  14438. $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
  14439. $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
  14440. }
  14441. /**
  14442. * @ngdoc type
  14443. * @name $rootScope.Scope
  14444. *
  14445. * @description
  14446. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  14447. * {@link auto.$injector $injector}. Child scopes are created using the
  14448. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  14449. * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
  14450. * an in-depth introduction and usage examples.
  14451. *
  14452. *
  14453. * # Inheritance
  14454. * A scope can inherit from a parent scope, as in this example:
  14455. * ```js
  14456. var parent = $rootScope;
  14457. var child = parent.$new();
  14458. parent.salutation = "Hello";
  14459. expect(child.salutation).toEqual('Hello');
  14460. child.salutation = "Welcome";
  14461. expect(child.salutation).toEqual('Welcome');
  14462. expect(parent.salutation).toEqual('Hello');
  14463. * ```
  14464. *
  14465. * When interacting with `Scope` in tests, additional helper methods are available on the
  14466. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  14467. * details.
  14468. *
  14469. *
  14470. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  14471. * provided for the current scope. Defaults to {@link ng}.
  14472. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  14473. * append/override services provided by `providers`. This is handy
  14474. * when unit-testing and having the need to override a default
  14475. * service.
  14476. * @returns {Object} Newly created scope.
  14477. *
  14478. */
  14479. function Scope() {
  14480. this.$id = nextUid();
  14481. this.$$phase = this.$parent = this.$$watchers =
  14482. this.$$nextSibling = this.$$prevSibling =
  14483. this.$$childHead = this.$$childTail = null;
  14484. this.$root = this;
  14485. this.$$destroyed = false;
  14486. this.$$listeners = {};
  14487. this.$$listenerCount = {};
  14488. this.$$watchersCount = 0;
  14489. this.$$isolateBindings = null;
  14490. }
  14491. /**
  14492. * @ngdoc property
  14493. * @name $rootScope.Scope#$id
  14494. *
  14495. * @description
  14496. * Unique scope ID (monotonically increasing) useful for debugging.
  14497. */
  14498. /**
  14499. * @ngdoc property
  14500. * @name $rootScope.Scope#$parent
  14501. *
  14502. * @description
  14503. * Reference to the parent scope.
  14504. */
  14505. /**
  14506. * @ngdoc property
  14507. * @name $rootScope.Scope#$root
  14508. *
  14509. * @description
  14510. * Reference to the root scope.
  14511. */
  14512. Scope.prototype = {
  14513. constructor: Scope,
  14514. /**
  14515. * @ngdoc method
  14516. * @name $rootScope.Scope#$new
  14517. * @kind function
  14518. *
  14519. * @description
  14520. * Creates a new child {@link ng.$rootScope.Scope scope}.
  14521. *
  14522. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  14523. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  14524. *
  14525. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  14526. * desired for the scope and its child scopes to be permanently detached from the parent and
  14527. * thus stop participating in model change detection and listener notification by invoking.
  14528. *
  14529. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  14530. * parent scope. The scope is isolated, as it can not see parent scope properties.
  14531. * When creating widgets, it is useful for the widget to not accidentally read parent
  14532. * state.
  14533. *
  14534. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  14535. * of the newly created scope. Defaults to `this` scope if not provided.
  14536. * This is used when creating a transclude scope to correctly place it
  14537. * in the scope hierarchy while maintaining the correct prototypical
  14538. * inheritance.
  14539. *
  14540. * @returns {Object} The newly created child scope.
  14541. *
  14542. */
  14543. $new: function(isolate, parent) {
  14544. var child;
  14545. parent = parent || this;
  14546. if (isolate) {
  14547. child = new Scope();
  14548. child.$root = this.$root;
  14549. } else {
  14550. // Only create a child scope class if somebody asks for one,
  14551. // but cache it to allow the VM to optimize lookups.
  14552. if (!this.$$ChildScope) {
  14553. this.$$ChildScope = createChildScopeClass(this);
  14554. }
  14555. child = new this.$$ChildScope();
  14556. }
  14557. child.$parent = parent;
  14558. child.$$prevSibling = parent.$$childTail;
  14559. if (parent.$$childHead) {
  14560. parent.$$childTail.$$nextSibling = child;
  14561. parent.$$childTail = child;
  14562. } else {
  14563. parent.$$childHead = parent.$$childTail = child;
  14564. }
  14565. // When the new scope is not isolated or we inherit from `this`, and
  14566. // the parent scope is destroyed, the property `$$destroyed` is inherited
  14567. // prototypically. In all other cases, this property needs to be set
  14568. // when the parent scope is destroyed.
  14569. // The listener needs to be added after the parent is set
  14570. if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
  14571. return child;
  14572. },
  14573. /**
  14574. * @ngdoc method
  14575. * @name $rootScope.Scope#$watch
  14576. * @kind function
  14577. *
  14578. * @description
  14579. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  14580. *
  14581. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  14582. * $digest()} and should return the value that will be watched. (`watchExpression` should not change
  14583. * its value when executed multiple times with the same input because it may be executed multiple
  14584. * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
  14585. * [idempotent](http://en.wikipedia.org/wiki/Idempotence).
  14586. * - The `listener` is called only when the value from the current `watchExpression` and the
  14587. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  14588. * see below). Inequality is determined according to reference inequality,
  14589. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  14590. * via the `!==` Javascript operator, unless `objectEquality == true`
  14591. * (see next point)
  14592. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  14593. * according to the {@link angular.equals} function. To save the value of the object for
  14594. * later comparison, the {@link angular.copy} function is used. This therefore means that
  14595. * watching complex objects will have adverse memory and performance implications.
  14596. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  14597. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  14598. * iteration limit is 10 to prevent an infinite loop deadlock.
  14599. *
  14600. *
  14601. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  14602. * you can register a `watchExpression` function with no `listener`. (Be prepared for
  14603. * multiple calls to your `watchExpression` because it will execute multiple times in a
  14604. * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
  14605. *
  14606. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  14607. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  14608. * watcher. In rare cases, this is undesirable because the listener is called when the result
  14609. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  14610. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  14611. * listener was called due to initialization.
  14612. *
  14613. *
  14614. *
  14615. * # Example
  14616. * ```js
  14617. // let's assume that scope was dependency injected as the $rootScope
  14618. var scope = $rootScope;
  14619. scope.name = 'misko';
  14620. scope.counter = 0;
  14621. expect(scope.counter).toEqual(0);
  14622. scope.$watch('name', function(newValue, oldValue) {
  14623. scope.counter = scope.counter + 1;
  14624. });
  14625. expect(scope.counter).toEqual(0);
  14626. scope.$digest();
  14627. // the listener is always called during the first $digest loop after it was registered
  14628. expect(scope.counter).toEqual(1);
  14629. scope.$digest();
  14630. // but now it will not be called unless the value changes
  14631. expect(scope.counter).toEqual(1);
  14632. scope.name = 'adam';
  14633. scope.$digest();
  14634. expect(scope.counter).toEqual(2);
  14635. // Using a function as a watchExpression
  14636. var food;
  14637. scope.foodCounter = 0;
  14638. expect(scope.foodCounter).toEqual(0);
  14639. scope.$watch(
  14640. // This function returns the value being watched. It is called for each turn of the $digest loop
  14641. function() { return food; },
  14642. // This is the change listener, called when the value returned from the above function changes
  14643. function(newValue, oldValue) {
  14644. if ( newValue !== oldValue ) {
  14645. // Only increment the counter if the value changed
  14646. scope.foodCounter = scope.foodCounter + 1;
  14647. }
  14648. }
  14649. );
  14650. // No digest has been run so the counter will be zero
  14651. expect(scope.foodCounter).toEqual(0);
  14652. // Run the digest but since food has not changed count will still be zero
  14653. scope.$digest();
  14654. expect(scope.foodCounter).toEqual(0);
  14655. // Update food and run digest. Now the counter will increment
  14656. food = 'cheeseburger';
  14657. scope.$digest();
  14658. expect(scope.foodCounter).toEqual(1);
  14659. * ```
  14660. *
  14661. *
  14662. *
  14663. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  14664. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  14665. * a call to the `listener`.
  14666. *
  14667. * - `string`: Evaluated as {@link guide/expression expression}
  14668. * - `function(scope)`: called with current `scope` as a parameter.
  14669. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  14670. * of `watchExpression` changes.
  14671. *
  14672. * - `newVal` contains the current value of the `watchExpression`
  14673. * - `oldVal` contains the previous value of the `watchExpression`
  14674. * - `scope` refers to the current scope
  14675. * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of
  14676. * comparing for reference equality.
  14677. * @returns {function()} Returns a deregistration function for this listener.
  14678. */
  14679. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  14680. var get = $parse(watchExp);
  14681. if (get.$$watchDelegate) {
  14682. return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
  14683. }
  14684. var scope = this,
  14685. array = scope.$$watchers,
  14686. watcher = {
  14687. fn: listener,
  14688. last: initWatchVal,
  14689. get: get,
  14690. exp: prettyPrintExpression || watchExp,
  14691. eq: !!objectEquality
  14692. };
  14693. lastDirtyWatch = null;
  14694. if (!isFunction(listener)) {
  14695. watcher.fn = noop;
  14696. }
  14697. if (!array) {
  14698. array = scope.$$watchers = [];
  14699. }
  14700. // we use unshift since we use a while loop in $digest for speed.
  14701. // the while loop reads in reverse order.
  14702. array.unshift(watcher);
  14703. incrementWatchersCount(this, 1);
  14704. return function deregisterWatch() {
  14705. if (arrayRemove(array, watcher) >= 0) {
  14706. incrementWatchersCount(scope, -1);
  14707. }
  14708. lastDirtyWatch = null;
  14709. };
  14710. },
  14711. /**
  14712. * @ngdoc method
  14713. * @name $rootScope.Scope#$watchGroup
  14714. * @kind function
  14715. *
  14716. * @description
  14717. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  14718. * If any one expression in the collection changes the `listener` is executed.
  14719. *
  14720. * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
  14721. * call to $digest() to see if any items changes.
  14722. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  14723. *
  14724. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  14725. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  14726. *
  14727. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  14728. * expression in `watchExpressions` changes
  14729. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  14730. * those of `watchExpression`
  14731. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  14732. * those of `watchExpression`
  14733. * The `scope` refers to the current scope.
  14734. * @returns {function()} Returns a de-registration function for all listeners.
  14735. */
  14736. $watchGroup: function(watchExpressions, listener) {
  14737. var oldValues = new Array(watchExpressions.length);
  14738. var newValues = new Array(watchExpressions.length);
  14739. var deregisterFns = [];
  14740. var self = this;
  14741. var changeReactionScheduled = false;
  14742. var firstRun = true;
  14743. if (!watchExpressions.length) {
  14744. // No expressions means we call the listener ASAP
  14745. var shouldCall = true;
  14746. self.$evalAsync(function() {
  14747. if (shouldCall) listener(newValues, newValues, self);
  14748. });
  14749. return function deregisterWatchGroup() {
  14750. shouldCall = false;
  14751. };
  14752. }
  14753. if (watchExpressions.length === 1) {
  14754. // Special case size of one
  14755. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  14756. newValues[0] = value;
  14757. oldValues[0] = oldValue;
  14758. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  14759. });
  14760. }
  14761. forEach(watchExpressions, function(expr, i) {
  14762. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  14763. newValues[i] = value;
  14764. oldValues[i] = oldValue;
  14765. if (!changeReactionScheduled) {
  14766. changeReactionScheduled = true;
  14767. self.$evalAsync(watchGroupAction);
  14768. }
  14769. });
  14770. deregisterFns.push(unwatchFn);
  14771. });
  14772. function watchGroupAction() {
  14773. changeReactionScheduled = false;
  14774. if (firstRun) {
  14775. firstRun = false;
  14776. listener(newValues, newValues, self);
  14777. } else {
  14778. listener(newValues, oldValues, self);
  14779. }
  14780. }
  14781. return function deregisterWatchGroup() {
  14782. while (deregisterFns.length) {
  14783. deregisterFns.shift()();
  14784. }
  14785. };
  14786. },
  14787. /**
  14788. * @ngdoc method
  14789. * @name $rootScope.Scope#$watchCollection
  14790. * @kind function
  14791. *
  14792. * @description
  14793. * Shallow watches the properties of an object and fires whenever any of the properties change
  14794. * (for arrays, this implies watching the array items; for object maps, this implies watching
  14795. * the properties). If a change is detected, the `listener` callback is fired.
  14796. *
  14797. * - The `obj` collection is observed via standard $watch operation and is examined on every
  14798. * call to $digest() to see if any items have been added, removed, or moved.
  14799. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  14800. * adding, removing, and moving items belonging to an object or array.
  14801. *
  14802. *
  14803. * # Example
  14804. * ```js
  14805. $scope.names = ['igor', 'matias', 'misko', 'james'];
  14806. $scope.dataCount = 4;
  14807. $scope.$watchCollection('names', function(newNames, oldNames) {
  14808. $scope.dataCount = newNames.length;
  14809. });
  14810. expect($scope.dataCount).toEqual(4);
  14811. $scope.$digest();
  14812. //still at 4 ... no changes
  14813. expect($scope.dataCount).toEqual(4);
  14814. $scope.names.pop();
  14815. $scope.$digest();
  14816. //now there's been a change
  14817. expect($scope.dataCount).toEqual(3);
  14818. * ```
  14819. *
  14820. *
  14821. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  14822. * expression value should evaluate to an object or an array which is observed on each
  14823. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  14824. * collection will trigger a call to the `listener`.
  14825. *
  14826. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  14827. * when a change is detected.
  14828. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  14829. * - The `oldCollection` object is a copy of the former collection data.
  14830. * Due to performance considerations, the`oldCollection` value is computed only if the
  14831. * `listener` function declares two or more arguments.
  14832. * - The `scope` argument refers to the current scope.
  14833. *
  14834. * @returns {function()} Returns a de-registration function for this listener. When the
  14835. * de-registration function is executed, the internal watch operation is terminated.
  14836. */
  14837. $watchCollection: function(obj, listener) {
  14838. $watchCollectionInterceptor.$stateful = true;
  14839. var self = this;
  14840. // the current value, updated on each dirty-check run
  14841. var newValue;
  14842. // a shallow copy of the newValue from the last dirty-check run,
  14843. // updated to match newValue during dirty-check run
  14844. var oldValue;
  14845. // a shallow copy of the newValue from when the last change happened
  14846. var veryOldValue;
  14847. // only track veryOldValue if the listener is asking for it
  14848. var trackVeryOldValue = (listener.length > 1);
  14849. var changeDetected = 0;
  14850. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  14851. var internalArray = [];
  14852. var internalObject = {};
  14853. var initRun = true;
  14854. var oldLength = 0;
  14855. function $watchCollectionInterceptor(_value) {
  14856. newValue = _value;
  14857. var newLength, key, bothNaN, newItem, oldItem;
  14858. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  14859. if (isUndefined(newValue)) return;
  14860. if (!isObject(newValue)) { // if primitive
  14861. if (oldValue !== newValue) {
  14862. oldValue = newValue;
  14863. changeDetected++;
  14864. }
  14865. } else if (isArrayLike(newValue)) {
  14866. if (oldValue !== internalArray) {
  14867. // we are transitioning from something which was not an array into array.
  14868. oldValue = internalArray;
  14869. oldLength = oldValue.length = 0;
  14870. changeDetected++;
  14871. }
  14872. newLength = newValue.length;
  14873. if (oldLength !== newLength) {
  14874. // if lengths do not match we need to trigger change notification
  14875. changeDetected++;
  14876. oldValue.length = oldLength = newLength;
  14877. }
  14878. // copy the items to oldValue and look for changes.
  14879. for (var i = 0; i < newLength; i++) {
  14880. oldItem = oldValue[i];
  14881. newItem = newValue[i];
  14882. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  14883. if (!bothNaN && (oldItem !== newItem)) {
  14884. changeDetected++;
  14885. oldValue[i] = newItem;
  14886. }
  14887. }
  14888. } else {
  14889. if (oldValue !== internalObject) {
  14890. // we are transitioning from something which was not an object into object.
  14891. oldValue = internalObject = {};
  14892. oldLength = 0;
  14893. changeDetected++;
  14894. }
  14895. // copy the items to oldValue and look for changes.
  14896. newLength = 0;
  14897. for (key in newValue) {
  14898. if (hasOwnProperty.call(newValue, key)) {
  14899. newLength++;
  14900. newItem = newValue[key];
  14901. oldItem = oldValue[key];
  14902. if (key in oldValue) {
  14903. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  14904. if (!bothNaN && (oldItem !== newItem)) {
  14905. changeDetected++;
  14906. oldValue[key] = newItem;
  14907. }
  14908. } else {
  14909. oldLength++;
  14910. oldValue[key] = newItem;
  14911. changeDetected++;
  14912. }
  14913. }
  14914. }
  14915. if (oldLength > newLength) {
  14916. // we used to have more keys, need to find them and destroy them.
  14917. changeDetected++;
  14918. for (key in oldValue) {
  14919. if (!hasOwnProperty.call(newValue, key)) {
  14920. oldLength--;
  14921. delete oldValue[key];
  14922. }
  14923. }
  14924. }
  14925. }
  14926. return changeDetected;
  14927. }
  14928. function $watchCollectionAction() {
  14929. if (initRun) {
  14930. initRun = false;
  14931. listener(newValue, newValue, self);
  14932. } else {
  14933. listener(newValue, veryOldValue, self);
  14934. }
  14935. // make a copy for the next time a collection is changed
  14936. if (trackVeryOldValue) {
  14937. if (!isObject(newValue)) {
  14938. //primitive
  14939. veryOldValue = newValue;
  14940. } else if (isArrayLike(newValue)) {
  14941. veryOldValue = new Array(newValue.length);
  14942. for (var i = 0; i < newValue.length; i++) {
  14943. veryOldValue[i] = newValue[i];
  14944. }
  14945. } else { // if object
  14946. veryOldValue = {};
  14947. for (var key in newValue) {
  14948. if (hasOwnProperty.call(newValue, key)) {
  14949. veryOldValue[key] = newValue[key];
  14950. }
  14951. }
  14952. }
  14953. }
  14954. }
  14955. return this.$watch(changeDetector, $watchCollectionAction);
  14956. },
  14957. /**
  14958. * @ngdoc method
  14959. * @name $rootScope.Scope#$digest
  14960. * @kind function
  14961. *
  14962. * @description
  14963. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  14964. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  14965. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  14966. * until no more listeners are firing. This means that it is possible to get into an infinite
  14967. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  14968. * iterations exceeds 10.
  14969. *
  14970. * Usually, you don't call `$digest()` directly in
  14971. * {@link ng.directive:ngController controllers} or in
  14972. * {@link ng.$compileProvider#directive directives}.
  14973. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  14974. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  14975. *
  14976. * If you want to be notified whenever `$digest()` is called,
  14977. * you can register a `watchExpression` function with
  14978. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  14979. *
  14980. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  14981. *
  14982. * # Example
  14983. * ```js
  14984. var scope = ...;
  14985. scope.name = 'misko';
  14986. scope.counter = 0;
  14987. expect(scope.counter).toEqual(0);
  14988. scope.$watch('name', function(newValue, oldValue) {
  14989. scope.counter = scope.counter + 1;
  14990. });
  14991. expect(scope.counter).toEqual(0);
  14992. scope.$digest();
  14993. // the listener is always called during the first $digest loop after it was registered
  14994. expect(scope.counter).toEqual(1);
  14995. scope.$digest();
  14996. // but now it will not be called unless the value changes
  14997. expect(scope.counter).toEqual(1);
  14998. scope.name = 'adam';
  14999. scope.$digest();
  15000. expect(scope.counter).toEqual(2);
  15001. * ```
  15002. *
  15003. */
  15004. $digest: function() {
  15005. var watch, value, last, fn, get,
  15006. watchers,
  15007. length,
  15008. dirty, ttl = TTL,
  15009. next, current, target = this,
  15010. watchLog = [],
  15011. logIdx, logMsg, asyncTask;
  15012. beginPhase('$digest');
  15013. // Check for changes to browser url that happened in sync before the call to $digest
  15014. $browser.$$checkUrlChange();
  15015. if (this === $rootScope && applyAsyncId !== null) {
  15016. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  15017. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  15018. $browser.defer.cancel(applyAsyncId);
  15019. flushApplyAsync();
  15020. }
  15021. lastDirtyWatch = null;
  15022. do { // "while dirty" loop
  15023. dirty = false;
  15024. current = target;
  15025. while (asyncQueue.length) {
  15026. try {
  15027. asyncTask = asyncQueue.shift();
  15028. asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
  15029. } catch (e) {
  15030. $exceptionHandler(e);
  15031. }
  15032. lastDirtyWatch = null;
  15033. }
  15034. traverseScopesLoop:
  15035. do { // "traverse the scopes" loop
  15036. if ((watchers = current.$$watchers)) {
  15037. // process our watches
  15038. length = watchers.length;
  15039. while (length--) {
  15040. try {
  15041. watch = watchers[length];
  15042. // Most common watches are on primitives, in which case we can short
  15043. // circuit it with === operator, only when === fails do we use .equals
  15044. if (watch) {
  15045. get = watch.get;
  15046. if ((value = get(current)) !== (last = watch.last) &&
  15047. !(watch.eq
  15048. ? equals(value, last)
  15049. : (typeof value === 'number' && typeof last === 'number'
  15050. && isNaN(value) && isNaN(last)))) {
  15051. dirty = true;
  15052. lastDirtyWatch = watch;
  15053. watch.last = watch.eq ? copy(value, null) : value;
  15054. fn = watch.fn;
  15055. fn(value, ((last === initWatchVal) ? value : last), current);
  15056. if (ttl < 5) {
  15057. logIdx = 4 - ttl;
  15058. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  15059. watchLog[logIdx].push({
  15060. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  15061. newVal: value,
  15062. oldVal: last
  15063. });
  15064. }
  15065. } else if (watch === lastDirtyWatch) {
  15066. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  15067. // have already been tested.
  15068. dirty = false;
  15069. break traverseScopesLoop;
  15070. }
  15071. }
  15072. } catch (e) {
  15073. $exceptionHandler(e);
  15074. }
  15075. }
  15076. }
  15077. // Insanity Warning: scope depth-first traversal
  15078. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  15079. // this piece should be kept in sync with the traversal in $broadcast
  15080. if (!(next = ((current.$$watchersCount && current.$$childHead) ||
  15081. (current !== target && current.$$nextSibling)))) {
  15082. while (current !== target && !(next = current.$$nextSibling)) {
  15083. current = current.$parent;
  15084. }
  15085. }
  15086. } while ((current = next));
  15087. // `break traverseScopesLoop;` takes us to here
  15088. if ((dirty || asyncQueue.length) && !(ttl--)) {
  15089. clearPhase();
  15090. throw $rootScopeMinErr('infdig',
  15091. '{0} $digest() iterations reached. Aborting!\n' +
  15092. 'Watchers fired in the last 5 iterations: {1}',
  15093. TTL, watchLog);
  15094. }
  15095. } while (dirty || asyncQueue.length);
  15096. clearPhase();
  15097. while (postDigestQueue.length) {
  15098. try {
  15099. postDigestQueue.shift()();
  15100. } catch (e) {
  15101. $exceptionHandler(e);
  15102. }
  15103. }
  15104. },
  15105. /**
  15106. * @ngdoc event
  15107. * @name $rootScope.Scope#$destroy
  15108. * @eventType broadcast on scope being destroyed
  15109. *
  15110. * @description
  15111. * Broadcasted when a scope and its children are being destroyed.
  15112. *
  15113. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  15114. * clean up DOM bindings before an element is removed from the DOM.
  15115. */
  15116. /**
  15117. * @ngdoc method
  15118. * @name $rootScope.Scope#$destroy
  15119. * @kind function
  15120. *
  15121. * @description
  15122. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  15123. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  15124. * propagate to the current scope and its children. Removal also implies that the current
  15125. * scope is eligible for garbage collection.
  15126. *
  15127. * The `$destroy()` is usually used by directives such as
  15128. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  15129. * unrolling of the loop.
  15130. *
  15131. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  15132. * Application code can register a `$destroy` event handler that will give it a chance to
  15133. * perform any necessary cleanup.
  15134. *
  15135. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  15136. * clean up DOM bindings before an element is removed from the DOM.
  15137. */
  15138. $destroy: function() {
  15139. // We can't destroy a scope that has been already destroyed.
  15140. if (this.$$destroyed) return;
  15141. var parent = this.$parent;
  15142. this.$broadcast('$destroy');
  15143. this.$$destroyed = true;
  15144. if (this === $rootScope) {
  15145. //Remove handlers attached to window when $rootScope is removed
  15146. $browser.$$applicationDestroyed();
  15147. }
  15148. incrementWatchersCount(this, -this.$$watchersCount);
  15149. for (var eventName in this.$$listenerCount) {
  15150. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  15151. }
  15152. // sever all the references to parent scopes (after this cleanup, the current scope should
  15153. // not be retained by any of our references and should be eligible for garbage collection)
  15154. if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  15155. if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  15156. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  15157. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  15158. // Disable listeners, watchers and apply/digest methods
  15159. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  15160. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  15161. this.$$listeners = {};
  15162. // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
  15163. this.$$nextSibling = null;
  15164. cleanUpScope(this);
  15165. },
  15166. /**
  15167. * @ngdoc method
  15168. * @name $rootScope.Scope#$eval
  15169. * @kind function
  15170. *
  15171. * @description
  15172. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  15173. * the expression are propagated (uncaught). This is useful when evaluating Angular
  15174. * expressions.
  15175. *
  15176. * # Example
  15177. * ```js
  15178. var scope = ng.$rootScope.Scope();
  15179. scope.a = 1;
  15180. scope.b = 2;
  15181. expect(scope.$eval('a+b')).toEqual(3);
  15182. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  15183. * ```
  15184. *
  15185. * @param {(string|function())=} expression An angular expression to be executed.
  15186. *
  15187. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  15188. * - `function(scope)`: execute the function with the current `scope` parameter.
  15189. *
  15190. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  15191. * @returns {*} The result of evaluating the expression.
  15192. */
  15193. $eval: function(expr, locals) {
  15194. return $parse(expr)(this, locals);
  15195. },
  15196. /**
  15197. * @ngdoc method
  15198. * @name $rootScope.Scope#$evalAsync
  15199. * @kind function
  15200. *
  15201. * @description
  15202. * Executes the expression on the current scope at a later point in time.
  15203. *
  15204. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  15205. * that:
  15206. *
  15207. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  15208. * rendering).
  15209. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  15210. * `expression` execution.
  15211. *
  15212. * Any exceptions from the execution of the expression are forwarded to the
  15213. * {@link ng.$exceptionHandler $exceptionHandler} service.
  15214. *
  15215. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  15216. * will be scheduled. However, it is encouraged to always call code that changes the model
  15217. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  15218. *
  15219. * @param {(string|function())=} expression An angular expression to be executed.
  15220. *
  15221. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  15222. * - `function(scope)`: execute the function with the current `scope` parameter.
  15223. *
  15224. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  15225. */
  15226. $evalAsync: function(expr, locals) {
  15227. // if we are outside of an $digest loop and this is the first time we are scheduling async
  15228. // task also schedule async auto-flush
  15229. if (!$rootScope.$$phase && !asyncQueue.length) {
  15230. $browser.defer(function() {
  15231. if (asyncQueue.length) {
  15232. $rootScope.$digest();
  15233. }
  15234. });
  15235. }
  15236. asyncQueue.push({scope: this, expression: $parse(expr), locals: locals});
  15237. },
  15238. $$postDigest: function(fn) {
  15239. postDigestQueue.push(fn);
  15240. },
  15241. /**
  15242. * @ngdoc method
  15243. * @name $rootScope.Scope#$apply
  15244. * @kind function
  15245. *
  15246. * @description
  15247. * `$apply()` is used to execute an expression in angular from outside of the angular
  15248. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  15249. * Because we are calling into the angular framework we need to perform proper scope life
  15250. * cycle of {@link ng.$exceptionHandler exception handling},
  15251. * {@link ng.$rootScope.Scope#$digest executing watches}.
  15252. *
  15253. * ## Life cycle
  15254. *
  15255. * # Pseudo-Code of `$apply()`
  15256. * ```js
  15257. function $apply(expr) {
  15258. try {
  15259. return $eval(expr);
  15260. } catch (e) {
  15261. $exceptionHandler(e);
  15262. } finally {
  15263. $root.$digest();
  15264. }
  15265. }
  15266. * ```
  15267. *
  15268. *
  15269. * Scope's `$apply()` method transitions through the following stages:
  15270. *
  15271. * 1. The {@link guide/expression expression} is executed using the
  15272. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  15273. * 2. Any exceptions from the execution of the expression are forwarded to the
  15274. * {@link ng.$exceptionHandler $exceptionHandler} service.
  15275. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  15276. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  15277. *
  15278. *
  15279. * @param {(string|function())=} exp An angular expression to be executed.
  15280. *
  15281. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  15282. * - `function(scope)`: execute the function with current `scope` parameter.
  15283. *
  15284. * @returns {*} The result of evaluating the expression.
  15285. */
  15286. $apply: function(expr) {
  15287. try {
  15288. beginPhase('$apply');
  15289. try {
  15290. return this.$eval(expr);
  15291. } finally {
  15292. clearPhase();
  15293. }
  15294. } catch (e) {
  15295. $exceptionHandler(e);
  15296. } finally {
  15297. try {
  15298. $rootScope.$digest();
  15299. } catch (e) {
  15300. $exceptionHandler(e);
  15301. throw e;
  15302. }
  15303. }
  15304. },
  15305. /**
  15306. * @ngdoc method
  15307. * @name $rootScope.Scope#$applyAsync
  15308. * @kind function
  15309. *
  15310. * @description
  15311. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  15312. * varies across browsers, but is typically around ~10 milliseconds.
  15313. *
  15314. * This can be used to queue up multiple expressions which need to be evaluated in the same
  15315. * digest.
  15316. *
  15317. * @param {(string|function())=} exp An angular expression to be executed.
  15318. *
  15319. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  15320. * - `function(scope)`: execute the function with current `scope` parameter.
  15321. */
  15322. $applyAsync: function(expr) {
  15323. var scope = this;
  15324. expr && applyAsyncQueue.push($applyAsyncExpression);
  15325. expr = $parse(expr);
  15326. scheduleApplyAsync();
  15327. function $applyAsyncExpression() {
  15328. scope.$eval(expr);
  15329. }
  15330. },
  15331. /**
  15332. * @ngdoc method
  15333. * @name $rootScope.Scope#$on
  15334. * @kind function
  15335. *
  15336. * @description
  15337. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  15338. * discussion of event life cycle.
  15339. *
  15340. * The event listener function format is: `function(event, args...)`. The `event` object
  15341. * passed into the listener has the following attributes:
  15342. *
  15343. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  15344. * `$broadcast`-ed.
  15345. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  15346. * event propagates through the scope hierarchy, this property is set to null.
  15347. * - `name` - `{string}`: name of the event.
  15348. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  15349. * further event propagation (available only for events that were `$emit`-ed).
  15350. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  15351. * to true.
  15352. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  15353. *
  15354. * @param {string} name Event name to listen on.
  15355. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  15356. * @returns {function()} Returns a deregistration function for this listener.
  15357. */
  15358. $on: function(name, listener) {
  15359. var namedListeners = this.$$listeners[name];
  15360. if (!namedListeners) {
  15361. this.$$listeners[name] = namedListeners = [];
  15362. }
  15363. namedListeners.push(listener);
  15364. var current = this;
  15365. do {
  15366. if (!current.$$listenerCount[name]) {
  15367. current.$$listenerCount[name] = 0;
  15368. }
  15369. current.$$listenerCount[name]++;
  15370. } while ((current = current.$parent));
  15371. var self = this;
  15372. return function() {
  15373. var indexOfListener = namedListeners.indexOf(listener);
  15374. if (indexOfListener !== -1) {
  15375. namedListeners[indexOfListener] = null;
  15376. decrementListenerCount(self, 1, name);
  15377. }
  15378. };
  15379. },
  15380. /**
  15381. * @ngdoc method
  15382. * @name $rootScope.Scope#$emit
  15383. * @kind function
  15384. *
  15385. * @description
  15386. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  15387. * registered {@link ng.$rootScope.Scope#$on} listeners.
  15388. *
  15389. * The event life cycle starts at the scope on which `$emit` was called. All
  15390. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  15391. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  15392. * registered listeners along the way. The event will stop propagating if one of the listeners
  15393. * cancels it.
  15394. *
  15395. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  15396. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  15397. *
  15398. * @param {string} name Event name to emit.
  15399. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  15400. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  15401. */
  15402. $emit: function(name, args) {
  15403. var empty = [],
  15404. namedListeners,
  15405. scope = this,
  15406. stopPropagation = false,
  15407. event = {
  15408. name: name,
  15409. targetScope: scope,
  15410. stopPropagation: function() {stopPropagation = true;},
  15411. preventDefault: function() {
  15412. event.defaultPrevented = true;
  15413. },
  15414. defaultPrevented: false
  15415. },
  15416. listenerArgs = concat([event], arguments, 1),
  15417. i, length;
  15418. do {
  15419. namedListeners = scope.$$listeners[name] || empty;
  15420. event.currentScope = scope;
  15421. for (i = 0, length = namedListeners.length; i < length; i++) {
  15422. // if listeners were deregistered, defragment the array
  15423. if (!namedListeners[i]) {
  15424. namedListeners.splice(i, 1);
  15425. i--;
  15426. length--;
  15427. continue;
  15428. }
  15429. try {
  15430. //allow all listeners attached to the current scope to run
  15431. namedListeners[i].apply(null, listenerArgs);
  15432. } catch (e) {
  15433. $exceptionHandler(e);
  15434. }
  15435. }
  15436. //if any listener on the current scope stops propagation, prevent bubbling
  15437. if (stopPropagation) {
  15438. event.currentScope = null;
  15439. return event;
  15440. }
  15441. //traverse upwards
  15442. scope = scope.$parent;
  15443. } while (scope);
  15444. event.currentScope = null;
  15445. return event;
  15446. },
  15447. /**
  15448. * @ngdoc method
  15449. * @name $rootScope.Scope#$broadcast
  15450. * @kind function
  15451. *
  15452. * @description
  15453. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  15454. * registered {@link ng.$rootScope.Scope#$on} listeners.
  15455. *
  15456. * The event life cycle starts at the scope on which `$broadcast` was called. All
  15457. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  15458. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  15459. * scope and calls all registered listeners along the way. The event cannot be canceled.
  15460. *
  15461. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  15462. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  15463. *
  15464. * @param {string} name Event name to broadcast.
  15465. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  15466. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  15467. */
  15468. $broadcast: function(name, args) {
  15469. var target = this,
  15470. current = target,
  15471. next = target,
  15472. event = {
  15473. name: name,
  15474. targetScope: target,
  15475. preventDefault: function() {
  15476. event.defaultPrevented = true;
  15477. },
  15478. defaultPrevented: false
  15479. };
  15480. if (!target.$$listenerCount[name]) return event;
  15481. var listenerArgs = concat([event], arguments, 1),
  15482. listeners, i, length;
  15483. //down while you can, then up and next sibling or up and next sibling until back at root
  15484. while ((current = next)) {
  15485. event.currentScope = current;
  15486. listeners = current.$$listeners[name] || [];
  15487. for (i = 0, length = listeners.length; i < length; i++) {
  15488. // if listeners were deregistered, defragment the array
  15489. if (!listeners[i]) {
  15490. listeners.splice(i, 1);
  15491. i--;
  15492. length--;
  15493. continue;
  15494. }
  15495. try {
  15496. listeners[i].apply(null, listenerArgs);
  15497. } catch (e) {
  15498. $exceptionHandler(e);
  15499. }
  15500. }
  15501. // Insanity Warning: scope depth-first traversal
  15502. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  15503. // this piece should be kept in sync with the traversal in $digest
  15504. // (though it differs due to having the extra check for $$listenerCount)
  15505. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  15506. (current !== target && current.$$nextSibling)))) {
  15507. while (current !== target && !(next = current.$$nextSibling)) {
  15508. current = current.$parent;
  15509. }
  15510. }
  15511. }
  15512. event.currentScope = null;
  15513. return event;
  15514. }
  15515. };
  15516. var $rootScope = new Scope();
  15517. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  15518. var asyncQueue = $rootScope.$$asyncQueue = [];
  15519. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  15520. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  15521. return $rootScope;
  15522. function beginPhase(phase) {
  15523. if ($rootScope.$$phase) {
  15524. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  15525. }
  15526. $rootScope.$$phase = phase;
  15527. }
  15528. function clearPhase() {
  15529. $rootScope.$$phase = null;
  15530. }
  15531. function incrementWatchersCount(current, count) {
  15532. do {
  15533. current.$$watchersCount += count;
  15534. } while ((current = current.$parent));
  15535. }
  15536. function decrementListenerCount(current, count, name) {
  15537. do {
  15538. current.$$listenerCount[name] -= count;
  15539. if (current.$$listenerCount[name] === 0) {
  15540. delete current.$$listenerCount[name];
  15541. }
  15542. } while ((current = current.$parent));
  15543. }
  15544. /**
  15545. * function used as an initial value for watchers.
  15546. * because it's unique we can easily tell it apart from other values
  15547. */
  15548. function initWatchVal() {}
  15549. function flushApplyAsync() {
  15550. while (applyAsyncQueue.length) {
  15551. try {
  15552. applyAsyncQueue.shift()();
  15553. } catch (e) {
  15554. $exceptionHandler(e);
  15555. }
  15556. }
  15557. applyAsyncId = null;
  15558. }
  15559. function scheduleApplyAsync() {
  15560. if (applyAsyncId === null) {
  15561. applyAsyncId = $browser.defer(function() {
  15562. $rootScope.$apply(flushApplyAsync);
  15563. });
  15564. }
  15565. }
  15566. }];
  15567. }
  15568. /**
  15569. * @ngdoc service
  15570. * @name $rootElement
  15571. *
  15572. * @description
  15573. * The root element of Angular application. This is either the element where {@link
  15574. * ng.directive:ngApp ngApp} was declared or the element passed into
  15575. * {@link angular.bootstrap}. The element represents the root element of application. It is also the
  15576. * location where the application's {@link auto.$injector $injector} service gets
  15577. * published, and can be retrieved using `$rootElement.injector()`.
  15578. */
  15579. // the implementation is in angular.bootstrap
  15580. /**
  15581. * @description
  15582. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  15583. */
  15584. function $$SanitizeUriProvider() {
  15585. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  15586. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  15587. /**
  15588. * @description
  15589. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  15590. * urls during a[href] sanitization.
  15591. *
  15592. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  15593. *
  15594. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  15595. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  15596. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  15597. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  15598. *
  15599. * @param {RegExp=} regexp New regexp to whitelist urls with.
  15600. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  15601. * chaining otherwise.
  15602. */
  15603. this.aHrefSanitizationWhitelist = function(regexp) {
  15604. if (isDefined(regexp)) {
  15605. aHrefSanitizationWhitelist = regexp;
  15606. return this;
  15607. }
  15608. return aHrefSanitizationWhitelist;
  15609. };
  15610. /**
  15611. * @description
  15612. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  15613. * urls during img[src] sanitization.
  15614. *
  15615. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  15616. *
  15617. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  15618. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  15619. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  15620. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  15621. *
  15622. * @param {RegExp=} regexp New regexp to whitelist urls with.
  15623. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  15624. * chaining otherwise.
  15625. */
  15626. this.imgSrcSanitizationWhitelist = function(regexp) {
  15627. if (isDefined(regexp)) {
  15628. imgSrcSanitizationWhitelist = regexp;
  15629. return this;
  15630. }
  15631. return imgSrcSanitizationWhitelist;
  15632. };
  15633. this.$get = function() {
  15634. return function sanitizeUri(uri, isImage) {
  15635. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  15636. var normalizedVal;
  15637. normalizedVal = urlResolve(uri).href;
  15638. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  15639. return 'unsafe:' + normalizedVal;
  15640. }
  15641. return uri;
  15642. };
  15643. };
  15644. }
  15645. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  15646. * Any commits to this file should be reviewed with security in mind. *
  15647. * Changes to this file can potentially create security vulnerabilities. *
  15648. * An approval from 2 Core members with history of modifying *
  15649. * this file is required. *
  15650. * *
  15651. * Does the change somehow allow for arbitrary javascript to be executed? *
  15652. * Or allows for someone to change the prototype of built-in objects? *
  15653. * Or gives undesired access to variables likes document or window? *
  15654. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  15655. var $sceMinErr = minErr('$sce');
  15656. var SCE_CONTEXTS = {
  15657. HTML: 'html',
  15658. CSS: 'css',
  15659. URL: 'url',
  15660. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  15661. // url. (e.g. ng-include, script src, templateUrl)
  15662. RESOURCE_URL: 'resourceUrl',
  15663. JS: 'js'
  15664. };
  15665. // Helper functions follow.
  15666. function adjustMatcher(matcher) {
  15667. if (matcher === 'self') {
  15668. return matcher;
  15669. } else if (isString(matcher)) {
  15670. // Strings match exactly except for 2 wildcards - '*' and '**'.
  15671. // '*' matches any character except those from the set ':/.?&'.
  15672. // '**' matches any character (like .* in a RegExp).
  15673. // More than 2 *'s raises an error as it's ill defined.
  15674. if (matcher.indexOf('***') > -1) {
  15675. throw $sceMinErr('iwcard',
  15676. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  15677. }
  15678. matcher = escapeForRegexp(matcher).
  15679. replace('\\*\\*', '.*').
  15680. replace('\\*', '[^:/.?&;]*');
  15681. return new RegExp('^' + matcher + '$');
  15682. } else if (isRegExp(matcher)) {
  15683. // The only other type of matcher allowed is a Regexp.
  15684. // Match entire URL / disallow partial matches.
  15685. // Flags are reset (i.e. no global, ignoreCase or multiline)
  15686. return new RegExp('^' + matcher.source + '$');
  15687. } else {
  15688. throw $sceMinErr('imatcher',
  15689. 'Matchers may only be "self", string patterns or RegExp objects');
  15690. }
  15691. }
  15692. function adjustMatchers(matchers) {
  15693. var adjustedMatchers = [];
  15694. if (isDefined(matchers)) {
  15695. forEach(matchers, function(matcher) {
  15696. adjustedMatchers.push(adjustMatcher(matcher));
  15697. });
  15698. }
  15699. return adjustedMatchers;
  15700. }
  15701. /**
  15702. * @ngdoc service
  15703. * @name $sceDelegate
  15704. * @kind function
  15705. *
  15706. * @description
  15707. *
  15708. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  15709. * Contextual Escaping (SCE)} services to AngularJS.
  15710. *
  15711. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  15712. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  15713. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  15714. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  15715. * work because `$sce` delegates to `$sceDelegate` for these operations.
  15716. *
  15717. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  15718. *
  15719. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  15720. * can override it completely to change the behavior of `$sce`, the common case would
  15721. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  15722. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  15723. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  15724. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  15725. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  15726. */
  15727. /**
  15728. * @ngdoc provider
  15729. * @name $sceDelegateProvider
  15730. * @description
  15731. *
  15732. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  15733. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  15734. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  15735. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  15736. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  15737. *
  15738. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  15739. * Strict Contextual Escaping (SCE)}.
  15740. *
  15741. * **Example**: Consider the following case. <a name="example"></a>
  15742. *
  15743. * - your app is hosted at url `http://myapp.example.com/`
  15744. * - but some of your templates are hosted on other domains you control such as
  15745. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  15746. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  15747. *
  15748. * Here is what a secure configuration for this scenario might look like:
  15749. *
  15750. * ```
  15751. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  15752. * $sceDelegateProvider.resourceUrlWhitelist([
  15753. * // Allow same origin resource loads.
  15754. * 'self',
  15755. * // Allow loading from our assets domain. Notice the difference between * and **.
  15756. * 'http://srv*.assets.example.com/**'
  15757. * ]);
  15758. *
  15759. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  15760. * $sceDelegateProvider.resourceUrlBlacklist([
  15761. * 'http://myapp.example.com/clickThru**'
  15762. * ]);
  15763. * });
  15764. * ```
  15765. */
  15766. function $SceDelegateProvider() {
  15767. this.SCE_CONTEXTS = SCE_CONTEXTS;
  15768. // Resource URLs can also be trusted by policy.
  15769. var resourceUrlWhitelist = ['self'],
  15770. resourceUrlBlacklist = [];
  15771. /**
  15772. * @ngdoc method
  15773. * @name $sceDelegateProvider#resourceUrlWhitelist
  15774. * @kind function
  15775. *
  15776. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  15777. * provided. This must be an array or null. A snapshot of this array is used so further
  15778. * changes to the array are ignored.
  15779. *
  15780. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  15781. * allowed in this array.
  15782. *
  15783. * <div class="alert alert-warning">
  15784. * **Note:** an empty whitelist array will block all URLs!
  15785. * </div>
  15786. *
  15787. * @return {Array} the currently set whitelist array.
  15788. *
  15789. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  15790. * same origin resource requests.
  15791. *
  15792. * @description
  15793. * Sets/Gets the whitelist of trusted resource URLs.
  15794. */
  15795. this.resourceUrlWhitelist = function(value) {
  15796. if (arguments.length) {
  15797. resourceUrlWhitelist = adjustMatchers(value);
  15798. }
  15799. return resourceUrlWhitelist;
  15800. };
  15801. /**
  15802. * @ngdoc method
  15803. * @name $sceDelegateProvider#resourceUrlBlacklist
  15804. * @kind function
  15805. *
  15806. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  15807. * provided. This must be an array or null. A snapshot of this array is used so further
  15808. * changes to the array are ignored.
  15809. *
  15810. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  15811. * allowed in this array.
  15812. *
  15813. * The typical usage for the blacklist is to **block
  15814. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  15815. * these would otherwise be trusted but actually return content from the redirected domain.
  15816. *
  15817. * Finally, **the blacklist overrides the whitelist** and has the final say.
  15818. *
  15819. * @return {Array} the currently set blacklist array.
  15820. *
  15821. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  15822. * is no blacklist.)
  15823. *
  15824. * @description
  15825. * Sets/Gets the blacklist of trusted resource URLs.
  15826. */
  15827. this.resourceUrlBlacklist = function(value) {
  15828. if (arguments.length) {
  15829. resourceUrlBlacklist = adjustMatchers(value);
  15830. }
  15831. return resourceUrlBlacklist;
  15832. };
  15833. this.$get = ['$injector', function($injector) {
  15834. var htmlSanitizer = function htmlSanitizer(html) {
  15835. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  15836. };
  15837. if ($injector.has('$sanitize')) {
  15838. htmlSanitizer = $injector.get('$sanitize');
  15839. }
  15840. function matchUrl(matcher, parsedUrl) {
  15841. if (matcher === 'self') {
  15842. return urlIsSameOrigin(parsedUrl);
  15843. } else {
  15844. // definitely a regex. See adjustMatchers()
  15845. return !!matcher.exec(parsedUrl.href);
  15846. }
  15847. }
  15848. function isResourceUrlAllowedByPolicy(url) {
  15849. var parsedUrl = urlResolve(url.toString());
  15850. var i, n, allowed = false;
  15851. // Ensure that at least one item from the whitelist allows this url.
  15852. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  15853. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  15854. allowed = true;
  15855. break;
  15856. }
  15857. }
  15858. if (allowed) {
  15859. // Ensure that no item from the blacklist blocked this url.
  15860. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  15861. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  15862. allowed = false;
  15863. break;
  15864. }
  15865. }
  15866. }
  15867. return allowed;
  15868. }
  15869. function generateHolderType(Base) {
  15870. var holderType = function TrustedValueHolderType(trustedValue) {
  15871. this.$$unwrapTrustedValue = function() {
  15872. return trustedValue;
  15873. };
  15874. };
  15875. if (Base) {
  15876. holderType.prototype = new Base();
  15877. }
  15878. holderType.prototype.valueOf = function sceValueOf() {
  15879. return this.$$unwrapTrustedValue();
  15880. };
  15881. holderType.prototype.toString = function sceToString() {
  15882. return this.$$unwrapTrustedValue().toString();
  15883. };
  15884. return holderType;
  15885. }
  15886. var trustedValueHolderBase = generateHolderType(),
  15887. byType = {};
  15888. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  15889. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  15890. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  15891. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  15892. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  15893. /**
  15894. * @ngdoc method
  15895. * @name $sceDelegate#trustAs
  15896. *
  15897. * @description
  15898. * Returns an object that is trusted by angular for use in specified strict
  15899. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  15900. * attribute interpolation, any dom event binding attribute interpolation
  15901. * such as for onclick, etc.) that uses the provided value.
  15902. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  15903. *
  15904. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  15905. * resourceUrl, html, js and css.
  15906. * @param {*} value The value that that should be considered trusted/safe.
  15907. * @returns {*} A value that can be used to stand in for the provided `value` in places
  15908. * where Angular expects a $sce.trustAs() return value.
  15909. */
  15910. function trustAs(type, trustedValue) {
  15911. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  15912. if (!Constructor) {
  15913. throw $sceMinErr('icontext',
  15914. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  15915. type, trustedValue);
  15916. }
  15917. if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
  15918. return trustedValue;
  15919. }
  15920. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  15921. // mutable objects, we ensure here that the value passed in is actually a string.
  15922. if (typeof trustedValue !== 'string') {
  15923. throw $sceMinErr('itype',
  15924. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  15925. type);
  15926. }
  15927. return new Constructor(trustedValue);
  15928. }
  15929. /**
  15930. * @ngdoc method
  15931. * @name $sceDelegate#valueOf
  15932. *
  15933. * @description
  15934. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  15935. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  15936. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  15937. *
  15938. * If the passed parameter is not a value that had been returned by {@link
  15939. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  15940. *
  15941. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  15942. * call or anything else.
  15943. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  15944. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  15945. * `value` unchanged.
  15946. */
  15947. function valueOf(maybeTrusted) {
  15948. if (maybeTrusted instanceof trustedValueHolderBase) {
  15949. return maybeTrusted.$$unwrapTrustedValue();
  15950. } else {
  15951. return maybeTrusted;
  15952. }
  15953. }
  15954. /**
  15955. * @ngdoc method
  15956. * @name $sceDelegate#getTrusted
  15957. *
  15958. * @description
  15959. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  15960. * returns the originally supplied value if the queried context type is a supertype of the
  15961. * created type. If this condition isn't satisfied, throws an exception.
  15962. *
  15963. * <div class="alert alert-danger">
  15964. * Disabling auto-escaping is extremely dangerous, it usually creates a Cross Site Scripting
  15965. * (XSS) vulnerability in your application.
  15966. * </div>
  15967. *
  15968. * @param {string} type The kind of context in which this value is to be used.
  15969. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  15970. * `$sceDelegate.trustAs`} call.
  15971. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  15972. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  15973. */
  15974. function getTrusted(type, maybeTrusted) {
  15975. if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
  15976. return maybeTrusted;
  15977. }
  15978. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  15979. if (constructor && maybeTrusted instanceof constructor) {
  15980. return maybeTrusted.$$unwrapTrustedValue();
  15981. }
  15982. // If we get here, then we may only take one of two actions.
  15983. // 1. sanitize the value for the requested type, or
  15984. // 2. throw an exception.
  15985. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  15986. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  15987. return maybeTrusted;
  15988. } else {
  15989. throw $sceMinErr('insecurl',
  15990. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  15991. maybeTrusted.toString());
  15992. }
  15993. } else if (type === SCE_CONTEXTS.HTML) {
  15994. return htmlSanitizer(maybeTrusted);
  15995. }
  15996. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  15997. }
  15998. return { trustAs: trustAs,
  15999. getTrusted: getTrusted,
  16000. valueOf: valueOf };
  16001. }];
  16002. }
  16003. /**
  16004. * @ngdoc provider
  16005. * @name $sceProvider
  16006. * @description
  16007. *
  16008. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  16009. * - enable/disable Strict Contextual Escaping (SCE) in a module
  16010. * - override the default implementation with a custom delegate
  16011. *
  16012. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  16013. */
  16014. /* jshint maxlen: false*/
  16015. /**
  16016. * @ngdoc service
  16017. * @name $sce
  16018. * @kind function
  16019. *
  16020. * @description
  16021. *
  16022. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  16023. *
  16024. * # Strict Contextual Escaping
  16025. *
  16026. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  16027. * contexts to result in a value that is marked as safe to use for that context. One example of
  16028. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  16029. * to these contexts as privileged or SCE contexts.
  16030. *
  16031. * As of version 1.2, Angular ships with SCE enabled by default.
  16032. *
  16033. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  16034. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  16035. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  16036. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  16037. * to the top of your HTML document.
  16038. *
  16039. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  16040. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  16041. *
  16042. * Here's an example of a binding in a privileged context:
  16043. *
  16044. * ```
  16045. * <input ng-model="userHtml" aria-label="User input">
  16046. * <div ng-bind-html="userHtml"></div>
  16047. * ```
  16048. *
  16049. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  16050. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  16051. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  16052. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  16053. * security vulnerabilities.)
  16054. *
  16055. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  16056. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  16057. *
  16058. * How would you ensure that every place that used these types of bindings was bound to a value that
  16059. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  16060. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  16061. * properties/fields and forgot to update the binding to the sanitized value?
  16062. *
  16063. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  16064. * determine that something explicitly says it's safe to use a value for binding in that
  16065. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  16066. * for those values that you can easily tell are safe - because they were received from your server,
  16067. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  16068. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  16069. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  16070. *
  16071. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  16072. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  16073. * obtain values that will be accepted by SCE / privileged contexts.
  16074. *
  16075. *
  16076. * ## How does it work?
  16077. *
  16078. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  16079. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  16080. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  16081. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  16082. *
  16083. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  16084. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  16085. * simplified):
  16086. *
  16087. * ```
  16088. * var ngBindHtmlDirective = ['$sce', function($sce) {
  16089. * return function(scope, element, attr) {
  16090. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  16091. * element.html(value || '');
  16092. * });
  16093. * };
  16094. * }];
  16095. * ```
  16096. *
  16097. * ## Impact on loading templates
  16098. *
  16099. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  16100. * `templateUrl`'s specified by {@link guide/directive directives}.
  16101. *
  16102. * By default, Angular only loads templates from the same domain and protocol as the application
  16103. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  16104. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  16105. * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  16106. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  16107. *
  16108. * *Please note*:
  16109. * The browser's
  16110. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  16111. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  16112. * policy apply in addition to this and may further restrict whether the template is successfully
  16113. * loaded. This means that without the right CORS policy, loading templates from a different domain
  16114. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  16115. * browsers.
  16116. *
  16117. * ## This feels like too much overhead
  16118. *
  16119. * It's important to remember that SCE only applies to interpolation expressions.
  16120. *
  16121. * If your expressions are constant literals, they're automatically trusted and you don't need to
  16122. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  16123. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  16124. *
  16125. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  16126. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  16127. *
  16128. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  16129. * templates in `ng-include` from your application's domain without having to even know about SCE.
  16130. * It blocks loading templates from other domains or loading templates over http from an https
  16131. * served document. You can change these by setting your own custom {@link
  16132. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  16133. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  16134. *
  16135. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  16136. * application that's secure and can be audited to verify that with much more ease than bolting
  16137. * security onto an application later.
  16138. *
  16139. * <a name="contexts"></a>
  16140. * ## What trusted context types are supported?
  16141. *
  16142. * | Context | Notes |
  16143. * |---------------------|----------------|
  16144. * | `$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. |
  16145. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  16146. * | `$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. |
  16147. * | `$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. |
  16148. * | `$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. |
  16149. *
  16150. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  16151. *
  16152. * Each element in these arrays must be one of the following:
  16153. *
  16154. * - **'self'**
  16155. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  16156. * domain** as the application document using the **same protocol**.
  16157. * - **String** (except the special value `'self'`)
  16158. * - The string is matched against the full *normalized / absolute URL* of the resource
  16159. * being tested (substring matches are not good enough.)
  16160. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  16161. * match themselves.
  16162. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  16163. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
  16164. * in a whitelist.
  16165. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  16166. * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
  16167. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  16168. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  16169. * http://foo.example.com/templates/**).
  16170. * - **RegExp** (*see caveat below*)
  16171. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  16172. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  16173. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  16174. * have good test coverage). For instance, the use of `.` in the regex is correct only in a
  16175. * small number of cases. A `.` character in the regex used when matching the scheme or a
  16176. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  16177. * is highly recommended to use the string patterns and only fall back to regular expressions
  16178. * as a last resort.
  16179. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  16180. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  16181. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  16182. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  16183. * - If you are generating your JavaScript from some other templating engine (not
  16184. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  16185. * remember to escape your regular expression (and be aware that you might need more than
  16186. * one level of escaping depending on your templating engine and the way you interpolated
  16187. * the value.) Do make use of your platform's escaping mechanism as it might be good
  16188. * enough before coding your own. E.g. Ruby has
  16189. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  16190. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  16191. * Javascript lacks a similar built in function for escaping. Take a look at Google
  16192. * Closure library's [goog.string.regExpEscape(s)](
  16193. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  16194. *
  16195. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  16196. *
  16197. * ## Show me an example using SCE.
  16198. *
  16199. * <example module="mySceApp" deps="angular-sanitize.js">
  16200. * <file name="index.html">
  16201. * <div ng-controller="AppController as myCtrl">
  16202. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  16203. * <b>User comments</b><br>
  16204. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  16205. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  16206. * exploit.
  16207. * <div class="well">
  16208. * <div ng-repeat="userComment in myCtrl.userComments">
  16209. * <b>{{userComment.name}}</b>:
  16210. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  16211. * <br>
  16212. * </div>
  16213. * </div>
  16214. * </div>
  16215. * </file>
  16216. *
  16217. * <file name="script.js">
  16218. * angular.module('mySceApp', ['ngSanitize'])
  16219. * .controller('AppController', ['$http', '$templateCache', '$sce',
  16220. * function($http, $templateCache, $sce) {
  16221. * var self = this;
  16222. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  16223. * self.userComments = userComments;
  16224. * });
  16225. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  16226. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  16227. * 'sanitization.&quot;">Hover over this text.</span>');
  16228. * }]);
  16229. * </file>
  16230. *
  16231. * <file name="test_data.json">
  16232. * [
  16233. * { "name": "Alice",
  16234. * "htmlComment":
  16235. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  16236. * },
  16237. * { "name": "Bob",
  16238. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  16239. * }
  16240. * ]
  16241. * </file>
  16242. *
  16243. * <file name="protractor.js" type="protractor">
  16244. * describe('SCE doc demo', function() {
  16245. * it('should sanitize untrusted values', function() {
  16246. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  16247. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  16248. * });
  16249. *
  16250. * it('should NOT sanitize explicitly trusted values', function() {
  16251. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  16252. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  16253. * 'sanitization.&quot;">Hover over this text.</span>');
  16254. * });
  16255. * });
  16256. * </file>
  16257. * </example>
  16258. *
  16259. *
  16260. *
  16261. * ## Can I disable SCE completely?
  16262. *
  16263. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  16264. * for little coding overhead. It will be much harder to take an SCE disabled application and
  16265. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  16266. * for cases where you have a lot of existing code that was written before SCE was introduced and
  16267. * you're migrating them a module at a time.
  16268. *
  16269. * That said, here's how you can completely disable SCE:
  16270. *
  16271. * ```
  16272. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  16273. * // Completely disable SCE. For demonstration purposes only!
  16274. * // Do not use in new projects.
  16275. * $sceProvider.enabled(false);
  16276. * });
  16277. * ```
  16278. *
  16279. */
  16280. /* jshint maxlen: 100 */
  16281. function $SceProvider() {
  16282. var enabled = true;
  16283. /**
  16284. * @ngdoc method
  16285. * @name $sceProvider#enabled
  16286. * @kind function
  16287. *
  16288. * @param {boolean=} value If provided, then enables/disables SCE.
  16289. * @return {boolean} true if SCE is enabled, false otherwise.
  16290. *
  16291. * @description
  16292. * Enables/disables SCE and returns the current value.
  16293. */
  16294. this.enabled = function(value) {
  16295. if (arguments.length) {
  16296. enabled = !!value;
  16297. }
  16298. return enabled;
  16299. };
  16300. /* Design notes on the default implementation for SCE.
  16301. *
  16302. * The API contract for the SCE delegate
  16303. * -------------------------------------
  16304. * The SCE delegate object must provide the following 3 methods:
  16305. *
  16306. * - trustAs(contextEnum, value)
  16307. * This method is used to tell the SCE service that the provided value is OK to use in the
  16308. * contexts specified by contextEnum. It must return an object that will be accepted by
  16309. * getTrusted() for a compatible contextEnum and return this value.
  16310. *
  16311. * - valueOf(value)
  16312. * For values that were not produced by trustAs(), return them as is. For values that were
  16313. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  16314. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  16315. * such a value.
  16316. *
  16317. * - getTrusted(contextEnum, value)
  16318. * This function should return the a value that is safe to use in the context specified by
  16319. * contextEnum or throw and exception otherwise.
  16320. *
  16321. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  16322. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  16323. * instance, an implementation could maintain a registry of all trusted objects by context. In
  16324. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  16325. * return the same object passed in if it was found in the registry under a compatible context or
  16326. * throw an exception otherwise. An implementation might only wrap values some of the time based
  16327. * on some criteria. getTrusted() might return a value and not throw an exception for special
  16328. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  16329. *
  16330. *
  16331. * A note on the inheritance model for SCE contexts
  16332. * ------------------------------------------------
  16333. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  16334. * is purely an implementation details.
  16335. *
  16336. * The contract is simply this:
  16337. *
  16338. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  16339. * will also succeed.
  16340. *
  16341. * Inheritance happens to capture this in a natural way. In some future, we
  16342. * may not use inheritance anymore. That is OK because no code outside of
  16343. * sce.js and sceSpecs.js would need to be aware of this detail.
  16344. */
  16345. this.$get = ['$parse', '$sceDelegate', function(
  16346. $parse, $sceDelegate) {
  16347. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  16348. // the "expression(javascript expression)" syntax which is insecure.
  16349. if (enabled && msie < 8) {
  16350. throw $sceMinErr('iequirks',
  16351. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  16352. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  16353. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  16354. }
  16355. var sce = shallowCopy(SCE_CONTEXTS);
  16356. /**
  16357. * @ngdoc method
  16358. * @name $sce#isEnabled
  16359. * @kind function
  16360. *
  16361. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  16362. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  16363. *
  16364. * @description
  16365. * Returns a boolean indicating if SCE is enabled.
  16366. */
  16367. sce.isEnabled = function() {
  16368. return enabled;
  16369. };
  16370. sce.trustAs = $sceDelegate.trustAs;
  16371. sce.getTrusted = $sceDelegate.getTrusted;
  16372. sce.valueOf = $sceDelegate.valueOf;
  16373. if (!enabled) {
  16374. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  16375. sce.valueOf = identity;
  16376. }
  16377. /**
  16378. * @ngdoc method
  16379. * @name $sce#parseAs
  16380. *
  16381. * @description
  16382. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  16383. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  16384. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  16385. * *result*)}
  16386. *
  16387. * @param {string} type The kind of SCE context in which this result will be used.
  16388. * @param {string} expression String expression to compile.
  16389. * @returns {function(context, locals)} a function which represents the compiled expression:
  16390. *
  16391. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  16392. * are evaluated against (typically a scope object).
  16393. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  16394. * `context`.
  16395. */
  16396. sce.parseAs = function sceParseAs(type, expr) {
  16397. var parsed = $parse(expr);
  16398. if (parsed.literal && parsed.constant) {
  16399. return parsed;
  16400. } else {
  16401. return $parse(expr, function(value) {
  16402. return sce.getTrusted(type, value);
  16403. });
  16404. }
  16405. };
  16406. /**
  16407. * @ngdoc method
  16408. * @name $sce#trustAs
  16409. *
  16410. * @description
  16411. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  16412. * returns an object that is trusted by angular for use in specified strict contextual
  16413. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  16414. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  16415. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  16416. * escaping.
  16417. *
  16418. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  16419. * resourceUrl, html, js and css.
  16420. * @param {*} value The value that that should be considered trusted/safe.
  16421. * @returns {*} A value that can be used to stand in for the provided `value` in places
  16422. * where Angular expects a $sce.trustAs() return value.
  16423. */
  16424. /**
  16425. * @ngdoc method
  16426. * @name $sce#trustAsHtml
  16427. *
  16428. * @description
  16429. * Shorthand method. `$sce.trustAsHtml(value)` →
  16430. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  16431. *
  16432. * @param {*} value The value to trustAs.
  16433. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  16434. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  16435. * only accept expressions that are either literal constants or are the
  16436. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  16437. */
  16438. /**
  16439. * @ngdoc method
  16440. * @name $sce#trustAsUrl
  16441. *
  16442. * @description
  16443. * Shorthand method. `$sce.trustAsUrl(value)` →
  16444. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  16445. *
  16446. * @param {*} value The value to trustAs.
  16447. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  16448. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  16449. * only accept expressions that are either literal constants or are the
  16450. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  16451. */
  16452. /**
  16453. * @ngdoc method
  16454. * @name $sce#trustAsResourceUrl
  16455. *
  16456. * @description
  16457. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  16458. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  16459. *
  16460. * @param {*} value The value to trustAs.
  16461. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  16462. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  16463. * only accept expressions that are either literal constants or are the return
  16464. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  16465. */
  16466. /**
  16467. * @ngdoc method
  16468. * @name $sce#trustAsJs
  16469. *
  16470. * @description
  16471. * Shorthand method. `$sce.trustAsJs(value)` →
  16472. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  16473. *
  16474. * @param {*} value The value to trustAs.
  16475. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  16476. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  16477. * only accept expressions that are either literal constants or are the
  16478. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  16479. */
  16480. /**
  16481. * @ngdoc method
  16482. * @name $sce#getTrusted
  16483. *
  16484. * @description
  16485. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  16486. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  16487. * originally supplied value if the queried context type is a supertype of the created type.
  16488. * If this condition isn't satisfied, throws an exception.
  16489. *
  16490. * @param {string} type The kind of context in which this value is to be used.
  16491. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  16492. * call.
  16493. * @returns {*} The value the was originally provided to
  16494. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  16495. * Otherwise, throws an exception.
  16496. */
  16497. /**
  16498. * @ngdoc method
  16499. * @name $sce#getTrustedHtml
  16500. *
  16501. * @description
  16502. * Shorthand method. `$sce.getTrustedHtml(value)` →
  16503. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  16504. *
  16505. * @param {*} value The value to pass to `$sce.getTrusted`.
  16506. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  16507. */
  16508. /**
  16509. * @ngdoc method
  16510. * @name $sce#getTrustedCss
  16511. *
  16512. * @description
  16513. * Shorthand method. `$sce.getTrustedCss(value)` →
  16514. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  16515. *
  16516. * @param {*} value The value to pass to `$sce.getTrusted`.
  16517. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  16518. */
  16519. /**
  16520. * @ngdoc method
  16521. * @name $sce#getTrustedUrl
  16522. *
  16523. * @description
  16524. * Shorthand method. `$sce.getTrustedUrl(value)` →
  16525. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  16526. *
  16527. * @param {*} value The value to pass to `$sce.getTrusted`.
  16528. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  16529. */
  16530. /**
  16531. * @ngdoc method
  16532. * @name $sce#getTrustedResourceUrl
  16533. *
  16534. * @description
  16535. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  16536. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  16537. *
  16538. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  16539. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  16540. */
  16541. /**
  16542. * @ngdoc method
  16543. * @name $sce#getTrustedJs
  16544. *
  16545. * @description
  16546. * Shorthand method. `$sce.getTrustedJs(value)` →
  16547. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  16548. *
  16549. * @param {*} value The value to pass to `$sce.getTrusted`.
  16550. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  16551. */
  16552. /**
  16553. * @ngdoc method
  16554. * @name $sce#parseAsHtml
  16555. *
  16556. * @description
  16557. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  16558. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  16559. *
  16560. * @param {string} expression String expression to compile.
  16561. * @returns {function(context, locals)} a function which represents the compiled expression:
  16562. *
  16563. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  16564. * are evaluated against (typically a scope object).
  16565. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  16566. * `context`.
  16567. */
  16568. /**
  16569. * @ngdoc method
  16570. * @name $sce#parseAsCss
  16571. *
  16572. * @description
  16573. * Shorthand method. `$sce.parseAsCss(value)` →
  16574. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  16575. *
  16576. * @param {string} expression String expression to compile.
  16577. * @returns {function(context, locals)} a function which represents the compiled expression:
  16578. *
  16579. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  16580. * are evaluated against (typically a scope object).
  16581. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  16582. * `context`.
  16583. */
  16584. /**
  16585. * @ngdoc method
  16586. * @name $sce#parseAsUrl
  16587. *
  16588. * @description
  16589. * Shorthand method. `$sce.parseAsUrl(value)` →
  16590. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  16591. *
  16592. * @param {string} expression String expression to compile.
  16593. * @returns {function(context, locals)} a function which represents the compiled expression:
  16594. *
  16595. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  16596. * are evaluated against (typically a scope object).
  16597. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  16598. * `context`.
  16599. */
  16600. /**
  16601. * @ngdoc method
  16602. * @name $sce#parseAsResourceUrl
  16603. *
  16604. * @description
  16605. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  16606. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  16607. *
  16608. * @param {string} expression String expression to compile.
  16609. * @returns {function(context, locals)} a function which represents the compiled expression:
  16610. *
  16611. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  16612. * are evaluated against (typically a scope object).
  16613. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  16614. * `context`.
  16615. */
  16616. /**
  16617. * @ngdoc method
  16618. * @name $sce#parseAsJs
  16619. *
  16620. * @description
  16621. * Shorthand method. `$sce.parseAsJs(value)` →
  16622. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  16623. *
  16624. * @param {string} expression String expression to compile.
  16625. * @returns {function(context, locals)} a function which represents the compiled expression:
  16626. *
  16627. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  16628. * are evaluated against (typically a scope object).
  16629. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  16630. * `context`.
  16631. */
  16632. // Shorthand delegations.
  16633. var parse = sce.parseAs,
  16634. getTrusted = sce.getTrusted,
  16635. trustAs = sce.trustAs;
  16636. forEach(SCE_CONTEXTS, function(enumValue, name) {
  16637. var lName = lowercase(name);
  16638. sce[camelCase("parse_as_" + lName)] = function(expr) {
  16639. return parse(enumValue, expr);
  16640. };
  16641. sce[camelCase("get_trusted_" + lName)] = function(value) {
  16642. return getTrusted(enumValue, value);
  16643. };
  16644. sce[camelCase("trust_as_" + lName)] = function(value) {
  16645. return trustAs(enumValue, value);
  16646. };
  16647. });
  16648. return sce;
  16649. }];
  16650. }
  16651. /**
  16652. * !!! This is an undocumented "private" service !!!
  16653. *
  16654. * @name $sniffer
  16655. * @requires $window
  16656. * @requires $document
  16657. *
  16658. * @property {boolean} history Does the browser support html5 history api ?
  16659. * @property {boolean} transitions Does the browser support CSS transition events ?
  16660. * @property {boolean} animations Does the browser support CSS animation events ?
  16661. *
  16662. * @description
  16663. * This is very simple implementation of testing browser's features.
  16664. */
  16665. function $SnifferProvider() {
  16666. this.$get = ['$window', '$document', function($window, $document) {
  16667. var eventSupport = {},
  16668. android =
  16669. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  16670. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  16671. document = $document[0] || {},
  16672. vendorPrefix,
  16673. vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
  16674. bodyStyle = document.body && document.body.style,
  16675. transitions = false,
  16676. animations = false,
  16677. match;
  16678. if (bodyStyle) {
  16679. for (var prop in bodyStyle) {
  16680. if (match = vendorRegex.exec(prop)) {
  16681. vendorPrefix = match[0];
  16682. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  16683. break;
  16684. }
  16685. }
  16686. if (!vendorPrefix) {
  16687. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  16688. }
  16689. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  16690. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  16691. if (android && (!transitions || !animations)) {
  16692. transitions = isString(bodyStyle.webkitTransition);
  16693. animations = isString(bodyStyle.webkitAnimation);
  16694. }
  16695. }
  16696. return {
  16697. // Android has history.pushState, but it does not update location correctly
  16698. // so let's not use the history API at all.
  16699. // http://code.google.com/p/android/issues/detail?id=17471
  16700. // https://github.com/angular/angular.js/issues/904
  16701. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  16702. // so let's not use the history API also
  16703. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  16704. // jshint -W018
  16705. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  16706. // jshint +W018
  16707. hasEvent: function(event) {
  16708. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  16709. // it. In particular the event is not fired when backspace or delete key are pressed or
  16710. // when cut operation is performed.
  16711. // IE10+ implements 'input' event but it erroneously fires under various situations,
  16712. // e.g. when placeholder changes, or a form is focused.
  16713. if (event === 'input' && msie <= 11) return false;
  16714. if (isUndefined(eventSupport[event])) {
  16715. var divElm = document.createElement('div');
  16716. eventSupport[event] = 'on' + event in divElm;
  16717. }
  16718. return eventSupport[event];
  16719. },
  16720. csp: csp(),
  16721. vendorPrefix: vendorPrefix,
  16722. transitions: transitions,
  16723. animations: animations,
  16724. android: android
  16725. };
  16726. }];
  16727. }
  16728. var $compileMinErr = minErr('$compile');
  16729. /**
  16730. * @ngdoc provider
  16731. * @name $templateRequestProvider
  16732. * @description
  16733. * Used to configure the options passed to the {@link $http} service when making a template request.
  16734. *
  16735. * For example, it can be used for specifying the "Accept" header that is sent to the server, when
  16736. * requesting a template.
  16737. */
  16738. function $TemplateRequestProvider() {
  16739. var httpOptions;
  16740. /**
  16741. * @ngdoc method
  16742. * @name $templateRequestProvider#httpOptions
  16743. * @description
  16744. * The options to be passed to the {@link $http} service when making the request.
  16745. * You can use this to override options such as the "Accept" header for template requests.
  16746. *
  16747. * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
  16748. * options if not overridden here.
  16749. *
  16750. * @param {string=} value new value for the {@link $http} options.
  16751. * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.
  16752. */
  16753. this.httpOptions = function(val) {
  16754. if (val) {
  16755. httpOptions = val;
  16756. return this;
  16757. }
  16758. return httpOptions;
  16759. };
  16760. /**
  16761. * @ngdoc service
  16762. * @name $templateRequest
  16763. *
  16764. * @description
  16765. * The `$templateRequest` service runs security checks then downloads the provided template using
  16766. * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
  16767. * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
  16768. * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
  16769. * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
  16770. * when `tpl` is of type string and `$templateCache` has the matching entry.
  16771. *
  16772. * If you want to pass custom options to the `$http` service, such as setting the Accept header you
  16773. * can configure this via {@link $templateRequestProvider#httpOptions}.
  16774. *
  16775. * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
  16776. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  16777. *
  16778. * @return {Promise} a promise for the HTTP response data of the given URL.
  16779. *
  16780. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  16781. */
  16782. this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
  16783. function handleRequestFn(tpl, ignoreRequestError) {
  16784. handleRequestFn.totalPendingRequests++;
  16785. // We consider the template cache holds only trusted templates, so
  16786. // there's no need to go through whitelisting again for keys that already
  16787. // are included in there. This also makes Angular accept any script
  16788. // directive, no matter its name. However, we still need to unwrap trusted
  16789. // types.
  16790. if (!isString(tpl) || !$templateCache.get(tpl)) {
  16791. tpl = $sce.getTrustedResourceUrl(tpl);
  16792. }
  16793. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  16794. if (isArray(transformResponse)) {
  16795. transformResponse = transformResponse.filter(function(transformer) {
  16796. return transformer !== defaultHttpResponseTransform;
  16797. });
  16798. } else if (transformResponse === defaultHttpResponseTransform) {
  16799. transformResponse = null;
  16800. }
  16801. return $http.get(tpl, extend({
  16802. cache: $templateCache,
  16803. transformResponse: transformResponse
  16804. }, httpOptions))
  16805. ['finally'](function() {
  16806. handleRequestFn.totalPendingRequests--;
  16807. })
  16808. .then(function(response) {
  16809. $templateCache.put(tpl, response.data);
  16810. return response.data;
  16811. }, handleError);
  16812. function handleError(resp) {
  16813. if (!ignoreRequestError) {
  16814. throw $compileMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
  16815. tpl, resp.status, resp.statusText);
  16816. }
  16817. return $q.reject(resp);
  16818. }
  16819. }
  16820. handleRequestFn.totalPendingRequests = 0;
  16821. return handleRequestFn;
  16822. }];
  16823. }
  16824. function $$TestabilityProvider() {
  16825. this.$get = ['$rootScope', '$browser', '$location',
  16826. function($rootScope, $browser, $location) {
  16827. /**
  16828. * @name $testability
  16829. *
  16830. * @description
  16831. * The private $$testability service provides a collection of methods for use when debugging
  16832. * or by automated test and debugging tools.
  16833. */
  16834. var testability = {};
  16835. /**
  16836. * @name $$testability#findBindings
  16837. *
  16838. * @description
  16839. * Returns an array of elements that are bound (via ng-bind or {{}})
  16840. * to expressions matching the input.
  16841. *
  16842. * @param {Element} element The element root to search from.
  16843. * @param {string} expression The binding expression to match.
  16844. * @param {boolean} opt_exactMatch If true, only returns exact matches
  16845. * for the expression. Filters and whitespace are ignored.
  16846. */
  16847. testability.findBindings = function(element, expression, opt_exactMatch) {
  16848. var bindings = element.getElementsByClassName('ng-binding');
  16849. var matches = [];
  16850. forEach(bindings, function(binding) {
  16851. var dataBinding = angular.element(binding).data('$binding');
  16852. if (dataBinding) {
  16853. forEach(dataBinding, function(bindingName) {
  16854. if (opt_exactMatch) {
  16855. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  16856. if (matcher.test(bindingName)) {
  16857. matches.push(binding);
  16858. }
  16859. } else {
  16860. if (bindingName.indexOf(expression) != -1) {
  16861. matches.push(binding);
  16862. }
  16863. }
  16864. });
  16865. }
  16866. });
  16867. return matches;
  16868. };
  16869. /**
  16870. * @name $$testability#findModels
  16871. *
  16872. * @description
  16873. * Returns an array of elements that are two-way found via ng-model to
  16874. * expressions matching the input.
  16875. *
  16876. * @param {Element} element The element root to search from.
  16877. * @param {string} expression The model expression to match.
  16878. * @param {boolean} opt_exactMatch If true, only returns exact matches
  16879. * for the expression.
  16880. */
  16881. testability.findModels = function(element, expression, opt_exactMatch) {
  16882. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  16883. for (var p = 0; p < prefixes.length; ++p) {
  16884. var attributeEquals = opt_exactMatch ? '=' : '*=';
  16885. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  16886. var elements = element.querySelectorAll(selector);
  16887. if (elements.length) {
  16888. return elements;
  16889. }
  16890. }
  16891. };
  16892. /**
  16893. * @name $$testability#getLocation
  16894. *
  16895. * @description
  16896. * Shortcut for getting the location in a browser agnostic way. Returns
  16897. * the path, search, and hash. (e.g. /path?a=b#hash)
  16898. */
  16899. testability.getLocation = function() {
  16900. return $location.url();
  16901. };
  16902. /**
  16903. * @name $$testability#setLocation
  16904. *
  16905. * @description
  16906. * Shortcut for navigating to a location without doing a full page reload.
  16907. *
  16908. * @param {string} url The location url (path, search and hash,
  16909. * e.g. /path?a=b#hash) to go to.
  16910. */
  16911. testability.setLocation = function(url) {
  16912. if (url !== $location.url()) {
  16913. $location.url(url);
  16914. $rootScope.$digest();
  16915. }
  16916. };
  16917. /**
  16918. * @name $$testability#whenStable
  16919. *
  16920. * @description
  16921. * Calls the callback when $timeout and $http requests are completed.
  16922. *
  16923. * @param {function} callback
  16924. */
  16925. testability.whenStable = function(callback) {
  16926. $browser.notifyWhenNoOutstandingRequests(callback);
  16927. };
  16928. return testability;
  16929. }];
  16930. }
  16931. function $TimeoutProvider() {
  16932. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  16933. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  16934. var deferreds = {};
  16935. /**
  16936. * @ngdoc service
  16937. * @name $timeout
  16938. *
  16939. * @description
  16940. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  16941. * block and delegates any exceptions to
  16942. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16943. *
  16944. * The return value of calling `$timeout` is a promise, which will be resolved when
  16945. * the delay has passed and the timeout function, if provided, is executed.
  16946. *
  16947. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  16948. *
  16949. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  16950. * synchronously flush the queue of deferred functions.
  16951. *
  16952. * If you only want a promise that will be resolved after some specified delay
  16953. * then you can call `$timeout` without the `fn` function.
  16954. *
  16955. * @param {function()=} fn A function, whose execution should be delayed.
  16956. * @param {number=} [delay=0] Delay in milliseconds.
  16957. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  16958. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  16959. * @param {...*=} Pass additional parameters to the executed function.
  16960. * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise
  16961. * will be resolved with the return value of the `fn` function.
  16962. *
  16963. */
  16964. function timeout(fn, delay, invokeApply) {
  16965. if (!isFunction(fn)) {
  16966. invokeApply = delay;
  16967. delay = fn;
  16968. fn = noop;
  16969. }
  16970. var args = sliceArgs(arguments, 3),
  16971. skipApply = (isDefined(invokeApply) && !invokeApply),
  16972. deferred = (skipApply ? $$q : $q).defer(),
  16973. promise = deferred.promise,
  16974. timeoutId;
  16975. timeoutId = $browser.defer(function() {
  16976. try {
  16977. deferred.resolve(fn.apply(null, args));
  16978. } catch (e) {
  16979. deferred.reject(e);
  16980. $exceptionHandler(e);
  16981. }
  16982. finally {
  16983. delete deferreds[promise.$$timeoutId];
  16984. }
  16985. if (!skipApply) $rootScope.$apply();
  16986. }, delay);
  16987. promise.$$timeoutId = timeoutId;
  16988. deferreds[timeoutId] = deferred;
  16989. return promise;
  16990. }
  16991. /**
  16992. * @ngdoc method
  16993. * @name $timeout#cancel
  16994. *
  16995. * @description
  16996. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  16997. * resolved with a rejection.
  16998. *
  16999. * @param {Promise=} promise Promise returned by the `$timeout` function.
  17000. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  17001. * canceled.
  17002. */
  17003. timeout.cancel = function(promise) {
  17004. if (promise && promise.$$timeoutId in deferreds) {
  17005. deferreds[promise.$$timeoutId].reject('canceled');
  17006. delete deferreds[promise.$$timeoutId];
  17007. return $browser.defer.cancel(promise.$$timeoutId);
  17008. }
  17009. return false;
  17010. };
  17011. return timeout;
  17012. }];
  17013. }
  17014. // NOTE: The usage of window and document instead of $window and $document here is
  17015. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  17016. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  17017. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  17018. // doesn't know about mocked locations and resolves URLs to the real document - which is
  17019. // exactly the behavior needed here. There is little value is mocking these out for this
  17020. // service.
  17021. var urlParsingNode = document.createElement("a");
  17022. var originUrl = urlResolve(window.location.href);
  17023. /**
  17024. *
  17025. * Implementation Notes for non-IE browsers
  17026. * ----------------------------------------
  17027. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  17028. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  17029. * URL will be resolved into an absolute URL in the context of the application document.
  17030. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  17031. * properties are all populated to reflect the normalized URL. This approach has wide
  17032. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  17033. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  17034. *
  17035. * Implementation Notes for IE
  17036. * ---------------------------
  17037. * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
  17038. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  17039. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  17040. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  17041. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  17042. * properties such as protocol, hostname, port, etc.
  17043. *
  17044. * References:
  17045. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  17046. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  17047. * http://url.spec.whatwg.org/#urlutils
  17048. * https://github.com/angular/angular.js/pull/2902
  17049. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  17050. *
  17051. * @kind function
  17052. * @param {string} url The URL to be parsed.
  17053. * @description Normalizes and parses a URL.
  17054. * @returns {object} Returns the normalized URL as a dictionary.
  17055. *
  17056. * | member name | Description |
  17057. * |---------------|----------------|
  17058. * | href | A normalized version of the provided URL if it was not an absolute URL |
  17059. * | protocol | The protocol including the trailing colon |
  17060. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  17061. * | search | The search params, minus the question mark |
  17062. * | hash | The hash string, minus the hash symbol
  17063. * | hostname | The hostname
  17064. * | port | The port, without ":"
  17065. * | pathname | The pathname, beginning with "/"
  17066. *
  17067. */
  17068. function urlResolve(url) {
  17069. var href = url;
  17070. if (msie) {
  17071. // Normalize before parse. Refer Implementation Notes on why this is
  17072. // done in two steps on IE.
  17073. urlParsingNode.setAttribute("href", href);
  17074. href = urlParsingNode.href;
  17075. }
  17076. urlParsingNode.setAttribute('href', href);
  17077. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  17078. return {
  17079. href: urlParsingNode.href,
  17080. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  17081. host: urlParsingNode.host,
  17082. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  17083. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  17084. hostname: urlParsingNode.hostname,
  17085. port: urlParsingNode.port,
  17086. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  17087. ? urlParsingNode.pathname
  17088. : '/' + urlParsingNode.pathname
  17089. };
  17090. }
  17091. /**
  17092. * Parse a request URL and determine whether this is a same-origin request as the application document.
  17093. *
  17094. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  17095. * or a parsed URL object.
  17096. * @returns {boolean} Whether the request is for the same origin as the application document.
  17097. */
  17098. function urlIsSameOrigin(requestUrl) {
  17099. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  17100. return (parsed.protocol === originUrl.protocol &&
  17101. parsed.host === originUrl.host);
  17102. }
  17103. /**
  17104. * @ngdoc service
  17105. * @name $window
  17106. *
  17107. * @description
  17108. * A reference to the browser's `window` object. While `window`
  17109. * is globally available in JavaScript, it causes testability problems, because
  17110. * it is a global variable. In angular we always refer to it through the
  17111. * `$window` service, so it may be overridden, removed or mocked for testing.
  17112. *
  17113. * Expressions, like the one defined for the `ngClick` directive in the example
  17114. * below, are evaluated with respect to the current scope. Therefore, there is
  17115. * no risk of inadvertently coding in a dependency on a global value in such an
  17116. * expression.
  17117. *
  17118. * @example
  17119. <example module="windowExample">
  17120. <file name="index.html">
  17121. <script>
  17122. angular.module('windowExample', [])
  17123. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  17124. $scope.greeting = 'Hello, World!';
  17125. $scope.doGreeting = function(greeting) {
  17126. $window.alert(greeting);
  17127. };
  17128. }]);
  17129. </script>
  17130. <div ng-controller="ExampleController">
  17131. <input type="text" ng-model="greeting" aria-label="greeting" />
  17132. <button ng-click="doGreeting(greeting)">ALERT</button>
  17133. </div>
  17134. </file>
  17135. <file name="protractor.js" type="protractor">
  17136. it('should display the greeting in the input box', function() {
  17137. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  17138. // If we click the button it will block the test runner
  17139. // element(':button').click();
  17140. });
  17141. </file>
  17142. </example>
  17143. */
  17144. function $WindowProvider() {
  17145. this.$get = valueFn(window);
  17146. }
  17147. /**
  17148. * @name $$cookieReader
  17149. * @requires $document
  17150. *
  17151. * @description
  17152. * This is a private service for reading cookies used by $http and ngCookies
  17153. *
  17154. * @return {Object} a key/value map of the current cookies
  17155. */
  17156. function $$CookieReader($document) {
  17157. var rawDocument = $document[0] || {};
  17158. var lastCookies = {};
  17159. var lastCookieString = '';
  17160. function safeDecodeURIComponent(str) {
  17161. try {
  17162. return decodeURIComponent(str);
  17163. } catch (e) {
  17164. return str;
  17165. }
  17166. }
  17167. return function() {
  17168. var cookieArray, cookie, i, index, name;
  17169. var currentCookieString = rawDocument.cookie || '';
  17170. if (currentCookieString !== lastCookieString) {
  17171. lastCookieString = currentCookieString;
  17172. cookieArray = lastCookieString.split('; ');
  17173. lastCookies = {};
  17174. for (i = 0; i < cookieArray.length; i++) {
  17175. cookie = cookieArray[i];
  17176. index = cookie.indexOf('=');
  17177. if (index > 0) { //ignore nameless cookies
  17178. name = safeDecodeURIComponent(cookie.substring(0, index));
  17179. // the first value that is seen for a cookie is the most
  17180. // specific one. values for the same cookie name that
  17181. // follow are for less specific paths.
  17182. if (isUndefined(lastCookies[name])) {
  17183. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  17184. }
  17185. }
  17186. }
  17187. }
  17188. return lastCookies;
  17189. };
  17190. }
  17191. $$CookieReader.$inject = ['$document'];
  17192. function $$CookieReaderProvider() {
  17193. this.$get = $$CookieReader;
  17194. }
  17195. /* global currencyFilter: true,
  17196. dateFilter: true,
  17197. filterFilter: true,
  17198. jsonFilter: true,
  17199. limitToFilter: true,
  17200. lowercaseFilter: true,
  17201. numberFilter: true,
  17202. orderByFilter: true,
  17203. uppercaseFilter: true,
  17204. */
  17205. /**
  17206. * @ngdoc provider
  17207. * @name $filterProvider
  17208. * @description
  17209. *
  17210. * Filters are just functions which transform input to an output. However filters need to be
  17211. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  17212. * annotated with dependencies and is responsible for creating a filter function.
  17213. *
  17214. * <div class="alert alert-warning">
  17215. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  17216. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  17217. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  17218. * (`myapp_subsection_filterx`).
  17219. * </div>
  17220. *
  17221. * ```js
  17222. * // Filter registration
  17223. * function MyModule($provide, $filterProvider) {
  17224. * // create a service to demonstrate injection (not always needed)
  17225. * $provide.value('greet', function(name){
  17226. * return 'Hello ' + name + '!';
  17227. * });
  17228. *
  17229. * // register a filter factory which uses the
  17230. * // greet service to demonstrate DI.
  17231. * $filterProvider.register('greet', function(greet){
  17232. * // return the filter function which uses the greet service
  17233. * // to generate salutation
  17234. * return function(text) {
  17235. * // filters need to be forgiving so check input validity
  17236. * return text && greet(text) || text;
  17237. * };
  17238. * });
  17239. * }
  17240. * ```
  17241. *
  17242. * The filter function is registered with the `$injector` under the filter name suffix with
  17243. * `Filter`.
  17244. *
  17245. * ```js
  17246. * it('should be the same instance', inject(
  17247. * function($filterProvider) {
  17248. * $filterProvider.register('reverse', function(){
  17249. * return ...;
  17250. * });
  17251. * },
  17252. * function($filter, reverseFilter) {
  17253. * expect($filter('reverse')).toBe(reverseFilter);
  17254. * });
  17255. * ```
  17256. *
  17257. *
  17258. * For more information about how angular filters work, and how to create your own filters, see
  17259. * {@link guide/filter Filters} in the Angular Developer Guide.
  17260. */
  17261. /**
  17262. * @ngdoc service
  17263. * @name $filter
  17264. * @kind function
  17265. * @description
  17266. * Filters are used for formatting data displayed to the user.
  17267. *
  17268. * The general syntax in templates is as follows:
  17269. *
  17270. * {{ expression [| filter_name[:parameter_value] ... ] }}
  17271. *
  17272. * @param {String} name Name of the filter function to retrieve
  17273. * @return {Function} the filter function
  17274. * @example
  17275. <example name="$filter" module="filterExample">
  17276. <file name="index.html">
  17277. <div ng-controller="MainCtrl">
  17278. <h3>{{ originalText }}</h3>
  17279. <h3>{{ filteredText }}</h3>
  17280. </div>
  17281. </file>
  17282. <file name="script.js">
  17283. angular.module('filterExample', [])
  17284. .controller('MainCtrl', function($scope, $filter) {
  17285. $scope.originalText = 'hello';
  17286. $scope.filteredText = $filter('uppercase')($scope.originalText);
  17287. });
  17288. </file>
  17289. </example>
  17290. */
  17291. $FilterProvider.$inject = ['$provide'];
  17292. function $FilterProvider($provide) {
  17293. var suffix = 'Filter';
  17294. /**
  17295. * @ngdoc method
  17296. * @name $filterProvider#register
  17297. * @param {string|Object} name Name of the filter function, or an object map of filters where
  17298. * the keys are the filter names and the values are the filter factories.
  17299. *
  17300. * <div class="alert alert-warning">
  17301. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  17302. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  17303. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  17304. * (`myapp_subsection_filterx`).
  17305. * </div>
  17306. * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
  17307. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  17308. * of the registered filter instances.
  17309. */
  17310. function register(name, factory) {
  17311. if (isObject(name)) {
  17312. var filters = {};
  17313. forEach(name, function(filter, key) {
  17314. filters[key] = register(key, filter);
  17315. });
  17316. return filters;
  17317. } else {
  17318. return $provide.factory(name + suffix, factory);
  17319. }
  17320. }
  17321. this.register = register;
  17322. this.$get = ['$injector', function($injector) {
  17323. return function(name) {
  17324. return $injector.get(name + suffix);
  17325. };
  17326. }];
  17327. ////////////////////////////////////////
  17328. /* global
  17329. currencyFilter: false,
  17330. dateFilter: false,
  17331. filterFilter: false,
  17332. jsonFilter: false,
  17333. limitToFilter: false,
  17334. lowercaseFilter: false,
  17335. numberFilter: false,
  17336. orderByFilter: false,
  17337. uppercaseFilter: false,
  17338. */
  17339. register('currency', currencyFilter);
  17340. register('date', dateFilter);
  17341. register('filter', filterFilter);
  17342. register('json', jsonFilter);
  17343. register('limitTo', limitToFilter);
  17344. register('lowercase', lowercaseFilter);
  17345. register('number', numberFilter);
  17346. register('orderBy', orderByFilter);
  17347. register('uppercase', uppercaseFilter);
  17348. }
  17349. /**
  17350. * @ngdoc filter
  17351. * @name filter
  17352. * @kind function
  17353. *
  17354. * @description
  17355. * Selects a subset of items from `array` and returns it as a new array.
  17356. *
  17357. * @param {Array} array The source array.
  17358. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  17359. * `array`.
  17360. *
  17361. * Can be one of:
  17362. *
  17363. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  17364. * objects with string properties in `array` that match this string will be returned. This also
  17365. * applies to nested object properties.
  17366. * The predicate can be negated by prefixing the string with `!`.
  17367. *
  17368. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  17369. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  17370. * which have property `name` containing "M" and property `phone` containing "1". A special
  17371. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  17372. * property of the object or its nested object properties. That's equivalent to the simple
  17373. * substring match with a `string` as described above. The predicate can be negated by prefixing
  17374. * the string with `!`.
  17375. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  17376. * not containing "M".
  17377. *
  17378. * Note that a named property will match properties on the same level only, while the special
  17379. * `$` property will match properties on the same level or deeper. E.g. an array item like
  17380. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  17381. * **will** be matched by `{$: 'John'}`.
  17382. *
  17383. * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
  17384. * The function is called for each element of the array, with the element, its index, and
  17385. * the entire array itself as arguments.
  17386. *
  17387. * The final result is an array of those elements that the predicate returned true for.
  17388. *
  17389. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  17390. * determining if the expected value (from the filter expression) and actual value (from
  17391. * the object in the array) should be considered a match.
  17392. *
  17393. * Can be one of:
  17394. *
  17395. * - `function(actual, expected)`:
  17396. * The function will be given the object value and the predicate value to compare and
  17397. * should return true if both values should be considered equal.
  17398. *
  17399. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  17400. * This is essentially strict comparison of expected and actual.
  17401. *
  17402. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  17403. * insensitive way.
  17404. *
  17405. * Primitive values are converted to strings. Objects are not compared against primitives,
  17406. * unless they have a custom `toString` method (e.g. `Date` objects).
  17407. *
  17408. * @example
  17409. <example>
  17410. <file name="index.html">
  17411. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  17412. {name:'Mary', phone:'800-BIG-MARY'},
  17413. {name:'Mike', phone:'555-4321'},
  17414. {name:'Adam', phone:'555-5678'},
  17415. {name:'Julie', phone:'555-8765'},
  17416. {name:'Juliette', phone:'555-5678'}]"></div>
  17417. <label>Search: <input ng-model="searchText"></label>
  17418. <table id="searchTextResults">
  17419. <tr><th>Name</th><th>Phone</th></tr>
  17420. <tr ng-repeat="friend in friends | filter:searchText">
  17421. <td>{{friend.name}}</td>
  17422. <td>{{friend.phone}}</td>
  17423. </tr>
  17424. </table>
  17425. <hr>
  17426. <label>Any: <input ng-model="search.$"></label> <br>
  17427. <label>Name only <input ng-model="search.name"></label><br>
  17428. <label>Phone only <input ng-model="search.phone"></label><br>
  17429. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  17430. <table id="searchObjResults">
  17431. <tr><th>Name</th><th>Phone</th></tr>
  17432. <tr ng-repeat="friendObj in friends | filter:search:strict">
  17433. <td>{{friendObj.name}}</td>
  17434. <td>{{friendObj.phone}}</td>
  17435. </tr>
  17436. </table>
  17437. </file>
  17438. <file name="protractor.js" type="protractor">
  17439. var expectFriendNames = function(expectedNames, key) {
  17440. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  17441. arr.forEach(function(wd, i) {
  17442. expect(wd.getText()).toMatch(expectedNames[i]);
  17443. });
  17444. });
  17445. };
  17446. it('should search across all fields when filtering with a string', function() {
  17447. var searchText = element(by.model('searchText'));
  17448. searchText.clear();
  17449. searchText.sendKeys('m');
  17450. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  17451. searchText.clear();
  17452. searchText.sendKeys('76');
  17453. expectFriendNames(['John', 'Julie'], 'friend');
  17454. });
  17455. it('should search in specific fields when filtering with a predicate object', function() {
  17456. var searchAny = element(by.model('search.$'));
  17457. searchAny.clear();
  17458. searchAny.sendKeys('i');
  17459. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  17460. });
  17461. it('should use a equal comparison when comparator is true', function() {
  17462. var searchName = element(by.model('search.name'));
  17463. var strict = element(by.model('strict'));
  17464. searchName.clear();
  17465. searchName.sendKeys('Julie');
  17466. strict.click();
  17467. expectFriendNames(['Julie'], 'friendObj');
  17468. });
  17469. </file>
  17470. </example>
  17471. */
  17472. function filterFilter() {
  17473. return function(array, expression, comparator) {
  17474. if (!isArrayLike(array)) {
  17475. if (array == null) {
  17476. return array;
  17477. } else {
  17478. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  17479. }
  17480. }
  17481. var expressionType = getTypeForFilter(expression);
  17482. var predicateFn;
  17483. var matchAgainstAnyProp;
  17484. switch (expressionType) {
  17485. case 'function':
  17486. predicateFn = expression;
  17487. break;
  17488. case 'boolean':
  17489. case 'null':
  17490. case 'number':
  17491. case 'string':
  17492. matchAgainstAnyProp = true;
  17493. //jshint -W086
  17494. case 'object':
  17495. //jshint +W086
  17496. predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
  17497. break;
  17498. default:
  17499. return array;
  17500. }
  17501. return Array.prototype.filter.call(array, predicateFn);
  17502. };
  17503. }
  17504. // Helper functions for `filterFilter`
  17505. function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
  17506. var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
  17507. var predicateFn;
  17508. if (comparator === true) {
  17509. comparator = equals;
  17510. } else if (!isFunction(comparator)) {
  17511. comparator = function(actual, expected) {
  17512. if (isUndefined(actual)) {
  17513. // No substring matching against `undefined`
  17514. return false;
  17515. }
  17516. if ((actual === null) || (expected === null)) {
  17517. // No substring matching against `null`; only match against `null`
  17518. return actual === expected;
  17519. }
  17520. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  17521. // Should not compare primitives against objects, unless they have custom `toString` method
  17522. return false;
  17523. }
  17524. actual = lowercase('' + actual);
  17525. expected = lowercase('' + expected);
  17526. return actual.indexOf(expected) !== -1;
  17527. };
  17528. }
  17529. predicateFn = function(item) {
  17530. if (shouldMatchPrimitives && !isObject(item)) {
  17531. return deepCompare(item, expression.$, comparator, false);
  17532. }
  17533. return deepCompare(item, expression, comparator, matchAgainstAnyProp);
  17534. };
  17535. return predicateFn;
  17536. }
  17537. function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
  17538. var actualType = getTypeForFilter(actual);
  17539. var expectedType = getTypeForFilter(expected);
  17540. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  17541. return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
  17542. } else if (isArray(actual)) {
  17543. // In case `actual` is an array, consider it a match
  17544. // if ANY of it's items matches `expected`
  17545. return actual.some(function(item) {
  17546. return deepCompare(item, expected, comparator, matchAgainstAnyProp);
  17547. });
  17548. }
  17549. switch (actualType) {
  17550. case 'object':
  17551. var key;
  17552. if (matchAgainstAnyProp) {
  17553. for (key in actual) {
  17554. if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
  17555. return true;
  17556. }
  17557. }
  17558. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
  17559. } else if (expectedType === 'object') {
  17560. for (key in expected) {
  17561. var expectedVal = expected[key];
  17562. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  17563. continue;
  17564. }
  17565. var matchAnyProperty = key === '$';
  17566. var actualVal = matchAnyProperty ? actual : actual[key];
  17567. if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
  17568. return false;
  17569. }
  17570. }
  17571. return true;
  17572. } else {
  17573. return comparator(actual, expected);
  17574. }
  17575. break;
  17576. case 'function':
  17577. return false;
  17578. default:
  17579. return comparator(actual, expected);
  17580. }
  17581. }
  17582. // Used for easily differentiating between `null` and actual `object`
  17583. function getTypeForFilter(val) {
  17584. return (val === null) ? 'null' : typeof val;
  17585. }
  17586. var MAX_DIGITS = 22;
  17587. var DECIMAL_SEP = '.';
  17588. var ZERO_CHAR = '0';
  17589. /**
  17590. * @ngdoc filter
  17591. * @name currency
  17592. * @kind function
  17593. *
  17594. * @description
  17595. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  17596. * symbol for current locale is used.
  17597. *
  17598. * @param {number} amount Input to filter.
  17599. * @param {string=} symbol Currency symbol or identifier to be displayed.
  17600. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  17601. * @returns {string} Formatted number.
  17602. *
  17603. *
  17604. * @example
  17605. <example module="currencyExample">
  17606. <file name="index.html">
  17607. <script>
  17608. angular.module('currencyExample', [])
  17609. .controller('ExampleController', ['$scope', function($scope) {
  17610. $scope.amount = 1234.56;
  17611. }]);
  17612. </script>
  17613. <div ng-controller="ExampleController">
  17614. <input type="number" ng-model="amount" aria-label="amount"> <br>
  17615. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  17616. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
  17617. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  17618. </div>
  17619. </file>
  17620. <file name="protractor.js" type="protractor">
  17621. it('should init with 1234.56', function() {
  17622. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  17623. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  17624. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  17625. });
  17626. it('should update', function() {
  17627. if (browser.params.browser == 'safari') {
  17628. // Safari does not understand the minus key. See
  17629. // https://github.com/angular/protractor/issues/481
  17630. return;
  17631. }
  17632. element(by.model('amount')).clear();
  17633. element(by.model('amount')).sendKeys('-1234');
  17634. expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
  17635. expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
  17636. expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
  17637. });
  17638. </file>
  17639. </example>
  17640. */
  17641. currencyFilter.$inject = ['$locale'];
  17642. function currencyFilter($locale) {
  17643. var formats = $locale.NUMBER_FORMATS;
  17644. return function(amount, currencySymbol, fractionSize) {
  17645. if (isUndefined(currencySymbol)) {
  17646. currencySymbol = formats.CURRENCY_SYM;
  17647. }
  17648. if (isUndefined(fractionSize)) {
  17649. fractionSize = formats.PATTERNS[1].maxFrac;
  17650. }
  17651. // if null or undefined pass it through
  17652. return (amount == null)
  17653. ? amount
  17654. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  17655. replace(/\u00A4/g, currencySymbol);
  17656. };
  17657. }
  17658. /**
  17659. * @ngdoc filter
  17660. * @name number
  17661. * @kind function
  17662. *
  17663. * @description
  17664. * Formats a number as text.
  17665. *
  17666. * If the input is null or undefined, it will just be returned.
  17667. * If the input is infinite (Infinity/-Infinity) the Infinity symbol '∞' is returned.
  17668. * If the input is not a number an empty string is returned.
  17669. *
  17670. *
  17671. * @param {number|string} number Number to format.
  17672. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  17673. * If this is not provided then the fraction size is computed from the current locale's number
  17674. * formatting pattern. In the case of the default locale, it will be 3.
  17675. * @returns {string} Number rounded to fractionSize and places a “,” after each third digit.
  17676. *
  17677. * @example
  17678. <example module="numberFilterExample">
  17679. <file name="index.html">
  17680. <script>
  17681. angular.module('numberFilterExample', [])
  17682. .controller('ExampleController', ['$scope', function($scope) {
  17683. $scope.val = 1234.56789;
  17684. }]);
  17685. </script>
  17686. <div ng-controller="ExampleController">
  17687. <label>Enter number: <input ng-model='val'></label><br>
  17688. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  17689. No fractions: <span>{{val | number:0}}</span><br>
  17690. Negative number: <span>{{-val | number:4}}</span>
  17691. </div>
  17692. </file>
  17693. <file name="protractor.js" type="protractor">
  17694. it('should format numbers', function() {
  17695. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  17696. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  17697. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  17698. });
  17699. it('should update', function() {
  17700. element(by.model('val')).clear();
  17701. element(by.model('val')).sendKeys('3374.333');
  17702. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  17703. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  17704. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  17705. });
  17706. </file>
  17707. </example>
  17708. */
  17709. numberFilter.$inject = ['$locale'];
  17710. function numberFilter($locale) {
  17711. var formats = $locale.NUMBER_FORMATS;
  17712. return function(number, fractionSize) {
  17713. // if null or undefined pass it through
  17714. return (number == null)
  17715. ? number
  17716. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  17717. fractionSize);
  17718. };
  17719. }
  17720. /**
  17721. * Parse a number (as a string) into three components that can be used
  17722. * for formatting the number.
  17723. *
  17724. * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)
  17725. *
  17726. * @param {string} numStr The number to parse
  17727. * @return {object} An object describing this number, containing the following keys:
  17728. * - d : an array of digits containing leading zeros as necessary
  17729. * - i : the number of the digits in `d` that are to the left of the decimal point
  17730. * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`
  17731. *
  17732. */
  17733. function parse(numStr) {
  17734. var exponent = 0, digits, numberOfIntegerDigits;
  17735. var i, j, zeros;
  17736. // Decimal point?
  17737. if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {
  17738. numStr = numStr.replace(DECIMAL_SEP, '');
  17739. }
  17740. // Exponential form?
  17741. if ((i = numStr.search(/e/i)) > 0) {
  17742. // Work out the exponent.
  17743. if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i;
  17744. numberOfIntegerDigits += +numStr.slice(i + 1);
  17745. numStr = numStr.substring(0, i);
  17746. } else if (numberOfIntegerDigits < 0) {
  17747. // There was no decimal point or exponent so it is an integer.
  17748. numberOfIntegerDigits = numStr.length;
  17749. }
  17750. // Count the number of leading zeros.
  17751. for (i = 0; numStr.charAt(i) == ZERO_CHAR; i++) {/* jshint noempty: false */}
  17752. if (i == (zeros = numStr.length)) {
  17753. // The digits are all zero.
  17754. digits = [0];
  17755. numberOfIntegerDigits = 1;
  17756. } else {
  17757. // Count the number of trailing zeros
  17758. zeros--;
  17759. while (numStr.charAt(zeros) == ZERO_CHAR) zeros--;
  17760. // Trailing zeros are insignificant so ignore them
  17761. numberOfIntegerDigits -= i;
  17762. digits = [];
  17763. // Convert string to array of digits without leading/trailing zeros.
  17764. for (j = 0; i <= zeros; i++, j++) {
  17765. digits[j] = +numStr.charAt(i);
  17766. }
  17767. }
  17768. // If the number overflows the maximum allowed digits then use an exponent.
  17769. if (numberOfIntegerDigits > MAX_DIGITS) {
  17770. digits = digits.splice(0, MAX_DIGITS - 1);
  17771. exponent = numberOfIntegerDigits - 1;
  17772. numberOfIntegerDigits = 1;
  17773. }
  17774. return { d: digits, e: exponent, i: numberOfIntegerDigits };
  17775. }
  17776. /**
  17777. * Round the parsed number to the specified number of decimal places
  17778. * This function changed the parsedNumber in-place
  17779. */
  17780. function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
  17781. var digits = parsedNumber.d;
  17782. var fractionLen = digits.length - parsedNumber.i;
  17783. // determine fractionSize if it is not specified; `+fractionSize` converts it to a number
  17784. fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
  17785. // The index of the digit to where rounding is to occur
  17786. var roundAt = fractionSize + parsedNumber.i;
  17787. var digit = digits[roundAt];
  17788. if (roundAt > 0) {
  17789. digits.splice(roundAt);
  17790. } else {
  17791. // We rounded to zero so reset the parsedNumber
  17792. parsedNumber.i = 1;
  17793. digits.length = roundAt = fractionSize + 1;
  17794. for (var i=0; i < roundAt; i++) digits[i] = 0;
  17795. }
  17796. if (digit >= 5) digits[roundAt - 1]++;
  17797. // Pad out with zeros to get the required fraction length
  17798. for (; fractionLen < fractionSize; fractionLen++) digits.push(0);
  17799. // Do any carrying, e.g. a digit was rounded up to 10
  17800. var carry = digits.reduceRight(function(carry, d, i, digits) {
  17801. d = d + carry;
  17802. digits[i] = d % 10;
  17803. return Math.floor(d / 10);
  17804. }, 0);
  17805. if (carry) {
  17806. digits.unshift(carry);
  17807. parsedNumber.i++;
  17808. }
  17809. }
  17810. /**
  17811. * Format a number into a string
  17812. * @param {number} number The number to format
  17813. * @param {{
  17814. * minFrac, // the minimum number of digits required in the fraction part of the number
  17815. * maxFrac, // the maximum number of digits required in the fraction part of the number
  17816. * gSize, // number of digits in each group of separated digits
  17817. * lgSize, // number of digits in the last group of digits before the decimal separator
  17818. * negPre, // the string to go in front of a negative number (e.g. `-` or `(`))
  17819. * posPre, // the string to go in front of a positive number
  17820. * negSuf, // the string to go after a negative number (e.g. `)`)
  17821. * posSuf // the string to go after a positive number
  17822. * }} pattern
  17823. * @param {string} groupSep The string to separate groups of number (e.g. `,`)
  17824. * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`)
  17825. * @param {[type]} fractionSize The size of the fractional part of the number
  17826. * @return {string} The number formatted as a string
  17827. */
  17828. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  17829. if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';
  17830. var isInfinity = !isFinite(number);
  17831. var isZero = false;
  17832. var numStr = Math.abs(number) + '',
  17833. formattedText = '',
  17834. parsedNumber;
  17835. if (isInfinity) {
  17836. formattedText = '\u221e';
  17837. } else {
  17838. parsedNumber = parse(numStr);
  17839. roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);
  17840. var digits = parsedNumber.d;
  17841. var integerLen = parsedNumber.i;
  17842. var exponent = parsedNumber.e;
  17843. var decimals = [];
  17844. isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);
  17845. // pad zeros for small numbers
  17846. while (integerLen < 0) {
  17847. digits.unshift(0);
  17848. integerLen++;
  17849. }
  17850. // extract decimals digits
  17851. if (integerLen > 0) {
  17852. decimals = digits.splice(integerLen);
  17853. } else {
  17854. decimals = digits;
  17855. digits = [0];
  17856. }
  17857. // format the integer digits with grouping separators
  17858. var groups = [];
  17859. if (digits.length > pattern.lgSize) {
  17860. groups.unshift(digits.splice(-pattern.lgSize).join(''));
  17861. }
  17862. while (digits.length > pattern.gSize) {
  17863. groups.unshift(digits.splice(-pattern.gSize).join(''));
  17864. }
  17865. if (digits.length) {
  17866. groups.unshift(digits.join(''));
  17867. }
  17868. formattedText = groups.join(groupSep);
  17869. // append the decimal digits
  17870. if (decimals.length) {
  17871. formattedText += decimalSep + decimals.join('');
  17872. }
  17873. if (exponent) {
  17874. formattedText += 'e+' + exponent;
  17875. }
  17876. }
  17877. if (number < 0 && !isZero) {
  17878. return pattern.negPre + formattedText + pattern.negSuf;
  17879. } else {
  17880. return pattern.posPre + formattedText + pattern.posSuf;
  17881. }
  17882. }
  17883. function padNumber(num, digits, trim) {
  17884. var neg = '';
  17885. if (num < 0) {
  17886. neg = '-';
  17887. num = -num;
  17888. }
  17889. num = '' + num;
  17890. while (num.length < digits) num = ZERO_CHAR + num;
  17891. if (trim) {
  17892. num = num.substr(num.length - digits);
  17893. }
  17894. return neg + num;
  17895. }
  17896. function dateGetter(name, size, offset, trim) {
  17897. offset = offset || 0;
  17898. return function(date) {
  17899. var value = date['get' + name]();
  17900. if (offset > 0 || value > -offset) {
  17901. value += offset;
  17902. }
  17903. if (value === 0 && offset == -12) value = 12;
  17904. return padNumber(value, size, trim);
  17905. };
  17906. }
  17907. function dateStrGetter(name, shortForm) {
  17908. return function(date, formats) {
  17909. var value = date['get' + name]();
  17910. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  17911. return formats[get][value];
  17912. };
  17913. }
  17914. function timeZoneGetter(date, formats, offset) {
  17915. var zone = -1 * offset;
  17916. var paddedZone = (zone >= 0) ? "+" : "";
  17917. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  17918. padNumber(Math.abs(zone % 60), 2);
  17919. return paddedZone;
  17920. }
  17921. function getFirstThursdayOfYear(year) {
  17922. // 0 = index of January
  17923. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  17924. // 4 = index of Thursday (+1 to account for 1st = 5)
  17925. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  17926. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  17927. }
  17928. function getThursdayThisWeek(datetime) {
  17929. return new Date(datetime.getFullYear(), datetime.getMonth(),
  17930. // 4 = index of Thursday
  17931. datetime.getDate() + (4 - datetime.getDay()));
  17932. }
  17933. function weekGetter(size) {
  17934. return function(date) {
  17935. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  17936. thisThurs = getThursdayThisWeek(date);
  17937. var diff = +thisThurs - +firstThurs,
  17938. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  17939. return padNumber(result, size);
  17940. };
  17941. }
  17942. function ampmGetter(date, formats) {
  17943. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  17944. }
  17945. function eraGetter(date, formats) {
  17946. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  17947. }
  17948. function longEraGetter(date, formats) {
  17949. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  17950. }
  17951. var DATE_FORMATS = {
  17952. yyyy: dateGetter('FullYear', 4),
  17953. yy: dateGetter('FullYear', 2, 0, true),
  17954. y: dateGetter('FullYear', 1),
  17955. MMMM: dateStrGetter('Month'),
  17956. MMM: dateStrGetter('Month', true),
  17957. MM: dateGetter('Month', 2, 1),
  17958. M: dateGetter('Month', 1, 1),
  17959. dd: dateGetter('Date', 2),
  17960. d: dateGetter('Date', 1),
  17961. HH: dateGetter('Hours', 2),
  17962. H: dateGetter('Hours', 1),
  17963. hh: dateGetter('Hours', 2, -12),
  17964. h: dateGetter('Hours', 1, -12),
  17965. mm: dateGetter('Minutes', 2),
  17966. m: dateGetter('Minutes', 1),
  17967. ss: dateGetter('Seconds', 2),
  17968. s: dateGetter('Seconds', 1),
  17969. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  17970. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  17971. sss: dateGetter('Milliseconds', 3),
  17972. EEEE: dateStrGetter('Day'),
  17973. EEE: dateStrGetter('Day', true),
  17974. a: ampmGetter,
  17975. Z: timeZoneGetter,
  17976. ww: weekGetter(2),
  17977. w: weekGetter(1),
  17978. G: eraGetter,
  17979. GG: eraGetter,
  17980. GGG: eraGetter,
  17981. GGGG: longEraGetter
  17982. };
  17983. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
  17984. NUMBER_STRING = /^\-?\d+$/;
  17985. /**
  17986. * @ngdoc filter
  17987. * @name date
  17988. * @kind function
  17989. *
  17990. * @description
  17991. * Formats `date` to a string based on the requested `format`.
  17992. *
  17993. * `format` string can be composed of the following elements:
  17994. *
  17995. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  17996. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  17997. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  17998. * * `'MMMM'`: Month in year (January-December)
  17999. * * `'MMM'`: Month in year (Jan-Dec)
  18000. * * `'MM'`: Month in year, padded (01-12)
  18001. * * `'M'`: Month in year (1-12)
  18002. * * `'dd'`: Day in month, padded (01-31)
  18003. * * `'d'`: Day in month (1-31)
  18004. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  18005. * * `'EEE'`: Day in Week, (Sun-Sat)
  18006. * * `'HH'`: Hour in day, padded (00-23)
  18007. * * `'H'`: Hour in day (0-23)
  18008. * * `'hh'`: Hour in AM/PM, padded (01-12)
  18009. * * `'h'`: Hour in AM/PM, (1-12)
  18010. * * `'mm'`: Minute in hour, padded (00-59)
  18011. * * `'m'`: Minute in hour (0-59)
  18012. * * `'ss'`: Second in minute, padded (00-59)
  18013. * * `'s'`: Second in minute (0-59)
  18014. * * `'sss'`: Millisecond in second, padded (000-999)
  18015. * * `'a'`: AM/PM marker
  18016. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  18017. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  18018. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  18019. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  18020. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  18021. *
  18022. * `format` string can also be one of the following predefined
  18023. * {@link guide/i18n localizable formats}:
  18024. *
  18025. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  18026. * (e.g. Sep 3, 2010 12:05:08 PM)
  18027. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  18028. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  18029. * (e.g. Friday, September 3, 2010)
  18030. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  18031. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  18032. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  18033. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  18034. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  18035. *
  18036. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  18037. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  18038. * (e.g. `"h 'o''clock'"`).
  18039. *
  18040. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  18041. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  18042. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  18043. * specified in the string input, the time is considered to be in the local timezone.
  18044. * @param {string=} format Formatting rules (see Description). If not specified,
  18045. * `mediumDate` is used.
  18046. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  18047. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  18048. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  18049. * If not specified, the timezone of the browser will be used.
  18050. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  18051. *
  18052. * @example
  18053. <example>
  18054. <file name="index.html">
  18055. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  18056. <span>{{1288323623006 | date:'medium'}}</span><br>
  18057. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  18058. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  18059. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  18060. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  18061. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  18062. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  18063. </file>
  18064. <file name="protractor.js" type="protractor">
  18065. it('should format date', function() {
  18066. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  18067. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  18068. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  18069. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  18070. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  18071. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  18072. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  18073. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  18074. });
  18075. </file>
  18076. </example>
  18077. */
  18078. dateFilter.$inject = ['$locale'];
  18079. function dateFilter($locale) {
  18080. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  18081. // 1 2 3 4 5 6 7 8 9 10 11
  18082. function jsonStringToDate(string) {
  18083. var match;
  18084. if (match = string.match(R_ISO8601_STR)) {
  18085. var date = new Date(0),
  18086. tzHour = 0,
  18087. tzMin = 0,
  18088. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  18089. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  18090. if (match[9]) {
  18091. tzHour = toInt(match[9] + match[10]);
  18092. tzMin = toInt(match[9] + match[11]);
  18093. }
  18094. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  18095. var h = toInt(match[4] || 0) - tzHour;
  18096. var m = toInt(match[5] || 0) - tzMin;
  18097. var s = toInt(match[6] || 0);
  18098. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  18099. timeSetter.call(date, h, m, s, ms);
  18100. return date;
  18101. }
  18102. return string;
  18103. }
  18104. return function(date, format, timezone) {
  18105. var text = '',
  18106. parts = [],
  18107. fn, match;
  18108. format = format || 'mediumDate';
  18109. format = $locale.DATETIME_FORMATS[format] || format;
  18110. if (isString(date)) {
  18111. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  18112. }
  18113. if (isNumber(date)) {
  18114. date = new Date(date);
  18115. }
  18116. if (!isDate(date) || !isFinite(date.getTime())) {
  18117. return date;
  18118. }
  18119. while (format) {
  18120. match = DATE_FORMATS_SPLIT.exec(format);
  18121. if (match) {
  18122. parts = concat(parts, match, 1);
  18123. format = parts.pop();
  18124. } else {
  18125. parts.push(format);
  18126. format = null;
  18127. }
  18128. }
  18129. var dateTimezoneOffset = date.getTimezoneOffset();
  18130. if (timezone) {
  18131. dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  18132. date = convertTimezoneToLocal(date, timezone, true);
  18133. }
  18134. forEach(parts, function(value) {
  18135. fn = DATE_FORMATS[value];
  18136. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  18137. : value === "''" ? "'" : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  18138. });
  18139. return text;
  18140. };
  18141. }
  18142. /**
  18143. * @ngdoc filter
  18144. * @name json
  18145. * @kind function
  18146. *
  18147. * @description
  18148. * Allows you to convert a JavaScript object into JSON string.
  18149. *
  18150. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  18151. * the binding is automatically converted to JSON.
  18152. *
  18153. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  18154. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  18155. * @returns {string} JSON string.
  18156. *
  18157. *
  18158. * @example
  18159. <example>
  18160. <file name="index.html">
  18161. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  18162. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  18163. </file>
  18164. <file name="protractor.js" type="protractor">
  18165. it('should jsonify filtered objects', function() {
  18166. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  18167. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  18168. });
  18169. </file>
  18170. </example>
  18171. *
  18172. */
  18173. function jsonFilter() {
  18174. return function(object, spacing) {
  18175. if (isUndefined(spacing)) {
  18176. spacing = 2;
  18177. }
  18178. return toJson(object, spacing);
  18179. };
  18180. }
  18181. /**
  18182. * @ngdoc filter
  18183. * @name lowercase
  18184. * @kind function
  18185. * @description
  18186. * Converts string to lowercase.
  18187. * @see angular.lowercase
  18188. */
  18189. var lowercaseFilter = valueFn(lowercase);
  18190. /**
  18191. * @ngdoc filter
  18192. * @name uppercase
  18193. * @kind function
  18194. * @description
  18195. * Converts string to uppercase.
  18196. * @see angular.uppercase
  18197. */
  18198. var uppercaseFilter = valueFn(uppercase);
  18199. /**
  18200. * @ngdoc filter
  18201. * @name limitTo
  18202. * @kind function
  18203. *
  18204. * @description
  18205. * Creates a new array or string containing only a specified number of elements. The elements
  18206. * are taken from either the beginning or the end of the source array, string or number, as specified by
  18207. * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
  18208. * converted to a string.
  18209. *
  18210. * @param {Array|string|number} input Source array, string or number to be limited.
  18211. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  18212. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  18213. * If the number is negative, `limit` number of items from the end of the source array/string
  18214. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  18215. * the input will be returned unchanged.
  18216. * @param {(string|number)=} begin Index at which to begin limitation. As a negative index, `begin`
  18217. * indicates an offset from the end of `input`. Defaults to `0`.
  18218. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  18219. * had less than `limit` elements.
  18220. *
  18221. * @example
  18222. <example module="limitToExample">
  18223. <file name="index.html">
  18224. <script>
  18225. angular.module('limitToExample', [])
  18226. .controller('ExampleController', ['$scope', function($scope) {
  18227. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  18228. $scope.letters = "abcdefghi";
  18229. $scope.longNumber = 2345432342;
  18230. $scope.numLimit = 3;
  18231. $scope.letterLimit = 3;
  18232. $scope.longNumberLimit = 3;
  18233. }]);
  18234. </script>
  18235. <div ng-controller="ExampleController">
  18236. <label>
  18237. Limit {{numbers}} to:
  18238. <input type="number" step="1" ng-model="numLimit">
  18239. </label>
  18240. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  18241. <label>
  18242. Limit {{letters}} to:
  18243. <input type="number" step="1" ng-model="letterLimit">
  18244. </label>
  18245. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  18246. <label>
  18247. Limit {{longNumber}} to:
  18248. <input type="number" step="1" ng-model="longNumberLimit">
  18249. </label>
  18250. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  18251. </div>
  18252. </file>
  18253. <file name="protractor.js" type="protractor">
  18254. var numLimitInput = element(by.model('numLimit'));
  18255. var letterLimitInput = element(by.model('letterLimit'));
  18256. var longNumberLimitInput = element(by.model('longNumberLimit'));
  18257. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  18258. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  18259. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  18260. it('should limit the number array to first three items', function() {
  18261. expect(numLimitInput.getAttribute('value')).toBe('3');
  18262. expect(letterLimitInput.getAttribute('value')).toBe('3');
  18263. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  18264. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  18265. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  18266. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  18267. });
  18268. // There is a bug in safari and protractor that doesn't like the minus key
  18269. // it('should update the output when -3 is entered', function() {
  18270. // numLimitInput.clear();
  18271. // numLimitInput.sendKeys('-3');
  18272. // letterLimitInput.clear();
  18273. // letterLimitInput.sendKeys('-3');
  18274. // longNumberLimitInput.clear();
  18275. // longNumberLimitInput.sendKeys('-3');
  18276. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  18277. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  18278. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  18279. // });
  18280. it('should not exceed the maximum size of input array', function() {
  18281. numLimitInput.clear();
  18282. numLimitInput.sendKeys('100');
  18283. letterLimitInput.clear();
  18284. letterLimitInput.sendKeys('100');
  18285. longNumberLimitInput.clear();
  18286. longNumberLimitInput.sendKeys('100');
  18287. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  18288. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  18289. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  18290. });
  18291. </file>
  18292. </example>
  18293. */
  18294. function limitToFilter() {
  18295. return function(input, limit, begin) {
  18296. if (Math.abs(Number(limit)) === Infinity) {
  18297. limit = Number(limit);
  18298. } else {
  18299. limit = toInt(limit);
  18300. }
  18301. if (isNaN(limit)) return input;
  18302. if (isNumber(input)) input = input.toString();
  18303. if (!isArray(input) && !isString(input)) return input;
  18304. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  18305. begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
  18306. if (limit >= 0) {
  18307. return input.slice(begin, begin + limit);
  18308. } else {
  18309. if (begin === 0) {
  18310. return input.slice(limit, input.length);
  18311. } else {
  18312. return input.slice(Math.max(0, begin + limit), begin);
  18313. }
  18314. }
  18315. };
  18316. }
  18317. /**
  18318. * @ngdoc filter
  18319. * @name orderBy
  18320. * @kind function
  18321. *
  18322. * @description
  18323. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  18324. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  18325. * as expected, make sure they are actually being saved as numbers and not strings.
  18326. * Array-like values (e.g. NodeLists, jQuery objects, TypedArrays, Strings, etc) are also supported.
  18327. *
  18328. * @param {Array} array The array (or array-like object) to sort.
  18329. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
  18330. * used by the comparator to determine the order of elements.
  18331. *
  18332. * Can be one of:
  18333. *
  18334. * - `function`: Getter function. The result of this function will be sorted using the
  18335. * `<`, `===`, `>` operator.
  18336. * - `string`: An Angular expression. The result of this expression is used to compare elements
  18337. * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
  18338. * 3 first characters of a property called `name`). The result of a constant expression
  18339. * is interpreted as a property name to be used in comparisons (for example `"special name"`
  18340. * to sort object by the value of their `special name` property). An expression can be
  18341. * optionally prefixed with `+` or `-` to control ascending or descending sort order
  18342. * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
  18343. * element itself is used to compare where sorting.
  18344. * - `Array`: An array of function or string predicates. The first predicate in the array
  18345. * is used for sorting, but when two items are equivalent, the next predicate is used.
  18346. *
  18347. * If the predicate is missing or empty then it defaults to `'+'`.
  18348. *
  18349. * @param {boolean=} reverse Reverse the order of the array.
  18350. * @returns {Array} Sorted copy of the source array.
  18351. *
  18352. *
  18353. * @example
  18354. * The example below demonstrates a simple ngRepeat, where the data is sorted
  18355. * by age in descending order (predicate is set to `'-age'`).
  18356. * `reverse` is not set, which means it defaults to `false`.
  18357. <example module="orderByExample">
  18358. <file name="index.html">
  18359. <div ng-controller="ExampleController">
  18360. <table class="friend">
  18361. <tr>
  18362. <th>Name</th>
  18363. <th>Phone Number</th>
  18364. <th>Age</th>
  18365. </tr>
  18366. <tr ng-repeat="friend in friends | orderBy:'-age'">
  18367. <td>{{friend.name}}</td>
  18368. <td>{{friend.phone}}</td>
  18369. <td>{{friend.age}}</td>
  18370. </tr>
  18371. </table>
  18372. </div>
  18373. </file>
  18374. <file name="script.js">
  18375. angular.module('orderByExample', [])
  18376. .controller('ExampleController', ['$scope', function($scope) {
  18377. $scope.friends =
  18378. [{name:'John', phone:'555-1212', age:10},
  18379. {name:'Mary', phone:'555-9876', age:19},
  18380. {name:'Mike', phone:'555-4321', age:21},
  18381. {name:'Adam', phone:'555-5678', age:35},
  18382. {name:'Julie', phone:'555-8765', age:29}];
  18383. }]);
  18384. </file>
  18385. </example>
  18386. *
  18387. * The predicate and reverse parameters can be controlled dynamically through scope properties,
  18388. * as shown in the next example.
  18389. * @example
  18390. <example module="orderByExample">
  18391. <file name="index.html">
  18392. <div ng-controller="ExampleController">
  18393. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  18394. <hr/>
  18395. <button ng-click="predicate=''">Set to unsorted</button>
  18396. <table class="friend">
  18397. <tr>
  18398. <th>
  18399. <button ng-click="order('name')">Name</button>
  18400. <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
  18401. </th>
  18402. <th>
  18403. <button ng-click="order('phone')">Phone Number</button>
  18404. <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
  18405. </th>
  18406. <th>
  18407. <button ng-click="order('age')">Age</button>
  18408. <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
  18409. </th>
  18410. </tr>
  18411. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  18412. <td>{{friend.name}}</td>
  18413. <td>{{friend.phone}}</td>
  18414. <td>{{friend.age}}</td>
  18415. </tr>
  18416. </table>
  18417. </div>
  18418. </file>
  18419. <file name="script.js">
  18420. angular.module('orderByExample', [])
  18421. .controller('ExampleController', ['$scope', function($scope) {
  18422. $scope.friends =
  18423. [{name:'John', phone:'555-1212', age:10},
  18424. {name:'Mary', phone:'555-9876', age:19},
  18425. {name:'Mike', phone:'555-4321', age:21},
  18426. {name:'Adam', phone:'555-5678', age:35},
  18427. {name:'Julie', phone:'555-8765', age:29}];
  18428. $scope.predicate = 'age';
  18429. $scope.reverse = true;
  18430. $scope.order = function(predicate) {
  18431. $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
  18432. $scope.predicate = predicate;
  18433. };
  18434. }]);
  18435. </file>
  18436. <file name="style.css">
  18437. .sortorder:after {
  18438. content: '\25b2';
  18439. }
  18440. .sortorder.reverse:after {
  18441. content: '\25bc';
  18442. }
  18443. </file>
  18444. </example>
  18445. *
  18446. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  18447. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  18448. * desired parameters.
  18449. *
  18450. * Example:
  18451. *
  18452. * @example
  18453. <example module="orderByExample">
  18454. <file name="index.html">
  18455. <div ng-controller="ExampleController">
  18456. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  18457. <table class="friend">
  18458. <tr>
  18459. <th>
  18460. <button ng-click="order('name')">Name</button>
  18461. <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
  18462. </th>
  18463. <th>
  18464. <button ng-click="order('phone')">Phone Number</button>
  18465. <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
  18466. </th>
  18467. <th>
  18468. <button ng-click="order('age')">Age</button>
  18469. <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
  18470. </th>
  18471. </tr>
  18472. <tr ng-repeat="friend in friends">
  18473. <td>{{friend.name}}</td>
  18474. <td>{{friend.phone}}</td>
  18475. <td>{{friend.age}}</td>
  18476. </tr>
  18477. </table>
  18478. </div>
  18479. </file>
  18480. <file name="script.js">
  18481. angular.module('orderByExample', [])
  18482. .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
  18483. var orderBy = $filter('orderBy');
  18484. $scope.friends = [
  18485. { name: 'John', phone: '555-1212', age: 10 },
  18486. { name: 'Mary', phone: '555-9876', age: 19 },
  18487. { name: 'Mike', phone: '555-4321', age: 21 },
  18488. { name: 'Adam', phone: '555-5678', age: 35 },
  18489. { name: 'Julie', phone: '555-8765', age: 29 }
  18490. ];
  18491. $scope.order = function(predicate) {
  18492. $scope.predicate = predicate;
  18493. $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
  18494. $scope.friends = orderBy($scope.friends, predicate, $scope.reverse);
  18495. };
  18496. $scope.order('age', true);
  18497. }]);
  18498. </file>
  18499. <file name="style.css">
  18500. .sortorder:after {
  18501. content: '\25b2';
  18502. }
  18503. .sortorder.reverse:after {
  18504. content: '\25bc';
  18505. }
  18506. </file>
  18507. </example>
  18508. */
  18509. orderByFilter.$inject = ['$parse'];
  18510. function orderByFilter($parse) {
  18511. return function(array, sortPredicate, reverseOrder) {
  18512. if (array == null) return array;
  18513. if (!isArrayLike(array)) {
  18514. throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
  18515. }
  18516. if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
  18517. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  18518. var predicates = processPredicates(sortPredicate, reverseOrder);
  18519. // Add a predicate at the end that evaluates to the element index. This makes the
  18520. // sort stable as it works as a tie-breaker when all the input predicates cannot
  18521. // distinguish between two elements.
  18522. predicates.push({ get: function() { return {}; }, descending: reverseOrder ? -1 : 1});
  18523. // The next three lines are a version of a Swartzian Transform idiom from Perl
  18524. // (sometimes called the Decorate-Sort-Undecorate idiom)
  18525. // See https://en.wikipedia.org/wiki/Schwartzian_transform
  18526. var compareValues = Array.prototype.map.call(array, getComparisonObject);
  18527. compareValues.sort(doComparison);
  18528. array = compareValues.map(function(item) { return item.value; });
  18529. return array;
  18530. function getComparisonObject(value, index) {
  18531. return {
  18532. value: value,
  18533. predicateValues: predicates.map(function(predicate) {
  18534. return getPredicateValue(predicate.get(value), index);
  18535. })
  18536. };
  18537. }
  18538. function doComparison(v1, v2) {
  18539. var result = 0;
  18540. for (var index=0, length = predicates.length; index < length; ++index) {
  18541. result = compare(v1.predicateValues[index], v2.predicateValues[index]) * predicates[index].descending;
  18542. if (result) break;
  18543. }
  18544. return result;
  18545. }
  18546. };
  18547. function processPredicates(sortPredicate, reverseOrder) {
  18548. reverseOrder = reverseOrder ? -1 : 1;
  18549. return sortPredicate.map(function(predicate) {
  18550. var descending = 1, get = identity;
  18551. if (isFunction(predicate)) {
  18552. get = predicate;
  18553. } else if (isString(predicate)) {
  18554. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  18555. descending = predicate.charAt(0) == '-' ? -1 : 1;
  18556. predicate = predicate.substring(1);
  18557. }
  18558. if (predicate !== '') {
  18559. get = $parse(predicate);
  18560. if (get.constant) {
  18561. var key = get();
  18562. get = function(value) { return value[key]; };
  18563. }
  18564. }
  18565. }
  18566. return { get: get, descending: descending * reverseOrder };
  18567. });
  18568. }
  18569. function isPrimitive(value) {
  18570. switch (typeof value) {
  18571. case 'number': /* falls through */
  18572. case 'boolean': /* falls through */
  18573. case 'string':
  18574. return true;
  18575. default:
  18576. return false;
  18577. }
  18578. }
  18579. function objectValue(value, index) {
  18580. // If `valueOf` is a valid function use that
  18581. if (typeof value.valueOf === 'function') {
  18582. value = value.valueOf();
  18583. if (isPrimitive(value)) return value;
  18584. }
  18585. // If `toString` is a valid function and not the one from `Object.prototype` use that
  18586. if (hasCustomToString(value)) {
  18587. value = value.toString();
  18588. if (isPrimitive(value)) return value;
  18589. }
  18590. // We have a basic object so we use the position of the object in the collection
  18591. return index;
  18592. }
  18593. function getPredicateValue(value, index) {
  18594. var type = typeof value;
  18595. if (value === null) {
  18596. type = 'string';
  18597. value = 'null';
  18598. } else if (type === 'string') {
  18599. value = value.toLowerCase();
  18600. } else if (type === 'object') {
  18601. value = objectValue(value, index);
  18602. }
  18603. return { value: value, type: type };
  18604. }
  18605. function compare(v1, v2) {
  18606. var result = 0;
  18607. if (v1.type === v2.type) {
  18608. if (v1.value !== v2.value) {
  18609. result = v1.value < v2.value ? -1 : 1;
  18610. }
  18611. } else {
  18612. result = v1.type < v2.type ? -1 : 1;
  18613. }
  18614. return result;
  18615. }
  18616. }
  18617. function ngDirective(directive) {
  18618. if (isFunction(directive)) {
  18619. directive = {
  18620. link: directive
  18621. };
  18622. }
  18623. directive.restrict = directive.restrict || 'AC';
  18624. return valueFn(directive);
  18625. }
  18626. /**
  18627. * @ngdoc directive
  18628. * @name a
  18629. * @restrict E
  18630. *
  18631. * @description
  18632. * Modifies the default behavior of the html A tag so that the default action is prevented when
  18633. * the href attribute is empty.
  18634. *
  18635. * This change permits the easy creation of action links with the `ngClick` directive
  18636. * without changing the location or causing page reloads, e.g.:
  18637. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  18638. */
  18639. var htmlAnchorDirective = valueFn({
  18640. restrict: 'E',
  18641. compile: function(element, attr) {
  18642. if (!attr.href && !attr.xlinkHref) {
  18643. return function(scope, element) {
  18644. // If the linked element is not an anchor tag anymore, do nothing
  18645. if (element[0].nodeName.toLowerCase() !== 'a') return;
  18646. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  18647. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  18648. 'xlink:href' : 'href';
  18649. element.on('click', function(event) {
  18650. // if we have no href url, then don't navigate anywhere.
  18651. if (!element.attr(href)) {
  18652. event.preventDefault();
  18653. }
  18654. });
  18655. };
  18656. }
  18657. }
  18658. });
  18659. /**
  18660. * @ngdoc directive
  18661. * @name ngHref
  18662. * @restrict A
  18663. * @priority 99
  18664. *
  18665. * @description
  18666. * Using Angular markup like `{{hash}}` in an href attribute will
  18667. * make the link go to the wrong URL if the user clicks it before
  18668. * Angular has a chance to replace the `{{hash}}` markup with its
  18669. * value. Until Angular replaces the markup the link will be broken
  18670. * and will most likely return a 404 error. The `ngHref` directive
  18671. * solves this problem.
  18672. *
  18673. * The wrong way to write it:
  18674. * ```html
  18675. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  18676. * ```
  18677. *
  18678. * The correct way to write it:
  18679. * ```html
  18680. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  18681. * ```
  18682. *
  18683. * @element A
  18684. * @param {template} ngHref any string which can contain `{{}}` markup.
  18685. *
  18686. * @example
  18687. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  18688. * in links and their different behaviors:
  18689. <example>
  18690. <file name="index.html">
  18691. <input ng-model="value" /><br />
  18692. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  18693. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  18694. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  18695. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  18696. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  18697. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  18698. </file>
  18699. <file name="protractor.js" type="protractor">
  18700. it('should execute ng-click but not reload when href without value', function() {
  18701. element(by.id('link-1')).click();
  18702. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  18703. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  18704. });
  18705. it('should execute ng-click but not reload when href empty string', function() {
  18706. element(by.id('link-2')).click();
  18707. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  18708. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  18709. });
  18710. it('should execute ng-click and change url when ng-href specified', function() {
  18711. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  18712. element(by.id('link-3')).click();
  18713. // At this point, we navigate away from an Angular page, so we need
  18714. // to use browser.driver to get the base webdriver.
  18715. browser.wait(function() {
  18716. return browser.driver.getCurrentUrl().then(function(url) {
  18717. return url.match(/\/123$/);
  18718. });
  18719. }, 5000, 'page should navigate to /123');
  18720. });
  18721. it('should execute ng-click but not reload when href empty string and name specified', function() {
  18722. element(by.id('link-4')).click();
  18723. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  18724. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  18725. });
  18726. it('should execute ng-click but not reload when no href but name specified', function() {
  18727. element(by.id('link-5')).click();
  18728. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  18729. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  18730. });
  18731. it('should only change url when only ng-href', function() {
  18732. element(by.model('value')).clear();
  18733. element(by.model('value')).sendKeys('6');
  18734. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  18735. element(by.id('link-6')).click();
  18736. // At this point, we navigate away from an Angular page, so we need
  18737. // to use browser.driver to get the base webdriver.
  18738. browser.wait(function() {
  18739. return browser.driver.getCurrentUrl().then(function(url) {
  18740. return url.match(/\/6$/);
  18741. });
  18742. }, 5000, 'page should navigate to /6');
  18743. });
  18744. </file>
  18745. </example>
  18746. */
  18747. /**
  18748. * @ngdoc directive
  18749. * @name ngSrc
  18750. * @restrict A
  18751. * @priority 99
  18752. *
  18753. * @description
  18754. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  18755. * work right: The browser will fetch from the URL with the literal
  18756. * text `{{hash}}` until Angular replaces the expression inside
  18757. * `{{hash}}`. The `ngSrc` directive solves this problem.
  18758. *
  18759. * The buggy way to write it:
  18760. * ```html
  18761. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  18762. * ```
  18763. *
  18764. * The correct way to write it:
  18765. * ```html
  18766. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  18767. * ```
  18768. *
  18769. * @element IMG
  18770. * @param {template} ngSrc any string which can contain `{{}}` markup.
  18771. */
  18772. /**
  18773. * @ngdoc directive
  18774. * @name ngSrcset
  18775. * @restrict A
  18776. * @priority 99
  18777. *
  18778. * @description
  18779. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  18780. * work right: The browser will fetch from the URL with the literal
  18781. * text `{{hash}}` until Angular replaces the expression inside
  18782. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  18783. *
  18784. * The buggy way to write it:
  18785. * ```html
  18786. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  18787. * ```
  18788. *
  18789. * The correct way to write it:
  18790. * ```html
  18791. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  18792. * ```
  18793. *
  18794. * @element IMG
  18795. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  18796. */
  18797. /**
  18798. * @ngdoc directive
  18799. * @name ngDisabled
  18800. * @restrict A
  18801. * @priority 100
  18802. *
  18803. * @description
  18804. *
  18805. * This directive sets the `disabled` attribute on the element if the
  18806. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  18807. *
  18808. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  18809. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  18810. *
  18811. * @example
  18812. <example>
  18813. <file name="index.html">
  18814. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  18815. <button ng-model="button" ng-disabled="checked">Button</button>
  18816. </file>
  18817. <file name="protractor.js" type="protractor">
  18818. it('should toggle button', function() {
  18819. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  18820. element(by.model('checked')).click();
  18821. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  18822. });
  18823. </file>
  18824. </example>
  18825. *
  18826. * @element INPUT
  18827. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  18828. * then the `disabled` attribute will be set on the element
  18829. */
  18830. /**
  18831. * @ngdoc directive
  18832. * @name ngChecked
  18833. * @restrict A
  18834. * @priority 100
  18835. *
  18836. * @description
  18837. * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
  18838. *
  18839. * Note that this directive should not be used together with {@link ngModel `ngModel`},
  18840. * as this can lead to unexpected behavior.
  18841. *
  18842. * A special directive is necessary because we cannot use interpolation inside the `checked`
  18843. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  18844. *
  18845. * @example
  18846. <example>
  18847. <file name="index.html">
  18848. <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
  18849. <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
  18850. </file>
  18851. <file name="protractor.js" type="protractor">
  18852. it('should check both checkBoxes', function() {
  18853. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  18854. element(by.model('master')).click();
  18855. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  18856. });
  18857. </file>
  18858. </example>
  18859. *
  18860. * @element INPUT
  18861. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  18862. * then the `checked` attribute will be set on the element
  18863. */
  18864. /**
  18865. * @ngdoc directive
  18866. * @name ngReadonly
  18867. * @restrict A
  18868. * @priority 100
  18869. *
  18870. * @description
  18871. *
  18872. * Sets the `readOnly` attribute on the element, if the expression inside `ngReadonly` is truthy.
  18873. *
  18874. * A special directive is necessary because we cannot use interpolation inside the `readOnly`
  18875. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  18876. *
  18877. * @example
  18878. <example>
  18879. <file name="index.html">
  18880. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  18881. <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
  18882. </file>
  18883. <file name="protractor.js" type="protractor">
  18884. it('should toggle readonly attr', function() {
  18885. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  18886. element(by.model('checked')).click();
  18887. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  18888. });
  18889. </file>
  18890. </example>
  18891. *
  18892. * @element INPUT
  18893. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  18894. * then special attribute "readonly" will be set on the element
  18895. */
  18896. /**
  18897. * @ngdoc directive
  18898. * @name ngSelected
  18899. * @restrict A
  18900. * @priority 100
  18901. *
  18902. * @description
  18903. *
  18904. * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy.
  18905. *
  18906. * A special directive is necessary because we cannot use interpolation inside the `selected`
  18907. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  18908. *
  18909. * @example
  18910. <example>
  18911. <file name="index.html">
  18912. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  18913. <select aria-label="ngSelected demo">
  18914. <option>Hello!</option>
  18915. <option id="greet" ng-selected="selected">Greetings!</option>
  18916. </select>
  18917. </file>
  18918. <file name="protractor.js" type="protractor">
  18919. it('should select Greetings!', function() {
  18920. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  18921. element(by.model('selected')).click();
  18922. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  18923. });
  18924. </file>
  18925. </example>
  18926. *
  18927. * @element OPTION
  18928. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  18929. * then special attribute "selected" will be set on the element
  18930. */
  18931. /**
  18932. * @ngdoc directive
  18933. * @name ngOpen
  18934. * @restrict A
  18935. * @priority 100
  18936. *
  18937. * @description
  18938. *
  18939. * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy.
  18940. *
  18941. * A special directive is necessary because we cannot use interpolation inside the `open`
  18942. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  18943. *
  18944. * @example
  18945. <example>
  18946. <file name="index.html">
  18947. <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
  18948. <details id="details" ng-open="open">
  18949. <summary>Show/Hide me</summary>
  18950. </details>
  18951. </file>
  18952. <file name="protractor.js" type="protractor">
  18953. it('should toggle open', function() {
  18954. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  18955. element(by.model('open')).click();
  18956. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  18957. });
  18958. </file>
  18959. </example>
  18960. *
  18961. * @element DETAILS
  18962. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  18963. * then special attribute "open" will be set on the element
  18964. */
  18965. var ngAttributeAliasDirectives = {};
  18966. // boolean attrs are evaluated
  18967. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  18968. // binding to multiple is not supported
  18969. if (propName == "multiple") return;
  18970. function defaultLinkFn(scope, element, attr) {
  18971. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  18972. attr.$set(attrName, !!value);
  18973. });
  18974. }
  18975. var normalized = directiveNormalize('ng-' + attrName);
  18976. var linkFn = defaultLinkFn;
  18977. if (propName === 'checked') {
  18978. linkFn = function(scope, element, attr) {
  18979. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  18980. if (attr.ngModel !== attr[normalized]) {
  18981. defaultLinkFn(scope, element, attr);
  18982. }
  18983. };
  18984. }
  18985. ngAttributeAliasDirectives[normalized] = function() {
  18986. return {
  18987. restrict: 'A',
  18988. priority: 100,
  18989. link: linkFn
  18990. };
  18991. };
  18992. });
  18993. // aliased input attrs are evaluated
  18994. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  18995. ngAttributeAliasDirectives[ngAttr] = function() {
  18996. return {
  18997. priority: 100,
  18998. link: function(scope, element, attr) {
  18999. //special case ngPattern when a literal regular expression value
  19000. //is used as the expression (this way we don't have to watch anything).
  19001. if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
  19002. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  19003. if (match) {
  19004. attr.$set("ngPattern", new RegExp(match[1], match[2]));
  19005. return;
  19006. }
  19007. }
  19008. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  19009. attr.$set(ngAttr, value);
  19010. });
  19011. }
  19012. };
  19013. };
  19014. });
  19015. // ng-src, ng-srcset, ng-href are interpolated
  19016. forEach(['src', 'srcset', 'href'], function(attrName) {
  19017. var normalized = directiveNormalize('ng-' + attrName);
  19018. ngAttributeAliasDirectives[normalized] = function() {
  19019. return {
  19020. priority: 99, // it needs to run after the attributes are interpolated
  19021. link: function(scope, element, attr) {
  19022. var propName = attrName,
  19023. name = attrName;
  19024. if (attrName === 'href' &&
  19025. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  19026. name = 'xlinkHref';
  19027. attr.$attr[name] = 'xlink:href';
  19028. propName = null;
  19029. }
  19030. attr.$observe(normalized, function(value) {
  19031. if (!value) {
  19032. if (attrName === 'href') {
  19033. attr.$set(name, null);
  19034. }
  19035. return;
  19036. }
  19037. attr.$set(name, value);
  19038. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  19039. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  19040. // to set the property as well to achieve the desired effect.
  19041. // we use attr[attrName] value since $set can sanitize the url.
  19042. if (msie && propName) element.prop(propName, attr[name]);
  19043. });
  19044. }
  19045. };
  19046. };
  19047. });
  19048. /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
  19049. */
  19050. var nullFormCtrl = {
  19051. $addControl: noop,
  19052. $$renameControl: nullFormRenameControl,
  19053. $removeControl: noop,
  19054. $setValidity: noop,
  19055. $setDirty: noop,
  19056. $setPristine: noop,
  19057. $setSubmitted: noop
  19058. },
  19059. SUBMITTED_CLASS = 'ng-submitted';
  19060. function nullFormRenameControl(control, name) {
  19061. control.$name = name;
  19062. }
  19063. /**
  19064. * @ngdoc type
  19065. * @name form.FormController
  19066. *
  19067. * @property {boolean} $pristine True if user has not interacted with the form yet.
  19068. * @property {boolean} $dirty True if user has already interacted with the form.
  19069. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  19070. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  19071. * @property {boolean} $pending True if at least one containing control or form is pending.
  19072. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  19073. *
  19074. * @property {Object} $error Is an object hash, containing references to controls or
  19075. * forms with failing validators, where:
  19076. *
  19077. * - keys are validation tokens (error names),
  19078. * - values are arrays of controls or forms that have a failing validator for given error name.
  19079. *
  19080. * Built-in validation tokens:
  19081. *
  19082. * - `email`
  19083. * - `max`
  19084. * - `maxlength`
  19085. * - `min`
  19086. * - `minlength`
  19087. * - `number`
  19088. * - `pattern`
  19089. * - `required`
  19090. * - `url`
  19091. * - `date`
  19092. * - `datetimelocal`
  19093. * - `time`
  19094. * - `week`
  19095. * - `month`
  19096. *
  19097. * @description
  19098. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  19099. * such as being valid/invalid or dirty/pristine.
  19100. *
  19101. * Each {@link ng.directive:form form} directive creates an instance
  19102. * of `FormController`.
  19103. *
  19104. */
  19105. //asks for $scope to fool the BC controller module
  19106. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  19107. function FormController(element, attrs, $scope, $animate, $interpolate) {
  19108. var form = this,
  19109. controls = [];
  19110. // init state
  19111. form.$error = {};
  19112. form.$$success = {};
  19113. form.$pending = undefined;
  19114. form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
  19115. form.$dirty = false;
  19116. form.$pristine = true;
  19117. form.$valid = true;
  19118. form.$invalid = false;
  19119. form.$submitted = false;
  19120. form.$$parentForm = nullFormCtrl;
  19121. /**
  19122. * @ngdoc method
  19123. * @name form.FormController#$rollbackViewValue
  19124. *
  19125. * @description
  19126. * Rollback all form controls pending updates to the `$modelValue`.
  19127. *
  19128. * Updates may be pending by a debounced event or because the input is waiting for a some future
  19129. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  19130. * a form that uses `ng-model-options` to pend updates.
  19131. */
  19132. form.$rollbackViewValue = function() {
  19133. forEach(controls, function(control) {
  19134. control.$rollbackViewValue();
  19135. });
  19136. };
  19137. /**
  19138. * @ngdoc method
  19139. * @name form.FormController#$commitViewValue
  19140. *
  19141. * @description
  19142. * Commit all form controls pending updates to the `$modelValue`.
  19143. *
  19144. * Updates may be pending by a debounced event or because the input is waiting for a some future
  19145. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  19146. * usually handles calling this in response to input events.
  19147. */
  19148. form.$commitViewValue = function() {
  19149. forEach(controls, function(control) {
  19150. control.$commitViewValue();
  19151. });
  19152. };
  19153. /**
  19154. * @ngdoc method
  19155. * @name form.FormController#$addControl
  19156. * @param {object} control control object, either a {@link form.FormController} or an
  19157. * {@link ngModel.NgModelController}
  19158. *
  19159. * @description
  19160. * Register a control with the form. Input elements using ngModelController do this automatically
  19161. * when they are linked.
  19162. *
  19163. * Note that the current state of the control will not be reflected on the new parent form. This
  19164. * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
  19165. * state.
  19166. *
  19167. * However, if the method is used programmatically, for example by adding dynamically created controls,
  19168. * or controls that have been previously removed without destroying their corresponding DOM element,
  19169. * it's the developers responsibility to make sure the current state propagates to the parent form.
  19170. *
  19171. * For example, if an input control is added that is already `$dirty` and has `$error` properties,
  19172. * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
  19173. */
  19174. form.$addControl = function(control) {
  19175. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  19176. // and not added to the scope. Now we throw an error.
  19177. assertNotHasOwnProperty(control.$name, 'input');
  19178. controls.push(control);
  19179. if (control.$name) {
  19180. form[control.$name] = control;
  19181. }
  19182. control.$$parentForm = form;
  19183. };
  19184. // Private API: rename a form control
  19185. form.$$renameControl = function(control, newName) {
  19186. var oldName = control.$name;
  19187. if (form[oldName] === control) {
  19188. delete form[oldName];
  19189. }
  19190. form[newName] = control;
  19191. control.$name = newName;
  19192. };
  19193. /**
  19194. * @ngdoc method
  19195. * @name form.FormController#$removeControl
  19196. * @param {object} control control object, either a {@link form.FormController} or an
  19197. * {@link ngModel.NgModelController}
  19198. *
  19199. * @description
  19200. * Deregister a control from the form.
  19201. *
  19202. * Input elements using ngModelController do this automatically when they are destroyed.
  19203. *
  19204. * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
  19205. * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
  19206. * different from case to case. For example, removing the only `$dirty` control from a form may or
  19207. * may not mean that the form is still `$dirty`.
  19208. */
  19209. form.$removeControl = function(control) {
  19210. if (control.$name && form[control.$name] === control) {
  19211. delete form[control.$name];
  19212. }
  19213. forEach(form.$pending, function(value, name) {
  19214. form.$setValidity(name, null, control);
  19215. });
  19216. forEach(form.$error, function(value, name) {
  19217. form.$setValidity(name, null, control);
  19218. });
  19219. forEach(form.$$success, function(value, name) {
  19220. form.$setValidity(name, null, control);
  19221. });
  19222. arrayRemove(controls, control);
  19223. control.$$parentForm = nullFormCtrl;
  19224. };
  19225. /**
  19226. * @ngdoc method
  19227. * @name form.FormController#$setValidity
  19228. *
  19229. * @description
  19230. * Sets the validity of a form control.
  19231. *
  19232. * This method will also propagate to parent forms.
  19233. */
  19234. addSetValidityMethod({
  19235. ctrl: this,
  19236. $element: element,
  19237. set: function(object, property, controller) {
  19238. var list = object[property];
  19239. if (!list) {
  19240. object[property] = [controller];
  19241. } else {
  19242. var index = list.indexOf(controller);
  19243. if (index === -1) {
  19244. list.push(controller);
  19245. }
  19246. }
  19247. },
  19248. unset: function(object, property, controller) {
  19249. var list = object[property];
  19250. if (!list) {
  19251. return;
  19252. }
  19253. arrayRemove(list, controller);
  19254. if (list.length === 0) {
  19255. delete object[property];
  19256. }
  19257. },
  19258. $animate: $animate
  19259. });
  19260. /**
  19261. * @ngdoc method
  19262. * @name form.FormController#$setDirty
  19263. *
  19264. * @description
  19265. * Sets the form to a dirty state.
  19266. *
  19267. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  19268. * state (ng-dirty class). This method will also propagate to parent forms.
  19269. */
  19270. form.$setDirty = function() {
  19271. $animate.removeClass(element, PRISTINE_CLASS);
  19272. $animate.addClass(element, DIRTY_CLASS);
  19273. form.$dirty = true;
  19274. form.$pristine = false;
  19275. form.$$parentForm.$setDirty();
  19276. };
  19277. /**
  19278. * @ngdoc method
  19279. * @name form.FormController#$setPristine
  19280. *
  19281. * @description
  19282. * Sets the form to its pristine state.
  19283. *
  19284. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  19285. * state (ng-pristine class). This method will also propagate to all the controls contained
  19286. * in this form.
  19287. *
  19288. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  19289. * saving or resetting it.
  19290. */
  19291. form.$setPristine = function() {
  19292. $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  19293. form.$dirty = false;
  19294. form.$pristine = true;
  19295. form.$submitted = false;
  19296. forEach(controls, function(control) {
  19297. control.$setPristine();
  19298. });
  19299. };
  19300. /**
  19301. * @ngdoc method
  19302. * @name form.FormController#$setUntouched
  19303. *
  19304. * @description
  19305. * Sets the form to its untouched state.
  19306. *
  19307. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  19308. * untouched state (ng-untouched class).
  19309. *
  19310. * Setting a form controls back to their untouched state is often useful when setting the form
  19311. * back to its pristine state.
  19312. */
  19313. form.$setUntouched = function() {
  19314. forEach(controls, function(control) {
  19315. control.$setUntouched();
  19316. });
  19317. };
  19318. /**
  19319. * @ngdoc method
  19320. * @name form.FormController#$setSubmitted
  19321. *
  19322. * @description
  19323. * Sets the form to its submitted state.
  19324. */
  19325. form.$setSubmitted = function() {
  19326. $animate.addClass(element, SUBMITTED_CLASS);
  19327. form.$submitted = true;
  19328. form.$$parentForm.$setSubmitted();
  19329. };
  19330. }
  19331. /**
  19332. * @ngdoc directive
  19333. * @name ngForm
  19334. * @restrict EAC
  19335. *
  19336. * @description
  19337. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  19338. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  19339. * sub-group of controls needs to be determined.
  19340. *
  19341. * Note: the purpose of `ngForm` is to group controls,
  19342. * but not to be a replacement for the `<form>` tag with all of its capabilities
  19343. * (e.g. posting to the server, ...).
  19344. *
  19345. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  19346. * related scope, under this name.
  19347. *
  19348. */
  19349. /**
  19350. * @ngdoc directive
  19351. * @name form
  19352. * @restrict E
  19353. *
  19354. * @description
  19355. * Directive that instantiates
  19356. * {@link form.FormController FormController}.
  19357. *
  19358. * If the `name` attribute is specified, the form controller is published onto the current scope under
  19359. * this name.
  19360. *
  19361. * # Alias: {@link ng.directive:ngForm `ngForm`}
  19362. *
  19363. * In Angular, forms can be nested. This means that the outer form is valid when all of the child
  19364. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  19365. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to
  19366. * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group
  19367. * of controls needs to be determined.
  19368. *
  19369. * # CSS classes
  19370. * - `ng-valid` is set if the form is valid.
  19371. * - `ng-invalid` is set if the form is invalid.
  19372. * - `ng-pending` is set if the form is pending.
  19373. * - `ng-pristine` is set if the form is pristine.
  19374. * - `ng-dirty` is set if the form is dirty.
  19375. * - `ng-submitted` is set if the form was submitted.
  19376. *
  19377. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  19378. *
  19379. *
  19380. * # Submitting a form and preventing the default action
  19381. *
  19382. * Since the role of forms in client-side Angular applications is different than in classical
  19383. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  19384. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  19385. * to handle the form submission in an application-specific way.
  19386. *
  19387. * For this reason, Angular prevents the default action (form submission to the server) unless the
  19388. * `<form>` element has an `action` attribute specified.
  19389. *
  19390. * You can use one of the following two ways to specify what javascript method should be called when
  19391. * a form is submitted:
  19392. *
  19393. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  19394. * - {@link ng.directive:ngClick ngClick} directive on the first
  19395. * button or input field of type submit (input[type=submit])
  19396. *
  19397. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  19398. * or {@link ng.directive:ngClick ngClick} directives.
  19399. * This is because of the following form submission rules in the HTML specification:
  19400. *
  19401. * - If a form has only one input field then hitting enter in this field triggers form submit
  19402. * (`ngSubmit`)
  19403. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  19404. * doesn't trigger submit
  19405. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  19406. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  19407. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  19408. *
  19409. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  19410. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  19411. * to have access to the updated model.
  19412. *
  19413. * ## Animation Hooks
  19414. *
  19415. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  19416. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  19417. * other validations that are performed within the form. Animations in ngForm are similar to how
  19418. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  19419. * as JS animations.
  19420. *
  19421. * The following example shows a simple way to utilize CSS transitions to style a form element
  19422. * that has been rendered as invalid after it has been validated:
  19423. *
  19424. * <pre>
  19425. * //be sure to include ngAnimate as a module to hook into more
  19426. * //advanced animations
  19427. * .my-form {
  19428. * transition:0.5s linear all;
  19429. * background: white;
  19430. * }
  19431. * .my-form.ng-invalid {
  19432. * background: red;
  19433. * color:white;
  19434. * }
  19435. * </pre>
  19436. *
  19437. * @example
  19438. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  19439. <file name="index.html">
  19440. <script>
  19441. angular.module('formExample', [])
  19442. .controller('FormController', ['$scope', function($scope) {
  19443. $scope.userType = 'guest';
  19444. }]);
  19445. </script>
  19446. <style>
  19447. .my-form {
  19448. transition:all linear 0.5s;
  19449. background: transparent;
  19450. }
  19451. .my-form.ng-invalid {
  19452. background: red;
  19453. }
  19454. </style>
  19455. <form name="myForm" ng-controller="FormController" class="my-form">
  19456. userType: <input name="input" ng-model="userType" required>
  19457. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  19458. <code>userType = {{userType}}</code><br>
  19459. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  19460. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  19461. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  19462. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  19463. </form>
  19464. </file>
  19465. <file name="protractor.js" type="protractor">
  19466. it('should initialize to model', function() {
  19467. var userType = element(by.binding('userType'));
  19468. var valid = element(by.binding('myForm.input.$valid'));
  19469. expect(userType.getText()).toContain('guest');
  19470. expect(valid.getText()).toContain('true');
  19471. });
  19472. it('should be invalid if empty', function() {
  19473. var userType = element(by.binding('userType'));
  19474. var valid = element(by.binding('myForm.input.$valid'));
  19475. var userInput = element(by.model('userType'));
  19476. userInput.clear();
  19477. userInput.sendKeys('');
  19478. expect(userType.getText()).toEqual('userType =');
  19479. expect(valid.getText()).toContain('false');
  19480. });
  19481. </file>
  19482. </example>
  19483. *
  19484. * @param {string=} name Name of the form. If specified, the form controller will be published into
  19485. * related scope, under this name.
  19486. */
  19487. var formDirectiveFactory = function(isNgForm) {
  19488. return ['$timeout', '$parse', function($timeout, $parse) {
  19489. var formDirective = {
  19490. name: 'form',
  19491. restrict: isNgForm ? 'EAC' : 'E',
  19492. require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
  19493. controller: FormController,
  19494. compile: function ngFormCompile(formElement, attr) {
  19495. // Setup initial state of the control
  19496. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  19497. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  19498. return {
  19499. pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
  19500. var controller = ctrls[0];
  19501. // if `action` attr is not present on the form, prevent the default action (submission)
  19502. if (!('action' in attr)) {
  19503. // we can't use jq events because if a form is destroyed during submission the default
  19504. // action is not prevented. see #1238
  19505. //
  19506. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  19507. // page reload if the form was destroyed by submission of the form via a click handler
  19508. // on a button in the form. Looks like an IE9 specific bug.
  19509. var handleFormSubmission = function(event) {
  19510. scope.$apply(function() {
  19511. controller.$commitViewValue();
  19512. controller.$setSubmitted();
  19513. });
  19514. event.preventDefault();
  19515. };
  19516. addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  19517. // unregister the preventDefault listener so that we don't not leak memory but in a
  19518. // way that will achieve the prevention of the default action.
  19519. formElement.on('$destroy', function() {
  19520. $timeout(function() {
  19521. removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  19522. }, 0, false);
  19523. });
  19524. }
  19525. var parentFormCtrl = ctrls[1] || controller.$$parentForm;
  19526. parentFormCtrl.$addControl(controller);
  19527. var setter = nameAttr ? getSetter(controller.$name) : noop;
  19528. if (nameAttr) {
  19529. setter(scope, controller);
  19530. attr.$observe(nameAttr, function(newValue) {
  19531. if (controller.$name === newValue) return;
  19532. setter(scope, undefined);
  19533. controller.$$parentForm.$$renameControl(controller, newValue);
  19534. setter = getSetter(controller.$name);
  19535. setter(scope, controller);
  19536. });
  19537. }
  19538. formElement.on('$destroy', function() {
  19539. controller.$$parentForm.$removeControl(controller);
  19540. setter(scope, undefined);
  19541. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  19542. });
  19543. }
  19544. };
  19545. }
  19546. };
  19547. return formDirective;
  19548. function getSetter(expression) {
  19549. if (expression === '') {
  19550. //create an assignable expression, so forms with an empty name can be renamed later
  19551. return $parse('this[""]').assign;
  19552. }
  19553. return $parse(expression).assign || noop;
  19554. }
  19555. }];
  19556. };
  19557. var formDirective = formDirectiveFactory();
  19558. var ngFormDirective = formDirectiveFactory(true);
  19559. /* global VALID_CLASS: false,
  19560. INVALID_CLASS: false,
  19561. PRISTINE_CLASS: false,
  19562. DIRTY_CLASS: false,
  19563. UNTOUCHED_CLASS: false,
  19564. TOUCHED_CLASS: false,
  19565. ngModelMinErr: false,
  19566. */
  19567. // Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  19568. 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)/;
  19569. // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
  19570. // Note: We are being more lenient, because browsers are too.
  19571. // 1. Scheme
  19572. // 2. Slashes
  19573. // 3. Username
  19574. // 4. Password
  19575. // 5. Hostname
  19576. // 6. Port
  19577. // 7. Path
  19578. // 8. Query
  19579. // 9. Fragment
  19580. // 1111111111111111 222 333333 44444 555555555555555555555555 666 77777777 8888888 999
  19581. var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+\])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
  19582. 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;
  19583. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
  19584. var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
  19585. var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  19586. var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
  19587. var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
  19588. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  19589. var inputType = {
  19590. /**
  19591. * @ngdoc input
  19592. * @name input[text]
  19593. *
  19594. * @description
  19595. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  19596. *
  19597. *
  19598. * @param {string} ngModel Assignable angular expression to data-bind to.
  19599. * @param {string=} name Property name of the form under which the control is published.
  19600. * @param {string=} required Adds `required` validation error key if the value is not entered.
  19601. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19602. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19603. * `required` when you want to data-bind to the `required` attribute.
  19604. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19605. * minlength.
  19606. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19607. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19608. * any length.
  19609. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19610. * that contains the regular expression body that will be converted to a regular expression
  19611. * as in the ngPattern directive.
  19612. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  19613. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  19614. * If the expression evaluates to a RegExp object, then this is used directly.
  19615. * If the expression evaluates to a string, then it will be converted to a RegExp
  19616. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19617. * `new RegExp('^abc$')`.<br />
  19618. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19619. * start at the index of the last search's match, thus not taking the whole input value into
  19620. * account.
  19621. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19622. * interaction with the input element.
  19623. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  19624. * This parameter is ignored for input[type=password] controls, which will never trim the
  19625. * input.
  19626. *
  19627. * @example
  19628. <example name="text-input-directive" module="textInputExample">
  19629. <file name="index.html">
  19630. <script>
  19631. angular.module('textInputExample', [])
  19632. .controller('ExampleController', ['$scope', function($scope) {
  19633. $scope.example = {
  19634. text: 'guest',
  19635. word: /^\s*\w*\s*$/
  19636. };
  19637. }]);
  19638. </script>
  19639. <form name="myForm" ng-controller="ExampleController">
  19640. <label>Single word:
  19641. <input type="text" name="input" ng-model="example.text"
  19642. ng-pattern="example.word" required ng-trim="false">
  19643. </label>
  19644. <div role="alert">
  19645. <span class="error" ng-show="myForm.input.$error.required">
  19646. Required!</span>
  19647. <span class="error" ng-show="myForm.input.$error.pattern">
  19648. Single word only!</span>
  19649. </div>
  19650. <tt>text = {{example.text}}</tt><br/>
  19651. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19652. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19653. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19654. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19655. </form>
  19656. </file>
  19657. <file name="protractor.js" type="protractor">
  19658. var text = element(by.binding('example.text'));
  19659. var valid = element(by.binding('myForm.input.$valid'));
  19660. var input = element(by.model('example.text'));
  19661. it('should initialize to model', function() {
  19662. expect(text.getText()).toContain('guest');
  19663. expect(valid.getText()).toContain('true');
  19664. });
  19665. it('should be invalid if empty', function() {
  19666. input.clear();
  19667. input.sendKeys('');
  19668. expect(text.getText()).toEqual('text =');
  19669. expect(valid.getText()).toContain('false');
  19670. });
  19671. it('should be invalid if multi word', function() {
  19672. input.clear();
  19673. input.sendKeys('hello world');
  19674. expect(valid.getText()).toContain('false');
  19675. });
  19676. </file>
  19677. </example>
  19678. */
  19679. 'text': textInputType,
  19680. /**
  19681. * @ngdoc input
  19682. * @name input[date]
  19683. *
  19684. * @description
  19685. * Input with date validation and transformation. In browsers that do not yet support
  19686. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  19687. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  19688. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  19689. * expected input format via a placeholder or label.
  19690. *
  19691. * The model must always be a Date object, otherwise Angular will throw an error.
  19692. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  19693. *
  19694. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  19695. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  19696. *
  19697. * @param {string} ngModel Assignable angular expression to data-bind to.
  19698. * @param {string=} name Property name of the form under which the control is published.
  19699. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  19700. * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  19701. * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
  19702. * constraint validation.
  19703. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  19704. * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  19705. * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
  19706. * constraint validation.
  19707. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
  19708. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  19709. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
  19710. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  19711. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19712. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19713. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19714. * `required` when you want to data-bind to the `required` attribute.
  19715. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19716. * interaction with the input element.
  19717. *
  19718. * @example
  19719. <example name="date-input-directive" module="dateInputExample">
  19720. <file name="index.html">
  19721. <script>
  19722. angular.module('dateInputExample', [])
  19723. .controller('DateController', ['$scope', function($scope) {
  19724. $scope.example = {
  19725. value: new Date(2013, 9, 22)
  19726. };
  19727. }]);
  19728. </script>
  19729. <form name="myForm" ng-controller="DateController as dateCtrl">
  19730. <label for="exampleInput">Pick a date in 2013:</label>
  19731. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  19732. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  19733. <div role="alert">
  19734. <span class="error" ng-show="myForm.input.$error.required">
  19735. Required!</span>
  19736. <span class="error" ng-show="myForm.input.$error.date">
  19737. Not a valid date!</span>
  19738. </div>
  19739. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  19740. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19741. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19742. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19743. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19744. </form>
  19745. </file>
  19746. <file name="protractor.js" type="protractor">
  19747. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  19748. var valid = element(by.binding('myForm.input.$valid'));
  19749. var input = element(by.model('example.value'));
  19750. // currently protractor/webdriver does not support
  19751. // sending keys to all known HTML5 input controls
  19752. // for various browsers (see https://github.com/angular/protractor/issues/562).
  19753. function setInput(val) {
  19754. // set the value of the element and force validation.
  19755. var scr = "var ipt = document.getElementById('exampleInput'); " +
  19756. "ipt.value = '" + val + "';" +
  19757. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  19758. browser.executeScript(scr);
  19759. }
  19760. it('should initialize to model', function() {
  19761. expect(value.getText()).toContain('2013-10-22');
  19762. expect(valid.getText()).toContain('myForm.input.$valid = true');
  19763. });
  19764. it('should be invalid if empty', function() {
  19765. setInput('');
  19766. expect(value.getText()).toEqual('value =');
  19767. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19768. });
  19769. it('should be invalid if over max', function() {
  19770. setInput('2015-01-01');
  19771. expect(value.getText()).toContain('');
  19772. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19773. });
  19774. </file>
  19775. </example>
  19776. */
  19777. 'date': createDateInputType('date', DATE_REGEXP,
  19778. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  19779. 'yyyy-MM-dd'),
  19780. /**
  19781. * @ngdoc input
  19782. * @name input[datetime-local]
  19783. *
  19784. * @description
  19785. * Input with datetime validation and transformation. In browsers that do not yet support
  19786. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  19787. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  19788. *
  19789. * The model must always be a Date object, otherwise Angular will throw an error.
  19790. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  19791. *
  19792. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  19793. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  19794. *
  19795. * @param {string} ngModel Assignable angular expression to data-bind to.
  19796. * @param {string=} name Property name of the form under which the control is published.
  19797. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  19798. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  19799. * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  19800. * Note that `min` will also add native HTML5 constraint validation.
  19801. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  19802. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  19803. * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  19804. * Note that `max` will also add native HTML5 constraint validation.
  19805. * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
  19806. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  19807. * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
  19808. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  19809. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19810. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19811. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19812. * `required` when you want to data-bind to the `required` attribute.
  19813. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19814. * interaction with the input element.
  19815. *
  19816. * @example
  19817. <example name="datetimelocal-input-directive" module="dateExample">
  19818. <file name="index.html">
  19819. <script>
  19820. angular.module('dateExample', [])
  19821. .controller('DateController', ['$scope', function($scope) {
  19822. $scope.example = {
  19823. value: new Date(2010, 11, 28, 14, 57)
  19824. };
  19825. }]);
  19826. </script>
  19827. <form name="myForm" ng-controller="DateController as dateCtrl">
  19828. <label for="exampleInput">Pick a date between in 2013:</label>
  19829. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  19830. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  19831. <div role="alert">
  19832. <span class="error" ng-show="myForm.input.$error.required">
  19833. Required!</span>
  19834. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  19835. Not a valid date!</span>
  19836. </div>
  19837. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  19838. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19839. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19840. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19841. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19842. </form>
  19843. </file>
  19844. <file name="protractor.js" type="protractor">
  19845. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  19846. var valid = element(by.binding('myForm.input.$valid'));
  19847. var input = element(by.model('example.value'));
  19848. // currently protractor/webdriver does not support
  19849. // sending keys to all known HTML5 input controls
  19850. // for various browsers (https://github.com/angular/protractor/issues/562).
  19851. function setInput(val) {
  19852. // set the value of the element and force validation.
  19853. var scr = "var ipt = document.getElementById('exampleInput'); " +
  19854. "ipt.value = '" + val + "';" +
  19855. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  19856. browser.executeScript(scr);
  19857. }
  19858. it('should initialize to model', function() {
  19859. expect(value.getText()).toContain('2010-12-28T14:57:00');
  19860. expect(valid.getText()).toContain('myForm.input.$valid = true');
  19861. });
  19862. it('should be invalid if empty', function() {
  19863. setInput('');
  19864. expect(value.getText()).toEqual('value =');
  19865. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19866. });
  19867. it('should be invalid if over max', function() {
  19868. setInput('2015-01-01T23:59:00');
  19869. expect(value.getText()).toContain('');
  19870. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19871. });
  19872. </file>
  19873. </example>
  19874. */
  19875. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  19876. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  19877. 'yyyy-MM-ddTHH:mm:ss.sss'),
  19878. /**
  19879. * @ngdoc input
  19880. * @name input[time]
  19881. *
  19882. * @description
  19883. * Input with time validation and transformation. In browsers that do not yet support
  19884. * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  19885. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  19886. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  19887. *
  19888. * The model must always be a Date object, otherwise Angular will throw an error.
  19889. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  19890. *
  19891. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  19892. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  19893. *
  19894. * @param {string} ngModel Assignable angular expression to data-bind to.
  19895. * @param {string=} name Property name of the form under which the control is published.
  19896. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  19897. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  19898. * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
  19899. * native HTML5 constraint validation.
  19900. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  19901. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  19902. * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
  19903. * native HTML5 constraint validation.
  19904. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
  19905. * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  19906. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
  19907. * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  19908. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19909. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19910. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19911. * `required` when you want to data-bind to the `required` attribute.
  19912. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19913. * interaction with the input element.
  19914. *
  19915. * @example
  19916. <example name="time-input-directive" module="timeExample">
  19917. <file name="index.html">
  19918. <script>
  19919. angular.module('timeExample', [])
  19920. .controller('DateController', ['$scope', function($scope) {
  19921. $scope.example = {
  19922. value: new Date(1970, 0, 1, 14, 57, 0)
  19923. };
  19924. }]);
  19925. </script>
  19926. <form name="myForm" ng-controller="DateController as dateCtrl">
  19927. <label for="exampleInput">Pick a between 8am and 5pm:</label>
  19928. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  19929. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  19930. <div role="alert">
  19931. <span class="error" ng-show="myForm.input.$error.required">
  19932. Required!</span>
  19933. <span class="error" ng-show="myForm.input.$error.time">
  19934. Not a valid date!</span>
  19935. </div>
  19936. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  19937. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19938. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19939. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19940. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19941. </form>
  19942. </file>
  19943. <file name="protractor.js" type="protractor">
  19944. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  19945. var valid = element(by.binding('myForm.input.$valid'));
  19946. var input = element(by.model('example.value'));
  19947. // currently protractor/webdriver does not support
  19948. // sending keys to all known HTML5 input controls
  19949. // for various browsers (https://github.com/angular/protractor/issues/562).
  19950. function setInput(val) {
  19951. // set the value of the element and force validation.
  19952. var scr = "var ipt = document.getElementById('exampleInput'); " +
  19953. "ipt.value = '" + val + "';" +
  19954. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  19955. browser.executeScript(scr);
  19956. }
  19957. it('should initialize to model', function() {
  19958. expect(value.getText()).toContain('14:57:00');
  19959. expect(valid.getText()).toContain('myForm.input.$valid = true');
  19960. });
  19961. it('should be invalid if empty', function() {
  19962. setInput('');
  19963. expect(value.getText()).toEqual('value =');
  19964. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19965. });
  19966. it('should be invalid if over max', function() {
  19967. setInput('23:59:00');
  19968. expect(value.getText()).toContain('');
  19969. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19970. });
  19971. </file>
  19972. </example>
  19973. */
  19974. 'time': createDateInputType('time', TIME_REGEXP,
  19975. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  19976. 'HH:mm:ss.sss'),
  19977. /**
  19978. * @ngdoc input
  19979. * @name input[week]
  19980. *
  19981. * @description
  19982. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  19983. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  19984. * week format (yyyy-W##), for example: `2013-W02`.
  19985. *
  19986. * The model must always be a Date object, otherwise Angular will throw an error.
  19987. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  19988. *
  19989. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  19990. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  19991. *
  19992. * @param {string} ngModel Assignable angular expression to data-bind to.
  19993. * @param {string=} name Property name of the form under which the control is published.
  19994. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  19995. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  19996. * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
  19997. * native HTML5 constraint validation.
  19998. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  19999. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  20000. * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
  20001. * native HTML5 constraint validation.
  20002. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  20003. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  20004. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  20005. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  20006. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20007. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20008. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20009. * `required` when you want to data-bind to the `required` attribute.
  20010. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20011. * interaction with the input element.
  20012. *
  20013. * @example
  20014. <example name="week-input-directive" module="weekExample">
  20015. <file name="index.html">
  20016. <script>
  20017. angular.module('weekExample', [])
  20018. .controller('DateController', ['$scope', function($scope) {
  20019. $scope.example = {
  20020. value: new Date(2013, 0, 3)
  20021. };
  20022. }]);
  20023. </script>
  20024. <form name="myForm" ng-controller="DateController as dateCtrl">
  20025. <label>Pick a date between in 2013:
  20026. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  20027. placeholder="YYYY-W##" min="2012-W32"
  20028. max="2013-W52" required />
  20029. </label>
  20030. <div role="alert">
  20031. <span class="error" ng-show="myForm.input.$error.required">
  20032. Required!</span>
  20033. <span class="error" ng-show="myForm.input.$error.week">
  20034. Not a valid date!</span>
  20035. </div>
  20036. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  20037. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  20038. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  20039. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20040. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20041. </form>
  20042. </file>
  20043. <file name="protractor.js" type="protractor">
  20044. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  20045. var valid = element(by.binding('myForm.input.$valid'));
  20046. var input = element(by.model('example.value'));
  20047. // currently protractor/webdriver does not support
  20048. // sending keys to all known HTML5 input controls
  20049. // for various browsers (https://github.com/angular/protractor/issues/562).
  20050. function setInput(val) {
  20051. // set the value of the element and force validation.
  20052. var scr = "var ipt = document.getElementById('exampleInput'); " +
  20053. "ipt.value = '" + val + "';" +
  20054. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  20055. browser.executeScript(scr);
  20056. }
  20057. it('should initialize to model', function() {
  20058. expect(value.getText()).toContain('2013-W01');
  20059. expect(valid.getText()).toContain('myForm.input.$valid = true');
  20060. });
  20061. it('should be invalid if empty', function() {
  20062. setInput('');
  20063. expect(value.getText()).toEqual('value =');
  20064. expect(valid.getText()).toContain('myForm.input.$valid = false');
  20065. });
  20066. it('should be invalid if over max', function() {
  20067. setInput('2015-W01');
  20068. expect(value.getText()).toContain('');
  20069. expect(valid.getText()).toContain('myForm.input.$valid = false');
  20070. });
  20071. </file>
  20072. </example>
  20073. */
  20074. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  20075. /**
  20076. * @ngdoc input
  20077. * @name input[month]
  20078. *
  20079. * @description
  20080. * Input with month validation and transformation. In browsers that do not yet support
  20081. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  20082. * month format (yyyy-MM), for example: `2009-01`.
  20083. *
  20084. * The model must always be a Date object, otherwise Angular will throw an error.
  20085. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  20086. * If the model is not set to the first of the month, the next view to model update will set it
  20087. * to the first of the month.
  20088. *
  20089. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  20090. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  20091. *
  20092. * @param {string} ngModel Assignable angular expression to data-bind to.
  20093. * @param {string=} name Property name of the form under which the control is published.
  20094. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  20095. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  20096. * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
  20097. * native HTML5 constraint validation.
  20098. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  20099. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  20100. * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
  20101. * native HTML5 constraint validation.
  20102. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  20103. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  20104. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  20105. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  20106. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20107. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20108. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20109. * `required` when you want to data-bind to the `required` attribute.
  20110. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20111. * interaction with the input element.
  20112. *
  20113. * @example
  20114. <example name="month-input-directive" module="monthExample">
  20115. <file name="index.html">
  20116. <script>
  20117. angular.module('monthExample', [])
  20118. .controller('DateController', ['$scope', function($scope) {
  20119. $scope.example = {
  20120. value: new Date(2013, 9, 1)
  20121. };
  20122. }]);
  20123. </script>
  20124. <form name="myForm" ng-controller="DateController as dateCtrl">
  20125. <label for="exampleInput">Pick a month in 2013:</label>
  20126. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  20127. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  20128. <div role="alert">
  20129. <span class="error" ng-show="myForm.input.$error.required">
  20130. Required!</span>
  20131. <span class="error" ng-show="myForm.input.$error.month">
  20132. Not a valid month!</span>
  20133. </div>
  20134. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  20135. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  20136. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  20137. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20138. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20139. </form>
  20140. </file>
  20141. <file name="protractor.js" type="protractor">
  20142. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  20143. var valid = element(by.binding('myForm.input.$valid'));
  20144. var input = element(by.model('example.value'));
  20145. // currently protractor/webdriver does not support
  20146. // sending keys to all known HTML5 input controls
  20147. // for various browsers (https://github.com/angular/protractor/issues/562).
  20148. function setInput(val) {
  20149. // set the value of the element and force validation.
  20150. var scr = "var ipt = document.getElementById('exampleInput'); " +
  20151. "ipt.value = '" + val + "';" +
  20152. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  20153. browser.executeScript(scr);
  20154. }
  20155. it('should initialize to model', function() {
  20156. expect(value.getText()).toContain('2013-10');
  20157. expect(valid.getText()).toContain('myForm.input.$valid = true');
  20158. });
  20159. it('should be invalid if empty', function() {
  20160. setInput('');
  20161. expect(value.getText()).toEqual('value =');
  20162. expect(valid.getText()).toContain('myForm.input.$valid = false');
  20163. });
  20164. it('should be invalid if over max', function() {
  20165. setInput('2015-01');
  20166. expect(value.getText()).toContain('');
  20167. expect(valid.getText()).toContain('myForm.input.$valid = false');
  20168. });
  20169. </file>
  20170. </example>
  20171. */
  20172. 'month': createDateInputType('month', MONTH_REGEXP,
  20173. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  20174. 'yyyy-MM'),
  20175. /**
  20176. * @ngdoc input
  20177. * @name input[number]
  20178. *
  20179. * @description
  20180. * Text input with number validation and transformation. Sets the `number` validation
  20181. * error if not a valid number.
  20182. *
  20183. * <div class="alert alert-warning">
  20184. * The model must always be of type `number` otherwise Angular will throw an error.
  20185. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  20186. * error docs for more information and an example of how to convert your model if necessary.
  20187. * </div>
  20188. *
  20189. * ## Issues with HTML5 constraint validation
  20190. *
  20191. * In browsers that follow the
  20192. * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
  20193. * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
  20194. * If a non-number is entered in the input, the browser will report the value as an empty string,
  20195. * which means the view / model values in `ngModel` and subsequently the scope value
  20196. * will also be an empty string.
  20197. *
  20198. *
  20199. * @param {string} ngModel Assignable angular expression to data-bind to.
  20200. * @param {string=} name Property name of the form under which the control is published.
  20201. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  20202. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  20203. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20204. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20205. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20206. * `required` when you want to data-bind to the `required` attribute.
  20207. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  20208. * minlength.
  20209. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  20210. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  20211. * any length.
  20212. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  20213. * that contains the regular expression body that will be converted to a regular expression
  20214. * as in the ngPattern directive.
  20215. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  20216. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  20217. * If the expression evaluates to a RegExp object, then this is used directly.
  20218. * If the expression evaluates to a string, then it will be converted to a RegExp
  20219. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  20220. * `new RegExp('^abc$')`.<br />
  20221. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  20222. * start at the index of the last search's match, thus not taking the whole input value into
  20223. * account.
  20224. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20225. * interaction with the input element.
  20226. *
  20227. * @example
  20228. <example name="number-input-directive" module="numberExample">
  20229. <file name="index.html">
  20230. <script>
  20231. angular.module('numberExample', [])
  20232. .controller('ExampleController', ['$scope', function($scope) {
  20233. $scope.example = {
  20234. value: 12
  20235. };
  20236. }]);
  20237. </script>
  20238. <form name="myForm" ng-controller="ExampleController">
  20239. <label>Number:
  20240. <input type="number" name="input" ng-model="example.value"
  20241. min="0" max="99" required>
  20242. </label>
  20243. <div role="alert">
  20244. <span class="error" ng-show="myForm.input.$error.required">
  20245. Required!</span>
  20246. <span class="error" ng-show="myForm.input.$error.number">
  20247. Not valid number!</span>
  20248. </div>
  20249. <tt>value = {{example.value}}</tt><br/>
  20250. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  20251. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  20252. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20253. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20254. </form>
  20255. </file>
  20256. <file name="protractor.js" type="protractor">
  20257. var value = element(by.binding('example.value'));
  20258. var valid = element(by.binding('myForm.input.$valid'));
  20259. var input = element(by.model('example.value'));
  20260. it('should initialize to model', function() {
  20261. expect(value.getText()).toContain('12');
  20262. expect(valid.getText()).toContain('true');
  20263. });
  20264. it('should be invalid if empty', function() {
  20265. input.clear();
  20266. input.sendKeys('');
  20267. expect(value.getText()).toEqual('value =');
  20268. expect(valid.getText()).toContain('false');
  20269. });
  20270. it('should be invalid if over max', function() {
  20271. input.clear();
  20272. input.sendKeys('123');
  20273. expect(value.getText()).toEqual('value =');
  20274. expect(valid.getText()).toContain('false');
  20275. });
  20276. </file>
  20277. </example>
  20278. */
  20279. 'number': numberInputType,
  20280. /**
  20281. * @ngdoc input
  20282. * @name input[url]
  20283. *
  20284. * @description
  20285. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  20286. * valid URL.
  20287. *
  20288. * <div class="alert alert-warning">
  20289. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  20290. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  20291. * the built-in validators (see the {@link guide/forms Forms guide})
  20292. * </div>
  20293. *
  20294. * @param {string} ngModel Assignable angular expression to data-bind to.
  20295. * @param {string=} name Property name of the form under which the control is published.
  20296. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20297. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20298. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20299. * `required` when you want to data-bind to the `required` attribute.
  20300. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  20301. * minlength.
  20302. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  20303. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  20304. * any length.
  20305. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  20306. * that contains the regular expression body that will be converted to a regular expression
  20307. * as in the ngPattern directive.
  20308. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  20309. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  20310. * If the expression evaluates to a RegExp object, then this is used directly.
  20311. * If the expression evaluates to a string, then it will be converted to a RegExp
  20312. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  20313. * `new RegExp('^abc$')`.<br />
  20314. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  20315. * start at the index of the last search's match, thus not taking the whole input value into
  20316. * account.
  20317. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20318. * interaction with the input element.
  20319. *
  20320. * @example
  20321. <example name="url-input-directive" module="urlExample">
  20322. <file name="index.html">
  20323. <script>
  20324. angular.module('urlExample', [])
  20325. .controller('ExampleController', ['$scope', function($scope) {
  20326. $scope.url = {
  20327. text: 'http://google.com'
  20328. };
  20329. }]);
  20330. </script>
  20331. <form name="myForm" ng-controller="ExampleController">
  20332. <label>URL:
  20333. <input type="url" name="input" ng-model="url.text" required>
  20334. <label>
  20335. <div role="alert">
  20336. <span class="error" ng-show="myForm.input.$error.required">
  20337. Required!</span>
  20338. <span class="error" ng-show="myForm.input.$error.url">
  20339. Not valid url!</span>
  20340. </div>
  20341. <tt>text = {{url.text}}</tt><br/>
  20342. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  20343. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  20344. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20345. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20346. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  20347. </form>
  20348. </file>
  20349. <file name="protractor.js" type="protractor">
  20350. var text = element(by.binding('url.text'));
  20351. var valid = element(by.binding('myForm.input.$valid'));
  20352. var input = element(by.model('url.text'));
  20353. it('should initialize to model', function() {
  20354. expect(text.getText()).toContain('http://google.com');
  20355. expect(valid.getText()).toContain('true');
  20356. });
  20357. it('should be invalid if empty', function() {
  20358. input.clear();
  20359. input.sendKeys('');
  20360. expect(text.getText()).toEqual('text =');
  20361. expect(valid.getText()).toContain('false');
  20362. });
  20363. it('should be invalid if not url', function() {
  20364. input.clear();
  20365. input.sendKeys('box');
  20366. expect(valid.getText()).toContain('false');
  20367. });
  20368. </file>
  20369. </example>
  20370. */
  20371. 'url': urlInputType,
  20372. /**
  20373. * @ngdoc input
  20374. * @name input[email]
  20375. *
  20376. * @description
  20377. * Text input with email validation. Sets the `email` validation error key if not a valid email
  20378. * address.
  20379. *
  20380. * <div class="alert alert-warning">
  20381. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  20382. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  20383. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  20384. * </div>
  20385. *
  20386. * @param {string} ngModel Assignable angular expression to data-bind to.
  20387. * @param {string=} name Property name of the form under which the control is published.
  20388. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20389. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20390. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20391. * `required` when you want to data-bind to the `required` attribute.
  20392. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  20393. * minlength.
  20394. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  20395. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  20396. * any length.
  20397. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  20398. * that contains the regular expression body that will be converted to a regular expression
  20399. * as in the ngPattern directive.
  20400. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  20401. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  20402. * If the expression evaluates to a RegExp object, then this is used directly.
  20403. * If the expression evaluates to a string, then it will be converted to a RegExp
  20404. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  20405. * `new RegExp('^abc$')`.<br />
  20406. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  20407. * start at the index of the last search's match, thus not taking the whole input value into
  20408. * account.
  20409. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20410. * interaction with the input element.
  20411. *
  20412. * @example
  20413. <example name="email-input-directive" module="emailExample">
  20414. <file name="index.html">
  20415. <script>
  20416. angular.module('emailExample', [])
  20417. .controller('ExampleController', ['$scope', function($scope) {
  20418. $scope.email = {
  20419. text: 'me@example.com'
  20420. };
  20421. }]);
  20422. </script>
  20423. <form name="myForm" ng-controller="ExampleController">
  20424. <label>Email:
  20425. <input type="email" name="input" ng-model="email.text" required>
  20426. </label>
  20427. <div role="alert">
  20428. <span class="error" ng-show="myForm.input.$error.required">
  20429. Required!</span>
  20430. <span class="error" ng-show="myForm.input.$error.email">
  20431. Not valid email!</span>
  20432. </div>
  20433. <tt>text = {{email.text}}</tt><br/>
  20434. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  20435. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  20436. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20437. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20438. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  20439. </form>
  20440. </file>
  20441. <file name="protractor.js" type="protractor">
  20442. var text = element(by.binding('email.text'));
  20443. var valid = element(by.binding('myForm.input.$valid'));
  20444. var input = element(by.model('email.text'));
  20445. it('should initialize to model', function() {
  20446. expect(text.getText()).toContain('me@example.com');
  20447. expect(valid.getText()).toContain('true');
  20448. });
  20449. it('should be invalid if empty', function() {
  20450. input.clear();
  20451. input.sendKeys('');
  20452. expect(text.getText()).toEqual('text =');
  20453. expect(valid.getText()).toContain('false');
  20454. });
  20455. it('should be invalid if not email', function() {
  20456. input.clear();
  20457. input.sendKeys('xxx');
  20458. expect(valid.getText()).toContain('false');
  20459. });
  20460. </file>
  20461. </example>
  20462. */
  20463. 'email': emailInputType,
  20464. /**
  20465. * @ngdoc input
  20466. * @name input[radio]
  20467. *
  20468. * @description
  20469. * HTML radio button.
  20470. *
  20471. * @param {string} ngModel Assignable angular expression to data-bind to.
  20472. * @param {string} value The value to which the `ngModel` expression should be set when selected.
  20473. * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
  20474. * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
  20475. * @param {string=} name Property name of the form under which the control is published.
  20476. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20477. * interaction with the input element.
  20478. * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
  20479. * is selected. Should be used instead of the `value` attribute if you need
  20480. * a non-string `ngModel` (`boolean`, `array`, ...).
  20481. *
  20482. * @example
  20483. <example name="radio-input-directive" module="radioExample">
  20484. <file name="index.html">
  20485. <script>
  20486. angular.module('radioExample', [])
  20487. .controller('ExampleController', ['$scope', function($scope) {
  20488. $scope.color = {
  20489. name: 'blue'
  20490. };
  20491. $scope.specialValue = {
  20492. "id": "12345",
  20493. "value": "green"
  20494. };
  20495. }]);
  20496. </script>
  20497. <form name="myForm" ng-controller="ExampleController">
  20498. <label>
  20499. <input type="radio" ng-model="color.name" value="red">
  20500. Red
  20501. </label><br/>
  20502. <label>
  20503. <input type="radio" ng-model="color.name" ng-value="specialValue">
  20504. Green
  20505. </label><br/>
  20506. <label>
  20507. <input type="radio" ng-model="color.name" value="blue">
  20508. Blue
  20509. </label><br/>
  20510. <tt>color = {{color.name | json}}</tt><br/>
  20511. </form>
  20512. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  20513. </file>
  20514. <file name="protractor.js" type="protractor">
  20515. it('should change state', function() {
  20516. var color = element(by.binding('color.name'));
  20517. expect(color.getText()).toContain('blue');
  20518. element.all(by.model('color.name')).get(0).click();
  20519. expect(color.getText()).toContain('red');
  20520. });
  20521. </file>
  20522. </example>
  20523. */
  20524. 'radio': radioInputType,
  20525. /**
  20526. * @ngdoc input
  20527. * @name input[checkbox]
  20528. *
  20529. * @description
  20530. * HTML checkbox.
  20531. *
  20532. * @param {string} ngModel Assignable angular expression to data-bind to.
  20533. * @param {string=} name Property name of the form under which the control is published.
  20534. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  20535. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  20536. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20537. * interaction with the input element.
  20538. *
  20539. * @example
  20540. <example name="checkbox-input-directive" module="checkboxExample">
  20541. <file name="index.html">
  20542. <script>
  20543. angular.module('checkboxExample', [])
  20544. .controller('ExampleController', ['$scope', function($scope) {
  20545. $scope.checkboxModel = {
  20546. value1 : true,
  20547. value2 : 'YES'
  20548. };
  20549. }]);
  20550. </script>
  20551. <form name="myForm" ng-controller="ExampleController">
  20552. <label>Value1:
  20553. <input type="checkbox" ng-model="checkboxModel.value1">
  20554. </label><br/>
  20555. <label>Value2:
  20556. <input type="checkbox" ng-model="checkboxModel.value2"
  20557. ng-true-value="'YES'" ng-false-value="'NO'">
  20558. </label><br/>
  20559. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  20560. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  20561. </form>
  20562. </file>
  20563. <file name="protractor.js" type="protractor">
  20564. it('should change state', function() {
  20565. var value1 = element(by.binding('checkboxModel.value1'));
  20566. var value2 = element(by.binding('checkboxModel.value2'));
  20567. expect(value1.getText()).toContain('true');
  20568. expect(value2.getText()).toContain('YES');
  20569. element(by.model('checkboxModel.value1')).click();
  20570. element(by.model('checkboxModel.value2')).click();
  20571. expect(value1.getText()).toContain('false');
  20572. expect(value2.getText()).toContain('NO');
  20573. });
  20574. </file>
  20575. </example>
  20576. */
  20577. 'checkbox': checkboxInputType,
  20578. 'hidden': noop,
  20579. 'button': noop,
  20580. 'submit': noop,
  20581. 'reset': noop,
  20582. 'file': noop
  20583. };
  20584. function stringBasedInputType(ctrl) {
  20585. ctrl.$formatters.push(function(value) {
  20586. return ctrl.$isEmpty(value) ? value : value.toString();
  20587. });
  20588. }
  20589. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  20590. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  20591. stringBasedInputType(ctrl);
  20592. }
  20593. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  20594. var type = lowercase(element[0].type);
  20595. // In composition mode, users are still inputing intermediate text buffer,
  20596. // hold the listener until composition is done.
  20597. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  20598. if (!$sniffer.android) {
  20599. var composing = false;
  20600. element.on('compositionstart', function(data) {
  20601. composing = true;
  20602. });
  20603. element.on('compositionend', function() {
  20604. composing = false;
  20605. listener();
  20606. });
  20607. }
  20608. var listener = function(ev) {
  20609. if (timeout) {
  20610. $browser.defer.cancel(timeout);
  20611. timeout = null;
  20612. }
  20613. if (composing) return;
  20614. var value = element.val(),
  20615. event = ev && ev.type;
  20616. // By default we will trim the value
  20617. // If the attribute ng-trim exists we will avoid trimming
  20618. // If input type is 'password', the value is never trimmed
  20619. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  20620. value = trim(value);
  20621. }
  20622. // If a control is suffering from bad input (due to native validators), browsers discard its
  20623. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  20624. // control's value is the same empty value twice in a row.
  20625. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  20626. ctrl.$setViewValue(value, event);
  20627. }
  20628. };
  20629. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  20630. // input event on backspace, delete or cut
  20631. if ($sniffer.hasEvent('input')) {
  20632. element.on('input', listener);
  20633. } else {
  20634. var timeout;
  20635. var deferListener = function(ev, input, origValue) {
  20636. if (!timeout) {
  20637. timeout = $browser.defer(function() {
  20638. timeout = null;
  20639. if (!input || input.value !== origValue) {
  20640. listener(ev);
  20641. }
  20642. });
  20643. }
  20644. };
  20645. element.on('keydown', function(event) {
  20646. var key = event.keyCode;
  20647. // ignore
  20648. // command modifiers arrows
  20649. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  20650. deferListener(event, this, this.value);
  20651. });
  20652. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  20653. if ($sniffer.hasEvent('paste')) {
  20654. element.on('paste cut', deferListener);
  20655. }
  20656. }
  20657. // if user paste into input using mouse on older browser
  20658. // or form autocomplete on newer browser, we need "change" event to catch it
  20659. element.on('change', listener);
  20660. ctrl.$render = function() {
  20661. // Workaround for Firefox validation #12102.
  20662. var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
  20663. if (element.val() !== value) {
  20664. element.val(value);
  20665. }
  20666. };
  20667. }
  20668. function weekParser(isoWeek, existingDate) {
  20669. if (isDate(isoWeek)) {
  20670. return isoWeek;
  20671. }
  20672. if (isString(isoWeek)) {
  20673. WEEK_REGEXP.lastIndex = 0;
  20674. var parts = WEEK_REGEXP.exec(isoWeek);
  20675. if (parts) {
  20676. var year = +parts[1],
  20677. week = +parts[2],
  20678. hours = 0,
  20679. minutes = 0,
  20680. seconds = 0,
  20681. milliseconds = 0,
  20682. firstThurs = getFirstThursdayOfYear(year),
  20683. addDays = (week - 1) * 7;
  20684. if (existingDate) {
  20685. hours = existingDate.getHours();
  20686. minutes = existingDate.getMinutes();
  20687. seconds = existingDate.getSeconds();
  20688. milliseconds = existingDate.getMilliseconds();
  20689. }
  20690. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  20691. }
  20692. }
  20693. return NaN;
  20694. }
  20695. function createDateParser(regexp, mapping) {
  20696. return function(iso, date) {
  20697. var parts, map;
  20698. if (isDate(iso)) {
  20699. return iso;
  20700. }
  20701. if (isString(iso)) {
  20702. // When a date is JSON'ified to wraps itself inside of an extra
  20703. // set of double quotes. This makes the date parsing code unable
  20704. // to match the date string and parse it as a date.
  20705. if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
  20706. iso = iso.substring(1, iso.length - 1);
  20707. }
  20708. if (ISO_DATE_REGEXP.test(iso)) {
  20709. return new Date(iso);
  20710. }
  20711. regexp.lastIndex = 0;
  20712. parts = regexp.exec(iso);
  20713. if (parts) {
  20714. parts.shift();
  20715. if (date) {
  20716. map = {
  20717. yyyy: date.getFullYear(),
  20718. MM: date.getMonth() + 1,
  20719. dd: date.getDate(),
  20720. HH: date.getHours(),
  20721. mm: date.getMinutes(),
  20722. ss: date.getSeconds(),
  20723. sss: date.getMilliseconds() / 1000
  20724. };
  20725. } else {
  20726. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  20727. }
  20728. forEach(parts, function(part, index) {
  20729. if (index < mapping.length) {
  20730. map[mapping[index]] = +part;
  20731. }
  20732. });
  20733. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  20734. }
  20735. }
  20736. return NaN;
  20737. };
  20738. }
  20739. function createDateInputType(type, regexp, parseDate, format) {
  20740. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  20741. badInputChecker(scope, element, attr, ctrl);
  20742. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  20743. var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
  20744. var previousDate;
  20745. ctrl.$$parserName = type;
  20746. ctrl.$parsers.push(function(value) {
  20747. if (ctrl.$isEmpty(value)) return null;
  20748. if (regexp.test(value)) {
  20749. // Note: We cannot read ctrl.$modelValue, as there might be a different
  20750. // parser/formatter in the processing chain so that the model
  20751. // contains some different data format!
  20752. var parsedDate = parseDate(value, previousDate);
  20753. if (timezone) {
  20754. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  20755. }
  20756. return parsedDate;
  20757. }
  20758. return undefined;
  20759. });
  20760. ctrl.$formatters.push(function(value) {
  20761. if (value && !isDate(value)) {
  20762. throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  20763. }
  20764. if (isValidDate(value)) {
  20765. previousDate = value;
  20766. if (previousDate && timezone) {
  20767. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  20768. }
  20769. return $filter('date')(value, format, timezone);
  20770. } else {
  20771. previousDate = null;
  20772. return '';
  20773. }
  20774. });
  20775. if (isDefined(attr.min) || attr.ngMin) {
  20776. var minVal;
  20777. ctrl.$validators.min = function(value) {
  20778. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  20779. };
  20780. attr.$observe('min', function(val) {
  20781. minVal = parseObservedDateValue(val);
  20782. ctrl.$validate();
  20783. });
  20784. }
  20785. if (isDefined(attr.max) || attr.ngMax) {
  20786. var maxVal;
  20787. ctrl.$validators.max = function(value) {
  20788. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  20789. };
  20790. attr.$observe('max', function(val) {
  20791. maxVal = parseObservedDateValue(val);
  20792. ctrl.$validate();
  20793. });
  20794. }
  20795. function isValidDate(value) {
  20796. // Invalid Date: getTime() returns NaN
  20797. return value && !(value.getTime && value.getTime() !== value.getTime());
  20798. }
  20799. function parseObservedDateValue(val) {
  20800. return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
  20801. }
  20802. };
  20803. }
  20804. function badInputChecker(scope, element, attr, ctrl) {
  20805. var node = element[0];
  20806. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  20807. if (nativeValidation) {
  20808. ctrl.$parsers.push(function(value) {
  20809. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  20810. return validity.badInput || validity.typeMismatch ? undefined : value;
  20811. });
  20812. }
  20813. }
  20814. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  20815. badInputChecker(scope, element, attr, ctrl);
  20816. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  20817. ctrl.$$parserName = 'number';
  20818. ctrl.$parsers.push(function(value) {
  20819. if (ctrl.$isEmpty(value)) return null;
  20820. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  20821. return undefined;
  20822. });
  20823. ctrl.$formatters.push(function(value) {
  20824. if (!ctrl.$isEmpty(value)) {
  20825. if (!isNumber(value)) {
  20826. throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  20827. }
  20828. value = value.toString();
  20829. }
  20830. return value;
  20831. });
  20832. if (isDefined(attr.min) || attr.ngMin) {
  20833. var minVal;
  20834. ctrl.$validators.min = function(value) {
  20835. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  20836. };
  20837. attr.$observe('min', function(val) {
  20838. if (isDefined(val) && !isNumber(val)) {
  20839. val = parseFloat(val, 10);
  20840. }
  20841. minVal = isNumber(val) && !isNaN(val) ? val : undefined;
  20842. // TODO(matsko): implement validateLater to reduce number of validations
  20843. ctrl.$validate();
  20844. });
  20845. }
  20846. if (isDefined(attr.max) || attr.ngMax) {
  20847. var maxVal;
  20848. ctrl.$validators.max = function(value) {
  20849. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  20850. };
  20851. attr.$observe('max', function(val) {
  20852. if (isDefined(val) && !isNumber(val)) {
  20853. val = parseFloat(val, 10);
  20854. }
  20855. maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
  20856. // TODO(matsko): implement validateLater to reduce number of validations
  20857. ctrl.$validate();
  20858. });
  20859. }
  20860. }
  20861. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  20862. // Note: no badInputChecker here by purpose as `url` is only a validation
  20863. // in browsers, i.e. we can always read out input.value even if it is not valid!
  20864. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  20865. stringBasedInputType(ctrl);
  20866. ctrl.$$parserName = 'url';
  20867. ctrl.$validators.url = function(modelValue, viewValue) {
  20868. var value = modelValue || viewValue;
  20869. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  20870. };
  20871. }
  20872. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  20873. // Note: no badInputChecker here by purpose as `url` is only a validation
  20874. // in browsers, i.e. we can always read out input.value even if it is not valid!
  20875. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  20876. stringBasedInputType(ctrl);
  20877. ctrl.$$parserName = 'email';
  20878. ctrl.$validators.email = function(modelValue, viewValue) {
  20879. var value = modelValue || viewValue;
  20880. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  20881. };
  20882. }
  20883. function radioInputType(scope, element, attr, ctrl) {
  20884. // make the name unique, if not defined
  20885. if (isUndefined(attr.name)) {
  20886. element.attr('name', nextUid());
  20887. }
  20888. var listener = function(ev) {
  20889. if (element[0].checked) {
  20890. ctrl.$setViewValue(attr.value, ev && ev.type);
  20891. }
  20892. };
  20893. element.on('click', listener);
  20894. ctrl.$render = function() {
  20895. var value = attr.value;
  20896. element[0].checked = (value == ctrl.$viewValue);
  20897. };
  20898. attr.$observe('value', ctrl.$render);
  20899. }
  20900. function parseConstantExpr($parse, context, name, expression, fallback) {
  20901. var parseFn;
  20902. if (isDefined(expression)) {
  20903. parseFn = $parse(expression);
  20904. if (!parseFn.constant) {
  20905. throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  20906. '`{1}`.', name, expression);
  20907. }
  20908. return parseFn(context);
  20909. }
  20910. return fallback;
  20911. }
  20912. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  20913. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  20914. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  20915. var listener = function(ev) {
  20916. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  20917. };
  20918. element.on('click', listener);
  20919. ctrl.$render = function() {
  20920. element[0].checked = ctrl.$viewValue;
  20921. };
  20922. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  20923. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  20924. // it to a boolean.
  20925. ctrl.$isEmpty = function(value) {
  20926. return value === false;
  20927. };
  20928. ctrl.$formatters.push(function(value) {
  20929. return equals(value, trueValue);
  20930. });
  20931. ctrl.$parsers.push(function(value) {
  20932. return value ? trueValue : falseValue;
  20933. });
  20934. }
  20935. /**
  20936. * @ngdoc directive
  20937. * @name textarea
  20938. * @restrict E
  20939. *
  20940. * @description
  20941. * HTML textarea element control with angular data-binding. The data-binding and validation
  20942. * properties of this element are exactly the same as those of the
  20943. * {@link ng.directive:input input element}.
  20944. *
  20945. * @param {string} ngModel Assignable angular expression to data-bind to.
  20946. * @param {string=} name Property name of the form under which the control is published.
  20947. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20948. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20949. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20950. * `required` when you want to data-bind to the `required` attribute.
  20951. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  20952. * minlength.
  20953. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  20954. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  20955. * length.
  20956. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  20957. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  20958. * If the expression evaluates to a RegExp object, then this is used directly.
  20959. * If the expression evaluates to a string, then it will be converted to a RegExp
  20960. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  20961. * `new RegExp('^abc$')`.<br />
  20962. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  20963. * start at the index of the last search's match, thus not taking the whole input value into
  20964. * account.
  20965. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20966. * interaction with the input element.
  20967. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  20968. */
  20969. /**
  20970. * @ngdoc directive
  20971. * @name input
  20972. * @restrict E
  20973. *
  20974. * @description
  20975. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  20976. * input state control, and validation.
  20977. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  20978. *
  20979. * <div class="alert alert-warning">
  20980. * **Note:** Not every feature offered is available for all input types.
  20981. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  20982. * </div>
  20983. *
  20984. * @param {string} ngModel Assignable angular expression to data-bind to.
  20985. * @param {string=} name Property name of the form under which the control is published.
  20986. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20987. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  20988. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  20989. * minlength.
  20990. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  20991. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  20992. * length.
  20993. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  20994. * value does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  20995. * If the expression evaluates to a RegExp object, then this is used directly.
  20996. * If the expression evaluates to a string, then it will be converted to a RegExp
  20997. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  20998. * `new RegExp('^abc$')`.<br />
  20999. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21000. * start at the index of the last search's match, thus not taking the whole input value into
  21001. * account.
  21002. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21003. * interaction with the input element.
  21004. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  21005. * This parameter is ignored for input[type=password] controls, which will never trim the
  21006. * input.
  21007. *
  21008. * @example
  21009. <example name="input-directive" module="inputExample">
  21010. <file name="index.html">
  21011. <script>
  21012. angular.module('inputExample', [])
  21013. .controller('ExampleController', ['$scope', function($scope) {
  21014. $scope.user = {name: 'guest', last: 'visitor'};
  21015. }]);
  21016. </script>
  21017. <div ng-controller="ExampleController">
  21018. <form name="myForm">
  21019. <label>
  21020. User name:
  21021. <input type="text" name="userName" ng-model="user.name" required>
  21022. </label>
  21023. <div role="alert">
  21024. <span class="error" ng-show="myForm.userName.$error.required">
  21025. Required!</span>
  21026. </div>
  21027. <label>
  21028. Last name:
  21029. <input type="text" name="lastName" ng-model="user.last"
  21030. ng-minlength="3" ng-maxlength="10">
  21031. </label>
  21032. <div role="alert">
  21033. <span class="error" ng-show="myForm.lastName.$error.minlength">
  21034. Too short!</span>
  21035. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  21036. Too long!</span>
  21037. </div>
  21038. </form>
  21039. <hr>
  21040. <tt>user = {{user}}</tt><br/>
  21041. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  21042. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  21043. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  21044. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  21045. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21046. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21047. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  21048. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  21049. </div>
  21050. </file>
  21051. <file name="protractor.js" type="protractor">
  21052. var user = element(by.exactBinding('user'));
  21053. var userNameValid = element(by.binding('myForm.userName.$valid'));
  21054. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  21055. var lastNameError = element(by.binding('myForm.lastName.$error'));
  21056. var formValid = element(by.binding('myForm.$valid'));
  21057. var userNameInput = element(by.model('user.name'));
  21058. var userLastInput = element(by.model('user.last'));
  21059. it('should initialize to model', function() {
  21060. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  21061. expect(userNameValid.getText()).toContain('true');
  21062. expect(formValid.getText()).toContain('true');
  21063. });
  21064. it('should be invalid if empty when required', function() {
  21065. userNameInput.clear();
  21066. userNameInput.sendKeys('');
  21067. expect(user.getText()).toContain('{"last":"visitor"}');
  21068. expect(userNameValid.getText()).toContain('false');
  21069. expect(formValid.getText()).toContain('false');
  21070. });
  21071. it('should be valid if empty when min length is set', function() {
  21072. userLastInput.clear();
  21073. userLastInput.sendKeys('');
  21074. expect(user.getText()).toContain('{"name":"guest","last":""}');
  21075. expect(lastNameValid.getText()).toContain('true');
  21076. expect(formValid.getText()).toContain('true');
  21077. });
  21078. it('should be invalid if less than required min length', function() {
  21079. userLastInput.clear();
  21080. userLastInput.sendKeys('xx');
  21081. expect(user.getText()).toContain('{"name":"guest"}');
  21082. expect(lastNameValid.getText()).toContain('false');
  21083. expect(lastNameError.getText()).toContain('minlength');
  21084. expect(formValid.getText()).toContain('false');
  21085. });
  21086. it('should be invalid if longer than max length', function() {
  21087. userLastInput.clear();
  21088. userLastInput.sendKeys('some ridiculously long name');
  21089. expect(user.getText()).toContain('{"name":"guest"}');
  21090. expect(lastNameValid.getText()).toContain('false');
  21091. expect(lastNameError.getText()).toContain('maxlength');
  21092. expect(formValid.getText()).toContain('false');
  21093. });
  21094. </file>
  21095. </example>
  21096. */
  21097. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  21098. function($browser, $sniffer, $filter, $parse) {
  21099. return {
  21100. restrict: 'E',
  21101. require: ['?ngModel'],
  21102. link: {
  21103. pre: function(scope, element, attr, ctrls) {
  21104. if (ctrls[0]) {
  21105. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  21106. $browser, $filter, $parse);
  21107. }
  21108. }
  21109. }
  21110. };
  21111. }];
  21112. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  21113. /**
  21114. * @ngdoc directive
  21115. * @name ngValue
  21116. *
  21117. * @description
  21118. * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
  21119. * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
  21120. * the bound value.
  21121. *
  21122. * `ngValue` is useful when dynamically generating lists of radio buttons using
  21123. * {@link ngRepeat `ngRepeat`}, as shown below.
  21124. *
  21125. * Likewise, `ngValue` can be used to generate `<option>` elements for
  21126. * the {@link select `select`} element. In that case however, only strings are supported
  21127. * for the `value `attribute, so the resulting `ngModel` will always be a string.
  21128. * Support for `select` models with non-string values is available via `ngOptions`.
  21129. *
  21130. * @element input
  21131. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  21132. * of the `input` element
  21133. *
  21134. * @example
  21135. <example name="ngValue-directive" module="valueExample">
  21136. <file name="index.html">
  21137. <script>
  21138. angular.module('valueExample', [])
  21139. .controller('ExampleController', ['$scope', function($scope) {
  21140. $scope.names = ['pizza', 'unicorns', 'robots'];
  21141. $scope.my = { favorite: 'unicorns' };
  21142. }]);
  21143. </script>
  21144. <form ng-controller="ExampleController">
  21145. <h2>Which is your favorite?</h2>
  21146. <label ng-repeat="name in names" for="{{name}}">
  21147. {{name}}
  21148. <input type="radio"
  21149. ng-model="my.favorite"
  21150. ng-value="name"
  21151. id="{{name}}"
  21152. name="favorite">
  21153. </label>
  21154. <div>You chose {{my.favorite}}</div>
  21155. </form>
  21156. </file>
  21157. <file name="protractor.js" type="protractor">
  21158. var favorite = element(by.binding('my.favorite'));
  21159. it('should initialize to model', function() {
  21160. expect(favorite.getText()).toContain('unicorns');
  21161. });
  21162. it('should bind the values to the inputs', function() {
  21163. element.all(by.model('my.favorite')).get(0).click();
  21164. expect(favorite.getText()).toContain('pizza');
  21165. });
  21166. </file>
  21167. </example>
  21168. */
  21169. var ngValueDirective = function() {
  21170. return {
  21171. restrict: 'A',
  21172. priority: 100,
  21173. compile: function(tpl, tplAttr) {
  21174. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  21175. return function ngValueConstantLink(scope, elm, attr) {
  21176. attr.$set('value', scope.$eval(attr.ngValue));
  21177. };
  21178. } else {
  21179. return function ngValueLink(scope, elm, attr) {
  21180. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  21181. attr.$set('value', value);
  21182. });
  21183. };
  21184. }
  21185. }
  21186. };
  21187. };
  21188. /**
  21189. * @ngdoc directive
  21190. * @name ngBind
  21191. * @restrict AC
  21192. *
  21193. * @description
  21194. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  21195. * with the value of a given expression, and to update the text content when the value of that
  21196. * expression changes.
  21197. *
  21198. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  21199. * `{{ expression }}` which is similar but less verbose.
  21200. *
  21201. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  21202. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  21203. * element attribute, it makes the bindings invisible to the user while the page is loading.
  21204. *
  21205. * An alternative solution to this problem would be using the
  21206. * {@link ng.directive:ngCloak ngCloak} directive.
  21207. *
  21208. *
  21209. * @element ANY
  21210. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  21211. *
  21212. * @example
  21213. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  21214. <example module="bindExample">
  21215. <file name="index.html">
  21216. <script>
  21217. angular.module('bindExample', [])
  21218. .controller('ExampleController', ['$scope', function($scope) {
  21219. $scope.name = 'Whirled';
  21220. }]);
  21221. </script>
  21222. <div ng-controller="ExampleController">
  21223. <label>Enter name: <input type="text" ng-model="name"></label><br>
  21224. Hello <span ng-bind="name"></span>!
  21225. </div>
  21226. </file>
  21227. <file name="protractor.js" type="protractor">
  21228. it('should check ng-bind', function() {
  21229. var nameInput = element(by.model('name'));
  21230. expect(element(by.binding('name')).getText()).toBe('Whirled');
  21231. nameInput.clear();
  21232. nameInput.sendKeys('world');
  21233. expect(element(by.binding('name')).getText()).toBe('world');
  21234. });
  21235. </file>
  21236. </example>
  21237. */
  21238. var ngBindDirective = ['$compile', function($compile) {
  21239. return {
  21240. restrict: 'AC',
  21241. compile: function ngBindCompile(templateElement) {
  21242. $compile.$$addBindingClass(templateElement);
  21243. return function ngBindLink(scope, element, attr) {
  21244. $compile.$$addBindingInfo(element, attr.ngBind);
  21245. element = element[0];
  21246. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  21247. element.textContent = isUndefined(value) ? '' : value;
  21248. });
  21249. };
  21250. }
  21251. };
  21252. }];
  21253. /**
  21254. * @ngdoc directive
  21255. * @name ngBindTemplate
  21256. *
  21257. * @description
  21258. * The `ngBindTemplate` directive specifies that the element
  21259. * text content should be replaced with the interpolation of the template
  21260. * in the `ngBindTemplate` attribute.
  21261. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  21262. * expressions. This directive is needed since some HTML elements
  21263. * (such as TITLE and OPTION) cannot contain SPAN elements.
  21264. *
  21265. * @element ANY
  21266. * @param {string} ngBindTemplate template of form
  21267. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  21268. *
  21269. * @example
  21270. * Try it here: enter text in text box and watch the greeting change.
  21271. <example module="bindExample">
  21272. <file name="index.html">
  21273. <script>
  21274. angular.module('bindExample', [])
  21275. .controller('ExampleController', ['$scope', function($scope) {
  21276. $scope.salutation = 'Hello';
  21277. $scope.name = 'World';
  21278. }]);
  21279. </script>
  21280. <div ng-controller="ExampleController">
  21281. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  21282. <label>Name: <input type="text" ng-model="name"></label><br>
  21283. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  21284. </div>
  21285. </file>
  21286. <file name="protractor.js" type="protractor">
  21287. it('should check ng-bind', function() {
  21288. var salutationElem = element(by.binding('salutation'));
  21289. var salutationInput = element(by.model('salutation'));
  21290. var nameInput = element(by.model('name'));
  21291. expect(salutationElem.getText()).toBe('Hello World!');
  21292. salutationInput.clear();
  21293. salutationInput.sendKeys('Greetings');
  21294. nameInput.clear();
  21295. nameInput.sendKeys('user');
  21296. expect(salutationElem.getText()).toBe('Greetings user!');
  21297. });
  21298. </file>
  21299. </example>
  21300. */
  21301. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  21302. return {
  21303. compile: function ngBindTemplateCompile(templateElement) {
  21304. $compile.$$addBindingClass(templateElement);
  21305. return function ngBindTemplateLink(scope, element, attr) {
  21306. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  21307. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  21308. element = element[0];
  21309. attr.$observe('ngBindTemplate', function(value) {
  21310. element.textContent = isUndefined(value) ? '' : value;
  21311. });
  21312. };
  21313. }
  21314. };
  21315. }];
  21316. /**
  21317. * @ngdoc directive
  21318. * @name ngBindHtml
  21319. *
  21320. * @description
  21321. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  21322. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  21323. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  21324. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  21325. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  21326. *
  21327. * You may also bypass sanitization for values you know are safe. To do so, bind to
  21328. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  21329. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  21330. *
  21331. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  21332. * will have an exception (instead of an exploit.)
  21333. *
  21334. * @element ANY
  21335. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  21336. *
  21337. * @example
  21338. <example module="bindHtmlExample" deps="angular-sanitize.js">
  21339. <file name="index.html">
  21340. <div ng-controller="ExampleController">
  21341. <p ng-bind-html="myHTML"></p>
  21342. </div>
  21343. </file>
  21344. <file name="script.js">
  21345. angular.module('bindHtmlExample', ['ngSanitize'])
  21346. .controller('ExampleController', ['$scope', function($scope) {
  21347. $scope.myHTML =
  21348. 'I am an <code>HTML</code>string with ' +
  21349. '<a href="#">links!</a> and other <em>stuff</em>';
  21350. }]);
  21351. </file>
  21352. <file name="protractor.js" type="protractor">
  21353. it('should check ng-bind-html', function() {
  21354. expect(element(by.binding('myHTML')).getText()).toBe(
  21355. 'I am an HTMLstring with links! and other stuff');
  21356. });
  21357. </file>
  21358. </example>
  21359. */
  21360. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  21361. return {
  21362. restrict: 'A',
  21363. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  21364. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  21365. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
  21366. return (value || '').toString();
  21367. });
  21368. $compile.$$addBindingClass(tElement);
  21369. return function ngBindHtmlLink(scope, element, attr) {
  21370. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  21371. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  21372. // we re-evaluate the expr because we want a TrustedValueHolderType
  21373. // for $sce, not a string
  21374. element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
  21375. });
  21376. };
  21377. }
  21378. };
  21379. }];
  21380. /**
  21381. * @ngdoc directive
  21382. * @name ngChange
  21383. *
  21384. * @description
  21385. * Evaluate the given expression when the user changes the input.
  21386. * The expression is evaluated immediately, unlike the JavaScript onchange event
  21387. * which only triggers at the end of a change (usually, when the user leaves the
  21388. * form element or presses the return key).
  21389. *
  21390. * The `ngChange` expression is only evaluated when a change in the input value causes
  21391. * a new value to be committed to the model.
  21392. *
  21393. * It will not be evaluated:
  21394. * * if the value returned from the `$parsers` transformation pipeline has not changed
  21395. * * if the input has continued to be invalid since the model will stay `null`
  21396. * * if the model is changed programmatically and not by a change to the input value
  21397. *
  21398. *
  21399. * Note, this directive requires `ngModel` to be present.
  21400. *
  21401. * @element input
  21402. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  21403. * in input value.
  21404. *
  21405. * @example
  21406. * <example name="ngChange-directive" module="changeExample">
  21407. * <file name="index.html">
  21408. * <script>
  21409. * angular.module('changeExample', [])
  21410. * .controller('ExampleController', ['$scope', function($scope) {
  21411. * $scope.counter = 0;
  21412. * $scope.change = function() {
  21413. * $scope.counter++;
  21414. * };
  21415. * }]);
  21416. * </script>
  21417. * <div ng-controller="ExampleController">
  21418. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  21419. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  21420. * <label for="ng-change-example2">Confirmed</label><br />
  21421. * <tt>debug = {{confirmed}}</tt><br/>
  21422. * <tt>counter = {{counter}}</tt><br/>
  21423. * </div>
  21424. * </file>
  21425. * <file name="protractor.js" type="protractor">
  21426. * var counter = element(by.binding('counter'));
  21427. * var debug = element(by.binding('confirmed'));
  21428. *
  21429. * it('should evaluate the expression if changing from view', function() {
  21430. * expect(counter.getText()).toContain('0');
  21431. *
  21432. * element(by.id('ng-change-example1')).click();
  21433. *
  21434. * expect(counter.getText()).toContain('1');
  21435. * expect(debug.getText()).toContain('true');
  21436. * });
  21437. *
  21438. * it('should not evaluate the expression if changing from model', function() {
  21439. * element(by.id('ng-change-example2')).click();
  21440. * expect(counter.getText()).toContain('0');
  21441. * expect(debug.getText()).toContain('true');
  21442. * });
  21443. * </file>
  21444. * </example>
  21445. */
  21446. var ngChangeDirective = valueFn({
  21447. restrict: 'A',
  21448. require: 'ngModel',
  21449. link: function(scope, element, attr, ctrl) {
  21450. ctrl.$viewChangeListeners.push(function() {
  21451. scope.$eval(attr.ngChange);
  21452. });
  21453. }
  21454. });
  21455. function classDirective(name, selector) {
  21456. name = 'ngClass' + name;
  21457. return ['$animate', function($animate) {
  21458. return {
  21459. restrict: 'AC',
  21460. link: function(scope, element, attr) {
  21461. var oldVal;
  21462. scope.$watch(attr[name], ngClassWatchAction, true);
  21463. attr.$observe('class', function(value) {
  21464. ngClassWatchAction(scope.$eval(attr[name]));
  21465. });
  21466. if (name !== 'ngClass') {
  21467. scope.$watch('$index', function($index, old$index) {
  21468. // jshint bitwise: false
  21469. var mod = $index & 1;
  21470. if (mod !== (old$index & 1)) {
  21471. var classes = arrayClasses(scope.$eval(attr[name]));
  21472. mod === selector ?
  21473. addClasses(classes) :
  21474. removeClasses(classes);
  21475. }
  21476. });
  21477. }
  21478. function addClasses(classes) {
  21479. var newClasses = digestClassCounts(classes, 1);
  21480. attr.$addClass(newClasses);
  21481. }
  21482. function removeClasses(classes) {
  21483. var newClasses = digestClassCounts(classes, -1);
  21484. attr.$removeClass(newClasses);
  21485. }
  21486. function digestClassCounts(classes, count) {
  21487. // Use createMap() to prevent class assumptions involving property
  21488. // names in Object.prototype
  21489. var classCounts = element.data('$classCounts') || createMap();
  21490. var classesToUpdate = [];
  21491. forEach(classes, function(className) {
  21492. if (count > 0 || classCounts[className]) {
  21493. classCounts[className] = (classCounts[className] || 0) + count;
  21494. if (classCounts[className] === +(count > 0)) {
  21495. classesToUpdate.push(className);
  21496. }
  21497. }
  21498. });
  21499. element.data('$classCounts', classCounts);
  21500. return classesToUpdate.join(' ');
  21501. }
  21502. function updateClasses(oldClasses, newClasses) {
  21503. var toAdd = arrayDifference(newClasses, oldClasses);
  21504. var toRemove = arrayDifference(oldClasses, newClasses);
  21505. toAdd = digestClassCounts(toAdd, 1);
  21506. toRemove = digestClassCounts(toRemove, -1);
  21507. if (toAdd && toAdd.length) {
  21508. $animate.addClass(element, toAdd);
  21509. }
  21510. if (toRemove && toRemove.length) {
  21511. $animate.removeClass(element, toRemove);
  21512. }
  21513. }
  21514. function ngClassWatchAction(newVal) {
  21515. if (selector === true || scope.$index % 2 === selector) {
  21516. var newClasses = arrayClasses(newVal || []);
  21517. if (!oldVal) {
  21518. addClasses(newClasses);
  21519. } else if (!equals(newVal,oldVal)) {
  21520. var oldClasses = arrayClasses(oldVal);
  21521. updateClasses(oldClasses, newClasses);
  21522. }
  21523. }
  21524. oldVal = shallowCopy(newVal);
  21525. }
  21526. }
  21527. };
  21528. function arrayDifference(tokens1, tokens2) {
  21529. var values = [];
  21530. outer:
  21531. for (var i = 0; i < tokens1.length; i++) {
  21532. var token = tokens1[i];
  21533. for (var j = 0; j < tokens2.length; j++) {
  21534. if (token == tokens2[j]) continue outer;
  21535. }
  21536. values.push(token);
  21537. }
  21538. return values;
  21539. }
  21540. function arrayClasses(classVal) {
  21541. var classes = [];
  21542. if (isArray(classVal)) {
  21543. forEach(classVal, function(v) {
  21544. classes = classes.concat(arrayClasses(v));
  21545. });
  21546. return classes;
  21547. } else if (isString(classVal)) {
  21548. return classVal.split(' ');
  21549. } else if (isObject(classVal)) {
  21550. forEach(classVal, function(v, k) {
  21551. if (v) {
  21552. classes = classes.concat(k.split(' '));
  21553. }
  21554. });
  21555. return classes;
  21556. }
  21557. return classVal;
  21558. }
  21559. }];
  21560. }
  21561. /**
  21562. * @ngdoc directive
  21563. * @name ngClass
  21564. * @restrict AC
  21565. *
  21566. * @description
  21567. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  21568. * an expression that represents all classes to be added.
  21569. *
  21570. * The directive operates in three different ways, depending on which of three types the expression
  21571. * evaluates to:
  21572. *
  21573. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  21574. * names.
  21575. *
  21576. * 2. If the expression evaluates to an object, then for each key-value pair of the
  21577. * object with a truthy value the corresponding key is used as a class name.
  21578. *
  21579. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  21580. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  21581. * to give you more control over what CSS classes appear. See the code below for an example of this.
  21582. *
  21583. *
  21584. * The directive won't add duplicate classes if a particular class was already set.
  21585. *
  21586. * When the expression changes, the previously added classes are removed and only then are the
  21587. * new classes added.
  21588. *
  21589. * @animations
  21590. * | Animation | Occurs |
  21591. * |----------------------------------|-------------------------------------|
  21592. * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element |
  21593. * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element |
  21594. *
  21595. * @element ANY
  21596. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  21597. * of the evaluation can be a string representing space delimited class
  21598. * names, an array, or a map of class names to boolean values. In the case of a map, the
  21599. * names of the properties whose values are truthy will be added as css classes to the
  21600. * element.
  21601. *
  21602. * @example Example that demonstrates basic bindings via ngClass directive.
  21603. <example>
  21604. <file name="index.html">
  21605. <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
  21606. <label>
  21607. <input type="checkbox" ng-model="deleted">
  21608. deleted (apply "strike" class)
  21609. </label><br>
  21610. <label>
  21611. <input type="checkbox" ng-model="important">
  21612. important (apply "bold" class)
  21613. </label><br>
  21614. <label>
  21615. <input type="checkbox" ng-model="error">
  21616. error (apply "has-error" class)
  21617. </label>
  21618. <hr>
  21619. <p ng-class="style">Using String Syntax</p>
  21620. <input type="text" ng-model="style"
  21621. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  21622. <hr>
  21623. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  21624. <input ng-model="style1"
  21625. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  21626. <input ng-model="style2"
  21627. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  21628. <input ng-model="style3"
  21629. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  21630. <hr>
  21631. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  21632. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  21633. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  21634. </file>
  21635. <file name="style.css">
  21636. .strike {
  21637. text-decoration: line-through;
  21638. }
  21639. .bold {
  21640. font-weight: bold;
  21641. }
  21642. .red {
  21643. color: red;
  21644. }
  21645. .has-error {
  21646. color: red;
  21647. background-color: yellow;
  21648. }
  21649. .orange {
  21650. color: orange;
  21651. }
  21652. </file>
  21653. <file name="protractor.js" type="protractor">
  21654. var ps = element.all(by.css('p'));
  21655. it('should let you toggle the class', function() {
  21656. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  21657. expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
  21658. element(by.model('important')).click();
  21659. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  21660. element(by.model('error')).click();
  21661. expect(ps.first().getAttribute('class')).toMatch(/has-error/);
  21662. });
  21663. it('should let you toggle string example', function() {
  21664. expect(ps.get(1).getAttribute('class')).toBe('');
  21665. element(by.model('style')).clear();
  21666. element(by.model('style')).sendKeys('red');
  21667. expect(ps.get(1).getAttribute('class')).toBe('red');
  21668. });
  21669. it('array example should have 3 classes', function() {
  21670. expect(ps.get(2).getAttribute('class')).toBe('');
  21671. element(by.model('style1')).sendKeys('bold');
  21672. element(by.model('style2')).sendKeys('strike');
  21673. element(by.model('style3')).sendKeys('red');
  21674. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  21675. });
  21676. it('array with map example should have 2 classes', function() {
  21677. expect(ps.last().getAttribute('class')).toBe('');
  21678. element(by.model('style4')).sendKeys('bold');
  21679. element(by.model('warning')).click();
  21680. expect(ps.last().getAttribute('class')).toBe('bold orange');
  21681. });
  21682. </file>
  21683. </example>
  21684. ## Animations
  21685. The example below demonstrates how to perform animations using ngClass.
  21686. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  21687. <file name="index.html">
  21688. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  21689. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  21690. <br>
  21691. <span class="base-class" ng-class="myVar">Sample Text</span>
  21692. </file>
  21693. <file name="style.css">
  21694. .base-class {
  21695. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21696. }
  21697. .base-class.my-class {
  21698. color: red;
  21699. font-size:3em;
  21700. }
  21701. </file>
  21702. <file name="protractor.js" type="protractor">
  21703. it('should check ng-class', function() {
  21704. expect(element(by.css('.base-class')).getAttribute('class')).not.
  21705. toMatch(/my-class/);
  21706. element(by.id('setbtn')).click();
  21707. expect(element(by.css('.base-class')).getAttribute('class')).
  21708. toMatch(/my-class/);
  21709. element(by.id('clearbtn')).click();
  21710. expect(element(by.css('.base-class')).getAttribute('class')).not.
  21711. toMatch(/my-class/);
  21712. });
  21713. </file>
  21714. </example>
  21715. ## ngClass and pre-existing CSS3 Transitions/Animations
  21716. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  21717. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  21718. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  21719. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  21720. {@link $animate#removeClass $animate.removeClass}.
  21721. */
  21722. var ngClassDirective = classDirective('', true);
  21723. /**
  21724. * @ngdoc directive
  21725. * @name ngClassOdd
  21726. * @restrict AC
  21727. *
  21728. * @description
  21729. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  21730. * {@link ng.directive:ngClass ngClass}, except they work in
  21731. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  21732. *
  21733. * This directive can be applied only within the scope of an
  21734. * {@link ng.directive:ngRepeat ngRepeat}.
  21735. *
  21736. * @element ANY
  21737. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  21738. * of the evaluation can be a string representing space delimited class names or an array.
  21739. *
  21740. * @example
  21741. <example>
  21742. <file name="index.html">
  21743. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  21744. <li ng-repeat="name in names">
  21745. <span ng-class-odd="'odd'" ng-class-even="'even'">
  21746. {{name}}
  21747. </span>
  21748. </li>
  21749. </ol>
  21750. </file>
  21751. <file name="style.css">
  21752. .odd {
  21753. color: red;
  21754. }
  21755. .even {
  21756. color: blue;
  21757. }
  21758. </file>
  21759. <file name="protractor.js" type="protractor">
  21760. it('should check ng-class-odd and ng-class-even', function() {
  21761. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  21762. toMatch(/odd/);
  21763. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  21764. toMatch(/even/);
  21765. });
  21766. </file>
  21767. </example>
  21768. */
  21769. var ngClassOddDirective = classDirective('Odd', 0);
  21770. /**
  21771. * @ngdoc directive
  21772. * @name ngClassEven
  21773. * @restrict AC
  21774. *
  21775. * @description
  21776. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  21777. * {@link ng.directive:ngClass ngClass}, except they work in
  21778. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  21779. *
  21780. * This directive can be applied only within the scope of an
  21781. * {@link ng.directive:ngRepeat ngRepeat}.
  21782. *
  21783. * @element ANY
  21784. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  21785. * result of the evaluation can be a string representing space delimited class names or an array.
  21786. *
  21787. * @example
  21788. <example>
  21789. <file name="index.html">
  21790. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  21791. <li ng-repeat="name in names">
  21792. <span ng-class-odd="'odd'" ng-class-even="'even'">
  21793. {{name}} &nbsp; &nbsp; &nbsp;
  21794. </span>
  21795. </li>
  21796. </ol>
  21797. </file>
  21798. <file name="style.css">
  21799. .odd {
  21800. color: red;
  21801. }
  21802. .even {
  21803. color: blue;
  21804. }
  21805. </file>
  21806. <file name="protractor.js" type="protractor">
  21807. it('should check ng-class-odd and ng-class-even', function() {
  21808. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  21809. toMatch(/odd/);
  21810. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  21811. toMatch(/even/);
  21812. });
  21813. </file>
  21814. </example>
  21815. */
  21816. var ngClassEvenDirective = classDirective('Even', 1);
  21817. /**
  21818. * @ngdoc directive
  21819. * @name ngCloak
  21820. * @restrict AC
  21821. *
  21822. * @description
  21823. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  21824. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  21825. * directive to avoid the undesirable flicker effect caused by the html template display.
  21826. *
  21827. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  21828. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  21829. * of the browser view.
  21830. *
  21831. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  21832. * `angular.min.js`.
  21833. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  21834. *
  21835. * ```css
  21836. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  21837. * display: none !important;
  21838. * }
  21839. * ```
  21840. *
  21841. * When this css rule is loaded by the browser, all html elements (including their children) that
  21842. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  21843. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  21844. * the compiled element visible.
  21845. *
  21846. * For the best result, the `angular.js` script must be loaded in the head section of the html
  21847. * document; alternatively, the css rule above must be included in the external stylesheet of the
  21848. * application.
  21849. *
  21850. * @element ANY
  21851. *
  21852. * @example
  21853. <example>
  21854. <file name="index.html">
  21855. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  21856. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  21857. </file>
  21858. <file name="protractor.js" type="protractor">
  21859. it('should remove the template directive and css class', function() {
  21860. expect($('#template1').getAttribute('ng-cloak')).
  21861. toBeNull();
  21862. expect($('#template2').getAttribute('ng-cloak')).
  21863. toBeNull();
  21864. });
  21865. </file>
  21866. </example>
  21867. *
  21868. */
  21869. var ngCloakDirective = ngDirective({
  21870. compile: function(element, attr) {
  21871. attr.$set('ngCloak', undefined);
  21872. element.removeClass('ng-cloak');
  21873. }
  21874. });
  21875. /**
  21876. * @ngdoc directive
  21877. * @name ngController
  21878. *
  21879. * @description
  21880. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  21881. * supports the principles behind the Model-View-Controller design pattern.
  21882. *
  21883. * MVC components in angular:
  21884. *
  21885. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  21886. * are accessed through bindings.
  21887. * * View — The template (HTML with data bindings) that is rendered into the View.
  21888. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  21889. * logic behind the application to decorate the scope with functions and values
  21890. *
  21891. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  21892. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  21893. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  21894. * and executed twice.
  21895. *
  21896. * @element ANY
  21897. * @scope
  21898. * @priority 500
  21899. * @param {expression} ngController Name of a constructor function registered with the current
  21900. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  21901. * that on the current scope evaluates to a constructor function.
  21902. *
  21903. * The controller instance can be published into a scope property by specifying
  21904. * `ng-controller="as propertyName"`.
  21905. *
  21906. * If the current `$controllerProvider` is configured to use globals (via
  21907. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  21908. * also be the name of a globally accessible constructor function (not recommended).
  21909. *
  21910. * @example
  21911. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  21912. * greeting are methods declared on the controller (see source tab). These methods can
  21913. * easily be called from the angular markup. Any changes to the data are automatically reflected
  21914. * in the View without the need for a manual update.
  21915. *
  21916. * Two different declaration styles are included below:
  21917. *
  21918. * * one binds methods and properties directly onto the controller using `this`:
  21919. * `ng-controller="SettingsController1 as settings"`
  21920. * * one injects `$scope` into the controller:
  21921. * `ng-controller="SettingsController2"`
  21922. *
  21923. * The second option is more common in the Angular community, and is generally used in boilerplates
  21924. * and in this guide. However, there are advantages to binding properties directly to the controller
  21925. * and avoiding scope.
  21926. *
  21927. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  21928. * multiple controllers apply to an element.
  21929. * * If you are writing your controllers as classes you have easier access to the properties and
  21930. * methods, which will appear on the scope, from inside the controller code.
  21931. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  21932. * inheritance masking primitives.
  21933. *
  21934. * This example demonstrates the `controller as` syntax.
  21935. *
  21936. * <example name="ngControllerAs" module="controllerAsExample">
  21937. * <file name="index.html">
  21938. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  21939. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  21940. * <button ng-click="settings.greet()">greet</button><br/>
  21941. * Contact:
  21942. * <ul>
  21943. * <li ng-repeat="contact in settings.contacts">
  21944. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  21945. * <option>phone</option>
  21946. * <option>email</option>
  21947. * </select>
  21948. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  21949. * <button ng-click="settings.clearContact(contact)">clear</button>
  21950. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  21951. * </li>
  21952. * <li><button ng-click="settings.addContact()">add</button></li>
  21953. * </ul>
  21954. * </div>
  21955. * </file>
  21956. * <file name="app.js">
  21957. * angular.module('controllerAsExample', [])
  21958. * .controller('SettingsController1', SettingsController1);
  21959. *
  21960. * function SettingsController1() {
  21961. * this.name = "John Smith";
  21962. * this.contacts = [
  21963. * {type: 'phone', value: '408 555 1212'},
  21964. * {type: 'email', value: 'john.smith@example.org'} ];
  21965. * }
  21966. *
  21967. * SettingsController1.prototype.greet = function() {
  21968. * alert(this.name);
  21969. * };
  21970. *
  21971. * SettingsController1.prototype.addContact = function() {
  21972. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  21973. * };
  21974. *
  21975. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  21976. * var index = this.contacts.indexOf(contactToRemove);
  21977. * this.contacts.splice(index, 1);
  21978. * };
  21979. *
  21980. * SettingsController1.prototype.clearContact = function(contact) {
  21981. * contact.type = 'phone';
  21982. * contact.value = '';
  21983. * };
  21984. * </file>
  21985. * <file name="protractor.js" type="protractor">
  21986. * it('should check controller as', function() {
  21987. * var container = element(by.id('ctrl-as-exmpl'));
  21988. * expect(container.element(by.model('settings.name'))
  21989. * .getAttribute('value')).toBe('John Smith');
  21990. *
  21991. * var firstRepeat =
  21992. * container.element(by.repeater('contact in settings.contacts').row(0));
  21993. * var secondRepeat =
  21994. * container.element(by.repeater('contact in settings.contacts').row(1));
  21995. *
  21996. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  21997. * .toBe('408 555 1212');
  21998. *
  21999. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  22000. * .toBe('john.smith@example.org');
  22001. *
  22002. * firstRepeat.element(by.buttonText('clear')).click();
  22003. *
  22004. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  22005. * .toBe('');
  22006. *
  22007. * container.element(by.buttonText('add')).click();
  22008. *
  22009. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  22010. * .element(by.model('contact.value'))
  22011. * .getAttribute('value'))
  22012. * .toBe('yourname@example.org');
  22013. * });
  22014. * </file>
  22015. * </example>
  22016. *
  22017. * This example demonstrates the "attach to `$scope`" style of controller.
  22018. *
  22019. * <example name="ngController" module="controllerExample">
  22020. * <file name="index.html">
  22021. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  22022. * <label>Name: <input type="text" ng-model="name"/></label>
  22023. * <button ng-click="greet()">greet</button><br/>
  22024. * Contact:
  22025. * <ul>
  22026. * <li ng-repeat="contact in contacts">
  22027. * <select ng-model="contact.type" id="select_{{$index}}">
  22028. * <option>phone</option>
  22029. * <option>email</option>
  22030. * </select>
  22031. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  22032. * <button ng-click="clearContact(contact)">clear</button>
  22033. * <button ng-click="removeContact(contact)">X</button>
  22034. * </li>
  22035. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  22036. * </ul>
  22037. * </div>
  22038. * </file>
  22039. * <file name="app.js">
  22040. * angular.module('controllerExample', [])
  22041. * .controller('SettingsController2', ['$scope', SettingsController2]);
  22042. *
  22043. * function SettingsController2($scope) {
  22044. * $scope.name = "John Smith";
  22045. * $scope.contacts = [
  22046. * {type:'phone', value:'408 555 1212'},
  22047. * {type:'email', value:'john.smith@example.org'} ];
  22048. *
  22049. * $scope.greet = function() {
  22050. * alert($scope.name);
  22051. * };
  22052. *
  22053. * $scope.addContact = function() {
  22054. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  22055. * };
  22056. *
  22057. * $scope.removeContact = function(contactToRemove) {
  22058. * var index = $scope.contacts.indexOf(contactToRemove);
  22059. * $scope.contacts.splice(index, 1);
  22060. * };
  22061. *
  22062. * $scope.clearContact = function(contact) {
  22063. * contact.type = 'phone';
  22064. * contact.value = '';
  22065. * };
  22066. * }
  22067. * </file>
  22068. * <file name="protractor.js" type="protractor">
  22069. * it('should check controller', function() {
  22070. * var container = element(by.id('ctrl-exmpl'));
  22071. *
  22072. * expect(container.element(by.model('name'))
  22073. * .getAttribute('value')).toBe('John Smith');
  22074. *
  22075. * var firstRepeat =
  22076. * container.element(by.repeater('contact in contacts').row(0));
  22077. * var secondRepeat =
  22078. * container.element(by.repeater('contact in contacts').row(1));
  22079. *
  22080. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  22081. * .toBe('408 555 1212');
  22082. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  22083. * .toBe('john.smith@example.org');
  22084. *
  22085. * firstRepeat.element(by.buttonText('clear')).click();
  22086. *
  22087. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  22088. * .toBe('');
  22089. *
  22090. * container.element(by.buttonText('add')).click();
  22091. *
  22092. * expect(container.element(by.repeater('contact in contacts').row(2))
  22093. * .element(by.model('contact.value'))
  22094. * .getAttribute('value'))
  22095. * .toBe('yourname@example.org');
  22096. * });
  22097. * </file>
  22098. *</example>
  22099. */
  22100. var ngControllerDirective = [function() {
  22101. return {
  22102. restrict: 'A',
  22103. scope: true,
  22104. controller: '@',
  22105. priority: 500
  22106. };
  22107. }];
  22108. /**
  22109. * @ngdoc directive
  22110. * @name ngCsp
  22111. *
  22112. * @element html
  22113. * @description
  22114. *
  22115. * Angular has some features that can break certain
  22116. * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
  22117. *
  22118. * If you intend to implement these rules then you must tell Angular not to use these features.
  22119. *
  22120. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  22121. *
  22122. *
  22123. * The following rules affect Angular:
  22124. *
  22125. * * `unsafe-eval`: this rule forbids apps to use `eval` or `Function(string)` generated functions
  22126. * (among other things). Angular makes use of this in the {@link $parse} service to provide a 30%
  22127. * increase in the speed of evaluating Angular expressions.
  22128. *
  22129. * * `unsafe-inline`: this rule forbids apps from inject custom styles into the document. Angular
  22130. * makes use of this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}).
  22131. * To make these directives work when a CSP rule is blocking inline styles, you must link to the
  22132. * `angular-csp.css` in your HTML manually.
  22133. *
  22134. * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking unsafe-eval
  22135. * and automatically deactivates this feature in the {@link $parse} service. This autodetection,
  22136. * however, triggers a CSP error to be logged in the console:
  22137. *
  22138. * ```
  22139. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  22140. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  22141. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  22142. * ```
  22143. *
  22144. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  22145. * directive on an element of the HTML document that appears before the `<script>` tag that loads
  22146. * the `angular.js` file.
  22147. *
  22148. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  22149. *
  22150. * You can specify which of the CSP related Angular features should be deactivated by providing
  22151. * a value for the `ng-csp` attribute. The options are as follows:
  22152. *
  22153. * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
  22154. *
  22155. * * no-unsafe-eval: this stops Angular from optimizing $parse with unsafe eval of strings
  22156. *
  22157. * You can use these values in the following combinations:
  22158. *
  22159. *
  22160. * * No declaration means that Angular will assume that you can do inline styles, but it will do
  22161. * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous versions
  22162. * of Angular.
  22163. *
  22164. * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
  22165. * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous versions
  22166. * of Angular.
  22167. *
  22168. * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can inject
  22169. * inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
  22170. *
  22171. * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
  22172. * run eval - no automatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
  22173. *
  22174. * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
  22175. * styles nor use eval, which is the same as an empty: ng-csp.
  22176. * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
  22177. *
  22178. * @example
  22179. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  22180. ```html
  22181. <!doctype html>
  22182. <html ng-app ng-csp>
  22183. ...
  22184. ...
  22185. </html>
  22186. ```
  22187. * @example
  22188. // Note: the suffix `.csp` in the example name triggers
  22189. // csp mode in our http server!
  22190. <example name="example.csp" module="cspExample" ng-csp="true">
  22191. <file name="index.html">
  22192. <div ng-controller="MainController as ctrl">
  22193. <div>
  22194. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  22195. <span id="counter">
  22196. {{ctrl.counter}}
  22197. </span>
  22198. </div>
  22199. <div>
  22200. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  22201. <span id="evilError">
  22202. {{ctrl.evilError}}
  22203. </span>
  22204. </div>
  22205. </div>
  22206. </file>
  22207. <file name="script.js">
  22208. angular.module('cspExample', [])
  22209. .controller('MainController', function() {
  22210. this.counter = 0;
  22211. this.inc = function() {
  22212. this.counter++;
  22213. };
  22214. this.evil = function() {
  22215. // jshint evil:true
  22216. try {
  22217. eval('1+2');
  22218. } catch (e) {
  22219. this.evilError = e.message;
  22220. }
  22221. };
  22222. });
  22223. </file>
  22224. <file name="protractor.js" type="protractor">
  22225. var util, webdriver;
  22226. var incBtn = element(by.id('inc'));
  22227. var counter = element(by.id('counter'));
  22228. var evilBtn = element(by.id('evil'));
  22229. var evilError = element(by.id('evilError'));
  22230. function getAndClearSevereErrors() {
  22231. return browser.manage().logs().get('browser').then(function(browserLog) {
  22232. return browserLog.filter(function(logEntry) {
  22233. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  22234. });
  22235. });
  22236. }
  22237. function clearErrors() {
  22238. getAndClearSevereErrors();
  22239. }
  22240. function expectNoErrors() {
  22241. getAndClearSevereErrors().then(function(filteredLog) {
  22242. expect(filteredLog.length).toEqual(0);
  22243. if (filteredLog.length) {
  22244. console.log('browser console errors: ' + util.inspect(filteredLog));
  22245. }
  22246. });
  22247. }
  22248. function expectError(regex) {
  22249. getAndClearSevereErrors().then(function(filteredLog) {
  22250. var found = false;
  22251. filteredLog.forEach(function(log) {
  22252. if (log.message.match(regex)) {
  22253. found = true;
  22254. }
  22255. });
  22256. if (!found) {
  22257. throw new Error('expected an error that matches ' + regex);
  22258. }
  22259. });
  22260. }
  22261. beforeEach(function() {
  22262. util = require('util');
  22263. webdriver = require('protractor/node_modules/selenium-webdriver');
  22264. });
  22265. // For now, we only test on Chrome,
  22266. // as Safari does not load the page with Protractor's injected scripts,
  22267. // and Firefox webdriver always disables content security policy (#6358)
  22268. if (browser.params.browser !== 'chrome') {
  22269. return;
  22270. }
  22271. it('should not report errors when the page is loaded', function() {
  22272. // clear errors so we are not dependent on previous tests
  22273. clearErrors();
  22274. // Need to reload the page as the page is already loaded when
  22275. // we come here
  22276. browser.driver.getCurrentUrl().then(function(url) {
  22277. browser.get(url);
  22278. });
  22279. expectNoErrors();
  22280. });
  22281. it('should evaluate expressions', function() {
  22282. expect(counter.getText()).toEqual('0');
  22283. incBtn.click();
  22284. expect(counter.getText()).toEqual('1');
  22285. expectNoErrors();
  22286. });
  22287. it('should throw and report an error when using "eval"', function() {
  22288. evilBtn.click();
  22289. expect(evilError.getText()).toMatch(/Content Security Policy/);
  22290. expectError(/Content Security Policy/);
  22291. });
  22292. </file>
  22293. </example>
  22294. */
  22295. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  22296. // bootstrap the system (before $parse is instantiated), for this reason we just have
  22297. // the csp() fn that looks for the `ng-csp` attribute anywhere in the current doc
  22298. /**
  22299. * @ngdoc directive
  22300. * @name ngClick
  22301. *
  22302. * @description
  22303. * The ngClick directive allows you to specify custom behavior when
  22304. * an element is clicked.
  22305. *
  22306. * @element ANY
  22307. * @priority 0
  22308. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  22309. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  22310. *
  22311. * @example
  22312. <example>
  22313. <file name="index.html">
  22314. <button ng-click="count = count + 1" ng-init="count=0">
  22315. Increment
  22316. </button>
  22317. <span>
  22318. count: {{count}}
  22319. </span>
  22320. </file>
  22321. <file name="protractor.js" type="protractor">
  22322. it('should check ng-click', function() {
  22323. expect(element(by.binding('count')).getText()).toMatch('0');
  22324. element(by.css('button')).click();
  22325. expect(element(by.binding('count')).getText()).toMatch('1');
  22326. });
  22327. </file>
  22328. </example>
  22329. */
  22330. /*
  22331. * A collection of directives that allows creation of custom event handlers that are defined as
  22332. * angular expressions and are compiled and executed within the current scope.
  22333. */
  22334. var ngEventDirectives = {};
  22335. // For events that might fire synchronously during DOM manipulation
  22336. // we need to execute their event handlers asynchronously using $evalAsync,
  22337. // so that they are not executed in an inconsistent state.
  22338. var forceAsyncEvents = {
  22339. 'blur': true,
  22340. 'focus': true
  22341. };
  22342. forEach(
  22343. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  22344. function(eventName) {
  22345. var directiveName = directiveNormalize('ng-' + eventName);
  22346. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  22347. return {
  22348. restrict: 'A',
  22349. compile: function($element, attr) {
  22350. // We expose the powerful $event object on the scope that provides access to the Window,
  22351. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  22352. // checks at the cost of speed since event handler expressions are not executed as
  22353. // frequently as regular change detection.
  22354. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
  22355. return function ngEventHandler(scope, element) {
  22356. element.on(eventName, function(event) {
  22357. var callback = function() {
  22358. fn(scope, {$event:event});
  22359. };
  22360. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  22361. scope.$evalAsync(callback);
  22362. } else {
  22363. scope.$apply(callback);
  22364. }
  22365. });
  22366. };
  22367. }
  22368. };
  22369. }];
  22370. }
  22371. );
  22372. /**
  22373. * @ngdoc directive
  22374. * @name ngDblclick
  22375. *
  22376. * @description
  22377. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  22378. *
  22379. * @element ANY
  22380. * @priority 0
  22381. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  22382. * a dblclick. (The Event object is available as `$event`)
  22383. *
  22384. * @example
  22385. <example>
  22386. <file name="index.html">
  22387. <button ng-dblclick="count = count + 1" ng-init="count=0">
  22388. Increment (on double click)
  22389. </button>
  22390. count: {{count}}
  22391. </file>
  22392. </example>
  22393. */
  22394. /**
  22395. * @ngdoc directive
  22396. * @name ngMousedown
  22397. *
  22398. * @description
  22399. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  22400. *
  22401. * @element ANY
  22402. * @priority 0
  22403. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  22404. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  22405. *
  22406. * @example
  22407. <example>
  22408. <file name="index.html">
  22409. <button ng-mousedown="count = count + 1" ng-init="count=0">
  22410. Increment (on mouse down)
  22411. </button>
  22412. count: {{count}}
  22413. </file>
  22414. </example>
  22415. */
  22416. /**
  22417. * @ngdoc directive
  22418. * @name ngMouseup
  22419. *
  22420. * @description
  22421. * Specify custom behavior on mouseup event.
  22422. *
  22423. * @element ANY
  22424. * @priority 0
  22425. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  22426. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  22427. *
  22428. * @example
  22429. <example>
  22430. <file name="index.html">
  22431. <button ng-mouseup="count = count + 1" ng-init="count=0">
  22432. Increment (on mouse up)
  22433. </button>
  22434. count: {{count}}
  22435. </file>
  22436. </example>
  22437. */
  22438. /**
  22439. * @ngdoc directive
  22440. * @name ngMouseover
  22441. *
  22442. * @description
  22443. * Specify custom behavior on mouseover event.
  22444. *
  22445. * @element ANY
  22446. * @priority 0
  22447. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  22448. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  22449. *
  22450. * @example
  22451. <example>
  22452. <file name="index.html">
  22453. <button ng-mouseover="count = count + 1" ng-init="count=0">
  22454. Increment (when mouse is over)
  22455. </button>
  22456. count: {{count}}
  22457. </file>
  22458. </example>
  22459. */
  22460. /**
  22461. * @ngdoc directive
  22462. * @name ngMouseenter
  22463. *
  22464. * @description
  22465. * Specify custom behavior on mouseenter event.
  22466. *
  22467. * @element ANY
  22468. * @priority 0
  22469. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  22470. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  22471. *
  22472. * @example
  22473. <example>
  22474. <file name="index.html">
  22475. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  22476. Increment (when mouse enters)
  22477. </button>
  22478. count: {{count}}
  22479. </file>
  22480. </example>
  22481. */
  22482. /**
  22483. * @ngdoc directive
  22484. * @name ngMouseleave
  22485. *
  22486. * @description
  22487. * Specify custom behavior on mouseleave event.
  22488. *
  22489. * @element ANY
  22490. * @priority 0
  22491. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  22492. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  22493. *
  22494. * @example
  22495. <example>
  22496. <file name="index.html">
  22497. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  22498. Increment (when mouse leaves)
  22499. </button>
  22500. count: {{count}}
  22501. </file>
  22502. </example>
  22503. */
  22504. /**
  22505. * @ngdoc directive
  22506. * @name ngMousemove
  22507. *
  22508. * @description
  22509. * Specify custom behavior on mousemove event.
  22510. *
  22511. * @element ANY
  22512. * @priority 0
  22513. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  22514. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  22515. *
  22516. * @example
  22517. <example>
  22518. <file name="index.html">
  22519. <button ng-mousemove="count = count + 1" ng-init="count=0">
  22520. Increment (when mouse moves)
  22521. </button>
  22522. count: {{count}}
  22523. </file>
  22524. </example>
  22525. */
  22526. /**
  22527. * @ngdoc directive
  22528. * @name ngKeydown
  22529. *
  22530. * @description
  22531. * Specify custom behavior on keydown event.
  22532. *
  22533. * @element ANY
  22534. * @priority 0
  22535. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  22536. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  22537. *
  22538. * @example
  22539. <example>
  22540. <file name="index.html">
  22541. <input ng-keydown="count = count + 1" ng-init="count=0">
  22542. key down count: {{count}}
  22543. </file>
  22544. </example>
  22545. */
  22546. /**
  22547. * @ngdoc directive
  22548. * @name ngKeyup
  22549. *
  22550. * @description
  22551. * Specify custom behavior on keyup event.
  22552. *
  22553. * @element ANY
  22554. * @priority 0
  22555. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  22556. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  22557. *
  22558. * @example
  22559. <example>
  22560. <file name="index.html">
  22561. <p>Typing in the input box below updates the key count</p>
  22562. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  22563. <p>Typing in the input box below updates the keycode</p>
  22564. <input ng-keyup="event=$event">
  22565. <p>event keyCode: {{ event.keyCode }}</p>
  22566. <p>event altKey: {{ event.altKey }}</p>
  22567. </file>
  22568. </example>
  22569. */
  22570. /**
  22571. * @ngdoc directive
  22572. * @name ngKeypress
  22573. *
  22574. * @description
  22575. * Specify custom behavior on keypress event.
  22576. *
  22577. * @element ANY
  22578. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  22579. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  22580. * and can be interrogated for keyCode, altKey, etc.)
  22581. *
  22582. * @example
  22583. <example>
  22584. <file name="index.html">
  22585. <input ng-keypress="count = count + 1" ng-init="count=0">
  22586. key press count: {{count}}
  22587. </file>
  22588. </example>
  22589. */
  22590. /**
  22591. * @ngdoc directive
  22592. * @name ngSubmit
  22593. *
  22594. * @description
  22595. * Enables binding angular expressions to onsubmit events.
  22596. *
  22597. * Additionally it prevents the default action (which for form means sending the request to the
  22598. * server and reloading the current page), but only if the form does not contain `action`,
  22599. * `data-action`, or `x-action` attributes.
  22600. *
  22601. * <div class="alert alert-warning">
  22602. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  22603. * `ngSubmit` handlers together. See the
  22604. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  22605. * for a detailed discussion of when `ngSubmit` may be triggered.
  22606. * </div>
  22607. *
  22608. * @element form
  22609. * @priority 0
  22610. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  22611. * ({@link guide/expression#-event- Event object is available as `$event`})
  22612. *
  22613. * @example
  22614. <example module="submitExample">
  22615. <file name="index.html">
  22616. <script>
  22617. angular.module('submitExample', [])
  22618. .controller('ExampleController', ['$scope', function($scope) {
  22619. $scope.list = [];
  22620. $scope.text = 'hello';
  22621. $scope.submit = function() {
  22622. if ($scope.text) {
  22623. $scope.list.push(this.text);
  22624. $scope.text = '';
  22625. }
  22626. };
  22627. }]);
  22628. </script>
  22629. <form ng-submit="submit()" ng-controller="ExampleController">
  22630. Enter text and hit enter:
  22631. <input type="text" ng-model="text" name="text" />
  22632. <input type="submit" id="submit" value="Submit" />
  22633. <pre>list={{list}}</pre>
  22634. </form>
  22635. </file>
  22636. <file name="protractor.js" type="protractor">
  22637. it('should check ng-submit', function() {
  22638. expect(element(by.binding('list')).getText()).toBe('list=[]');
  22639. element(by.css('#submit')).click();
  22640. expect(element(by.binding('list')).getText()).toContain('hello');
  22641. expect(element(by.model('text')).getAttribute('value')).toBe('');
  22642. });
  22643. it('should ignore empty strings', function() {
  22644. expect(element(by.binding('list')).getText()).toBe('list=[]');
  22645. element(by.css('#submit')).click();
  22646. element(by.css('#submit')).click();
  22647. expect(element(by.binding('list')).getText()).toContain('hello');
  22648. });
  22649. </file>
  22650. </example>
  22651. */
  22652. /**
  22653. * @ngdoc directive
  22654. * @name ngFocus
  22655. *
  22656. * @description
  22657. * Specify custom behavior on focus event.
  22658. *
  22659. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  22660. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  22661. * during an `$apply` to ensure a consistent state.
  22662. *
  22663. * @element window, input, select, textarea, a
  22664. * @priority 0
  22665. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  22666. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  22667. *
  22668. * @example
  22669. * See {@link ng.directive:ngClick ngClick}
  22670. */
  22671. /**
  22672. * @ngdoc directive
  22673. * @name ngBlur
  22674. *
  22675. * @description
  22676. * Specify custom behavior on blur event.
  22677. *
  22678. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  22679. * an element has lost focus.
  22680. *
  22681. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  22682. * (e.g. removing a focussed input),
  22683. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  22684. * during an `$apply` to ensure a consistent state.
  22685. *
  22686. * @element window, input, select, textarea, a
  22687. * @priority 0
  22688. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  22689. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  22690. *
  22691. * @example
  22692. * See {@link ng.directive:ngClick ngClick}
  22693. */
  22694. /**
  22695. * @ngdoc directive
  22696. * @name ngCopy
  22697. *
  22698. * @description
  22699. * Specify custom behavior on copy event.
  22700. *
  22701. * @element window, input, select, textarea, a
  22702. * @priority 0
  22703. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  22704. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  22705. *
  22706. * @example
  22707. <example>
  22708. <file name="index.html">
  22709. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  22710. copied: {{copied}}
  22711. </file>
  22712. </example>
  22713. */
  22714. /**
  22715. * @ngdoc directive
  22716. * @name ngCut
  22717. *
  22718. * @description
  22719. * Specify custom behavior on cut event.
  22720. *
  22721. * @element window, input, select, textarea, a
  22722. * @priority 0
  22723. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  22724. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  22725. *
  22726. * @example
  22727. <example>
  22728. <file name="index.html">
  22729. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  22730. cut: {{cut}}
  22731. </file>
  22732. </example>
  22733. */
  22734. /**
  22735. * @ngdoc directive
  22736. * @name ngPaste
  22737. *
  22738. * @description
  22739. * Specify custom behavior on paste event.
  22740. *
  22741. * @element window, input, select, textarea, a
  22742. * @priority 0
  22743. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  22744. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  22745. *
  22746. * @example
  22747. <example>
  22748. <file name="index.html">
  22749. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  22750. pasted: {{paste}}
  22751. </file>
  22752. </example>
  22753. */
  22754. /**
  22755. * @ngdoc directive
  22756. * @name ngIf
  22757. * @restrict A
  22758. * @multiElement
  22759. *
  22760. * @description
  22761. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  22762. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  22763. * value then the element is removed from the DOM, otherwise a clone of the
  22764. * element is reinserted into the DOM.
  22765. *
  22766. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  22767. * element in the DOM rather than changing its visibility via the `display` css property. A common
  22768. * case when this difference is significant is when using css selectors that rely on an element's
  22769. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  22770. *
  22771. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  22772. * is created when the element is restored. The scope created within `ngIf` inherits from
  22773. * its parent scope using
  22774. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  22775. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  22776. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  22777. * variable within the child scope will override (hide) the value in the parent scope.
  22778. *
  22779. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  22780. * is if an element's class attribute is directly modified after it's compiled, using something like
  22781. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  22782. * the added class will be lost because the original compiled state is used to regenerate the element.
  22783. *
  22784. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  22785. * and `leave` effects.
  22786. *
  22787. * @animations
  22788. * | Animation | Occurs |
  22789. * |----------------------------------|-------------------------------------|
  22790. * | {@link ng.$animate#enter enter} | just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container |
  22791. * | {@link ng.$animate#leave leave} | just before the `ngIf` contents are removed from the DOM |
  22792. *
  22793. * @element ANY
  22794. * @scope
  22795. * @priority 600
  22796. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  22797. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  22798. * element is added to the DOM tree.
  22799. *
  22800. * @example
  22801. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  22802. <file name="index.html">
  22803. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  22804. Show when checked:
  22805. <span ng-if="checked" class="animate-if">
  22806. This is removed when the checkbox is unchecked.
  22807. </span>
  22808. </file>
  22809. <file name="animations.css">
  22810. .animate-if {
  22811. background:white;
  22812. border:1px solid black;
  22813. padding:10px;
  22814. }
  22815. .animate-if.ng-enter, .animate-if.ng-leave {
  22816. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  22817. }
  22818. .animate-if.ng-enter,
  22819. .animate-if.ng-leave.ng-leave-active {
  22820. opacity:0;
  22821. }
  22822. .animate-if.ng-leave,
  22823. .animate-if.ng-enter.ng-enter-active {
  22824. opacity:1;
  22825. }
  22826. </file>
  22827. </example>
  22828. */
  22829. var ngIfDirective = ['$animate', function($animate) {
  22830. return {
  22831. multiElement: true,
  22832. transclude: 'element',
  22833. priority: 600,
  22834. terminal: true,
  22835. restrict: 'A',
  22836. $$tlb: true,
  22837. link: function($scope, $element, $attr, ctrl, $transclude) {
  22838. var block, childScope, previousElements;
  22839. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  22840. if (value) {
  22841. if (!childScope) {
  22842. $transclude(function(clone, newScope) {
  22843. childScope = newScope;
  22844. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  22845. // Note: We only need the first/last node of the cloned nodes.
  22846. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  22847. // by a directive with templateUrl when its template arrives.
  22848. block = {
  22849. clone: clone
  22850. };
  22851. $animate.enter(clone, $element.parent(), $element);
  22852. });
  22853. }
  22854. } else {
  22855. if (previousElements) {
  22856. previousElements.remove();
  22857. previousElements = null;
  22858. }
  22859. if (childScope) {
  22860. childScope.$destroy();
  22861. childScope = null;
  22862. }
  22863. if (block) {
  22864. previousElements = getBlockNodes(block.clone);
  22865. $animate.leave(previousElements).then(function() {
  22866. previousElements = null;
  22867. });
  22868. block = null;
  22869. }
  22870. }
  22871. });
  22872. }
  22873. };
  22874. }];
  22875. /**
  22876. * @ngdoc directive
  22877. * @name ngInclude
  22878. * @restrict ECA
  22879. *
  22880. * @description
  22881. * Fetches, compiles and includes an external HTML fragment.
  22882. *
  22883. * By default, the template URL is restricted to the same domain and protocol as the
  22884. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  22885. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  22886. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  22887. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  22888. * ng.$sce Strict Contextual Escaping}.
  22889. *
  22890. * In addition, the browser's
  22891. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  22892. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  22893. * policy may further restrict whether the template is successfully loaded.
  22894. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  22895. * access on some browsers.
  22896. *
  22897. * @animations
  22898. * | Animation | Occurs |
  22899. * |----------------------------------|-------------------------------------|
  22900. * | {@link ng.$animate#enter enter} | when the expression changes, on the new include |
  22901. * | {@link ng.$animate#leave leave} | when the expression changes, on the old include |
  22902. *
  22903. * The enter and leave animation occur concurrently.
  22904. *
  22905. * @scope
  22906. * @priority 400
  22907. *
  22908. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  22909. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  22910. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  22911. * <div class="alert alert-warning">
  22912. * **Note:** When using onload on SVG elements in IE11, the browser will try to call
  22913. * a function with the name on the window element, which will usually throw a
  22914. * "function is undefined" error. To fix this, you can instead use `data-onload` or a
  22915. * different form that {@link guide/directive#normalization matches} `onload`.
  22916. * </div>
  22917. *
  22918. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  22919. * $anchorScroll} to scroll the viewport after the content is loaded.
  22920. *
  22921. * - If the attribute is not set, disable scrolling.
  22922. * - If the attribute is set without value, enable scrolling.
  22923. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  22924. *
  22925. * @example
  22926. <example module="includeExample" deps="angular-animate.js" animations="true">
  22927. <file name="index.html">
  22928. <div ng-controller="ExampleController">
  22929. <select ng-model="template" ng-options="t.name for t in templates">
  22930. <option value="">(blank)</option>
  22931. </select>
  22932. url of the template: <code>{{template.url}}</code>
  22933. <hr/>
  22934. <div class="slide-animate-container">
  22935. <div class="slide-animate" ng-include="template.url"></div>
  22936. </div>
  22937. </div>
  22938. </file>
  22939. <file name="script.js">
  22940. angular.module('includeExample', ['ngAnimate'])
  22941. .controller('ExampleController', ['$scope', function($scope) {
  22942. $scope.templates =
  22943. [ { name: 'template1.html', url: 'template1.html'},
  22944. { name: 'template2.html', url: 'template2.html'} ];
  22945. $scope.template = $scope.templates[0];
  22946. }]);
  22947. </file>
  22948. <file name="template1.html">
  22949. Content of template1.html
  22950. </file>
  22951. <file name="template2.html">
  22952. Content of template2.html
  22953. </file>
  22954. <file name="animations.css">
  22955. .slide-animate-container {
  22956. position:relative;
  22957. background:white;
  22958. border:1px solid black;
  22959. height:40px;
  22960. overflow:hidden;
  22961. }
  22962. .slide-animate {
  22963. padding:10px;
  22964. }
  22965. .slide-animate.ng-enter, .slide-animate.ng-leave {
  22966. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  22967. position:absolute;
  22968. top:0;
  22969. left:0;
  22970. right:0;
  22971. bottom:0;
  22972. display:block;
  22973. padding:10px;
  22974. }
  22975. .slide-animate.ng-enter {
  22976. top:-50px;
  22977. }
  22978. .slide-animate.ng-enter.ng-enter-active {
  22979. top:0;
  22980. }
  22981. .slide-animate.ng-leave {
  22982. top:0;
  22983. }
  22984. .slide-animate.ng-leave.ng-leave-active {
  22985. top:50px;
  22986. }
  22987. </file>
  22988. <file name="protractor.js" type="protractor">
  22989. var templateSelect = element(by.model('template'));
  22990. var includeElem = element(by.css('[ng-include]'));
  22991. it('should load template1.html', function() {
  22992. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  22993. });
  22994. it('should load template2.html', function() {
  22995. if (browser.params.browser == 'firefox') {
  22996. // Firefox can't handle using selects
  22997. // See https://github.com/angular/protractor/issues/480
  22998. return;
  22999. }
  23000. templateSelect.click();
  23001. templateSelect.all(by.css('option')).get(2).click();
  23002. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  23003. });
  23004. it('should change to blank', function() {
  23005. if (browser.params.browser == 'firefox') {
  23006. // Firefox can't handle using selects
  23007. return;
  23008. }
  23009. templateSelect.click();
  23010. templateSelect.all(by.css('option')).get(0).click();
  23011. expect(includeElem.isPresent()).toBe(false);
  23012. });
  23013. </file>
  23014. </example>
  23015. */
  23016. /**
  23017. * @ngdoc event
  23018. * @name ngInclude#$includeContentRequested
  23019. * @eventType emit on the scope ngInclude was declared in
  23020. * @description
  23021. * Emitted every time the ngInclude content is requested.
  23022. *
  23023. * @param {Object} angularEvent Synthetic event object.
  23024. * @param {String} src URL of content to load.
  23025. */
  23026. /**
  23027. * @ngdoc event
  23028. * @name ngInclude#$includeContentLoaded
  23029. * @eventType emit on the current ngInclude scope
  23030. * @description
  23031. * Emitted every time the ngInclude content is reloaded.
  23032. *
  23033. * @param {Object} angularEvent Synthetic event object.
  23034. * @param {String} src URL of content to load.
  23035. */
  23036. /**
  23037. * @ngdoc event
  23038. * @name ngInclude#$includeContentError
  23039. * @eventType emit on the scope ngInclude was declared in
  23040. * @description
  23041. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  23042. *
  23043. * @param {Object} angularEvent Synthetic event object.
  23044. * @param {String} src URL of content to load.
  23045. */
  23046. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
  23047. function($templateRequest, $anchorScroll, $animate) {
  23048. return {
  23049. restrict: 'ECA',
  23050. priority: 400,
  23051. terminal: true,
  23052. transclude: 'element',
  23053. controller: angular.noop,
  23054. compile: function(element, attr) {
  23055. var srcExp = attr.ngInclude || attr.src,
  23056. onloadExp = attr.onload || '',
  23057. autoScrollExp = attr.autoscroll;
  23058. return function(scope, $element, $attr, ctrl, $transclude) {
  23059. var changeCounter = 0,
  23060. currentScope,
  23061. previousElement,
  23062. currentElement;
  23063. var cleanupLastIncludeContent = function() {
  23064. if (previousElement) {
  23065. previousElement.remove();
  23066. previousElement = null;
  23067. }
  23068. if (currentScope) {
  23069. currentScope.$destroy();
  23070. currentScope = null;
  23071. }
  23072. if (currentElement) {
  23073. $animate.leave(currentElement).then(function() {
  23074. previousElement = null;
  23075. });
  23076. previousElement = currentElement;
  23077. currentElement = null;
  23078. }
  23079. };
  23080. scope.$watch(srcExp, function ngIncludeWatchAction(src) {
  23081. var afterAnimation = function() {
  23082. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  23083. $anchorScroll();
  23084. }
  23085. };
  23086. var thisChangeId = ++changeCounter;
  23087. if (src) {
  23088. //set the 2nd param to true to ignore the template request error so that the inner
  23089. //contents and scope can be cleaned up.
  23090. $templateRequest(src, true).then(function(response) {
  23091. if (scope.$$destroyed) return;
  23092. if (thisChangeId !== changeCounter) return;
  23093. var newScope = scope.$new();
  23094. ctrl.template = response;
  23095. // Note: This will also link all children of ng-include that were contained in the original
  23096. // html. If that content contains controllers, ... they could pollute/change the scope.
  23097. // However, using ng-include on an element with additional content does not make sense...
  23098. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  23099. // function is called before linking the content, which would apply child
  23100. // directives to non existing elements.
  23101. var clone = $transclude(newScope, function(clone) {
  23102. cleanupLastIncludeContent();
  23103. $animate.enter(clone, null, $element).then(afterAnimation);
  23104. });
  23105. currentScope = newScope;
  23106. currentElement = clone;
  23107. currentScope.$emit('$includeContentLoaded', src);
  23108. scope.$eval(onloadExp);
  23109. }, function() {
  23110. if (scope.$$destroyed) return;
  23111. if (thisChangeId === changeCounter) {
  23112. cleanupLastIncludeContent();
  23113. scope.$emit('$includeContentError', src);
  23114. }
  23115. });
  23116. scope.$emit('$includeContentRequested', src);
  23117. } else {
  23118. cleanupLastIncludeContent();
  23119. ctrl.template = null;
  23120. }
  23121. });
  23122. };
  23123. }
  23124. };
  23125. }];
  23126. // This directive is called during the $transclude call of the first `ngInclude` directive.
  23127. // It will replace and compile the content of the element with the loaded template.
  23128. // We need this directive so that the element content is already filled when
  23129. // the link function of another directive on the same element as ngInclude
  23130. // is called.
  23131. var ngIncludeFillContentDirective = ['$compile',
  23132. function($compile) {
  23133. return {
  23134. restrict: 'ECA',
  23135. priority: -400,
  23136. require: 'ngInclude',
  23137. link: function(scope, $element, $attr, ctrl) {
  23138. if (toString.call($element[0]).match(/SVG/)) {
  23139. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  23140. // support innerHTML, so detect this here and try to generate the contents
  23141. // specially.
  23142. $element.empty();
  23143. $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
  23144. function namespaceAdaptedClone(clone) {
  23145. $element.append(clone);
  23146. }, {futureParentElement: $element});
  23147. return;
  23148. }
  23149. $element.html(ctrl.template);
  23150. $compile($element.contents())(scope);
  23151. }
  23152. };
  23153. }];
  23154. /**
  23155. * @ngdoc directive
  23156. * @name ngInit
  23157. * @restrict AC
  23158. *
  23159. * @description
  23160. * The `ngInit` directive allows you to evaluate an expression in the
  23161. * current scope.
  23162. *
  23163. * <div class="alert alert-danger">
  23164. * This directive can be abused to add unnecessary amounts of logic into your templates.
  23165. * There are only a few appropriate uses of `ngInit`, such as for aliasing special properties of
  23166. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below; and for injecting data via
  23167. * server side scripting. Besides these few cases, you should use {@link guide/controller controllers}
  23168. * rather than `ngInit` to initialize values on a scope.
  23169. * </div>
  23170. *
  23171. * <div class="alert alert-warning">
  23172. * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
  23173. * sure you have parentheses to ensure correct operator precedence:
  23174. * <pre class="prettyprint">
  23175. * `<div ng-init="test1 = ($index | toString)"></div>`
  23176. * </pre>
  23177. * </div>
  23178. *
  23179. * @priority 450
  23180. *
  23181. * @element ANY
  23182. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  23183. *
  23184. * @example
  23185. <example module="initExample">
  23186. <file name="index.html">
  23187. <script>
  23188. angular.module('initExample', [])
  23189. .controller('ExampleController', ['$scope', function($scope) {
  23190. $scope.list = [['a', 'b'], ['c', 'd']];
  23191. }]);
  23192. </script>
  23193. <div ng-controller="ExampleController">
  23194. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  23195. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  23196. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  23197. </div>
  23198. </div>
  23199. </div>
  23200. </file>
  23201. <file name="protractor.js" type="protractor">
  23202. it('should alias index positions', function() {
  23203. var elements = element.all(by.css('.example-init'));
  23204. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  23205. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  23206. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  23207. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  23208. });
  23209. </file>
  23210. </example>
  23211. */
  23212. var ngInitDirective = ngDirective({
  23213. priority: 450,
  23214. compile: function() {
  23215. return {
  23216. pre: function(scope, element, attrs) {
  23217. scope.$eval(attrs.ngInit);
  23218. }
  23219. };
  23220. }
  23221. });
  23222. /**
  23223. * @ngdoc directive
  23224. * @name ngList
  23225. *
  23226. * @description
  23227. * Text input that converts between a delimited string and an array of strings. The default
  23228. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  23229. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  23230. *
  23231. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  23232. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  23233. * list item is respected. This implies that the user of the directive is responsible for
  23234. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  23235. * tab or newline character.
  23236. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  23237. * when joining the list items back together) and whitespace around each list item is stripped
  23238. * before it is added to the model.
  23239. *
  23240. * ### Example with Validation
  23241. *
  23242. * <example name="ngList-directive" module="listExample">
  23243. * <file name="app.js">
  23244. * angular.module('listExample', [])
  23245. * .controller('ExampleController', ['$scope', function($scope) {
  23246. * $scope.names = ['morpheus', 'neo', 'trinity'];
  23247. * }]);
  23248. * </file>
  23249. * <file name="index.html">
  23250. * <form name="myForm" ng-controller="ExampleController">
  23251. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  23252. * <span role="alert">
  23253. * <span class="error" ng-show="myForm.namesInput.$error.required">
  23254. * Required!</span>
  23255. * </span>
  23256. * <br>
  23257. * <tt>names = {{names}}</tt><br/>
  23258. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  23259. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  23260. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  23261. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  23262. * </form>
  23263. * </file>
  23264. * <file name="protractor.js" type="protractor">
  23265. * var listInput = element(by.model('names'));
  23266. * var names = element(by.exactBinding('names'));
  23267. * var valid = element(by.binding('myForm.namesInput.$valid'));
  23268. * var error = element(by.css('span.error'));
  23269. *
  23270. * it('should initialize to model', function() {
  23271. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  23272. * expect(valid.getText()).toContain('true');
  23273. * expect(error.getCssValue('display')).toBe('none');
  23274. * });
  23275. *
  23276. * it('should be invalid if empty', function() {
  23277. * listInput.clear();
  23278. * listInput.sendKeys('');
  23279. *
  23280. * expect(names.getText()).toContain('');
  23281. * expect(valid.getText()).toContain('false');
  23282. * expect(error.getCssValue('display')).not.toBe('none');
  23283. * });
  23284. * </file>
  23285. * </example>
  23286. *
  23287. * ### Example - splitting on newline
  23288. * <example name="ngList-directive-newlines">
  23289. * <file name="index.html">
  23290. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  23291. * <pre>{{ list | json }}</pre>
  23292. * </file>
  23293. * <file name="protractor.js" type="protractor">
  23294. * it("should split the text by newlines", function() {
  23295. * var listInput = element(by.model('list'));
  23296. * var output = element(by.binding('list | json'));
  23297. * listInput.sendKeys('abc\ndef\nghi');
  23298. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  23299. * });
  23300. * </file>
  23301. * </example>
  23302. *
  23303. * @element input
  23304. * @param {string=} ngList optional delimiter that should be used to split the value.
  23305. */
  23306. var ngListDirective = function() {
  23307. return {
  23308. restrict: 'A',
  23309. priority: 100,
  23310. require: 'ngModel',
  23311. link: function(scope, element, attr, ctrl) {
  23312. // We want to control whitespace trimming so we use this convoluted approach
  23313. // to access the ngList attribute, which doesn't pre-trim the attribute
  23314. var ngList = element.attr(attr.$attr.ngList) || ', ';
  23315. var trimValues = attr.ngTrim !== 'false';
  23316. var separator = trimValues ? trim(ngList) : ngList;
  23317. var parse = function(viewValue) {
  23318. // If the viewValue is invalid (say required but empty) it will be `undefined`
  23319. if (isUndefined(viewValue)) return;
  23320. var list = [];
  23321. if (viewValue) {
  23322. forEach(viewValue.split(separator), function(value) {
  23323. if (value) list.push(trimValues ? trim(value) : value);
  23324. });
  23325. }
  23326. return list;
  23327. };
  23328. ctrl.$parsers.push(parse);
  23329. ctrl.$formatters.push(function(value) {
  23330. if (isArray(value)) {
  23331. return value.join(ngList);
  23332. }
  23333. return undefined;
  23334. });
  23335. // Override the standard $isEmpty because an empty array means the input is empty.
  23336. ctrl.$isEmpty = function(value) {
  23337. return !value || !value.length;
  23338. };
  23339. }
  23340. };
  23341. };
  23342. /* global VALID_CLASS: true,
  23343. INVALID_CLASS: true,
  23344. PRISTINE_CLASS: true,
  23345. DIRTY_CLASS: true,
  23346. UNTOUCHED_CLASS: true,
  23347. TOUCHED_CLASS: true,
  23348. */
  23349. var VALID_CLASS = 'ng-valid',
  23350. INVALID_CLASS = 'ng-invalid',
  23351. PRISTINE_CLASS = 'ng-pristine',
  23352. DIRTY_CLASS = 'ng-dirty',
  23353. UNTOUCHED_CLASS = 'ng-untouched',
  23354. TOUCHED_CLASS = 'ng-touched',
  23355. PENDING_CLASS = 'ng-pending',
  23356. EMPTY_CLASS = 'ng-empty',
  23357. NOT_EMPTY_CLASS = 'ng-not-empty';
  23358. var ngModelMinErr = minErr('ngModel');
  23359. /**
  23360. * @ngdoc type
  23361. * @name ngModel.NgModelController
  23362. *
  23363. * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
  23364. * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
  23365. * is set.
  23366. * @property {*} $modelValue The value in the model that the control is bound to.
  23367. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  23368. the control reads value from the DOM. The functions are called in array order, each passing
  23369. its return value through to the next. The last return value is forwarded to the
  23370. {@link ngModel.NgModelController#$validators `$validators`} collection.
  23371. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  23372. `$viewValue`}.
  23373. Returning `undefined` from a parser means a parse error occurred. In that case,
  23374. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  23375. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  23376. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  23377. *
  23378. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  23379. the model value changes. The functions are called in reverse array order, each passing the value through to the
  23380. next. The last return value is used as the actual DOM value.
  23381. Used to format / convert values for display in the control.
  23382. * ```js
  23383. * function formatter(value) {
  23384. * if (value) {
  23385. * return value.toUpperCase();
  23386. * }
  23387. * }
  23388. * ngModel.$formatters.push(formatter);
  23389. * ```
  23390. *
  23391. * @property {Object.<string, function>} $validators A collection of validators that are applied
  23392. * whenever the model value changes. The key value within the object refers to the name of the
  23393. * validator while the function refers to the validation operation. The validation operation is
  23394. * provided with the model value as an argument and must return a true or false value depending
  23395. * on the response of that validation.
  23396. *
  23397. * ```js
  23398. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  23399. * var value = modelValue || viewValue;
  23400. * return /[0-9]+/.test(value) &&
  23401. * /[a-z]+/.test(value) &&
  23402. * /[A-Z]+/.test(value) &&
  23403. * /\W+/.test(value);
  23404. * };
  23405. * ```
  23406. *
  23407. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  23408. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  23409. * is expected to return a promise when it is run during the model validation process. Once the promise
  23410. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  23411. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  23412. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  23413. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  23414. * will only run once all synchronous validators have passed.
  23415. *
  23416. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  23417. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  23418. *
  23419. * ```js
  23420. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  23421. * var value = modelValue || viewValue;
  23422. *
  23423. * // Lookup user by username
  23424. * return $http.get('/api/users/' + value).
  23425. * then(function resolved() {
  23426. * //username exists, this means validation fails
  23427. * return $q.reject('exists');
  23428. * }, function rejected() {
  23429. * //username does not exist, therefore this validation passes
  23430. * return true;
  23431. * });
  23432. * };
  23433. * ```
  23434. *
  23435. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  23436. * view value has changed. It is called with no arguments, and its return value is ignored.
  23437. * This can be used in place of additional $watches against the model value.
  23438. *
  23439. * @property {Object} $error An object hash with all failing validator ids as keys.
  23440. * @property {Object} $pending An object hash with all pending validator ids as keys.
  23441. *
  23442. * @property {boolean} $untouched True if control has not lost focus yet.
  23443. * @property {boolean} $touched True if control has lost focus.
  23444. * @property {boolean} $pristine True if user has not interacted with the control yet.
  23445. * @property {boolean} $dirty True if user has already interacted with the control.
  23446. * @property {boolean} $valid True if there is no error.
  23447. * @property {boolean} $invalid True if at least one error on the control.
  23448. * @property {string} $name The name attribute of the control.
  23449. *
  23450. * @description
  23451. *
  23452. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  23453. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  23454. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  23455. * listening to DOM events.
  23456. * Such DOM related logic should be provided by other directives which make use of
  23457. * `NgModelController` for data-binding to control elements.
  23458. * Angular provides this DOM logic for most {@link input `input`} elements.
  23459. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  23460. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  23461. *
  23462. * @example
  23463. * ### Custom Control Example
  23464. * This example shows how to use `NgModelController` with a custom control to achieve
  23465. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  23466. * collaborate together to achieve the desired result.
  23467. *
  23468. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  23469. * contents be edited in place by the user.
  23470. *
  23471. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  23472. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  23473. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  23474. * that content using the `$sce` service.
  23475. *
  23476. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  23477. <file name="style.css">
  23478. [contenteditable] {
  23479. border: 1px solid black;
  23480. background-color: white;
  23481. min-height: 20px;
  23482. }
  23483. .ng-invalid {
  23484. border: 1px solid red;
  23485. }
  23486. </file>
  23487. <file name="script.js">
  23488. angular.module('customControl', ['ngSanitize']).
  23489. directive('contenteditable', ['$sce', function($sce) {
  23490. return {
  23491. restrict: 'A', // only activate on element attribute
  23492. require: '?ngModel', // get a hold of NgModelController
  23493. link: function(scope, element, attrs, ngModel) {
  23494. if (!ngModel) return; // do nothing if no ng-model
  23495. // Specify how UI should be updated
  23496. ngModel.$render = function() {
  23497. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  23498. };
  23499. // Listen for change events to enable binding
  23500. element.on('blur keyup change', function() {
  23501. scope.$evalAsync(read);
  23502. });
  23503. read(); // initialize
  23504. // Write data to the model
  23505. function read() {
  23506. var html = element.html();
  23507. // When we clear the content editable the browser leaves a <br> behind
  23508. // If strip-br attribute is provided then we strip this out
  23509. if ( attrs.stripBr && html == '<br>' ) {
  23510. html = '';
  23511. }
  23512. ngModel.$setViewValue(html);
  23513. }
  23514. }
  23515. };
  23516. }]);
  23517. </file>
  23518. <file name="index.html">
  23519. <form name="myForm">
  23520. <div contenteditable
  23521. name="myWidget" ng-model="userContent"
  23522. strip-br="true"
  23523. required>Change me!</div>
  23524. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  23525. <hr>
  23526. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  23527. </form>
  23528. </file>
  23529. <file name="protractor.js" type="protractor">
  23530. it('should data-bind and become invalid', function() {
  23531. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  23532. // SafariDriver can't handle contenteditable
  23533. // and Firefox driver can't clear contenteditables very well
  23534. return;
  23535. }
  23536. var contentEditable = element(by.css('[contenteditable]'));
  23537. var content = 'Change me!';
  23538. expect(contentEditable.getText()).toEqual(content);
  23539. contentEditable.clear();
  23540. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  23541. expect(contentEditable.getText()).toEqual('');
  23542. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  23543. });
  23544. </file>
  23545. * </example>
  23546. *
  23547. *
  23548. */
  23549. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
  23550. function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
  23551. this.$viewValue = Number.NaN;
  23552. this.$modelValue = Number.NaN;
  23553. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  23554. this.$validators = {};
  23555. this.$asyncValidators = {};
  23556. this.$parsers = [];
  23557. this.$formatters = [];
  23558. this.$viewChangeListeners = [];
  23559. this.$untouched = true;
  23560. this.$touched = false;
  23561. this.$pristine = true;
  23562. this.$dirty = false;
  23563. this.$valid = true;
  23564. this.$invalid = false;
  23565. this.$error = {}; // keep invalid keys here
  23566. this.$$success = {}; // keep valid keys here
  23567. this.$pending = undefined; // keep pending keys here
  23568. this.$name = $interpolate($attr.name || '', false)($scope);
  23569. this.$$parentForm = nullFormCtrl;
  23570. var parsedNgModel = $parse($attr.ngModel),
  23571. parsedNgModelAssign = parsedNgModel.assign,
  23572. ngModelGet = parsedNgModel,
  23573. ngModelSet = parsedNgModelAssign,
  23574. pendingDebounce = null,
  23575. parserValid,
  23576. ctrl = this;
  23577. this.$$setOptions = function(options) {
  23578. ctrl.$options = options;
  23579. if (options && options.getterSetter) {
  23580. var invokeModelGetter = $parse($attr.ngModel + '()'),
  23581. invokeModelSetter = $parse($attr.ngModel + '($$$p)');
  23582. ngModelGet = function($scope) {
  23583. var modelValue = parsedNgModel($scope);
  23584. if (isFunction(modelValue)) {
  23585. modelValue = invokeModelGetter($scope);
  23586. }
  23587. return modelValue;
  23588. };
  23589. ngModelSet = function($scope, newValue) {
  23590. if (isFunction(parsedNgModel($scope))) {
  23591. invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
  23592. } else {
  23593. parsedNgModelAssign($scope, ctrl.$modelValue);
  23594. }
  23595. };
  23596. } else if (!parsedNgModel.assign) {
  23597. throw ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  23598. $attr.ngModel, startingTag($element));
  23599. }
  23600. };
  23601. /**
  23602. * @ngdoc method
  23603. * @name ngModel.NgModelController#$render
  23604. *
  23605. * @description
  23606. * Called when the view needs to be updated. It is expected that the user of the ng-model
  23607. * directive will implement this method.
  23608. *
  23609. * The `$render()` method is invoked in the following situations:
  23610. *
  23611. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  23612. * committed value then `$render()` is called to update the input control.
  23613. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  23614. * the `$viewValue` are different from last time.
  23615. *
  23616. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  23617. * `$modelValue` and `$viewValue` are actually different from their previous value. If `$modelValue`
  23618. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  23619. * invoked if you only change a property on the objects.
  23620. */
  23621. this.$render = noop;
  23622. /**
  23623. * @ngdoc method
  23624. * @name ngModel.NgModelController#$isEmpty
  23625. *
  23626. * @description
  23627. * This is called when we need to determine if the value of an input is empty.
  23628. *
  23629. * For instance, the required directive does this to work out if the input has data or not.
  23630. *
  23631. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  23632. *
  23633. * You can override this for input directives whose concept of being empty is different from the
  23634. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  23635. * implies empty.
  23636. *
  23637. * @param {*} value The value of the input to check for emptiness.
  23638. * @returns {boolean} True if `value` is "empty".
  23639. */
  23640. this.$isEmpty = function(value) {
  23641. return isUndefined(value) || value === '' || value === null || value !== value;
  23642. };
  23643. this.$$updateEmptyClasses = function(value) {
  23644. if (ctrl.$isEmpty(value)) {
  23645. $animate.removeClass($element, NOT_EMPTY_CLASS);
  23646. $animate.addClass($element, EMPTY_CLASS);
  23647. } else {
  23648. $animate.removeClass($element, EMPTY_CLASS);
  23649. $animate.addClass($element, NOT_EMPTY_CLASS);
  23650. }
  23651. };
  23652. var currentValidationRunId = 0;
  23653. /**
  23654. * @ngdoc method
  23655. * @name ngModel.NgModelController#$setValidity
  23656. *
  23657. * @description
  23658. * Change the validity state, and notify the form.
  23659. *
  23660. * This method can be called within $parsers/$formatters or a custom validation implementation.
  23661. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  23662. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  23663. *
  23664. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  23665. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  23666. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  23667. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  23668. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  23669. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  23670. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  23671. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  23672. * Skipped is used by Angular when validators do not run because of parse errors and
  23673. * when `$asyncValidators` do not run because any of the `$validators` failed.
  23674. */
  23675. addSetValidityMethod({
  23676. ctrl: this,
  23677. $element: $element,
  23678. set: function(object, property) {
  23679. object[property] = true;
  23680. },
  23681. unset: function(object, property) {
  23682. delete object[property];
  23683. },
  23684. $animate: $animate
  23685. });
  23686. /**
  23687. * @ngdoc method
  23688. * @name ngModel.NgModelController#$setPristine
  23689. *
  23690. * @description
  23691. * Sets the control to its pristine state.
  23692. *
  23693. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  23694. * state (`ng-pristine` class). A model is considered to be pristine when the control
  23695. * has not been changed from when first compiled.
  23696. */
  23697. this.$setPristine = function() {
  23698. ctrl.$dirty = false;
  23699. ctrl.$pristine = true;
  23700. $animate.removeClass($element, DIRTY_CLASS);
  23701. $animate.addClass($element, PRISTINE_CLASS);
  23702. };
  23703. /**
  23704. * @ngdoc method
  23705. * @name ngModel.NgModelController#$setDirty
  23706. *
  23707. * @description
  23708. * Sets the control to its dirty state.
  23709. *
  23710. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  23711. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  23712. * from when first compiled.
  23713. */
  23714. this.$setDirty = function() {
  23715. ctrl.$dirty = true;
  23716. ctrl.$pristine = false;
  23717. $animate.removeClass($element, PRISTINE_CLASS);
  23718. $animate.addClass($element, DIRTY_CLASS);
  23719. ctrl.$$parentForm.$setDirty();
  23720. };
  23721. /**
  23722. * @ngdoc method
  23723. * @name ngModel.NgModelController#$setUntouched
  23724. *
  23725. * @description
  23726. * Sets the control to its untouched state.
  23727. *
  23728. * This method can be called to remove the `ng-touched` class and set the control to its
  23729. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  23730. * by default, however this function can be used to restore that state if the model has
  23731. * already been touched by the user.
  23732. */
  23733. this.$setUntouched = function() {
  23734. ctrl.$touched = false;
  23735. ctrl.$untouched = true;
  23736. $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  23737. };
  23738. /**
  23739. * @ngdoc method
  23740. * @name ngModel.NgModelController#$setTouched
  23741. *
  23742. * @description
  23743. * Sets the control to its touched state.
  23744. *
  23745. * This method can be called to remove the `ng-untouched` class and set the control to its
  23746. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  23747. * first focused the control element and then shifted focus away from the control (blur event).
  23748. */
  23749. this.$setTouched = function() {
  23750. ctrl.$touched = true;
  23751. ctrl.$untouched = false;
  23752. $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  23753. };
  23754. /**
  23755. * @ngdoc method
  23756. * @name ngModel.NgModelController#$rollbackViewValue
  23757. *
  23758. * @description
  23759. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  23760. * which may be caused by a pending debounced event or because the input is waiting for a some
  23761. * future event.
  23762. *
  23763. * If you have an input that uses `ng-model-options` to set up debounced updates or updates that
  23764. * depend on special events such as blur, you can have a situation where there is a period when
  23765. * the `$viewValue` is out of sync with the ngModel's `$modelValue`.
  23766. *
  23767. * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update
  23768. * and reset the input to the last committed view value.
  23769. *
  23770. * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`
  23771. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  23772. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  23773. *
  23774. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  23775. * input which may have such events pending. This is important in order to make sure that the
  23776. * input field will be updated with the new model value and any pending operations are cancelled.
  23777. *
  23778. * <example name="ng-model-cancel-update" module="cancel-update-example">
  23779. * <file name="app.js">
  23780. * angular.module('cancel-update-example', [])
  23781. *
  23782. * .controller('CancelUpdateController', ['$scope', function($scope) {
  23783. * $scope.model = {};
  23784. *
  23785. * $scope.setEmpty = function(e, value, rollback) {
  23786. * if (e.keyCode == 27) {
  23787. * e.preventDefault();
  23788. * if (rollback) {
  23789. * $scope.myForm[value].$rollbackViewValue();
  23790. * }
  23791. * $scope.model[value] = '';
  23792. * }
  23793. * };
  23794. * }]);
  23795. * </file>
  23796. * <file name="index.html">
  23797. * <div ng-controller="CancelUpdateController">
  23798. * <p>Both of these inputs are only updated if they are blurred. Hitting escape should
  23799. * empty them. Follow these steps and observe the difference:</p>
  23800. * <ol>
  23801. * <li>Type something in the input. You will see that the model is not yet updated</li>
  23802. * <li>Press the Escape key.
  23803. * <ol>
  23804. * <li> In the first example, nothing happens, because the model is already '', and no
  23805. * update is detected. If you blur the input, the model will be set to the current view.
  23806. * </li>
  23807. * <li> In the second example, the pending update is cancelled, and the input is set back
  23808. * to the last committed view value (''). Blurring the input does nothing.
  23809. * </li>
  23810. * </ol>
  23811. * </li>
  23812. * </ol>
  23813. *
  23814. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  23815. * <div>
  23816. * <p id="inputDescription1">Without $rollbackViewValue():</p>
  23817. * <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1"
  23818. * ng-keydown="setEmpty($event, 'value1')">
  23819. * value1: "{{ model.value1 }}"
  23820. * </div>
  23821. *
  23822. * <div>
  23823. * <p id="inputDescription2">With $rollbackViewValue():</p>
  23824. * <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2"
  23825. * ng-keydown="setEmpty($event, 'value2', true)">
  23826. * value2: "{{ model.value2 }}"
  23827. * </div>
  23828. * </form>
  23829. * </div>
  23830. * </file>
  23831. <file name="style.css">
  23832. div {
  23833. display: table-cell;
  23834. }
  23835. div:nth-child(1) {
  23836. padding-right: 30px;
  23837. }
  23838. </file>
  23839. * </example>
  23840. */
  23841. this.$rollbackViewValue = function() {
  23842. $timeout.cancel(pendingDebounce);
  23843. ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
  23844. ctrl.$render();
  23845. };
  23846. /**
  23847. * @ngdoc method
  23848. * @name ngModel.NgModelController#$validate
  23849. *
  23850. * @description
  23851. * Runs each of the registered validators (first synchronous validators and then
  23852. * asynchronous validators).
  23853. * If the validity changes to invalid, the model will be set to `undefined`,
  23854. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  23855. * If the validity changes to valid, it will set the model to the last available valid
  23856. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  23857. */
  23858. this.$validate = function() {
  23859. // ignore $validate before model is initialized
  23860. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  23861. return;
  23862. }
  23863. var viewValue = ctrl.$$lastCommittedViewValue;
  23864. // Note: we use the $$rawModelValue as $modelValue might have been
  23865. // set to undefined during a view -> model update that found validation
  23866. // errors. We can't parse the view here, since that could change
  23867. // the model although neither viewValue nor the model on the scope changed
  23868. var modelValue = ctrl.$$rawModelValue;
  23869. var prevValid = ctrl.$valid;
  23870. var prevModelValue = ctrl.$modelValue;
  23871. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  23872. ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
  23873. // If there was no change in validity, don't update the model
  23874. // This prevents changing an invalid modelValue to undefined
  23875. if (!allowInvalid && prevValid !== allValid) {
  23876. // Note: Don't check ctrl.$valid here, as we could have
  23877. // external validators (e.g. calculated on the server),
  23878. // that just call $setValidity and need the model value
  23879. // to calculate their validity.
  23880. ctrl.$modelValue = allValid ? modelValue : undefined;
  23881. if (ctrl.$modelValue !== prevModelValue) {
  23882. ctrl.$$writeModelToScope();
  23883. }
  23884. }
  23885. });
  23886. };
  23887. this.$$runValidators = function(modelValue, viewValue, doneCallback) {
  23888. currentValidationRunId++;
  23889. var localValidationRunId = currentValidationRunId;
  23890. // check parser error
  23891. if (!processParseErrors()) {
  23892. validationDone(false);
  23893. return;
  23894. }
  23895. if (!processSyncValidators()) {
  23896. validationDone(false);
  23897. return;
  23898. }
  23899. processAsyncValidators();
  23900. function processParseErrors() {
  23901. var errorKey = ctrl.$$parserName || 'parse';
  23902. if (isUndefined(parserValid)) {
  23903. setValidity(errorKey, null);
  23904. } else {
  23905. if (!parserValid) {
  23906. forEach(ctrl.$validators, function(v, name) {
  23907. setValidity(name, null);
  23908. });
  23909. forEach(ctrl.$asyncValidators, function(v, name) {
  23910. setValidity(name, null);
  23911. });
  23912. }
  23913. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  23914. setValidity(errorKey, parserValid);
  23915. return parserValid;
  23916. }
  23917. return true;
  23918. }
  23919. function processSyncValidators() {
  23920. var syncValidatorsValid = true;
  23921. forEach(ctrl.$validators, function(validator, name) {
  23922. var result = validator(modelValue, viewValue);
  23923. syncValidatorsValid = syncValidatorsValid && result;
  23924. setValidity(name, result);
  23925. });
  23926. if (!syncValidatorsValid) {
  23927. forEach(ctrl.$asyncValidators, function(v, name) {
  23928. setValidity(name, null);
  23929. });
  23930. return false;
  23931. }
  23932. return true;
  23933. }
  23934. function processAsyncValidators() {
  23935. var validatorPromises = [];
  23936. var allValid = true;
  23937. forEach(ctrl.$asyncValidators, function(validator, name) {
  23938. var promise = validator(modelValue, viewValue);
  23939. if (!isPromiseLike(promise)) {
  23940. throw ngModelMinErr('nopromise',
  23941. "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
  23942. }
  23943. setValidity(name, undefined);
  23944. validatorPromises.push(promise.then(function() {
  23945. setValidity(name, true);
  23946. }, function(error) {
  23947. allValid = false;
  23948. setValidity(name, false);
  23949. }));
  23950. });
  23951. if (!validatorPromises.length) {
  23952. validationDone(true);
  23953. } else {
  23954. $q.all(validatorPromises).then(function() {
  23955. validationDone(allValid);
  23956. }, noop);
  23957. }
  23958. }
  23959. function setValidity(name, isValid) {
  23960. if (localValidationRunId === currentValidationRunId) {
  23961. ctrl.$setValidity(name, isValid);
  23962. }
  23963. }
  23964. function validationDone(allValid) {
  23965. if (localValidationRunId === currentValidationRunId) {
  23966. doneCallback(allValid);
  23967. }
  23968. }
  23969. };
  23970. /**
  23971. * @ngdoc method
  23972. * @name ngModel.NgModelController#$commitViewValue
  23973. *
  23974. * @description
  23975. * Commit a pending update to the `$modelValue`.
  23976. *
  23977. * Updates may be pending by a debounced event or because the input is waiting for a some future
  23978. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  23979. * usually handles calling this in response to input events.
  23980. */
  23981. this.$commitViewValue = function() {
  23982. var viewValue = ctrl.$viewValue;
  23983. $timeout.cancel(pendingDebounce);
  23984. // If the view value has not changed then we should just exit, except in the case where there is
  23985. // a native validator on the element. In this case the validation state may have changed even though
  23986. // the viewValue has stayed empty.
  23987. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
  23988. return;
  23989. }
  23990. ctrl.$$updateEmptyClasses(viewValue);
  23991. ctrl.$$lastCommittedViewValue = viewValue;
  23992. // change to dirty
  23993. if (ctrl.$pristine) {
  23994. this.$setDirty();
  23995. }
  23996. this.$$parseAndValidate();
  23997. };
  23998. this.$$parseAndValidate = function() {
  23999. var viewValue = ctrl.$$lastCommittedViewValue;
  24000. var modelValue = viewValue;
  24001. parserValid = isUndefined(modelValue) ? undefined : true;
  24002. if (parserValid) {
  24003. for (var i = 0; i < ctrl.$parsers.length; i++) {
  24004. modelValue = ctrl.$parsers[i](modelValue);
  24005. if (isUndefined(modelValue)) {
  24006. parserValid = false;
  24007. break;
  24008. }
  24009. }
  24010. }
  24011. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  24012. // ctrl.$modelValue has not been touched yet...
  24013. ctrl.$modelValue = ngModelGet($scope);
  24014. }
  24015. var prevModelValue = ctrl.$modelValue;
  24016. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  24017. ctrl.$$rawModelValue = modelValue;
  24018. if (allowInvalid) {
  24019. ctrl.$modelValue = modelValue;
  24020. writeToModelIfNeeded();
  24021. }
  24022. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  24023. // This can happen if e.g. $setViewValue is called from inside a parser
  24024. ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
  24025. if (!allowInvalid) {
  24026. // Note: Don't check ctrl.$valid here, as we could have
  24027. // external validators (e.g. calculated on the server),
  24028. // that just call $setValidity and need the model value
  24029. // to calculate their validity.
  24030. ctrl.$modelValue = allValid ? modelValue : undefined;
  24031. writeToModelIfNeeded();
  24032. }
  24033. });
  24034. function writeToModelIfNeeded() {
  24035. if (ctrl.$modelValue !== prevModelValue) {
  24036. ctrl.$$writeModelToScope();
  24037. }
  24038. }
  24039. };
  24040. this.$$writeModelToScope = function() {
  24041. ngModelSet($scope, ctrl.$modelValue);
  24042. forEach(ctrl.$viewChangeListeners, function(listener) {
  24043. try {
  24044. listener();
  24045. } catch (e) {
  24046. $exceptionHandler(e);
  24047. }
  24048. });
  24049. };
  24050. /**
  24051. * @ngdoc method
  24052. * @name ngModel.NgModelController#$setViewValue
  24053. *
  24054. * @description
  24055. * Update the view value.
  24056. *
  24057. * This method should be called when a control wants to change the view value; typically,
  24058. * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
  24059. * directive calls it when the value of the input changes and {@link ng.directive:select select}
  24060. * calls it when an option is selected.
  24061. *
  24062. * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
  24063. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  24064. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  24065. * **expression** specified in the `ng-model` attribute. Lastly, all the registered change listeners,
  24066. * in the `$viewChangeListeners` list, are called.
  24067. *
  24068. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  24069. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  24070. * `updateOn` events is triggered on the DOM element.
  24071. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  24072. * directive is used with a custom debounce for this particular event.
  24073. * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
  24074. * is specified, once the timer runs out.
  24075. *
  24076. * When used with standard inputs, the view value will always be a string (which is in some cases
  24077. * parsed into another type, such as a `Date` object for `input[date]`.)
  24078. * However, custom controls might also pass objects to this method. In this case, we should make
  24079. * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
  24080. * perform a deep watch of objects, it only looks for a change of identity. If you only change
  24081. * the property of the object then ngModel will not realize that the object has changed and
  24082. * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
  24083. * not change properties of the copy once it has been passed to `$setViewValue`.
  24084. * Otherwise you may cause the model value on the scope to change incorrectly.
  24085. *
  24086. * <div class="alert alert-info">
  24087. * In any case, the value passed to the method should always reflect the current value
  24088. * of the control. For example, if you are calling `$setViewValue` for an input element,
  24089. * you should pass the input DOM value. Otherwise, the control and the scope model become
  24090. * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
  24091. * the control's DOM value in any way. If we want to change the control's DOM value
  24092. * programmatically, we should update the `ngModel` scope expression. Its new value will be
  24093. * picked up by the model controller, which will run it through the `$formatters`, `$render` it
  24094. * to update the DOM, and finally call `$validate` on it.
  24095. * </div>
  24096. *
  24097. * @param {*} value value from the view.
  24098. * @param {string} trigger Event that triggered the update.
  24099. */
  24100. this.$setViewValue = function(value, trigger) {
  24101. ctrl.$viewValue = value;
  24102. if (!ctrl.$options || ctrl.$options.updateOnDefault) {
  24103. ctrl.$$debounceViewValueCommit(trigger);
  24104. }
  24105. };
  24106. this.$$debounceViewValueCommit = function(trigger) {
  24107. var debounceDelay = 0,
  24108. options = ctrl.$options,
  24109. debounce;
  24110. if (options && isDefined(options.debounce)) {
  24111. debounce = options.debounce;
  24112. if (isNumber(debounce)) {
  24113. debounceDelay = debounce;
  24114. } else if (isNumber(debounce[trigger])) {
  24115. debounceDelay = debounce[trigger];
  24116. } else if (isNumber(debounce['default'])) {
  24117. debounceDelay = debounce['default'];
  24118. }
  24119. }
  24120. $timeout.cancel(pendingDebounce);
  24121. if (debounceDelay) {
  24122. pendingDebounce = $timeout(function() {
  24123. ctrl.$commitViewValue();
  24124. }, debounceDelay);
  24125. } else if ($rootScope.$$phase) {
  24126. ctrl.$commitViewValue();
  24127. } else {
  24128. $scope.$apply(function() {
  24129. ctrl.$commitViewValue();
  24130. });
  24131. }
  24132. };
  24133. // model -> value
  24134. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  24135. // 1. scope value is 'a'
  24136. // 2. user enters 'b'
  24137. // 3. ng-change kicks in and reverts scope value to 'a'
  24138. // -> scope value did not change since the last digest as
  24139. // ng-change executes in apply phase
  24140. // 4. view should be changed back to 'a'
  24141. $scope.$watch(function ngModelWatch() {
  24142. var modelValue = ngModelGet($scope);
  24143. // if scope model value and ngModel value are out of sync
  24144. // TODO(perf): why not move this to the action fn?
  24145. if (modelValue !== ctrl.$modelValue &&
  24146. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  24147. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  24148. ) {
  24149. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  24150. parserValid = undefined;
  24151. var formatters = ctrl.$formatters,
  24152. idx = formatters.length;
  24153. var viewValue = modelValue;
  24154. while (idx--) {
  24155. viewValue = formatters[idx](viewValue);
  24156. }
  24157. if (ctrl.$viewValue !== viewValue) {
  24158. ctrl.$$updateEmptyClasses(viewValue);
  24159. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  24160. ctrl.$render();
  24161. ctrl.$$runValidators(modelValue, viewValue, noop);
  24162. }
  24163. }
  24164. return modelValue;
  24165. });
  24166. }];
  24167. /**
  24168. * @ngdoc directive
  24169. * @name ngModel
  24170. *
  24171. * @element input
  24172. * @priority 1
  24173. *
  24174. * @description
  24175. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  24176. * property on the scope using {@link ngModel.NgModelController NgModelController},
  24177. * which is created and exposed by this directive.
  24178. *
  24179. * `ngModel` is responsible for:
  24180. *
  24181. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  24182. * require.
  24183. * - Providing validation behavior (i.e. required, number, email, url).
  24184. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  24185. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
  24186. * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
  24187. * - Registering the control with its parent {@link ng.directive:form form}.
  24188. *
  24189. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  24190. * current scope. If the property doesn't already exist on this scope, it will be created
  24191. * implicitly and added to the scope.
  24192. *
  24193. * For best practices on using `ngModel`, see:
  24194. *
  24195. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  24196. *
  24197. * For basic examples, how to use `ngModel`, see:
  24198. *
  24199. * - {@link ng.directive:input input}
  24200. * - {@link input[text] text}
  24201. * - {@link input[checkbox] checkbox}
  24202. * - {@link input[radio] radio}
  24203. * - {@link input[number] number}
  24204. * - {@link input[email] email}
  24205. * - {@link input[url] url}
  24206. * - {@link input[date] date}
  24207. * - {@link input[datetime-local] datetime-local}
  24208. * - {@link input[time] time}
  24209. * - {@link input[month] month}
  24210. * - {@link input[week] week}
  24211. * - {@link ng.directive:select select}
  24212. * - {@link ng.directive:textarea textarea}
  24213. *
  24214. * # Complex Models (objects or collections)
  24215. *
  24216. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  24217. * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the
  24218. * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered.
  24219. *
  24220. * The model must be assigned an entirely new object or collection before a re-rendering will occur.
  24221. *
  24222. * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression
  24223. * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or
  24224. * if the select is given the `multiple` attribute.
  24225. *
  24226. * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the
  24227. * first level of the object (or only changing the properties of an item in the collection if it's an array) will still
  24228. * not trigger a re-rendering of the model.
  24229. *
  24230. * # CSS classes
  24231. * The following CSS classes are added and removed on the associated input/select/textarea element
  24232. * depending on the validity of the model.
  24233. *
  24234. * - `ng-valid`: the model is valid
  24235. * - `ng-invalid`: the model is invalid
  24236. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  24237. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  24238. * - `ng-pristine`: the control hasn't been interacted with yet
  24239. * - `ng-dirty`: the control has been interacted with
  24240. * - `ng-touched`: the control has been blurred
  24241. * - `ng-untouched`: the control hasn't been blurred
  24242. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  24243. * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
  24244. * by the {@link ngModel.NgModelController#$isEmpty} method
  24245. * - `ng-not-empty`: the view contains a non-empty value
  24246. *
  24247. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  24248. *
  24249. * ## Animation Hooks
  24250. *
  24251. * Animations within models are triggered when any of the associated CSS classes are added and removed
  24252. * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
  24253. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  24254. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  24255. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  24256. *
  24257. * The following example shows a simple way to utilize CSS transitions to style an input element
  24258. * that has been rendered as invalid after it has been validated:
  24259. *
  24260. * <pre>
  24261. * //be sure to include ngAnimate as a module to hook into more
  24262. * //advanced animations
  24263. * .my-input {
  24264. * transition:0.5s linear all;
  24265. * background: white;
  24266. * }
  24267. * .my-input.ng-invalid {
  24268. * background: red;
  24269. * color:white;
  24270. * }
  24271. * </pre>
  24272. *
  24273. * @example
  24274. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  24275. <file name="index.html">
  24276. <script>
  24277. angular.module('inputExample', [])
  24278. .controller('ExampleController', ['$scope', function($scope) {
  24279. $scope.val = '1';
  24280. }]);
  24281. </script>
  24282. <style>
  24283. .my-input {
  24284. transition:all linear 0.5s;
  24285. background: transparent;
  24286. }
  24287. .my-input.ng-invalid {
  24288. color:white;
  24289. background: red;
  24290. }
  24291. </style>
  24292. <p id="inputDescription">
  24293. Update input to see transitions when valid/invalid.
  24294. Integer is a valid value.
  24295. </p>
  24296. <form name="testForm" ng-controller="ExampleController">
  24297. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  24298. aria-describedby="inputDescription" />
  24299. </form>
  24300. </file>
  24301. * </example>
  24302. *
  24303. * ## Binding to a getter/setter
  24304. *
  24305. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  24306. * function that returns a representation of the model when called with zero arguments, and sets
  24307. * the internal state of a model when called with an argument. It's sometimes useful to use this
  24308. * for models that have an internal representation that's different from what the model exposes
  24309. * to the view.
  24310. *
  24311. * <div class="alert alert-success">
  24312. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  24313. * frequently than other parts of your code.
  24314. * </div>
  24315. *
  24316. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  24317. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  24318. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  24319. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  24320. *
  24321. * The following example shows how to use `ngModel` with a getter/setter:
  24322. *
  24323. * @example
  24324. * <example name="ngModel-getter-setter" module="getterSetterExample">
  24325. <file name="index.html">
  24326. <div ng-controller="ExampleController">
  24327. <form name="userForm">
  24328. <label>Name:
  24329. <input type="text" name="userName"
  24330. ng-model="user.name"
  24331. ng-model-options="{ getterSetter: true }" />
  24332. </label>
  24333. </form>
  24334. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  24335. </div>
  24336. </file>
  24337. <file name="app.js">
  24338. angular.module('getterSetterExample', [])
  24339. .controller('ExampleController', ['$scope', function($scope) {
  24340. var _name = 'Brian';
  24341. $scope.user = {
  24342. name: function(newName) {
  24343. // Note that newName can be undefined for two reasons:
  24344. // 1. Because it is called as a getter and thus called with no arguments
  24345. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  24346. // input is invalid
  24347. return arguments.length ? (_name = newName) : _name;
  24348. }
  24349. };
  24350. }]);
  24351. </file>
  24352. * </example>
  24353. */
  24354. var ngModelDirective = ['$rootScope', function($rootScope) {
  24355. return {
  24356. restrict: 'A',
  24357. require: ['ngModel', '^?form', '^?ngModelOptions'],
  24358. controller: NgModelController,
  24359. // Prelink needs to run before any input directive
  24360. // so that we can set the NgModelOptions in NgModelController
  24361. // before anyone else uses it.
  24362. priority: 1,
  24363. compile: function ngModelCompile(element) {
  24364. // Setup initial state of the control
  24365. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  24366. return {
  24367. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  24368. var modelCtrl = ctrls[0],
  24369. formCtrl = ctrls[1] || modelCtrl.$$parentForm;
  24370. modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
  24371. // notify others, especially parent forms
  24372. formCtrl.$addControl(modelCtrl);
  24373. attr.$observe('name', function(newValue) {
  24374. if (modelCtrl.$name !== newValue) {
  24375. modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
  24376. }
  24377. });
  24378. scope.$on('$destroy', function() {
  24379. modelCtrl.$$parentForm.$removeControl(modelCtrl);
  24380. });
  24381. },
  24382. post: function ngModelPostLink(scope, element, attr, ctrls) {
  24383. var modelCtrl = ctrls[0];
  24384. if (modelCtrl.$options && modelCtrl.$options.updateOn) {
  24385. element.on(modelCtrl.$options.updateOn, function(ev) {
  24386. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  24387. });
  24388. }
  24389. element.on('blur', function(ev) {
  24390. if (modelCtrl.$touched) return;
  24391. if ($rootScope.$$phase) {
  24392. scope.$evalAsync(modelCtrl.$setTouched);
  24393. } else {
  24394. scope.$apply(modelCtrl.$setTouched);
  24395. }
  24396. });
  24397. }
  24398. };
  24399. }
  24400. };
  24401. }];
  24402. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  24403. /**
  24404. * @ngdoc directive
  24405. * @name ngModelOptions
  24406. *
  24407. * @description
  24408. * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
  24409. * events that will trigger a model update and/or a debouncing delay so that the actual update only
  24410. * takes place when a timer expires; this timer will be reset after another change takes place.
  24411. *
  24412. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  24413. * be different from the value in the actual model. This means that if you update the model you
  24414. * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
  24415. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  24416. *
  24417. * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
  24418. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  24419. * important because `form` controllers are published to the related scope under the name in their
  24420. * `name` attribute.
  24421. *
  24422. * Any pending changes will take place immediately when an enclosing form is submitted via the
  24423. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  24424. * to have access to the updated model.
  24425. *
  24426. * `ngModelOptions` has an effect on the element it's declared on and its descendants.
  24427. *
  24428. * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
  24429. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  24430. * events using an space delimited list. There is a special event called `default` that
  24431. * matches the default events belonging of the control.
  24432. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  24433. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  24434. * custom value for each event. For example:
  24435. * `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
  24436. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  24437. * not validate correctly instead of the default behavior of setting the model to undefined.
  24438. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  24439. `ngModel` as getters/setters.
  24440. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  24441. * `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
  24442. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  24443. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  24444. * If not specified, the timezone of the browser will be used.
  24445. *
  24446. * @example
  24447. The following example shows how to override immediate updates. Changes on the inputs within the
  24448. form will update the model only when the control loses focus (blur event). If `escape` key is
  24449. pressed while the input field is focused, the value is reset to the value in the current model.
  24450. <example name="ngModelOptions-directive-blur" module="optionsExample">
  24451. <file name="index.html">
  24452. <div ng-controller="ExampleController">
  24453. <form name="userForm">
  24454. <label>Name:
  24455. <input type="text" name="userName"
  24456. ng-model="user.name"
  24457. ng-model-options="{ updateOn: 'blur' }"
  24458. ng-keyup="cancel($event)" />
  24459. </label><br />
  24460. <label>Other data:
  24461. <input type="text" ng-model="user.data" />
  24462. </label><br />
  24463. </form>
  24464. <pre>user.name = <span ng-bind="user.name"></span></pre>
  24465. <pre>user.data = <span ng-bind="user.data"></span></pre>
  24466. </div>
  24467. </file>
  24468. <file name="app.js">
  24469. angular.module('optionsExample', [])
  24470. .controller('ExampleController', ['$scope', function($scope) {
  24471. $scope.user = { name: 'John', data: '' };
  24472. $scope.cancel = function(e) {
  24473. if (e.keyCode == 27) {
  24474. $scope.userForm.userName.$rollbackViewValue();
  24475. }
  24476. };
  24477. }]);
  24478. </file>
  24479. <file name="protractor.js" type="protractor">
  24480. var model = element(by.binding('user.name'));
  24481. var input = element(by.model('user.name'));
  24482. var other = element(by.model('user.data'));
  24483. it('should allow custom events', function() {
  24484. input.sendKeys(' Doe');
  24485. input.click();
  24486. expect(model.getText()).toEqual('John');
  24487. other.click();
  24488. expect(model.getText()).toEqual('John Doe');
  24489. });
  24490. it('should $rollbackViewValue when model changes', function() {
  24491. input.sendKeys(' Doe');
  24492. expect(input.getAttribute('value')).toEqual('John Doe');
  24493. input.sendKeys(protractor.Key.ESCAPE);
  24494. expect(input.getAttribute('value')).toEqual('John');
  24495. other.click();
  24496. expect(model.getText()).toEqual('John');
  24497. });
  24498. </file>
  24499. </example>
  24500. This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
  24501. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  24502. <example name="ngModelOptions-directive-debounce" module="optionsExample">
  24503. <file name="index.html">
  24504. <div ng-controller="ExampleController">
  24505. <form name="userForm">
  24506. <label>Name:
  24507. <input type="text" name="userName"
  24508. ng-model="user.name"
  24509. ng-model-options="{ debounce: 1000 }" />
  24510. </label>
  24511. <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
  24512. <br />
  24513. </form>
  24514. <pre>user.name = <span ng-bind="user.name"></span></pre>
  24515. </div>
  24516. </file>
  24517. <file name="app.js">
  24518. angular.module('optionsExample', [])
  24519. .controller('ExampleController', ['$scope', function($scope) {
  24520. $scope.user = { name: 'Igor' };
  24521. }]);
  24522. </file>
  24523. </example>
  24524. This one shows how to bind to getter/setters:
  24525. <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  24526. <file name="index.html">
  24527. <div ng-controller="ExampleController">
  24528. <form name="userForm">
  24529. <label>Name:
  24530. <input type="text" name="userName"
  24531. ng-model="user.name"
  24532. ng-model-options="{ getterSetter: true }" />
  24533. </label>
  24534. </form>
  24535. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  24536. </div>
  24537. </file>
  24538. <file name="app.js">
  24539. angular.module('getterSetterExample', [])
  24540. .controller('ExampleController', ['$scope', function($scope) {
  24541. var _name = 'Brian';
  24542. $scope.user = {
  24543. name: function(newName) {
  24544. // Note that newName can be undefined for two reasons:
  24545. // 1. Because it is called as a getter and thus called with no arguments
  24546. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  24547. // input is invalid
  24548. return arguments.length ? (_name = newName) : _name;
  24549. }
  24550. };
  24551. }]);
  24552. </file>
  24553. </example>
  24554. */
  24555. var ngModelOptionsDirective = function() {
  24556. return {
  24557. restrict: 'A',
  24558. controller: ['$scope', '$attrs', function($scope, $attrs) {
  24559. var that = this;
  24560. this.$options = copy($scope.$eval($attrs.ngModelOptions));
  24561. // Allow adding/overriding bound events
  24562. if (isDefined(this.$options.updateOn)) {
  24563. this.$options.updateOnDefault = false;
  24564. // extract "default" pseudo-event from list of events that can trigger a model update
  24565. this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
  24566. that.$options.updateOnDefault = true;
  24567. return ' ';
  24568. }));
  24569. } else {
  24570. this.$options.updateOnDefault = true;
  24571. }
  24572. }]
  24573. };
  24574. };
  24575. // helper methods
  24576. function addSetValidityMethod(context) {
  24577. var ctrl = context.ctrl,
  24578. $element = context.$element,
  24579. classCache = {},
  24580. set = context.set,
  24581. unset = context.unset,
  24582. $animate = context.$animate;
  24583. classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
  24584. ctrl.$setValidity = setValidity;
  24585. function setValidity(validationErrorKey, state, controller) {
  24586. if (isUndefined(state)) {
  24587. createAndSet('$pending', validationErrorKey, controller);
  24588. } else {
  24589. unsetAndCleanup('$pending', validationErrorKey, controller);
  24590. }
  24591. if (!isBoolean(state)) {
  24592. unset(ctrl.$error, validationErrorKey, controller);
  24593. unset(ctrl.$$success, validationErrorKey, controller);
  24594. } else {
  24595. if (state) {
  24596. unset(ctrl.$error, validationErrorKey, controller);
  24597. set(ctrl.$$success, validationErrorKey, controller);
  24598. } else {
  24599. set(ctrl.$error, validationErrorKey, controller);
  24600. unset(ctrl.$$success, validationErrorKey, controller);
  24601. }
  24602. }
  24603. if (ctrl.$pending) {
  24604. cachedToggleClass(PENDING_CLASS, true);
  24605. ctrl.$valid = ctrl.$invalid = undefined;
  24606. toggleValidationCss('', null);
  24607. } else {
  24608. cachedToggleClass(PENDING_CLASS, false);
  24609. ctrl.$valid = isObjectEmpty(ctrl.$error);
  24610. ctrl.$invalid = !ctrl.$valid;
  24611. toggleValidationCss('', ctrl.$valid);
  24612. }
  24613. // re-read the state as the set/unset methods could have
  24614. // combined state in ctrl.$error[validationError] (used for forms),
  24615. // where setting/unsetting only increments/decrements the value,
  24616. // and does not replace it.
  24617. var combinedState;
  24618. if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
  24619. combinedState = undefined;
  24620. } else if (ctrl.$error[validationErrorKey]) {
  24621. combinedState = false;
  24622. } else if (ctrl.$$success[validationErrorKey]) {
  24623. combinedState = true;
  24624. } else {
  24625. combinedState = null;
  24626. }
  24627. toggleValidationCss(validationErrorKey, combinedState);
  24628. ctrl.$$parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
  24629. }
  24630. function createAndSet(name, value, controller) {
  24631. if (!ctrl[name]) {
  24632. ctrl[name] = {};
  24633. }
  24634. set(ctrl[name], value, controller);
  24635. }
  24636. function unsetAndCleanup(name, value, controller) {
  24637. if (ctrl[name]) {
  24638. unset(ctrl[name], value, controller);
  24639. }
  24640. if (isObjectEmpty(ctrl[name])) {
  24641. ctrl[name] = undefined;
  24642. }
  24643. }
  24644. function cachedToggleClass(className, switchValue) {
  24645. if (switchValue && !classCache[className]) {
  24646. $animate.addClass($element, className);
  24647. classCache[className] = true;
  24648. } else if (!switchValue && classCache[className]) {
  24649. $animate.removeClass($element, className);
  24650. classCache[className] = false;
  24651. }
  24652. }
  24653. function toggleValidationCss(validationErrorKey, isValid) {
  24654. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  24655. cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
  24656. cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
  24657. }
  24658. }
  24659. function isObjectEmpty(obj) {
  24660. if (obj) {
  24661. for (var prop in obj) {
  24662. if (obj.hasOwnProperty(prop)) {
  24663. return false;
  24664. }
  24665. }
  24666. }
  24667. return true;
  24668. }
  24669. /**
  24670. * @ngdoc directive
  24671. * @name ngNonBindable
  24672. * @restrict AC
  24673. * @priority 1000
  24674. *
  24675. * @description
  24676. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  24677. * DOM element. This is useful if the element contains what appears to be Angular directives and
  24678. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  24679. * displays snippets of code, for instance.
  24680. *
  24681. * @element ANY
  24682. *
  24683. * @example
  24684. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  24685. * but the one wrapped in `ngNonBindable` is left alone.
  24686. *
  24687. * @example
  24688. <example>
  24689. <file name="index.html">
  24690. <div>Normal: {{1 + 2}}</div>
  24691. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  24692. </file>
  24693. <file name="protractor.js" type="protractor">
  24694. it('should check ng-non-bindable', function() {
  24695. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  24696. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  24697. });
  24698. </file>
  24699. </example>
  24700. */
  24701. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  24702. /* global jqLiteRemove */
  24703. var ngOptionsMinErr = minErr('ngOptions');
  24704. /**
  24705. * @ngdoc directive
  24706. * @name ngOptions
  24707. * @restrict A
  24708. *
  24709. * @description
  24710. *
  24711. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  24712. * elements for the `<select>` element using the array or object obtained by evaluating the
  24713. * `ngOptions` comprehension expression.
  24714. *
  24715. * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
  24716. * similar result. However, `ngOptions` provides some benefits such as reducing memory and
  24717. * increasing speed by not creating a new scope for each repeated instance, as well as providing
  24718. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  24719. * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
  24720. * to a non-string value. This is because an option element can only be bound to string values at
  24721. * present.
  24722. *
  24723. * When an item in the `<select>` menu is selected, the array element or object property
  24724. * represented by the selected option will be bound to the model identified by the `ngModel`
  24725. * directive.
  24726. *
  24727. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  24728. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  24729. * option. See example below for demonstration.
  24730. *
  24731. * ## Complex Models (objects or collections)
  24732. *
  24733. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  24734. * binding the select to a model that is an object or a collection.
  24735. *
  24736. * One issue occurs if you want to preselect an option. For example, if you set
  24737. * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
  24738. * because the objects are not identical. So by default, you should always reference the item in your collection
  24739. * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
  24740. *
  24741. * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
  24742. * of the item not by reference, but by the result of the `track by` expression. For example, if your
  24743. * collection items have an id property, you would `track by item.id`.
  24744. *
  24745. * A different issue with objects or collections is that ngModel won't detect if an object property or
  24746. * a collection item changes. For that reason, `ngOptions` additionally watches the model using
  24747. * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
  24748. * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
  24749. * has not changed identity, but only a property on the object or an item in the collection changes.
  24750. *
  24751. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  24752. * if the model is an array). This means that changing a property deeper than the first level inside the
  24753. * object/collection will not trigger a re-rendering.
  24754. *
  24755. * ## `select` **`as`**
  24756. *
  24757. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  24758. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  24759. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  24760. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  24761. *
  24762. *
  24763. * ### `select` **`as`** and **`track by`**
  24764. *
  24765. * <div class="alert alert-warning">
  24766. * Be careful when using `select` **`as`** and **`track by`** in the same expression.
  24767. * </div>
  24768. *
  24769. * Given this array of items on the $scope:
  24770. *
  24771. * ```js
  24772. * $scope.items = [{
  24773. * id: 1,
  24774. * label: 'aLabel',
  24775. * subItem: { name: 'aSubItem' }
  24776. * }, {
  24777. * id: 2,
  24778. * label: 'bLabel',
  24779. * subItem: { name: 'bSubItem' }
  24780. * }];
  24781. * ```
  24782. *
  24783. * This will work:
  24784. *
  24785. * ```html
  24786. * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
  24787. * ```
  24788. * ```js
  24789. * $scope.selected = $scope.items[0];
  24790. * ```
  24791. *
  24792. * but this will not work:
  24793. *
  24794. * ```html
  24795. * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
  24796. * ```
  24797. * ```js
  24798. * $scope.selected = $scope.items[0].subItem;
  24799. * ```
  24800. *
  24801. * In both examples, the **`track by`** expression is applied successfully to each `item` in the
  24802. * `items` array. Because the selected option has been set programmatically in the controller, the
  24803. * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
  24804. * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
  24805. * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
  24806. * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
  24807. * is not matched against any `<option>` and the `<select>` appears as having no selected value.
  24808. *
  24809. *
  24810. * @param {string} ngModel Assignable angular expression to data-bind to.
  24811. * @param {string=} name Property name of the form under which the control is published.
  24812. * @param {string=} required The control is considered valid only if value is entered.
  24813. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  24814. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  24815. * `required` when you want to data-bind to the `required` attribute.
  24816. * @param {comprehension_expression=} ngOptions in one of the following forms:
  24817. *
  24818. * * for array data sources:
  24819. * * `label` **`for`** `value` **`in`** `array`
  24820. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  24821. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  24822. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  24823. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  24824. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  24825. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  24826. * (for including a filter with `track by`)
  24827. * * for object data sources:
  24828. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  24829. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  24830. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  24831. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  24832. * * `select` **`as`** `label` **`group by`** `group`
  24833. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  24834. * * `select` **`as`** `label` **`disable when`** `disable`
  24835. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  24836. *
  24837. * Where:
  24838. *
  24839. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  24840. * * `value`: local variable which will refer to each item in the `array` or each property value
  24841. * of `object` during iteration.
  24842. * * `key`: local variable which will refer to a property name in `object` during iteration.
  24843. * * `label`: The result of this expression will be the label for `<option>` element. The
  24844. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  24845. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  24846. * element. If not specified, `select` expression will default to `value`.
  24847. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  24848. * DOM element.
  24849. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  24850. * element. Return `true` to disable.
  24851. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  24852. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  24853. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  24854. * even when the options are recreated (e.g. reloaded from the server).
  24855. *
  24856. * @example
  24857. <example module="selectExample">
  24858. <file name="index.html">
  24859. <script>
  24860. angular.module('selectExample', [])
  24861. .controller('ExampleController', ['$scope', function($scope) {
  24862. $scope.colors = [
  24863. {name:'black', shade:'dark'},
  24864. {name:'white', shade:'light', notAnOption: true},
  24865. {name:'red', shade:'dark'},
  24866. {name:'blue', shade:'dark', notAnOption: true},
  24867. {name:'yellow', shade:'light', notAnOption: false}
  24868. ];
  24869. $scope.myColor = $scope.colors[2]; // red
  24870. }]);
  24871. </script>
  24872. <div ng-controller="ExampleController">
  24873. <ul>
  24874. <li ng-repeat="color in colors">
  24875. <label>Name: <input ng-model="color.name"></label>
  24876. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  24877. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  24878. </li>
  24879. <li>
  24880. <button ng-click="colors.push({})">add</button>
  24881. </li>
  24882. </ul>
  24883. <hr/>
  24884. <label>Color (null not allowed):
  24885. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  24886. </label><br/>
  24887. <label>Color (null allowed):
  24888. <span class="nullable">
  24889. <select ng-model="myColor" ng-options="color.name for color in colors">
  24890. <option value="">-- choose color --</option>
  24891. </select>
  24892. </span></label><br/>
  24893. <label>Color grouped by shade:
  24894. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  24895. </select>
  24896. </label><br/>
  24897. <label>Color grouped by shade, with some disabled:
  24898. <select ng-model="myColor"
  24899. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  24900. </select>
  24901. </label><br/>
  24902. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  24903. <br/>
  24904. <hr/>
  24905. Currently selected: {{ {selected_color:myColor} }}
  24906. <div style="border:solid 1px black; height:20px"
  24907. ng-style="{'background-color':myColor.name}">
  24908. </div>
  24909. </div>
  24910. </file>
  24911. <file name="protractor.js" type="protractor">
  24912. it('should check ng-options', function() {
  24913. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  24914. element.all(by.model('myColor')).first().click();
  24915. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  24916. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  24917. element(by.css('.nullable select[ng-model="myColor"]')).click();
  24918. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  24919. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  24920. });
  24921. </file>
  24922. </example>
  24923. */
  24924. // jshint maxlen: false
  24925. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
  24926. 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]+?))?$/;
  24927. // 1: value expression (valueFn)
  24928. // 2: label expression (displayFn)
  24929. // 3: group by expression (groupByFn)
  24930. // 4: disable when expression (disableWhenFn)
  24931. // 5: array item variable name
  24932. // 6: object item key variable name
  24933. // 7: object item value variable name
  24934. // 8: collection expression
  24935. // 9: track by expression
  24936. // jshint maxlen: 100
  24937. var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
  24938. function parseOptionsExpression(optionsExp, selectElement, scope) {
  24939. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  24940. if (!(match)) {
  24941. throw ngOptionsMinErr('iexp',
  24942. "Expected expression in form of " +
  24943. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  24944. " but got '{0}'. Element: {1}",
  24945. optionsExp, startingTag(selectElement));
  24946. }
  24947. // Extract the parts from the ngOptions expression
  24948. // The variable name for the value of the item in the collection
  24949. var valueName = match[5] || match[7];
  24950. // The variable name for the key of the item in the collection
  24951. var keyName = match[6];
  24952. // An expression that generates the viewValue for an option if there is a label expression
  24953. var selectAs = / as /.test(match[0]) && match[1];
  24954. // An expression that is used to track the id of each object in the options collection
  24955. var trackBy = match[9];
  24956. // An expression that generates the viewValue for an option if there is no label expression
  24957. var valueFn = $parse(match[2] ? match[1] : valueName);
  24958. var selectAsFn = selectAs && $parse(selectAs);
  24959. var viewValueFn = selectAsFn || valueFn;
  24960. var trackByFn = trackBy && $parse(trackBy);
  24961. // Get the value by which we are going to track the option
  24962. // if we have a trackFn then use that (passing scope and locals)
  24963. // otherwise just hash the given viewValue
  24964. var getTrackByValueFn = trackBy ?
  24965. function(value, locals) { return trackByFn(scope, locals); } :
  24966. function getHashOfValue(value) { return hashKey(value); };
  24967. var getTrackByValue = function(value, key) {
  24968. return getTrackByValueFn(value, getLocals(value, key));
  24969. };
  24970. var displayFn = $parse(match[2] || match[1]);
  24971. var groupByFn = $parse(match[3] || '');
  24972. var disableWhenFn = $parse(match[4] || '');
  24973. var valuesFn = $parse(match[8]);
  24974. var locals = {};
  24975. var getLocals = keyName ? function(value, key) {
  24976. locals[keyName] = key;
  24977. locals[valueName] = value;
  24978. return locals;
  24979. } : function(value) {
  24980. locals[valueName] = value;
  24981. return locals;
  24982. };
  24983. function Option(selectValue, viewValue, label, group, disabled) {
  24984. this.selectValue = selectValue;
  24985. this.viewValue = viewValue;
  24986. this.label = label;
  24987. this.group = group;
  24988. this.disabled = disabled;
  24989. }
  24990. function getOptionValuesKeys(optionValues) {
  24991. var optionValuesKeys;
  24992. if (!keyName && isArrayLike(optionValues)) {
  24993. optionValuesKeys = optionValues;
  24994. } else {
  24995. // if object, extract keys, in enumeration order, unsorted
  24996. optionValuesKeys = [];
  24997. for (var itemKey in optionValues) {
  24998. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  24999. optionValuesKeys.push(itemKey);
  25000. }
  25001. }
  25002. }
  25003. return optionValuesKeys;
  25004. }
  25005. return {
  25006. trackBy: trackBy,
  25007. getTrackByValue: getTrackByValue,
  25008. getWatchables: $parse(valuesFn, function(optionValues) {
  25009. // Create a collection of things that we would like to watch (watchedArray)
  25010. // so that they can all be watched using a single $watchCollection
  25011. // that only runs the handler once if anything changes
  25012. var watchedArray = [];
  25013. optionValues = optionValues || [];
  25014. var optionValuesKeys = getOptionValuesKeys(optionValues);
  25015. var optionValuesLength = optionValuesKeys.length;
  25016. for (var index = 0; index < optionValuesLength; index++) {
  25017. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  25018. var value = optionValues[key];
  25019. var locals = getLocals(optionValues[key], key);
  25020. var selectValue = getTrackByValueFn(optionValues[key], locals);
  25021. watchedArray.push(selectValue);
  25022. // Only need to watch the displayFn if there is a specific label expression
  25023. if (match[2] || match[1]) {
  25024. var label = displayFn(scope, locals);
  25025. watchedArray.push(label);
  25026. }
  25027. // Only need to watch the disableWhenFn if there is a specific disable expression
  25028. if (match[4]) {
  25029. var disableWhen = disableWhenFn(scope, locals);
  25030. watchedArray.push(disableWhen);
  25031. }
  25032. }
  25033. return watchedArray;
  25034. }),
  25035. getOptions: function() {
  25036. var optionItems = [];
  25037. var selectValueMap = {};
  25038. // The option values were already computed in the `getWatchables` fn,
  25039. // which must have been called to trigger `getOptions`
  25040. var optionValues = valuesFn(scope) || [];
  25041. var optionValuesKeys = getOptionValuesKeys(optionValues);
  25042. var optionValuesLength = optionValuesKeys.length;
  25043. for (var index = 0; index < optionValuesLength; index++) {
  25044. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  25045. var value = optionValues[key];
  25046. var locals = getLocals(value, key);
  25047. var viewValue = viewValueFn(scope, locals);
  25048. var selectValue = getTrackByValueFn(viewValue, locals);
  25049. var label = displayFn(scope, locals);
  25050. var group = groupByFn(scope, locals);
  25051. var disabled = disableWhenFn(scope, locals);
  25052. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  25053. optionItems.push(optionItem);
  25054. selectValueMap[selectValue] = optionItem;
  25055. }
  25056. return {
  25057. items: optionItems,
  25058. selectValueMap: selectValueMap,
  25059. getOptionFromViewValue: function(value) {
  25060. return selectValueMap[getTrackByValue(value)];
  25061. },
  25062. getViewValueFromOption: function(option) {
  25063. // If the viewValue could be an object that may be mutated by the application,
  25064. // we need to make a copy and not return the reference to the value on the option.
  25065. return trackBy ? angular.copy(option.viewValue) : option.viewValue;
  25066. }
  25067. };
  25068. }
  25069. };
  25070. }
  25071. // we can't just jqLite('<option>') since jqLite is not smart enough
  25072. // to create it in <select> and IE barfs otherwise.
  25073. var optionTemplate = document.createElement('option'),
  25074. optGroupTemplate = document.createElement('optgroup');
  25075. function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
  25076. var selectCtrl = ctrls[0];
  25077. var ngModelCtrl = ctrls[1];
  25078. var multiple = attr.multiple;
  25079. // The emptyOption allows the application developer to provide their own custom "empty"
  25080. // option when the viewValue does not match any of the option values.
  25081. var emptyOption;
  25082. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  25083. if (children[i].value === '') {
  25084. emptyOption = children.eq(i);
  25085. break;
  25086. }
  25087. }
  25088. var providedEmptyOption = !!emptyOption;
  25089. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  25090. unknownOption.val('?');
  25091. var options;
  25092. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  25093. var renderEmptyOption = function() {
  25094. if (!providedEmptyOption) {
  25095. selectElement.prepend(emptyOption);
  25096. }
  25097. selectElement.val('');
  25098. emptyOption.prop('selected', true); // needed for IE
  25099. emptyOption.attr('selected', true);
  25100. };
  25101. var removeEmptyOption = function() {
  25102. if (!providedEmptyOption) {
  25103. emptyOption.remove();
  25104. }
  25105. };
  25106. var renderUnknownOption = function() {
  25107. selectElement.prepend(unknownOption);
  25108. selectElement.val('?');
  25109. unknownOption.prop('selected', true); // needed for IE
  25110. unknownOption.attr('selected', true);
  25111. };
  25112. var removeUnknownOption = function() {
  25113. unknownOption.remove();
  25114. };
  25115. // Update the controller methods for multiple selectable options
  25116. if (!multiple) {
  25117. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  25118. var option = options.getOptionFromViewValue(value);
  25119. if (option && !option.disabled) {
  25120. if (selectElement[0].value !== option.selectValue) {
  25121. removeUnknownOption();
  25122. removeEmptyOption();
  25123. selectElement[0].value = option.selectValue;
  25124. option.element.selected = true;
  25125. option.element.setAttribute('selected', 'selected');
  25126. }
  25127. } else {
  25128. if (value === null || providedEmptyOption) {
  25129. removeUnknownOption();
  25130. renderEmptyOption();
  25131. } else {
  25132. removeEmptyOption();
  25133. renderUnknownOption();
  25134. }
  25135. }
  25136. };
  25137. selectCtrl.readValue = function readNgOptionsValue() {
  25138. var selectedOption = options.selectValueMap[selectElement.val()];
  25139. if (selectedOption && !selectedOption.disabled) {
  25140. removeEmptyOption();
  25141. removeUnknownOption();
  25142. return options.getViewValueFromOption(selectedOption);
  25143. }
  25144. return null;
  25145. };
  25146. // If we are using `track by` then we must watch the tracked value on the model
  25147. // since ngModel only watches for object identity change
  25148. if (ngOptions.trackBy) {
  25149. scope.$watch(
  25150. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  25151. function() { ngModelCtrl.$render(); }
  25152. );
  25153. }
  25154. } else {
  25155. ngModelCtrl.$isEmpty = function(value) {
  25156. return !value || value.length === 0;
  25157. };
  25158. selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
  25159. options.items.forEach(function(option) {
  25160. option.element.selected = false;
  25161. });
  25162. if (value) {
  25163. value.forEach(function(item) {
  25164. var option = options.getOptionFromViewValue(item);
  25165. if (option && !option.disabled) option.element.selected = true;
  25166. });
  25167. }
  25168. };
  25169. selectCtrl.readValue = function readNgOptionsMultiple() {
  25170. var selectedValues = selectElement.val() || [],
  25171. selections = [];
  25172. forEach(selectedValues, function(value) {
  25173. var option = options.selectValueMap[value];
  25174. if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
  25175. });
  25176. return selections;
  25177. };
  25178. // If we are using `track by` then we must watch these tracked values on the model
  25179. // since ngModel only watches for object identity change
  25180. if (ngOptions.trackBy) {
  25181. scope.$watchCollection(function() {
  25182. if (isArray(ngModelCtrl.$viewValue)) {
  25183. return ngModelCtrl.$viewValue.map(function(value) {
  25184. return ngOptions.getTrackByValue(value);
  25185. });
  25186. }
  25187. }, function() {
  25188. ngModelCtrl.$render();
  25189. });
  25190. }
  25191. }
  25192. if (providedEmptyOption) {
  25193. // we need to remove it before calling selectElement.empty() because otherwise IE will
  25194. // remove the label from the element. wtf?
  25195. emptyOption.remove();
  25196. // compile the element since there might be bindings in it
  25197. $compile(emptyOption)(scope);
  25198. // remove the class, which is added automatically because we recompile the element and it
  25199. // becomes the compilation root
  25200. emptyOption.removeClass('ng-scope');
  25201. } else {
  25202. emptyOption = jqLite(optionTemplate.cloneNode(false));
  25203. }
  25204. // We need to do this here to ensure that the options object is defined
  25205. // when we first hit it in writeNgOptionsValue
  25206. updateOptions();
  25207. // We will re-render the option elements if the option values or labels change
  25208. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  25209. // ------------------------------------------------------------------ //
  25210. function updateOptionElement(option, element) {
  25211. option.element = element;
  25212. element.disabled = option.disabled;
  25213. // NOTE: The label must be set before the value, otherwise IE10/11/EDGE create unresponsive
  25214. // selects in certain circumstances when multiple selects are next to each other and display
  25215. // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
  25216. // See https://github.com/angular/angular.js/issues/11314 for more info.
  25217. // This is unfortunately untestable with unit / e2e tests
  25218. if (option.label !== element.label) {
  25219. element.label = option.label;
  25220. element.textContent = option.label;
  25221. }
  25222. if (option.value !== element.value) element.value = option.selectValue;
  25223. }
  25224. function addOrReuseElement(parent, current, type, templateElement) {
  25225. var element;
  25226. // Check whether we can reuse the next element
  25227. if (current && lowercase(current.nodeName) === type) {
  25228. // The next element is the right type so reuse it
  25229. element = current;
  25230. } else {
  25231. // The next element is not the right type so create a new one
  25232. element = templateElement.cloneNode(false);
  25233. if (!current) {
  25234. // There are no more elements so just append it to the select
  25235. parent.appendChild(element);
  25236. } else {
  25237. // The next element is not a group so insert the new one
  25238. parent.insertBefore(element, current);
  25239. }
  25240. }
  25241. return element;
  25242. }
  25243. function removeExcessElements(current) {
  25244. var next;
  25245. while (current) {
  25246. next = current.nextSibling;
  25247. jqLiteRemove(current);
  25248. current = next;
  25249. }
  25250. }
  25251. function skipEmptyAndUnknownOptions(current) {
  25252. var emptyOption_ = emptyOption && emptyOption[0];
  25253. var unknownOption_ = unknownOption && unknownOption[0];
  25254. // We cannot rely on the extracted empty option being the same as the compiled empty option,
  25255. // because the compiled empty option might have been replaced by a comment because
  25256. // it had an "element" transclusion directive on it (such as ngIf)
  25257. if (emptyOption_ || unknownOption_) {
  25258. while (current &&
  25259. (current === emptyOption_ ||
  25260. current === unknownOption_ ||
  25261. current.nodeType === NODE_TYPE_COMMENT ||
  25262. (nodeName_(current) === 'option' && current.value === ''))) {
  25263. current = current.nextSibling;
  25264. }
  25265. }
  25266. return current;
  25267. }
  25268. function updateOptions() {
  25269. var previousValue = options && selectCtrl.readValue();
  25270. options = ngOptions.getOptions();
  25271. var groupMap = {};
  25272. var currentElement = selectElement[0].firstChild;
  25273. // Ensure that the empty option is always there if it was explicitly provided
  25274. if (providedEmptyOption) {
  25275. selectElement.prepend(emptyOption);
  25276. }
  25277. currentElement = skipEmptyAndUnknownOptions(currentElement);
  25278. options.items.forEach(function updateOption(option) {
  25279. var group;
  25280. var groupElement;
  25281. var optionElement;
  25282. if (isDefined(option.group)) {
  25283. // This option is to live in a group
  25284. // See if we have already created this group
  25285. group = groupMap[option.group];
  25286. if (!group) {
  25287. // We have not already created this group
  25288. groupElement = addOrReuseElement(selectElement[0],
  25289. currentElement,
  25290. 'optgroup',
  25291. optGroupTemplate);
  25292. // Move to the next element
  25293. currentElement = groupElement.nextSibling;
  25294. // Update the label on the group element
  25295. groupElement.label = option.group;
  25296. // Store it for use later
  25297. group = groupMap[option.group] = {
  25298. groupElement: groupElement,
  25299. currentOptionElement: groupElement.firstChild
  25300. };
  25301. }
  25302. // So now we have a group for this option we add the option to the group
  25303. optionElement = addOrReuseElement(group.groupElement,
  25304. group.currentOptionElement,
  25305. 'option',
  25306. optionTemplate);
  25307. updateOptionElement(option, optionElement);
  25308. // Move to the next element
  25309. group.currentOptionElement = optionElement.nextSibling;
  25310. } else {
  25311. // This option is not in a group
  25312. optionElement = addOrReuseElement(selectElement[0],
  25313. currentElement,
  25314. 'option',
  25315. optionTemplate);
  25316. updateOptionElement(option, optionElement);
  25317. // Move to the next element
  25318. currentElement = optionElement.nextSibling;
  25319. }
  25320. });
  25321. // Now remove all excess options and group
  25322. Object.keys(groupMap).forEach(function(key) {
  25323. removeExcessElements(groupMap[key].currentOptionElement);
  25324. });
  25325. removeExcessElements(currentElement);
  25326. ngModelCtrl.$render();
  25327. // Check to see if the value has changed due to the update to the options
  25328. if (!ngModelCtrl.$isEmpty(previousValue)) {
  25329. var nextValue = selectCtrl.readValue();
  25330. var isNotPrimitive = ngOptions.trackBy || multiple;
  25331. if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
  25332. ngModelCtrl.$setViewValue(nextValue);
  25333. ngModelCtrl.$render();
  25334. }
  25335. }
  25336. }
  25337. }
  25338. return {
  25339. restrict: 'A',
  25340. terminal: true,
  25341. require: ['select', 'ngModel'],
  25342. link: {
  25343. pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
  25344. // Deactivate the SelectController.register method to prevent
  25345. // option directives from accidentally registering themselves
  25346. // (and unwanted $destroy handlers etc.)
  25347. ctrls[0].registerOption = noop;
  25348. },
  25349. post: ngOptionsPostLink
  25350. }
  25351. };
  25352. }];
  25353. /**
  25354. * @ngdoc directive
  25355. * @name ngPluralize
  25356. * @restrict EA
  25357. *
  25358. * @description
  25359. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  25360. * These rules are bundled with angular.js, but can be overridden
  25361. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  25362. * by specifying the mappings between
  25363. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  25364. * and the strings to be displayed.
  25365. *
  25366. * # Plural categories and explicit number rules
  25367. * There are two
  25368. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  25369. * in Angular's default en-US locale: "one" and "other".
  25370. *
  25371. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  25372. * any number that is not 1), an explicit number rule can only match one number. For example, the
  25373. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  25374. * and explicit number rules throughout the rest of this documentation.
  25375. *
  25376. * # Configuring ngPluralize
  25377. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  25378. * You can also provide an optional attribute, `offset`.
  25379. *
  25380. * The value of the `count` attribute can be either a string or an {@link guide/expression
  25381. * Angular expression}; these are evaluated on the current scope for its bound value.
  25382. *
  25383. * The `when` attribute specifies the mappings between plural categories and the actual
  25384. * string to be displayed. The value of the attribute should be a JSON object.
  25385. *
  25386. * The following example shows how to configure ngPluralize:
  25387. *
  25388. * ```html
  25389. * <ng-pluralize count="personCount"
  25390. when="{'0': 'Nobody is viewing.',
  25391. * 'one': '1 person is viewing.',
  25392. * 'other': '{} people are viewing.'}">
  25393. * </ng-pluralize>
  25394. *```
  25395. *
  25396. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  25397. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  25398. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  25399. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  25400. * show "a dozen people are viewing".
  25401. *
  25402. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  25403. * into pluralized strings. In the previous example, Angular will replace `{}` with
  25404. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  25405. * for <span ng-non-bindable>{{numberExpression}}</span>.
  25406. *
  25407. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  25408. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  25409. *
  25410. * # Configuring ngPluralize with offset
  25411. * The `offset` attribute allows further customization of pluralized text, which can result in
  25412. * a better user experience. For example, instead of the message "4 people are viewing this document",
  25413. * you might display "John, Kate and 2 others are viewing this document".
  25414. * The offset attribute allows you to offset a number by any desired value.
  25415. * Let's take a look at an example:
  25416. *
  25417. * ```html
  25418. * <ng-pluralize count="personCount" offset=2
  25419. * when="{'0': 'Nobody is viewing.',
  25420. * '1': '{{person1}} is viewing.',
  25421. * '2': '{{person1}} and {{person2}} are viewing.',
  25422. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  25423. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  25424. * </ng-pluralize>
  25425. * ```
  25426. *
  25427. * Notice that we are still using two plural categories(one, other), but we added
  25428. * three explicit number rules 0, 1 and 2.
  25429. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  25430. * When three people view the document, no explicit number rule is found, so
  25431. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  25432. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  25433. * is shown.
  25434. *
  25435. * Note that when you specify offsets, you must provide explicit number rules for
  25436. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  25437. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  25438. * plural categories "one" and "other".
  25439. *
  25440. * @param {string|expression} count The variable to be bound to.
  25441. * @param {string} when The mapping between plural category to its corresponding strings.
  25442. * @param {number=} offset Offset to deduct from the total number.
  25443. *
  25444. * @example
  25445. <example module="pluralizeExample">
  25446. <file name="index.html">
  25447. <script>
  25448. angular.module('pluralizeExample', [])
  25449. .controller('ExampleController', ['$scope', function($scope) {
  25450. $scope.person1 = 'Igor';
  25451. $scope.person2 = 'Misko';
  25452. $scope.personCount = 1;
  25453. }]);
  25454. </script>
  25455. <div ng-controller="ExampleController">
  25456. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  25457. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  25458. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  25459. <!--- Example with simple pluralization rules for en locale --->
  25460. Without Offset:
  25461. <ng-pluralize count="personCount"
  25462. when="{'0': 'Nobody is viewing.',
  25463. 'one': '1 person is viewing.',
  25464. 'other': '{} people are viewing.'}">
  25465. </ng-pluralize><br>
  25466. <!--- Example with offset --->
  25467. With Offset(2):
  25468. <ng-pluralize count="personCount" offset=2
  25469. when="{'0': 'Nobody is viewing.',
  25470. '1': '{{person1}} is viewing.',
  25471. '2': '{{person1}} and {{person2}} are viewing.',
  25472. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  25473. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  25474. </ng-pluralize>
  25475. </div>
  25476. </file>
  25477. <file name="protractor.js" type="protractor">
  25478. it('should show correct pluralized string', function() {
  25479. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  25480. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  25481. var countInput = element(by.model('personCount'));
  25482. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  25483. expect(withOffset.getText()).toEqual('Igor is viewing.');
  25484. countInput.clear();
  25485. countInput.sendKeys('0');
  25486. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  25487. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  25488. countInput.clear();
  25489. countInput.sendKeys('2');
  25490. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  25491. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  25492. countInput.clear();
  25493. countInput.sendKeys('3');
  25494. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  25495. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  25496. countInput.clear();
  25497. countInput.sendKeys('4');
  25498. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  25499. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  25500. });
  25501. it('should show data-bound names', function() {
  25502. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  25503. var personCount = element(by.model('personCount'));
  25504. var person1 = element(by.model('person1'));
  25505. var person2 = element(by.model('person2'));
  25506. personCount.clear();
  25507. personCount.sendKeys('4');
  25508. person1.clear();
  25509. person1.sendKeys('Di');
  25510. person2.clear();
  25511. person2.sendKeys('Vojta');
  25512. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  25513. });
  25514. </file>
  25515. </example>
  25516. */
  25517. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  25518. var BRACE = /{}/g,
  25519. IS_WHEN = /^when(Minus)?(.+)$/;
  25520. return {
  25521. link: function(scope, element, attr) {
  25522. var numberExp = attr.count,
  25523. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  25524. offset = attr.offset || 0,
  25525. whens = scope.$eval(whenExp) || {},
  25526. whensExpFns = {},
  25527. startSymbol = $interpolate.startSymbol(),
  25528. endSymbol = $interpolate.endSymbol(),
  25529. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  25530. watchRemover = angular.noop,
  25531. lastCount;
  25532. forEach(attr, function(expression, attributeName) {
  25533. var tmpMatch = IS_WHEN.exec(attributeName);
  25534. if (tmpMatch) {
  25535. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  25536. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  25537. }
  25538. });
  25539. forEach(whens, function(expression, key) {
  25540. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  25541. });
  25542. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  25543. var count = parseFloat(newVal);
  25544. var countIsNaN = isNaN(count);
  25545. if (!countIsNaN && !(count in whens)) {
  25546. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  25547. // Otherwise, check it against pluralization rules in $locale service.
  25548. count = $locale.pluralCat(count - offset);
  25549. }
  25550. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  25551. // In JS `NaN !== NaN`, so we have to explicitly check.
  25552. if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {
  25553. watchRemover();
  25554. var whenExpFn = whensExpFns[count];
  25555. if (isUndefined(whenExpFn)) {
  25556. if (newVal != null) {
  25557. $log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp);
  25558. }
  25559. watchRemover = noop;
  25560. updateElementText();
  25561. } else {
  25562. watchRemover = scope.$watch(whenExpFn, updateElementText);
  25563. }
  25564. lastCount = count;
  25565. }
  25566. });
  25567. function updateElementText(newText) {
  25568. element.text(newText || '');
  25569. }
  25570. }
  25571. };
  25572. }];
  25573. /**
  25574. * @ngdoc directive
  25575. * @name ngRepeat
  25576. * @multiElement
  25577. *
  25578. * @description
  25579. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  25580. * instance gets its own scope, where the given loop variable is set to the current collection item,
  25581. * and `$index` is set to the item index or key.
  25582. *
  25583. * Special properties are exposed on the local scope of each template instance, including:
  25584. *
  25585. * | Variable | Type | Details |
  25586. * |-----------|-----------------|-----------------------------------------------------------------------------|
  25587. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  25588. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  25589. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  25590. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  25591. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  25592. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  25593. *
  25594. * <div class="alert alert-info">
  25595. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  25596. * This may be useful when, for instance, nesting ngRepeats.
  25597. * </div>
  25598. *
  25599. *
  25600. * # Iterating over object properties
  25601. *
  25602. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  25603. * syntax:
  25604. *
  25605. * ```js
  25606. * <div ng-repeat="(key, value) in myObj"> ... </div>
  25607. * ```
  25608. *
  25609. * However, there are a limitations compared to array iteration:
  25610. *
  25611. * - The JavaScript specification does not define the order of keys
  25612. * returned for an object, so Angular relies on the order returned by the browser
  25613. * when running `for key in myObj`. Browsers generally follow the strategy of providing
  25614. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  25615. * and reinstated. See the
  25616. * [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
  25617. *
  25618. * - `ngRepeat` will silently *ignore* object keys starting with `$`, because
  25619. * it's a prefix used by Angular for public (`$`) and private (`$$`) properties.
  25620. *
  25621. * - The built-in filters {@link ng.orderBy orderBy} and {@link ng.filter filter} do not work with
  25622. * objects, and will throw if used with one.
  25623. *
  25624. * If you are hitting any of these limitations, the recommended workaround is to convert your object into an array
  25625. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  25626. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  25627. * or implement a `$watch` on the object yourself.
  25628. *
  25629. *
  25630. * # Tracking and Duplicates
  25631. *
  25632. * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
  25633. * the collection. When a change happens, ngRepeat then makes the corresponding changes to the DOM:
  25634. *
  25635. * * When an item is added, a new instance of the template is added to the DOM.
  25636. * * When an item is removed, its template instance is removed from the DOM.
  25637. * * When items are reordered, their respective templates are reordered in the DOM.
  25638. *
  25639. * To minimize creation of DOM elements, `ngRepeat` uses a function
  25640. * to "keep track" of all items in the collection and their corresponding DOM elements.
  25641. * For example, if an item is added to the collection, ngRepeat will know that all other items
  25642. * already have DOM elements, and will not re-render them.
  25643. *
  25644. * The default tracking function (which tracks items by their identity) does not allow
  25645. * duplicate items in arrays. This is because when there are duplicates, it is not possible
  25646. * to maintain a one-to-one mapping between collection items and DOM elements.
  25647. *
  25648. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  25649. * with your own using the `track by` expression.
  25650. *
  25651. * For example, you may track items by the index of each item in the collection, using the
  25652. * special scope property `$index`:
  25653. * ```html
  25654. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  25655. * {{n}}
  25656. * </div>
  25657. * ```
  25658. *
  25659. * You may also use arbitrary expressions in `track by`, including references to custom functions
  25660. * on the scope:
  25661. * ```html
  25662. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  25663. * {{n}}
  25664. * </div>
  25665. * ```
  25666. *
  25667. * <div class="alert alert-success">
  25668. * If you are working with objects that have an identifier property, you should track
  25669. * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
  25670. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  25671. * JavaScript objects in the collection have been substituted for new ones. For large collections,
  25672. * this significantly improves rendering performance. If you don't have a unique identifier,
  25673. * `track by $index` can also provide a performance boost.
  25674. * </div>
  25675. * ```html
  25676. * <div ng-repeat="model in collection track by model.id">
  25677. * {{model.name}}
  25678. * </div>
  25679. * ```
  25680. *
  25681. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  25682. * `$id` function, which tracks items by their identity:
  25683. * ```html
  25684. * <div ng-repeat="obj in collection track by $id(obj)">
  25685. * {{obj.prop}}
  25686. * </div>
  25687. * ```
  25688. *
  25689. * <div class="alert alert-warning">
  25690. * **Note:** `track by` must always be the last expression:
  25691. * </div>
  25692. * ```
  25693. * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
  25694. * {{model.name}}
  25695. * </div>
  25696. * ```
  25697. *
  25698. * # Special repeat start and end points
  25699. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  25700. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  25701. * 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)
  25702. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  25703. *
  25704. * The example below makes use of this feature:
  25705. * ```html
  25706. * <header ng-repeat-start="item in items">
  25707. * Header {{ item }}
  25708. * </header>
  25709. * <div class="body">
  25710. * Body {{ item }}
  25711. * </div>
  25712. * <footer ng-repeat-end>
  25713. * Footer {{ item }}
  25714. * </footer>
  25715. * ```
  25716. *
  25717. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  25718. * ```html
  25719. * <header>
  25720. * Header A
  25721. * </header>
  25722. * <div class="body">
  25723. * Body A
  25724. * </div>
  25725. * <footer>
  25726. * Footer A
  25727. * </footer>
  25728. * <header>
  25729. * Header B
  25730. * </header>
  25731. * <div class="body">
  25732. * Body B
  25733. * </div>
  25734. * <footer>
  25735. * Footer B
  25736. * </footer>
  25737. * ```
  25738. *
  25739. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  25740. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  25741. *
  25742. * @animations
  25743. * | Animation | Occurs |
  25744. * |----------------------------------|-------------------------------------|
  25745. * | {@link ng.$animate#enter enter} | when a new item is added to the list or when an item is revealed after a filter |
  25746. * | {@link ng.$animate#leave leave} | when an item is removed from the list or when an item is filtered out |
  25747. * | {@link ng.$animate#move move } | when an adjacent item is filtered out causing a reorder or when the item contents are reordered |
  25748. *
  25749. * See the example below for defining CSS animations with ngRepeat.
  25750. *
  25751. * @element ANY
  25752. * @scope
  25753. * @priority 1000
  25754. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  25755. * formats are currently supported:
  25756. *
  25757. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  25758. * is a scope expression giving the collection to enumerate.
  25759. *
  25760. * For example: `album in artist.albums`.
  25761. *
  25762. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  25763. * and `expression` is the scope expression giving the collection to enumerate.
  25764. *
  25765. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  25766. *
  25767. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  25768. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  25769. * is specified, ng-repeat associates elements by identity. It is an error to have
  25770. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  25771. * mapped to the same DOM element, which is not possible.)
  25772. *
  25773. * Note that the tracking expression must come last, after any filters, and the alias expression.
  25774. *
  25775. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  25776. * will be associated by item identity in the array.
  25777. *
  25778. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  25779. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  25780. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  25781. * element in the same way in the DOM.
  25782. *
  25783. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  25784. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  25785. * property is same.
  25786. *
  25787. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  25788. * to items in conjunction with a tracking expression.
  25789. *
  25790. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  25791. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  25792. * when a filter is active on the repeater, but the filtered result set is empty.
  25793. *
  25794. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  25795. * the items have been processed through the filter.
  25796. *
  25797. * 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
  25798. * (and not as operator, inside an expression).
  25799. *
  25800. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
  25801. *
  25802. * @example
  25803. * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed
  25804. * results by name. New (entering) and removed (leaving) items are animated.
  25805. <example module="ngRepeat" name="ngRepeat" deps="angular-animate.js" animations="true">
  25806. <file name="index.html">
  25807. <div ng-controller="repeatController">
  25808. I have {{friends.length}} friends. They are:
  25809. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  25810. <ul class="example-animate-container">
  25811. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  25812. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  25813. </li>
  25814. <li class="animate-repeat" ng-if="results.length == 0">
  25815. <strong>No results found...</strong>
  25816. </li>
  25817. </ul>
  25818. </div>
  25819. </file>
  25820. <file name="script.js">
  25821. angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
  25822. $scope.friends = [
  25823. {name:'John', age:25, gender:'boy'},
  25824. {name:'Jessie', age:30, gender:'girl'},
  25825. {name:'Johanna', age:28, gender:'girl'},
  25826. {name:'Joy', age:15, gender:'girl'},
  25827. {name:'Mary', age:28, gender:'girl'},
  25828. {name:'Peter', age:95, gender:'boy'},
  25829. {name:'Sebastian', age:50, gender:'boy'},
  25830. {name:'Erika', age:27, gender:'girl'},
  25831. {name:'Patrick', age:40, gender:'boy'},
  25832. {name:'Samantha', age:60, gender:'girl'}
  25833. ];
  25834. });
  25835. </file>
  25836. <file name="animations.css">
  25837. .example-animate-container {
  25838. background:white;
  25839. border:1px solid black;
  25840. list-style:none;
  25841. margin:0;
  25842. padding:0 10px;
  25843. }
  25844. .animate-repeat {
  25845. line-height:30px;
  25846. list-style:none;
  25847. box-sizing:border-box;
  25848. }
  25849. .animate-repeat.ng-move,
  25850. .animate-repeat.ng-enter,
  25851. .animate-repeat.ng-leave {
  25852. transition:all linear 0.5s;
  25853. }
  25854. .animate-repeat.ng-leave.ng-leave-active,
  25855. .animate-repeat.ng-move,
  25856. .animate-repeat.ng-enter {
  25857. opacity:0;
  25858. max-height:0;
  25859. }
  25860. .animate-repeat.ng-leave,
  25861. .animate-repeat.ng-move.ng-move-active,
  25862. .animate-repeat.ng-enter.ng-enter-active {
  25863. opacity:1;
  25864. max-height:30px;
  25865. }
  25866. </file>
  25867. <file name="protractor.js" type="protractor">
  25868. var friends = element.all(by.repeater('friend in friends'));
  25869. it('should render initial data set', function() {
  25870. expect(friends.count()).toBe(10);
  25871. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  25872. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  25873. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  25874. expect(element(by.binding('friends.length')).getText())
  25875. .toMatch("I have 10 friends. They are:");
  25876. });
  25877. it('should update repeater when filter predicate changes', function() {
  25878. expect(friends.count()).toBe(10);
  25879. element(by.model('q')).sendKeys('ma');
  25880. expect(friends.count()).toBe(2);
  25881. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  25882. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  25883. });
  25884. </file>
  25885. </example>
  25886. */
  25887. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  25888. var NG_REMOVED = '$$NG_REMOVED';
  25889. var ngRepeatMinErr = minErr('ngRepeat');
  25890. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  25891. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  25892. scope[valueIdentifier] = value;
  25893. if (keyIdentifier) scope[keyIdentifier] = key;
  25894. scope.$index = index;
  25895. scope.$first = (index === 0);
  25896. scope.$last = (index === (arrayLength - 1));
  25897. scope.$middle = !(scope.$first || scope.$last);
  25898. // jshint bitwise: false
  25899. scope.$odd = !(scope.$even = (index&1) === 0);
  25900. // jshint bitwise: true
  25901. };
  25902. var getBlockStart = function(block) {
  25903. return block.clone[0];
  25904. };
  25905. var getBlockEnd = function(block) {
  25906. return block.clone[block.clone.length - 1];
  25907. };
  25908. return {
  25909. restrict: 'A',
  25910. multiElement: true,
  25911. transclude: 'element',
  25912. priority: 1000,
  25913. terminal: true,
  25914. $$tlb: true,
  25915. compile: function ngRepeatCompile($element, $attr) {
  25916. var expression = $attr.ngRepeat;
  25917. var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
  25918. 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*$/);
  25919. if (!match) {
  25920. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  25921. expression);
  25922. }
  25923. var lhs = match[1];
  25924. var rhs = match[2];
  25925. var aliasAs = match[3];
  25926. var trackByExp = match[4];
  25927. match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
  25928. if (!match) {
  25929. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  25930. lhs);
  25931. }
  25932. var valueIdentifier = match[3] || match[1];
  25933. var keyIdentifier = match[2];
  25934. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  25935. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  25936. throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
  25937. aliasAs);
  25938. }
  25939. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  25940. var hashFnLocals = {$id: hashKey};
  25941. if (trackByExp) {
  25942. trackByExpGetter = $parse(trackByExp);
  25943. } else {
  25944. trackByIdArrayFn = function(key, value) {
  25945. return hashKey(value);
  25946. };
  25947. trackByIdObjFn = function(key) {
  25948. return key;
  25949. };
  25950. }
  25951. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  25952. if (trackByExpGetter) {
  25953. trackByIdExpFn = function(key, value, index) {
  25954. // assign key, value, and $index to the locals so that they can be used in hash functions
  25955. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  25956. hashFnLocals[valueIdentifier] = value;
  25957. hashFnLocals.$index = index;
  25958. return trackByExpGetter($scope, hashFnLocals);
  25959. };
  25960. }
  25961. // Store a list of elements from previous run. This is a hash where key is the item from the
  25962. // iterator, and the value is objects with following properties.
  25963. // - scope: bound scope
  25964. // - element: previous element.
  25965. // - index: position
  25966. //
  25967. // We are using no-proto object so that we don't need to guard against inherited props via
  25968. // hasOwnProperty.
  25969. var lastBlockMap = createMap();
  25970. //watch props
  25971. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  25972. var index, length,
  25973. previousNode = $element[0], // node that cloned nodes should be inserted after
  25974. // initialized to the comment node anchor
  25975. nextNode,
  25976. // Same as lastBlockMap but it has the current state. It will become the
  25977. // lastBlockMap on the next iteration.
  25978. nextBlockMap = createMap(),
  25979. collectionLength,
  25980. key, value, // key/value of iteration
  25981. trackById,
  25982. trackByIdFn,
  25983. collectionKeys,
  25984. block, // last object information {scope, element, id}
  25985. nextBlockOrder,
  25986. elementsToRemove;
  25987. if (aliasAs) {
  25988. $scope[aliasAs] = collection;
  25989. }
  25990. if (isArrayLike(collection)) {
  25991. collectionKeys = collection;
  25992. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  25993. } else {
  25994. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  25995. // if object, extract keys, in enumeration order, unsorted
  25996. collectionKeys = [];
  25997. for (var itemKey in collection) {
  25998. if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
  25999. collectionKeys.push(itemKey);
  26000. }
  26001. }
  26002. }
  26003. collectionLength = collectionKeys.length;
  26004. nextBlockOrder = new Array(collectionLength);
  26005. // locate existing items
  26006. for (index = 0; index < collectionLength; index++) {
  26007. key = (collection === collectionKeys) ? index : collectionKeys[index];
  26008. value = collection[key];
  26009. trackById = trackByIdFn(key, value, index);
  26010. if (lastBlockMap[trackById]) {
  26011. // found previously seen block
  26012. block = lastBlockMap[trackById];
  26013. delete lastBlockMap[trackById];
  26014. nextBlockMap[trackById] = block;
  26015. nextBlockOrder[index] = block;
  26016. } else if (nextBlockMap[trackById]) {
  26017. // if collision detected. restore lastBlockMap and throw an error
  26018. forEach(nextBlockOrder, function(block) {
  26019. if (block && block.scope) lastBlockMap[block.id] = block;
  26020. });
  26021. throw ngRepeatMinErr('dupes',
  26022. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  26023. expression, trackById, value);
  26024. } else {
  26025. // new never before seen block
  26026. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  26027. nextBlockMap[trackById] = true;
  26028. }
  26029. }
  26030. // remove leftover items
  26031. for (var blockKey in lastBlockMap) {
  26032. block = lastBlockMap[blockKey];
  26033. elementsToRemove = getBlockNodes(block.clone);
  26034. $animate.leave(elementsToRemove);
  26035. if (elementsToRemove[0].parentNode) {
  26036. // if the element was not removed yet because of pending animation, mark it as deleted
  26037. // so that we can ignore it later
  26038. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  26039. elementsToRemove[index][NG_REMOVED] = true;
  26040. }
  26041. }
  26042. block.scope.$destroy();
  26043. }
  26044. // we are not using forEach for perf reasons (trying to avoid #call)
  26045. for (index = 0; index < collectionLength; index++) {
  26046. key = (collection === collectionKeys) ? index : collectionKeys[index];
  26047. value = collection[key];
  26048. block = nextBlockOrder[index];
  26049. if (block.scope) {
  26050. // if we have already seen this object, then we need to reuse the
  26051. // associated scope/element
  26052. nextNode = previousNode;
  26053. // skip nodes that are already pending removal via leave animation
  26054. do {
  26055. nextNode = nextNode.nextSibling;
  26056. } while (nextNode && nextNode[NG_REMOVED]);
  26057. if (getBlockStart(block) != nextNode) {
  26058. // existing item which got moved
  26059. $animate.move(getBlockNodes(block.clone), null, previousNode);
  26060. }
  26061. previousNode = getBlockEnd(block);
  26062. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  26063. } else {
  26064. // new item which we don't know about
  26065. $transclude(function ngRepeatTransclude(clone, scope) {
  26066. block.scope = scope;
  26067. // http://jsperf.com/clone-vs-createcomment
  26068. var endNode = ngRepeatEndComment.cloneNode(false);
  26069. clone[clone.length++] = endNode;
  26070. $animate.enter(clone, null, previousNode);
  26071. previousNode = endNode;
  26072. // Note: We only need the first/last node of the cloned nodes.
  26073. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  26074. // by a directive with templateUrl when its template arrives.
  26075. block.clone = clone;
  26076. nextBlockMap[block.id] = block;
  26077. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  26078. });
  26079. }
  26080. }
  26081. lastBlockMap = nextBlockMap;
  26082. });
  26083. };
  26084. }
  26085. };
  26086. }];
  26087. var NG_HIDE_CLASS = 'ng-hide';
  26088. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  26089. /**
  26090. * @ngdoc directive
  26091. * @name ngShow
  26092. * @multiElement
  26093. *
  26094. * @description
  26095. * The `ngShow` directive shows or hides the given HTML element based on the expression
  26096. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  26097. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  26098. * in AngularJS and sets the display style to none (using an !important flag).
  26099. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  26100. *
  26101. * ```html
  26102. * <!-- when $scope.myValue is truthy (element is visible) -->
  26103. * <div ng-show="myValue"></div>
  26104. *
  26105. * <!-- when $scope.myValue is falsy (element is hidden) -->
  26106. * <div ng-show="myValue" class="ng-hide"></div>
  26107. * ```
  26108. *
  26109. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
  26110. * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
  26111. * from the element causing the element not to appear hidden.
  26112. *
  26113. * ## Why is !important used?
  26114. *
  26115. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  26116. * can be easily overridden by heavier selectors. For example, something as simple
  26117. * as changing the display style on a HTML list item would make hidden elements appear visible.
  26118. * This also becomes a bigger issue when dealing with CSS frameworks.
  26119. *
  26120. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  26121. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  26122. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  26123. *
  26124. * ### Overriding `.ng-hide`
  26125. *
  26126. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  26127. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  26128. * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
  26129. * with extra animation classes that can be added.
  26130. *
  26131. * ```css
  26132. * .ng-hide:not(.ng-hide-animate) {
  26133. * /&#42; this is just another form of hiding an element &#42;/
  26134. * display: block!important;
  26135. * position: absolute;
  26136. * top: -9999px;
  26137. * left: -9999px;
  26138. * }
  26139. * ```
  26140. *
  26141. * By default you don't need to override in CSS anything and the animations will work around the display style.
  26142. *
  26143. * ## A note about animations with `ngShow`
  26144. *
  26145. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  26146. * is true and false. This system works like the animation system present with ngClass except that
  26147. * you must also include the !important flag to override the display property
  26148. * so that you can perform an animation when the element is hidden during the time of the animation.
  26149. *
  26150. * ```css
  26151. * //
  26152. * //a working example can be found at the bottom of this page
  26153. * //
  26154. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  26155. * /&#42; this is required as of 1.3x to properly
  26156. * apply all styling in a show/hide animation &#42;/
  26157. * transition: 0s linear all;
  26158. * }
  26159. *
  26160. * .my-element.ng-hide-add-active,
  26161. * .my-element.ng-hide-remove-active {
  26162. * /&#42; the transition is defined in the active class &#42;/
  26163. * transition: 1s linear all;
  26164. * }
  26165. *
  26166. * .my-element.ng-hide-add { ... }
  26167. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  26168. * .my-element.ng-hide-remove { ... }
  26169. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  26170. * ```
  26171. *
  26172. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display
  26173. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  26174. *
  26175. * @animations
  26176. * | Animation | Occurs |
  26177. * |----------------------------------|-------------------------------------|
  26178. * | {@link $animate#addClass addClass} `.ng-hide` | after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden |
  26179. * | {@link $animate#removeClass removeClass} `.ng-hide` | after the `ngShow` expression evaluates to a truthy value and just before contents are set to visible |
  26180. *
  26181. * @element ANY
  26182. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  26183. * then the element is shown or hidden respectively.
  26184. *
  26185. * @example
  26186. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  26187. <file name="index.html">
  26188. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
  26189. <div>
  26190. Show:
  26191. <div class="check-element animate-show" ng-show="checked">
  26192. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  26193. </div>
  26194. </div>
  26195. <div>
  26196. Hide:
  26197. <div class="check-element animate-show" ng-hide="checked">
  26198. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  26199. </div>
  26200. </div>
  26201. </file>
  26202. <file name="glyphicons.css">
  26203. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  26204. </file>
  26205. <file name="animations.css">
  26206. .animate-show {
  26207. line-height: 20px;
  26208. opacity: 1;
  26209. padding: 10px;
  26210. border: 1px solid black;
  26211. background: white;
  26212. }
  26213. .animate-show.ng-hide-add, .animate-show.ng-hide-remove {
  26214. transition: all linear 0.5s;
  26215. }
  26216. .animate-show.ng-hide {
  26217. line-height: 0;
  26218. opacity: 0;
  26219. padding: 0 10px;
  26220. }
  26221. .check-element {
  26222. padding: 10px;
  26223. border: 1px solid black;
  26224. background: white;
  26225. }
  26226. </file>
  26227. <file name="protractor.js" type="protractor">
  26228. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  26229. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  26230. it('should check ng-show / ng-hide', function() {
  26231. expect(thumbsUp.isDisplayed()).toBeFalsy();
  26232. expect(thumbsDown.isDisplayed()).toBeTruthy();
  26233. element(by.model('checked')).click();
  26234. expect(thumbsUp.isDisplayed()).toBeTruthy();
  26235. expect(thumbsDown.isDisplayed()).toBeFalsy();
  26236. });
  26237. </file>
  26238. </example>
  26239. */
  26240. var ngShowDirective = ['$animate', function($animate) {
  26241. return {
  26242. restrict: 'A',
  26243. multiElement: true,
  26244. link: function(scope, element, attr) {
  26245. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  26246. // we're adding a temporary, animation-specific class for ng-hide since this way
  26247. // we can control when the element is actually displayed on screen without having
  26248. // to have a global/greedy CSS selector that breaks when other animations are run.
  26249. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  26250. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  26251. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  26252. });
  26253. });
  26254. }
  26255. };
  26256. }];
  26257. /**
  26258. * @ngdoc directive
  26259. * @name ngHide
  26260. * @multiElement
  26261. *
  26262. * @description
  26263. * The `ngHide` directive shows or hides the given HTML element based on the expression
  26264. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  26265. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  26266. * in AngularJS and sets the display style to none (using an !important flag).
  26267. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  26268. *
  26269. * ```html
  26270. * <!-- when $scope.myValue is truthy (element is hidden) -->
  26271. * <div ng-hide="myValue" class="ng-hide"></div>
  26272. *
  26273. * <!-- when $scope.myValue is falsy (element is visible) -->
  26274. * <div ng-hide="myValue"></div>
  26275. * ```
  26276. *
  26277. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
  26278. * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
  26279. * from the element causing the element not to appear hidden.
  26280. *
  26281. * ## Why is !important used?
  26282. *
  26283. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  26284. * can be easily overridden by heavier selectors. For example, something as simple
  26285. * as changing the display style on a HTML list item would make hidden elements appear visible.
  26286. * This also becomes a bigger issue when dealing with CSS frameworks.
  26287. *
  26288. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  26289. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  26290. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  26291. *
  26292. * ### Overriding `.ng-hide`
  26293. *
  26294. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  26295. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  26296. * class in CSS:
  26297. *
  26298. * ```css
  26299. * .ng-hide {
  26300. * /&#42; this is just another form of hiding an element &#42;/
  26301. * display: block!important;
  26302. * position: absolute;
  26303. * top: -9999px;
  26304. * left: -9999px;
  26305. * }
  26306. * ```
  26307. *
  26308. * By default you don't need to override in CSS anything and the animations will work around the display style.
  26309. *
  26310. * ## A note about animations with `ngHide`
  26311. *
  26312. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  26313. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  26314. * CSS class is added and removed for you instead of your own CSS class.
  26315. *
  26316. * ```css
  26317. * //
  26318. * //a working example can be found at the bottom of this page
  26319. * //
  26320. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  26321. * transition: 0.5s linear all;
  26322. * }
  26323. *
  26324. * .my-element.ng-hide-add { ... }
  26325. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  26326. * .my-element.ng-hide-remove { ... }
  26327. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  26328. * ```
  26329. *
  26330. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display
  26331. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  26332. *
  26333. * @animations
  26334. * | Animation | Occurs |
  26335. * |----------------------------------|-------------------------------------|
  26336. * | {@link $animate#addClass addClass} `.ng-hide` | after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden |
  26337. * | {@link $animate#removeClass removeClass} `.ng-hide` | after the `ngHide` expression evaluates to a non truthy value and just before contents are set to visible |
  26338. *
  26339. *
  26340. * @element ANY
  26341. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  26342. * the element is shown or hidden respectively.
  26343. *
  26344. * @example
  26345. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  26346. <file name="index.html">
  26347. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
  26348. <div>
  26349. Show:
  26350. <div class="check-element animate-hide" ng-show="checked">
  26351. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  26352. </div>
  26353. </div>
  26354. <div>
  26355. Hide:
  26356. <div class="check-element animate-hide" ng-hide="checked">
  26357. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  26358. </div>
  26359. </div>
  26360. </file>
  26361. <file name="glyphicons.css">
  26362. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  26363. </file>
  26364. <file name="animations.css">
  26365. .animate-hide {
  26366. transition: all linear 0.5s;
  26367. line-height: 20px;
  26368. opacity: 1;
  26369. padding: 10px;
  26370. border: 1px solid black;
  26371. background: white;
  26372. }
  26373. .animate-hide.ng-hide {
  26374. line-height: 0;
  26375. opacity: 0;
  26376. padding: 0 10px;
  26377. }
  26378. .check-element {
  26379. padding: 10px;
  26380. border: 1px solid black;
  26381. background: white;
  26382. }
  26383. </file>
  26384. <file name="protractor.js" type="protractor">
  26385. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  26386. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  26387. it('should check ng-show / ng-hide', function() {
  26388. expect(thumbsUp.isDisplayed()).toBeFalsy();
  26389. expect(thumbsDown.isDisplayed()).toBeTruthy();
  26390. element(by.model('checked')).click();
  26391. expect(thumbsUp.isDisplayed()).toBeTruthy();
  26392. expect(thumbsDown.isDisplayed()).toBeFalsy();
  26393. });
  26394. </file>
  26395. </example>
  26396. */
  26397. var ngHideDirective = ['$animate', function($animate) {
  26398. return {
  26399. restrict: 'A',
  26400. multiElement: true,
  26401. link: function(scope, element, attr) {
  26402. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  26403. // The comment inside of the ngShowDirective explains why we add and
  26404. // remove a temporary class for the show/hide animation
  26405. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  26406. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  26407. });
  26408. });
  26409. }
  26410. };
  26411. }];
  26412. /**
  26413. * @ngdoc directive
  26414. * @name ngStyle
  26415. * @restrict AC
  26416. *
  26417. * @description
  26418. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  26419. *
  26420. * @element ANY
  26421. * @param {expression} ngStyle
  26422. *
  26423. * {@link guide/expression Expression} which evals to an
  26424. * object whose keys are CSS style names and values are corresponding values for those CSS
  26425. * keys.
  26426. *
  26427. * Since some CSS style names are not valid keys for an object, they must be quoted.
  26428. * See the 'background-color' style in the example below.
  26429. *
  26430. * @example
  26431. <example>
  26432. <file name="index.html">
  26433. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  26434. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  26435. <input type="button" value="clear" ng-click="myStyle={}">
  26436. <br/>
  26437. <span ng-style="myStyle">Sample Text</span>
  26438. <pre>myStyle={{myStyle}}</pre>
  26439. </file>
  26440. <file name="style.css">
  26441. span {
  26442. color: black;
  26443. }
  26444. </file>
  26445. <file name="protractor.js" type="protractor">
  26446. var colorSpan = element(by.css('span'));
  26447. it('should check ng-style', function() {
  26448. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  26449. element(by.css('input[value=\'set color\']')).click();
  26450. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  26451. element(by.css('input[value=clear]')).click();
  26452. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  26453. });
  26454. </file>
  26455. </example>
  26456. */
  26457. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  26458. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  26459. if (oldStyles && (newStyles !== oldStyles)) {
  26460. forEach(oldStyles, function(val, style) { element.css(style, '');});
  26461. }
  26462. if (newStyles) element.css(newStyles);
  26463. }, true);
  26464. });
  26465. /**
  26466. * @ngdoc directive
  26467. * @name ngSwitch
  26468. * @restrict EA
  26469. *
  26470. * @description
  26471. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  26472. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  26473. * as specified in the template.
  26474. *
  26475. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  26476. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  26477. * matches the value obtained from the evaluated expression. In other words, you define a container element
  26478. * (where you place the directive), place an expression on the **`on="..."` attribute**
  26479. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  26480. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  26481. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  26482. * attribute is displayed.
  26483. *
  26484. * <div class="alert alert-info">
  26485. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  26486. * as literal string values to match against.
  26487. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  26488. * value of the expression `$scope.someVal`.
  26489. * </div>
  26490. * @animations
  26491. * | Animation | Occurs |
  26492. * |----------------------------------|-------------------------------------|
  26493. * | {@link ng.$animate#enter enter} | after the ngSwitch contents change and the matched child element is placed inside the container |
  26494. * | {@link ng.$animate#leave leave} | after the ngSwitch contents change and just before the former contents are removed from the DOM |
  26495. *
  26496. * @usage
  26497. *
  26498. * ```
  26499. * <ANY ng-switch="expression">
  26500. * <ANY ng-switch-when="matchValue1">...</ANY>
  26501. * <ANY ng-switch-when="matchValue2">...</ANY>
  26502. * <ANY ng-switch-default>...</ANY>
  26503. * </ANY>
  26504. * ```
  26505. *
  26506. *
  26507. * @scope
  26508. * @priority 1200
  26509. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  26510. * On child elements add:
  26511. *
  26512. * * `ngSwitchWhen`: the case statement to match against. If match then this
  26513. * case will be displayed. If the same match appears multiple times, all the
  26514. * elements will be displayed.
  26515. * * `ngSwitchDefault`: the default case when no other case match. If there
  26516. * are multiple default cases, all of them will be displayed when no other
  26517. * case match.
  26518. *
  26519. *
  26520. * @example
  26521. <example module="switchExample" deps="angular-animate.js" animations="true">
  26522. <file name="index.html">
  26523. <div ng-controller="ExampleController">
  26524. <select ng-model="selection" ng-options="item for item in items">
  26525. </select>
  26526. <code>selection={{selection}}</code>
  26527. <hr/>
  26528. <div class="animate-switch-container"
  26529. ng-switch on="selection">
  26530. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  26531. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  26532. <div class="animate-switch" ng-switch-default>default</div>
  26533. </div>
  26534. </div>
  26535. </file>
  26536. <file name="script.js">
  26537. angular.module('switchExample', ['ngAnimate'])
  26538. .controller('ExampleController', ['$scope', function($scope) {
  26539. $scope.items = ['settings', 'home', 'other'];
  26540. $scope.selection = $scope.items[0];
  26541. }]);
  26542. </file>
  26543. <file name="animations.css">
  26544. .animate-switch-container {
  26545. position:relative;
  26546. background:white;
  26547. border:1px solid black;
  26548. height:40px;
  26549. overflow:hidden;
  26550. }
  26551. .animate-switch {
  26552. padding:10px;
  26553. }
  26554. .animate-switch.ng-animate {
  26555. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  26556. position:absolute;
  26557. top:0;
  26558. left:0;
  26559. right:0;
  26560. bottom:0;
  26561. }
  26562. .animate-switch.ng-leave.ng-leave-active,
  26563. .animate-switch.ng-enter {
  26564. top:-50px;
  26565. }
  26566. .animate-switch.ng-leave,
  26567. .animate-switch.ng-enter.ng-enter-active {
  26568. top:0;
  26569. }
  26570. </file>
  26571. <file name="protractor.js" type="protractor">
  26572. var switchElem = element(by.css('[ng-switch]'));
  26573. var select = element(by.model('selection'));
  26574. it('should start in settings', function() {
  26575. expect(switchElem.getText()).toMatch(/Settings Div/);
  26576. });
  26577. it('should change to home', function() {
  26578. select.all(by.css('option')).get(1).click();
  26579. expect(switchElem.getText()).toMatch(/Home Span/);
  26580. });
  26581. it('should select default', function() {
  26582. select.all(by.css('option')).get(2).click();
  26583. expect(switchElem.getText()).toMatch(/default/);
  26584. });
  26585. </file>
  26586. </example>
  26587. */
  26588. var ngSwitchDirective = ['$animate', function($animate) {
  26589. return {
  26590. require: 'ngSwitch',
  26591. // asks for $scope to fool the BC controller module
  26592. controller: ['$scope', function ngSwitchController() {
  26593. this.cases = {};
  26594. }],
  26595. link: function(scope, element, attr, ngSwitchController) {
  26596. var watchExpr = attr.ngSwitch || attr.on,
  26597. selectedTranscludes = [],
  26598. selectedElements = [],
  26599. previousLeaveAnimations = [],
  26600. selectedScopes = [];
  26601. var spliceFactory = function(array, index) {
  26602. return function() { array.splice(index, 1); };
  26603. };
  26604. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  26605. var i, ii;
  26606. for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
  26607. $animate.cancel(previousLeaveAnimations[i]);
  26608. }
  26609. previousLeaveAnimations.length = 0;
  26610. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  26611. var selected = getBlockNodes(selectedElements[i].clone);
  26612. selectedScopes[i].$destroy();
  26613. var promise = previousLeaveAnimations[i] = $animate.leave(selected);
  26614. promise.then(spliceFactory(previousLeaveAnimations, i));
  26615. }
  26616. selectedElements.length = 0;
  26617. selectedScopes.length = 0;
  26618. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  26619. forEach(selectedTranscludes, function(selectedTransclude) {
  26620. selectedTransclude.transclude(function(caseElement, selectedScope) {
  26621. selectedScopes.push(selectedScope);
  26622. var anchor = selectedTransclude.element;
  26623. caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
  26624. var block = { clone: caseElement };
  26625. selectedElements.push(block);
  26626. $animate.enter(caseElement, anchor.parent(), anchor);
  26627. });
  26628. });
  26629. }
  26630. });
  26631. }
  26632. };
  26633. }];
  26634. var ngSwitchWhenDirective = ngDirective({
  26635. transclude: 'element',
  26636. priority: 1200,
  26637. require: '^ngSwitch',
  26638. multiElement: true,
  26639. link: function(scope, element, attrs, ctrl, $transclude) {
  26640. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  26641. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  26642. }
  26643. });
  26644. var ngSwitchDefaultDirective = ngDirective({
  26645. transclude: 'element',
  26646. priority: 1200,
  26647. require: '^ngSwitch',
  26648. multiElement: true,
  26649. link: function(scope, element, attr, ctrl, $transclude) {
  26650. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  26651. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  26652. }
  26653. });
  26654. /**
  26655. * @ngdoc directive
  26656. * @name ngTransclude
  26657. * @restrict EAC
  26658. *
  26659. * @description
  26660. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  26661. *
  26662. * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name
  26663. * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.
  26664. *
  26665. * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing
  26666. * content of this element will be removed before the transcluded content is inserted.
  26667. * If the transcluded content is empty, the existing content is left intact. This lets you provide fallback content in the case
  26668. * that no transcluded content is provided.
  26669. *
  26670. * @element ANY
  26671. *
  26672. * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty
  26673. * or its value is the same as the name of the attribute then the default slot is used.
  26674. *
  26675. * @example
  26676. * ### Basic transclusion
  26677. * This example demonstrates basic transclusion of content into a component directive.
  26678. * <example name="simpleTranscludeExample" module="transcludeExample">
  26679. * <file name="index.html">
  26680. * <script>
  26681. * angular.module('transcludeExample', [])
  26682. * .directive('pane', function(){
  26683. * return {
  26684. * restrict: 'E',
  26685. * transclude: true,
  26686. * scope: { title:'@' },
  26687. * template: '<div style="border: 1px solid black;">' +
  26688. * '<div style="background-color: gray">{{title}}</div>' +
  26689. * '<ng-transclude></ng-transclude>' +
  26690. * '</div>'
  26691. * };
  26692. * })
  26693. * .controller('ExampleController', ['$scope', function($scope) {
  26694. * $scope.title = 'Lorem Ipsum';
  26695. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  26696. * }]);
  26697. * </script>
  26698. * <div ng-controller="ExampleController">
  26699. * <input ng-model="title" aria-label="title"> <br/>
  26700. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  26701. * <pane title="{{title}}">{{text}}</pane>
  26702. * </div>
  26703. * </file>
  26704. * <file name="protractor.js" type="protractor">
  26705. * it('should have transcluded', function() {
  26706. * var titleElement = element(by.model('title'));
  26707. * titleElement.clear();
  26708. * titleElement.sendKeys('TITLE');
  26709. * var textElement = element(by.model('text'));
  26710. * textElement.clear();
  26711. * textElement.sendKeys('TEXT');
  26712. * expect(element(by.binding('title')).getText()).toEqual('TITLE');
  26713. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  26714. * });
  26715. * </file>
  26716. * </example>
  26717. *
  26718. * @example
  26719. * ### Transclude fallback content
  26720. * This example shows how to use `NgTransclude` with fallback content, that
  26721. * is displayed if no transcluded content is provided.
  26722. *
  26723. * <example module="transcludeFallbackContentExample">
  26724. * <file name="index.html">
  26725. * <script>
  26726. * angular.module('transcludeFallbackContentExample', [])
  26727. * .directive('myButton', function(){
  26728. * return {
  26729. * restrict: 'E',
  26730. * transclude: true,
  26731. * scope: true,
  26732. * template: '<button style="cursor: pointer;">' +
  26733. * '<ng-transclude>' +
  26734. * '<b style="color: red;">Button1</b>' +
  26735. * '</ng-transclude>' +
  26736. * '</button>'
  26737. * };
  26738. * });
  26739. * </script>
  26740. * <!-- fallback button content -->
  26741. * <my-button id="fallback"></my-button>
  26742. * <!-- modified button content -->
  26743. * <my-button id="modified">
  26744. * <i style="color: green;">Button2</i>
  26745. * </my-button>
  26746. * </file>
  26747. * <file name="protractor.js" type="protractor">
  26748. * it('should have different transclude element content', function() {
  26749. * expect(element(by.id('fallback')).getText()).toBe('Button1');
  26750. * expect(element(by.id('modified')).getText()).toBe('Button2');
  26751. * });
  26752. * </file>
  26753. * </example>
  26754. *
  26755. * @example
  26756. * ### Multi-slot transclusion
  26757. * This example demonstrates using multi-slot transclusion in a component directive.
  26758. * <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample">
  26759. * <file name="index.html">
  26760. * <style>
  26761. * .title, .footer {
  26762. * background-color: gray
  26763. * }
  26764. * </style>
  26765. * <div ng-controller="ExampleController">
  26766. * <input ng-model="title" aria-label="title"> <br/>
  26767. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  26768. * <pane>
  26769. * <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
  26770. * <pane-body><p>{{text}}</p></pane-body>
  26771. * </pane>
  26772. * </div>
  26773. * </file>
  26774. * <file name="app.js">
  26775. * angular.module('multiSlotTranscludeExample', [])
  26776. * .directive('pane', function(){
  26777. * return {
  26778. * restrict: 'E',
  26779. * transclude: {
  26780. * 'title': '?paneTitle',
  26781. * 'body': 'paneBody',
  26782. * 'footer': '?paneFooter'
  26783. * },
  26784. * template: '<div style="border: 1px solid black;">' +
  26785. * '<div class="title" ng-transclude="title">Fallback Title</div>' +
  26786. * '<div ng-transclude="body"></div>' +
  26787. * '<div class="footer" ng-transclude="footer">Fallback Footer</div>' +
  26788. * '</div>'
  26789. * };
  26790. * })
  26791. * .controller('ExampleController', ['$scope', function($scope) {
  26792. * $scope.title = 'Lorem Ipsum';
  26793. * $scope.link = "https://google.com";
  26794. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  26795. * }]);
  26796. * </file>
  26797. * <file name="protractor.js" type="protractor">
  26798. * it('should have transcluded the title and the body', function() {
  26799. * var titleElement = element(by.model('title'));
  26800. * titleElement.clear();
  26801. * titleElement.sendKeys('TITLE');
  26802. * var textElement = element(by.model('text'));
  26803. * textElement.clear();
  26804. * textElement.sendKeys('TEXT');
  26805. * expect(element(by.css('.title')).getText()).toEqual('TITLE');
  26806. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  26807. * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer');
  26808. * });
  26809. * </file>
  26810. * </example>
  26811. */
  26812. var ngTranscludeMinErr = minErr('ngTransclude');
  26813. var ngTranscludeDirective = ngDirective({
  26814. restrict: 'EAC',
  26815. link: function($scope, $element, $attrs, controller, $transclude) {
  26816. if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) {
  26817. // If the attribute is of the form: `ng-transclude="ng-transclude"`
  26818. // then treat it like the default
  26819. $attrs.ngTransclude = '';
  26820. }
  26821. function ngTranscludeCloneAttachFn(clone) {
  26822. if (clone.length) {
  26823. $element.empty();
  26824. $element.append(clone);
  26825. }
  26826. }
  26827. if (!$transclude) {
  26828. throw ngTranscludeMinErr('orphan',
  26829. 'Illegal use of ngTransclude directive in the template! ' +
  26830. 'No parent directive that requires a transclusion found. ' +
  26831. 'Element: {0}',
  26832. startingTag($element));
  26833. }
  26834. // If there is no slot name defined or the slot name is not optional
  26835. // then transclude the slot
  26836. var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot;
  26837. $transclude(ngTranscludeCloneAttachFn, null, slotName);
  26838. }
  26839. });
  26840. /**
  26841. * @ngdoc directive
  26842. * @name script
  26843. * @restrict E
  26844. *
  26845. * @description
  26846. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  26847. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  26848. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  26849. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  26850. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  26851. *
  26852. * @param {string} type Must be set to `'text/ng-template'`.
  26853. * @param {string} id Cache name of the template.
  26854. *
  26855. * @example
  26856. <example>
  26857. <file name="index.html">
  26858. <script type="text/ng-template" id="/tpl.html">
  26859. Content of the template.
  26860. </script>
  26861. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  26862. <div id="tpl-content" ng-include src="currentTpl"></div>
  26863. </file>
  26864. <file name="protractor.js" type="protractor">
  26865. it('should load template defined inside script tag', function() {
  26866. element(by.css('#tpl-link')).click();
  26867. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  26868. });
  26869. </file>
  26870. </example>
  26871. */
  26872. var scriptDirective = ['$templateCache', function($templateCache) {
  26873. return {
  26874. restrict: 'E',
  26875. terminal: true,
  26876. compile: function(element, attr) {
  26877. if (attr.type == 'text/ng-template') {
  26878. var templateUrl = attr.id,
  26879. text = element[0].text;
  26880. $templateCache.put(templateUrl, text);
  26881. }
  26882. }
  26883. };
  26884. }];
  26885. var noopNgModelController = { $setViewValue: noop, $render: noop };
  26886. function chromeHack(optionElement) {
  26887. // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
  26888. // Adding an <option selected="selected"> element to a <select required="required"> should
  26889. // automatically select the new element
  26890. if (optionElement[0].hasAttribute('selected')) {
  26891. optionElement[0].selected = true;
  26892. }
  26893. }
  26894. /**
  26895. * @ngdoc type
  26896. * @name select.SelectController
  26897. * @description
  26898. * The controller for the `<select>` directive. This provides support for reading
  26899. * and writing the selected value(s) of the control and also coordinates dynamically
  26900. * added `<option>` elements, perhaps by an `ngRepeat` directive.
  26901. */
  26902. var SelectController =
  26903. ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  26904. var self = this,
  26905. optionsMap = new HashMap();
  26906. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  26907. self.ngModelCtrl = noopNgModelController;
  26908. // The "unknown" option is one that is prepended to the list if the viewValue
  26909. // does not match any of the options. When it is rendered the value of the unknown
  26910. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  26911. //
  26912. // We can't just jqLite('<option>') since jqLite is not smart enough
  26913. // to create it in <select> and IE barfs otherwise.
  26914. self.unknownOption = jqLite(document.createElement('option'));
  26915. self.renderUnknownOption = function(val) {
  26916. var unknownVal = '? ' + hashKey(val) + ' ?';
  26917. self.unknownOption.val(unknownVal);
  26918. $element.prepend(self.unknownOption);
  26919. $element.val(unknownVal);
  26920. };
  26921. $scope.$on('$destroy', function() {
  26922. // disable unknown option so that we don't do work when the whole select is being destroyed
  26923. self.renderUnknownOption = noop;
  26924. });
  26925. self.removeUnknownOption = function() {
  26926. if (self.unknownOption.parent()) self.unknownOption.remove();
  26927. };
  26928. // Read the value of the select control, the implementation of this changes depending
  26929. // upon whether the select can have multiple values and whether ngOptions is at work.
  26930. self.readValue = function readSingleValue() {
  26931. self.removeUnknownOption();
  26932. return $element.val();
  26933. };
  26934. // Write the value to the select control, the implementation of this changes depending
  26935. // upon whether the select can have multiple values and whether ngOptions is at work.
  26936. self.writeValue = function writeSingleValue(value) {
  26937. if (self.hasOption(value)) {
  26938. self.removeUnknownOption();
  26939. $element.val(value);
  26940. if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy
  26941. } else {
  26942. if (value == null && self.emptyOption) {
  26943. self.removeUnknownOption();
  26944. $element.val('');
  26945. } else {
  26946. self.renderUnknownOption(value);
  26947. }
  26948. }
  26949. };
  26950. // Tell the select control that an option, with the given value, has been added
  26951. self.addOption = function(value, element) {
  26952. // Skip comment nodes, as they only pollute the `optionsMap`
  26953. if (element[0].nodeType === NODE_TYPE_COMMENT) return;
  26954. assertNotHasOwnProperty(value, '"option value"');
  26955. if (value === '') {
  26956. self.emptyOption = element;
  26957. }
  26958. var count = optionsMap.get(value) || 0;
  26959. optionsMap.put(value, count + 1);
  26960. self.ngModelCtrl.$render();
  26961. chromeHack(element);
  26962. };
  26963. // Tell the select control that an option, with the given value, has been removed
  26964. self.removeOption = function(value) {
  26965. var count = optionsMap.get(value);
  26966. if (count) {
  26967. if (count === 1) {
  26968. optionsMap.remove(value);
  26969. if (value === '') {
  26970. self.emptyOption = undefined;
  26971. }
  26972. } else {
  26973. optionsMap.put(value, count - 1);
  26974. }
  26975. }
  26976. };
  26977. // Check whether the select control has an option matching the given value
  26978. self.hasOption = function(value) {
  26979. return !!optionsMap.get(value);
  26980. };
  26981. self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
  26982. if (interpolateValueFn) {
  26983. // The value attribute is interpolated
  26984. var oldVal;
  26985. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  26986. if (isDefined(oldVal)) {
  26987. self.removeOption(oldVal);
  26988. }
  26989. oldVal = newVal;
  26990. self.addOption(newVal, optionElement);
  26991. });
  26992. } else if (interpolateTextFn) {
  26993. // The text content is interpolated
  26994. optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
  26995. optionAttrs.$set('value', newVal);
  26996. if (oldVal !== newVal) {
  26997. self.removeOption(oldVal);
  26998. }
  26999. self.addOption(newVal, optionElement);
  27000. });
  27001. } else {
  27002. // The value attribute is static
  27003. self.addOption(optionAttrs.value, optionElement);
  27004. }
  27005. optionElement.on('$destroy', function() {
  27006. self.removeOption(optionAttrs.value);
  27007. self.ngModelCtrl.$render();
  27008. });
  27009. };
  27010. }];
  27011. /**
  27012. * @ngdoc directive
  27013. * @name select
  27014. * @restrict E
  27015. *
  27016. * @description
  27017. * HTML `SELECT` element with angular data-binding.
  27018. *
  27019. * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
  27020. * between the scope and the `<select>` control (including setting default values).
  27021. * It also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
  27022. * {@link ngOptions `ngOptions`} directives.
  27023. *
  27024. * When an item in the `<select>` menu is selected, the value of the selected option will be bound
  27025. * to the model identified by the `ngModel` directive. With static or repeated options, this is
  27026. * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
  27027. * If you want dynamic value attributes, you can use interpolation inside the value attribute.
  27028. *
  27029. * <div class="alert alert-warning">
  27030. * Note that the value of a `select` directive used without `ngOptions` is always a string.
  27031. * When the model needs to be bound to a non-string value, you must either explicitly convert it
  27032. * using a directive (see example below) or use `ngOptions` to specify the set of options.
  27033. * This is because an option element can only be bound to string values at present.
  27034. * </div>
  27035. *
  27036. * If the viewValue of `ngModel` does not match any of the options, then the control
  27037. * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
  27038. *
  27039. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  27040. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  27041. * option. See example below for demonstration.
  27042. *
  27043. * <div class="alert alert-info">
  27044. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  27045. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits, such as
  27046. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  27047. * comprehension expression, and additionally in reducing memory and increasing speed by not creating
  27048. * a new scope for each repeated instance.
  27049. * </div>
  27050. *
  27051. *
  27052. * @param {string} ngModel Assignable angular expression to data-bind to.
  27053. * @param {string=} name Property name of the form under which the control is published.
  27054. * @param {string=} multiple Allows multiple options to be selected. The selected values will be
  27055. * bound to the model as an array.
  27056. * @param {string=} required Sets `required` validation error key if the value is not entered.
  27057. * @param {string=} ngRequired Adds required attribute and required validation constraint to
  27058. * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
  27059. * when you want to data-bind to the required attribute.
  27060. * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
  27061. * interaction with the select element.
  27062. * @param {string=} ngOptions sets the options that the select is populated with and defines what is
  27063. * set on the model on selection. See {@link ngOptions `ngOptions`}.
  27064. *
  27065. * @example
  27066. * ### Simple `select` elements with static options
  27067. *
  27068. * <example name="static-select" module="staticSelect">
  27069. * <file name="index.html">
  27070. * <div ng-controller="ExampleController">
  27071. * <form name="myForm">
  27072. * <label for="singleSelect"> Single select: </label><br>
  27073. * <select name="singleSelect" ng-model="data.singleSelect">
  27074. * <option value="option-1">Option 1</option>
  27075. * <option value="option-2">Option 2</option>
  27076. * </select><br>
  27077. *
  27078. * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
  27079. * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
  27080. * <option value="">---Please select---</option> <!-- not selected / blank option -->
  27081. * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
  27082. * <option value="option-2">Option 2</option>
  27083. * </select><br>
  27084. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  27085. * <tt>singleSelect = {{data.singleSelect}}</tt>
  27086. *
  27087. * <hr>
  27088. * <label for="multipleSelect"> Multiple select: </label><br>
  27089. * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
  27090. * <option value="option-1">Option 1</option>
  27091. * <option value="option-2">Option 2</option>
  27092. * <option value="option-3">Option 3</option>
  27093. * </select><br>
  27094. * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
  27095. * </form>
  27096. * </div>
  27097. * </file>
  27098. * <file name="app.js">
  27099. * angular.module('staticSelect', [])
  27100. * .controller('ExampleController', ['$scope', function($scope) {
  27101. * $scope.data = {
  27102. * singleSelect: null,
  27103. * multipleSelect: [],
  27104. * option1: 'option-1',
  27105. * };
  27106. *
  27107. * $scope.forceUnknownOption = function() {
  27108. * $scope.data.singleSelect = 'nonsense';
  27109. * };
  27110. * }]);
  27111. * </file>
  27112. *</example>
  27113. *
  27114. * ### Using `ngRepeat` to generate `select` options
  27115. * <example name="ngrepeat-select" module="ngrepeatSelect">
  27116. * <file name="index.html">
  27117. * <div ng-controller="ExampleController">
  27118. * <form name="myForm">
  27119. * <label for="repeatSelect"> Repeat select: </label>
  27120. * <select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect">
  27121. * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
  27122. * </select>
  27123. * </form>
  27124. * <hr>
  27125. * <tt>repeatSelect = {{data.repeatSelect}}</tt><br/>
  27126. * </div>
  27127. * </file>
  27128. * <file name="app.js">
  27129. * angular.module('ngrepeatSelect', [])
  27130. * .controller('ExampleController', ['$scope', function($scope) {
  27131. * $scope.data = {
  27132. * repeatSelect: null,
  27133. * availableOptions: [
  27134. * {id: '1', name: 'Option A'},
  27135. * {id: '2', name: 'Option B'},
  27136. * {id: '3', name: 'Option C'}
  27137. * ],
  27138. * };
  27139. * }]);
  27140. * </file>
  27141. *</example>
  27142. *
  27143. *
  27144. * ### Using `select` with `ngOptions` and setting a default value
  27145. * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
  27146. *
  27147. * <example name="select-with-default-values" module="defaultValueSelect">
  27148. * <file name="index.html">
  27149. * <div ng-controller="ExampleController">
  27150. * <form name="myForm">
  27151. * <label for="mySelect">Make a choice:</label>
  27152. * <select name="mySelect" id="mySelect"
  27153. * ng-options="option.name for option in data.availableOptions track by option.id"
  27154. * ng-model="data.selectedOption"></select>
  27155. * </form>
  27156. * <hr>
  27157. * <tt>option = {{data.selectedOption}}</tt><br/>
  27158. * </div>
  27159. * </file>
  27160. * <file name="app.js">
  27161. * angular.module('defaultValueSelect', [])
  27162. * .controller('ExampleController', ['$scope', function($scope) {
  27163. * $scope.data = {
  27164. * availableOptions: [
  27165. * {id: '1', name: 'Option A'},
  27166. * {id: '2', name: 'Option B'},
  27167. * {id: '3', name: 'Option C'}
  27168. * ],
  27169. * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
  27170. * };
  27171. * }]);
  27172. * </file>
  27173. *</example>
  27174. *
  27175. *
  27176. * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
  27177. *
  27178. * <example name="select-with-non-string-options" module="nonStringSelect">
  27179. * <file name="index.html">
  27180. * <select ng-model="model.id" convert-to-number>
  27181. * <option value="0">Zero</option>
  27182. * <option value="1">One</option>
  27183. * <option value="2">Two</option>
  27184. * </select>
  27185. * {{ model }}
  27186. * </file>
  27187. * <file name="app.js">
  27188. * angular.module('nonStringSelect', [])
  27189. * .run(function($rootScope) {
  27190. * $rootScope.model = { id: 2 };
  27191. * })
  27192. * .directive('convertToNumber', function() {
  27193. * return {
  27194. * require: 'ngModel',
  27195. * link: function(scope, element, attrs, ngModel) {
  27196. * ngModel.$parsers.push(function(val) {
  27197. * return parseInt(val, 10);
  27198. * });
  27199. * ngModel.$formatters.push(function(val) {
  27200. * return '' + val;
  27201. * });
  27202. * }
  27203. * };
  27204. * });
  27205. * </file>
  27206. * <file name="protractor.js" type="protractor">
  27207. * it('should initialize to model', function() {
  27208. * var select = element(by.css('select'));
  27209. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  27210. * });
  27211. * </file>
  27212. * </example>
  27213. *
  27214. */
  27215. var selectDirective = function() {
  27216. return {
  27217. restrict: 'E',
  27218. require: ['select', '?ngModel'],
  27219. controller: SelectController,
  27220. priority: 1,
  27221. link: {
  27222. pre: selectPreLink,
  27223. post: selectPostLink
  27224. }
  27225. };
  27226. function selectPreLink(scope, element, attr, ctrls) {
  27227. // if ngModel is not defined, we don't need to do anything
  27228. var ngModelCtrl = ctrls[1];
  27229. if (!ngModelCtrl) return;
  27230. var selectCtrl = ctrls[0];
  27231. selectCtrl.ngModelCtrl = ngModelCtrl;
  27232. // When the selected item(s) changes we delegate getting the value of the select control
  27233. // to the `readValue` method, which can be changed if the select can have multiple
  27234. // selected values or if the options are being generated by `ngOptions`
  27235. element.on('change', function() {
  27236. scope.$apply(function() {
  27237. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  27238. });
  27239. });
  27240. // If the select allows multiple values then we need to modify how we read and write
  27241. // values from and to the control; also what it means for the value to be empty and
  27242. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  27243. // doesn't trigger rendering if only an item in the array changes.
  27244. if (attr.multiple) {
  27245. // Read value now needs to check each option to see if it is selected
  27246. selectCtrl.readValue = function readMultipleValue() {
  27247. var array = [];
  27248. forEach(element.find('option'), function(option) {
  27249. if (option.selected) {
  27250. array.push(option.value);
  27251. }
  27252. });
  27253. return array;
  27254. };
  27255. // Write value now needs to set the selected property of each matching option
  27256. selectCtrl.writeValue = function writeMultipleValue(value) {
  27257. var items = new HashMap(value);
  27258. forEach(element.find('option'), function(option) {
  27259. option.selected = isDefined(items.get(option.value));
  27260. });
  27261. };
  27262. // we have to do it on each watch since ngModel watches reference, but
  27263. // we need to work of an array, so we need to see if anything was inserted/removed
  27264. var lastView, lastViewRef = NaN;
  27265. scope.$watch(function selectMultipleWatch() {
  27266. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  27267. lastView = shallowCopy(ngModelCtrl.$viewValue);
  27268. ngModelCtrl.$render();
  27269. }
  27270. lastViewRef = ngModelCtrl.$viewValue;
  27271. });
  27272. // If we are a multiple select then value is now a collection
  27273. // so the meaning of $isEmpty changes
  27274. ngModelCtrl.$isEmpty = function(value) {
  27275. return !value || value.length === 0;
  27276. };
  27277. }
  27278. }
  27279. function selectPostLink(scope, element, attrs, ctrls) {
  27280. // if ngModel is not defined, we don't need to do anything
  27281. var ngModelCtrl = ctrls[1];
  27282. if (!ngModelCtrl) return;
  27283. var selectCtrl = ctrls[0];
  27284. // We delegate rendering to the `writeValue` method, which can be changed
  27285. // if the select can have multiple selected values or if the options are being
  27286. // generated by `ngOptions`.
  27287. // This must be done in the postLink fn to prevent $render to be called before
  27288. // all nodes have been linked correctly.
  27289. ngModelCtrl.$render = function() {
  27290. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  27291. };
  27292. }
  27293. };
  27294. // The option directive is purely designed to communicate the existence (or lack of)
  27295. // of dynamically created (and destroyed) option elements to their containing select
  27296. // directive via its controller.
  27297. var optionDirective = ['$interpolate', function($interpolate) {
  27298. return {
  27299. restrict: 'E',
  27300. priority: 100,
  27301. compile: function(element, attr) {
  27302. if (isDefined(attr.value)) {
  27303. // If the value attribute is defined, check if it contains an interpolation
  27304. var interpolateValueFn = $interpolate(attr.value, true);
  27305. } else {
  27306. // If the value attribute is not defined then we fall back to the
  27307. // text content of the option element, which may be interpolated
  27308. var interpolateTextFn = $interpolate(element.text(), true);
  27309. if (!interpolateTextFn) {
  27310. attr.$set('value', element.text());
  27311. }
  27312. }
  27313. return function(scope, element, attr) {
  27314. // This is an optimization over using ^^ since we don't want to have to search
  27315. // all the way to the root of the DOM for every single option element
  27316. var selectCtrlName = '$selectController',
  27317. parent = element.parent(),
  27318. selectCtrl = parent.data(selectCtrlName) ||
  27319. parent.parent().data(selectCtrlName); // in case we are in optgroup
  27320. if (selectCtrl) {
  27321. selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
  27322. }
  27323. };
  27324. }
  27325. };
  27326. }];
  27327. var styleDirective = valueFn({
  27328. restrict: 'E',
  27329. terminal: false
  27330. });
  27331. /**
  27332. * @ngdoc directive
  27333. * @name ngRequired
  27334. *
  27335. * @description
  27336. *
  27337. * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  27338. * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be
  27339. * applied to custom controls.
  27340. *
  27341. * The directive sets the `required` attribute on the element if the Angular expression inside
  27342. * `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we
  27343. * cannot use interpolation inside `required`. See the {@link guide/interpolation interpolation guide}
  27344. * for more info.
  27345. *
  27346. * The validator will set the `required` error key to true if the `required` attribute is set and
  27347. * calling {@link ngModel.NgModelController#$isEmpty `NgModelController.$isEmpty`} with the
  27348. * {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} returns `true`. For example, the
  27349. * `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing
  27350. * custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based.
  27351. *
  27352. * @example
  27353. * <example name="ngRequiredDirective" module="ngRequiredExample">
  27354. * <file name="index.html">
  27355. * <script>
  27356. * angular.module('ngRequiredExample', [])
  27357. * .controller('ExampleController', ['$scope', function($scope) {
  27358. * $scope.required = true;
  27359. * }]);
  27360. * </script>
  27361. * <div ng-controller="ExampleController">
  27362. * <form name="form">
  27363. * <label for="required">Toggle required: </label>
  27364. * <input type="checkbox" ng-model="required" id="required" />
  27365. * <br>
  27366. * <label for="input">This input must be filled if `required` is true: </label>
  27367. * <input type="text" ng-model="model" id="input" name="input" ng-required="required" /><br>
  27368. * <hr>
  27369. * required error set? = <code>{{form.input.$error.required}}</code><br>
  27370. * model = <code>{{model}}</code>
  27371. * </form>
  27372. * </div>
  27373. * </file>
  27374. * <file name="protractor.js" type="protractor">
  27375. var required = element(by.binding('form.input.$error.required'));
  27376. var model = element(by.binding('model'));
  27377. var input = element(by.id('input'));
  27378. it('should set the required error', function() {
  27379. expect(required.getText()).toContain('true');
  27380. input.sendKeys('123');
  27381. expect(required.getText()).not.toContain('true');
  27382. expect(model.getText()).toContain('123');
  27383. });
  27384. * </file>
  27385. * </example>
  27386. */
  27387. var requiredDirective = function() {
  27388. return {
  27389. restrict: 'A',
  27390. require: '?ngModel',
  27391. link: function(scope, elm, attr, ctrl) {
  27392. if (!ctrl) return;
  27393. attr.required = true; // force truthy in case we are on non input element
  27394. ctrl.$validators.required = function(modelValue, viewValue) {
  27395. return !attr.required || !ctrl.$isEmpty(viewValue);
  27396. };
  27397. attr.$observe('required', function() {
  27398. ctrl.$validate();
  27399. });
  27400. }
  27401. };
  27402. };
  27403. /**
  27404. * @ngdoc directive
  27405. * @name ngPattern
  27406. *
  27407. * @description
  27408. *
  27409. * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  27410. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  27411. *
  27412. * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  27413. * does not match a RegExp which is obtained by evaluating the Angular expression given in the
  27414. * `ngPattern` attribute value:
  27415. * * If the expression evaluates to a RegExp object, then this is used directly.
  27416. * * If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it
  27417. * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  27418. *
  27419. * <div class="alert alert-info">
  27420. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  27421. * start at the index of the last search's match, thus not taking the whole input value into
  27422. * account.
  27423. * </div>
  27424. *
  27425. * <div class="alert alert-info">
  27426. * **Note:** This directive is also added when the plain `pattern` attribute is used, with two
  27427. * differences:
  27428. * <ol>
  27429. * <li>
  27430. * `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is
  27431. * not available.
  27432. * </li>
  27433. * <li>
  27434. * The `ngPattern` attribute must be an expression, while the `pattern` value must be
  27435. * interpolated.
  27436. * </li>
  27437. * </ol>
  27438. * </div>
  27439. *
  27440. * @example
  27441. * <example name="ngPatternDirective" module="ngPatternExample">
  27442. * <file name="index.html">
  27443. * <script>
  27444. * angular.module('ngPatternExample', [])
  27445. * .controller('ExampleController', ['$scope', function($scope) {
  27446. * $scope.regex = '\\d+';
  27447. * }]);
  27448. * </script>
  27449. * <div ng-controller="ExampleController">
  27450. * <form name="form">
  27451. * <label for="regex">Set a pattern (regex string): </label>
  27452. * <input type="text" ng-model="regex" id="regex" />
  27453. * <br>
  27454. * <label for="input">This input is restricted by the current pattern: </label>
  27455. * <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
  27456. * <hr>
  27457. * input valid? = <code>{{form.input.$valid}}</code><br>
  27458. * model = <code>{{model}}</code>
  27459. * </form>
  27460. * </div>
  27461. * </file>
  27462. * <file name="protractor.js" type="protractor">
  27463. var model = element(by.binding('model'));
  27464. var input = element(by.id('input'));
  27465. it('should validate the input with the default pattern', function() {
  27466. input.sendKeys('aaa');
  27467. expect(model.getText()).not.toContain('aaa');
  27468. input.clear().then(function() {
  27469. input.sendKeys('123');
  27470. expect(model.getText()).toContain('123');
  27471. });
  27472. });
  27473. * </file>
  27474. * </example>
  27475. */
  27476. var patternDirective = function() {
  27477. return {
  27478. restrict: 'A',
  27479. require: '?ngModel',
  27480. link: function(scope, elm, attr, ctrl) {
  27481. if (!ctrl) return;
  27482. var regexp, patternExp = attr.ngPattern || attr.pattern;
  27483. attr.$observe('pattern', function(regex) {
  27484. if (isString(regex) && regex.length > 0) {
  27485. regex = new RegExp('^' + regex + '$');
  27486. }
  27487. if (regex && !regex.test) {
  27488. throw minErr('ngPattern')('noregexp',
  27489. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  27490. regex, startingTag(elm));
  27491. }
  27492. regexp = regex || undefined;
  27493. ctrl.$validate();
  27494. });
  27495. ctrl.$validators.pattern = function(modelValue, viewValue) {
  27496. // HTML5 pattern constraint validates the input value, so we validate the viewValue
  27497. return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
  27498. };
  27499. }
  27500. };
  27501. };
  27502. /**
  27503. * @ngdoc directive
  27504. * @name ngMaxlength
  27505. *
  27506. * @description
  27507. *
  27508. * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  27509. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  27510. *
  27511. * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  27512. * is longer than the integer obtained by evaluating the Angular expression given in the
  27513. * `ngMaxlength` attribute value.
  27514. *
  27515. * <div class="alert alert-info">
  27516. * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two
  27517. * differences:
  27518. * <ol>
  27519. * <li>
  27520. * `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint
  27521. * validation is not available.
  27522. * </li>
  27523. * <li>
  27524. * The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be
  27525. * interpolated.
  27526. * </li>
  27527. * </ol>
  27528. * </div>
  27529. *
  27530. * @example
  27531. * <example name="ngMaxlengthDirective" module="ngMaxlengthExample">
  27532. * <file name="index.html">
  27533. * <script>
  27534. * angular.module('ngMaxlengthExample', [])
  27535. * .controller('ExampleController', ['$scope', function($scope) {
  27536. * $scope.maxlength = 5;
  27537. * }]);
  27538. * </script>
  27539. * <div ng-controller="ExampleController">
  27540. * <form name="form">
  27541. * <label for="maxlength">Set a maxlength: </label>
  27542. * <input type="number" ng-model="maxlength" id="maxlength" />
  27543. * <br>
  27544. * <label for="input">This input is restricted by the current maxlength: </label>
  27545. * <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br>
  27546. * <hr>
  27547. * input valid? = <code>{{form.input.$valid}}</code><br>
  27548. * model = <code>{{model}}</code>
  27549. * </form>
  27550. * </div>
  27551. * </file>
  27552. * <file name="protractor.js" type="protractor">
  27553. var model = element(by.binding('model'));
  27554. var input = element(by.id('input'));
  27555. it('should validate the input with the default maxlength', function() {
  27556. input.sendKeys('abcdef');
  27557. expect(model.getText()).not.toContain('abcdef');
  27558. input.clear().then(function() {
  27559. input.sendKeys('abcde');
  27560. expect(model.getText()).toContain('abcde');
  27561. });
  27562. });
  27563. * </file>
  27564. * </example>
  27565. */
  27566. var maxlengthDirective = function() {
  27567. return {
  27568. restrict: 'A',
  27569. require: '?ngModel',
  27570. link: function(scope, elm, attr, ctrl) {
  27571. if (!ctrl) return;
  27572. var maxlength = -1;
  27573. attr.$observe('maxlength', function(value) {
  27574. var intVal = toInt(value);
  27575. maxlength = isNaN(intVal) ? -1 : intVal;
  27576. ctrl.$validate();
  27577. });
  27578. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  27579. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  27580. };
  27581. }
  27582. };
  27583. };
  27584. /**
  27585. * @ngdoc directive
  27586. * @name ngMinlength
  27587. *
  27588. * @description
  27589. *
  27590. * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  27591. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  27592. *
  27593. * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  27594. * is shorter than the integer obtained by evaluating the Angular expression given in the
  27595. * `ngMinlength` attribute value.
  27596. *
  27597. * <div class="alert alert-info">
  27598. * **Note:** This directive is also added when the plain `minlength` attribute is used, with two
  27599. * differences:
  27600. * <ol>
  27601. * <li>
  27602. * `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint
  27603. * validation is not available.
  27604. * </li>
  27605. * <li>
  27606. * The `ngMinlength` value must be an expression, while the `minlength` value must be
  27607. * interpolated.
  27608. * </li>
  27609. * </ol>
  27610. * </div>
  27611. *
  27612. * @example
  27613. * <example name="ngMinlengthDirective" module="ngMinlengthExample">
  27614. * <file name="index.html">
  27615. * <script>
  27616. * angular.module('ngMinlengthExample', [])
  27617. * .controller('ExampleController', ['$scope', function($scope) {
  27618. * $scope.minlength = 3;
  27619. * }]);
  27620. * </script>
  27621. * <div ng-controller="ExampleController">
  27622. * <form name="form">
  27623. * <label for="minlength">Set a minlength: </label>
  27624. * <input type="number" ng-model="minlength" id="minlength" />
  27625. * <br>
  27626. * <label for="input">This input is restricted by the current minlength: </label>
  27627. * <input type="text" ng-model="model" id="input" name="input" ng-minlength="minlength" /><br>
  27628. * <hr>
  27629. * input valid? = <code>{{form.input.$valid}}</code><br>
  27630. * model = <code>{{model}}</code>
  27631. * </form>
  27632. * </div>
  27633. * </file>
  27634. * <file name="protractor.js" type="protractor">
  27635. var model = element(by.binding('model'));
  27636. var input = element(by.id('input'));
  27637. it('should validate the input with the default minlength', function() {
  27638. input.sendKeys('ab');
  27639. expect(model.getText()).not.toContain('ab');
  27640. input.sendKeys('abc');
  27641. expect(model.getText()).toContain('abc');
  27642. });
  27643. * </file>
  27644. * </example>
  27645. */
  27646. var minlengthDirective = function() {
  27647. return {
  27648. restrict: 'A',
  27649. require: '?ngModel',
  27650. link: function(scope, elm, attr, ctrl) {
  27651. if (!ctrl) return;
  27652. var minlength = 0;
  27653. attr.$observe('minlength', function(value) {
  27654. minlength = toInt(value) || 0;
  27655. ctrl.$validate();
  27656. });
  27657. ctrl.$validators.minlength = function(modelValue, viewValue) {
  27658. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  27659. };
  27660. }
  27661. };
  27662. };
  27663. if (window.angular.bootstrap) {
  27664. //AngularJS is already loaded, so we can return here...
  27665. console.log('WARNING: Tried to load angular more than once.');
  27666. return;
  27667. }
  27668. //try to bind to jquery now so that one can write jqLite(document).ready()
  27669. //but we will rebind on bootstrap again.
  27670. bindJQuery();
  27671. publishExternalAPI(angular);
  27672. angular.module("ngLocale", [], ["$provide", function($provide) {
  27673. var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
  27674. function getDecimals(n) {
  27675. n = n + '';
  27676. var i = n.indexOf('.');
  27677. return (i == -1) ? 0 : n.length - i - 1;
  27678. }
  27679. function getVF(n, opt_precision) {
  27680. var v = opt_precision;
  27681. if (undefined === v) {
  27682. v = Math.min(getDecimals(n), 3);
  27683. }
  27684. var base = Math.pow(10, v);
  27685. var f = ((n * base) | 0) % base;
  27686. return {v: v, f: f};
  27687. }
  27688. $provide.value("$locale", {
  27689. "DATETIME_FORMATS": {
  27690. "AMPMS": [
  27691. "AM",
  27692. "PM"
  27693. ],
  27694. "DAY": [
  27695. "Sunday",
  27696. "Monday",
  27697. "Tuesday",
  27698. "Wednesday",
  27699. "Thursday",
  27700. "Friday",
  27701. "Saturday"
  27702. ],
  27703. "ERANAMES": [
  27704. "Before Christ",
  27705. "Anno Domini"
  27706. ],
  27707. "ERAS": [
  27708. "BC",
  27709. "AD"
  27710. ],
  27711. "FIRSTDAYOFWEEK": 6,
  27712. "MONTH": [
  27713. "January",
  27714. "February",
  27715. "March",
  27716. "April",
  27717. "May",
  27718. "June",
  27719. "July",
  27720. "August",
  27721. "September",
  27722. "October",
  27723. "November",
  27724. "December"
  27725. ],
  27726. "SHORTDAY": [
  27727. "Sun",
  27728. "Mon",
  27729. "Tue",
  27730. "Wed",
  27731. "Thu",
  27732. "Fri",
  27733. "Sat"
  27734. ],
  27735. "SHORTMONTH": [
  27736. "Jan",
  27737. "Feb",
  27738. "Mar",
  27739. "Apr",
  27740. "May",
  27741. "Jun",
  27742. "Jul",
  27743. "Aug",
  27744. "Sep",
  27745. "Oct",
  27746. "Nov",
  27747. "Dec"
  27748. ],
  27749. "STANDALONEMONTH": [
  27750. "January",
  27751. "February",
  27752. "March",
  27753. "April",
  27754. "May",
  27755. "June",
  27756. "July",
  27757. "August",
  27758. "September",
  27759. "October",
  27760. "November",
  27761. "December"
  27762. ],
  27763. "WEEKENDRANGE": [
  27764. 5,
  27765. 6
  27766. ],
  27767. "fullDate": "EEEE, MMMM d, y",
  27768. "longDate": "MMMM d, y",
  27769. "medium": "MMM d, y h:mm:ss a",
  27770. "mediumDate": "MMM d, y",
  27771. "mediumTime": "h:mm:ss a",
  27772. "short": "M/d/yy h:mm a",
  27773. "shortDate": "M/d/yy",
  27774. "shortTime": "h:mm a"
  27775. },
  27776. "NUMBER_FORMATS": {
  27777. "CURRENCY_SYM": "$",
  27778. "DECIMAL_SEP": ".",
  27779. "GROUP_SEP": ",",
  27780. "PATTERNS": [
  27781. {
  27782. "gSize": 3,
  27783. "lgSize": 3,
  27784. "maxFrac": 3,
  27785. "minFrac": 0,
  27786. "minInt": 1,
  27787. "negPre": "-",
  27788. "negSuf": "",
  27789. "posPre": "",
  27790. "posSuf": ""
  27791. },
  27792. {
  27793. "gSize": 3,
  27794. "lgSize": 3,
  27795. "maxFrac": 2,
  27796. "minFrac": 2,
  27797. "minInt": 1,
  27798. "negPre": "-\u00a4",
  27799. "negSuf": "",
  27800. "posPre": "\u00a4",
  27801. "posSuf": ""
  27802. }
  27803. ]
  27804. },
  27805. "id": "en-us",
  27806. "localeID": "en_US",
  27807. "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
  27808. });
  27809. }]);
  27810. jqLite(document).ready(function() {
  27811. angularInit(document, bootstrap);
  27812. });
  27813. })(window, document);
  27814. !window.angular.$$csp().noInlineStyle && window.angular.element(document.head).prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>');