angular.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473
  1. /**
  2. * @license AngularJS v1.5.7
  3. * (c) 2010-2016 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window) {'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.7/' +
  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. equals: true,
  119. csp: true,
  120. jq: true,
  121. concat: true,
  122. sliceArgs: true,
  123. bind: true,
  124. toJsonReplacer: true,
  125. toJson: true,
  126. fromJson: true,
  127. convertTimezoneToLocal: true,
  128. timezoneToOffset: true,
  129. startingTag: true,
  130. tryDecodeURIComponent: true,
  131. parseKeyValue: true,
  132. toKeyValue: true,
  133. encodeUriSegment: true,
  134. encodeUriQuery: true,
  135. angularInit: true,
  136. bootstrap: true,
  137. getTestability: true,
  138. snake_case: true,
  139. bindJQuery: true,
  140. assertArg: true,
  141. assertArgFn: true,
  142. assertNotHasOwnProperty: true,
  143. getter: true,
  144. getBlockNodes: true,
  145. hasOwnProperty: true,
  146. createMap: true,
  147. NODE_TYPE_ELEMENT: true,
  148. NODE_TYPE_ATTRIBUTE: true,
  149. NODE_TYPE_TEXT: true,
  150. NODE_TYPE_COMMENT: true,
  151. NODE_TYPE_DOCUMENT: true,
  152. NODE_TYPE_DOCUMENT_FRAGMENT: true,
  153. */
  154. ////////////////////////////////////
  155. /**
  156. * @ngdoc module
  157. * @name ng
  158. * @module ng
  159. * @installation
  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 = window.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. // E.g.
  465. function getResult(fn, input) {
  466. return (fn || angular.identity)(input);
  467. };
  468. getResult(function(n) { return n * 2; }, 21); // returns 42
  469. getResult(null, 21); // returns 21
  470. getResult(undefined, 21); // returns 21
  471. ```
  472. *
  473. * @param {*} value to be returned.
  474. * @returns {*} the value passed in.
  475. */
  476. function identity($) {return $;}
  477. identity.$inject = [];
  478. function valueFn(value) {return function valueRef() {return value;};}
  479. function hasCustomToString(obj) {
  480. return isFunction(obj.toString) && obj.toString !== toString;
  481. }
  482. /**
  483. * @ngdoc function
  484. * @name angular.isUndefined
  485. * @module ng
  486. * @kind function
  487. *
  488. * @description
  489. * Determines if a reference is undefined.
  490. *
  491. * @param {*} value Reference to check.
  492. * @returns {boolean} True if `value` is undefined.
  493. */
  494. function isUndefined(value) {return typeof value === 'undefined';}
  495. /**
  496. * @ngdoc function
  497. * @name angular.isDefined
  498. * @module ng
  499. * @kind function
  500. *
  501. * @description
  502. * Determines if a reference is defined.
  503. *
  504. * @param {*} value Reference to check.
  505. * @returns {boolean} True if `value` is defined.
  506. */
  507. function isDefined(value) {return typeof value !== 'undefined';}
  508. /**
  509. * @ngdoc function
  510. * @name angular.isObject
  511. * @module ng
  512. * @kind function
  513. *
  514. * @description
  515. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  516. * considered to be objects. Note that JavaScript arrays are objects.
  517. *
  518. * @param {*} value Reference to check.
  519. * @returns {boolean} True if `value` is an `Object` but not `null`.
  520. */
  521. function isObject(value) {
  522. // http://jsperf.com/isobject4
  523. return value !== null && typeof value === 'object';
  524. }
  525. /**
  526. * Determine if a value is an object with a null prototype
  527. *
  528. * @returns {boolean} True if `value` is an `Object` with a null prototype
  529. */
  530. function isBlankObject(value) {
  531. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  532. }
  533. /**
  534. * @ngdoc function
  535. * @name angular.isString
  536. * @module ng
  537. * @kind function
  538. *
  539. * @description
  540. * Determines if a reference is a `String`.
  541. *
  542. * @param {*} value Reference to check.
  543. * @returns {boolean} True if `value` is a `String`.
  544. */
  545. function isString(value) {return typeof value === 'string';}
  546. /**
  547. * @ngdoc function
  548. * @name angular.isNumber
  549. * @module ng
  550. * @kind function
  551. *
  552. * @description
  553. * Determines if a reference is a `Number`.
  554. *
  555. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  556. *
  557. * If you wish to exclude these then you can use the native
  558. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  559. * method.
  560. *
  561. * @param {*} value Reference to check.
  562. * @returns {boolean} True if `value` is a `Number`.
  563. */
  564. function isNumber(value) {return typeof value === 'number';}
  565. /**
  566. * @ngdoc function
  567. * @name angular.isDate
  568. * @module ng
  569. * @kind function
  570. *
  571. * @description
  572. * Determines if a value is a date.
  573. *
  574. * @param {*} value Reference to check.
  575. * @returns {boolean} True if `value` is a `Date`.
  576. */
  577. function isDate(value) {
  578. return toString.call(value) === '[object Date]';
  579. }
  580. /**
  581. * @ngdoc function
  582. * @name angular.isArray
  583. * @module ng
  584. * @kind function
  585. *
  586. * @description
  587. * Determines if a reference is an `Array`.
  588. *
  589. * @param {*} value Reference to check.
  590. * @returns {boolean} True if `value` is an `Array`.
  591. */
  592. var isArray = Array.isArray;
  593. /**
  594. * @ngdoc function
  595. * @name angular.isFunction
  596. * @module ng
  597. * @kind function
  598. *
  599. * @description
  600. * Determines if a reference is a `Function`.
  601. *
  602. * @param {*} value Reference to check.
  603. * @returns {boolean} True if `value` is a `Function`.
  604. */
  605. function isFunction(value) {return typeof value === 'function';}
  606. /**
  607. * Determines if a value is a regular expression object.
  608. *
  609. * @private
  610. * @param {*} value Reference to check.
  611. * @returns {boolean} True if `value` is a `RegExp`.
  612. */
  613. function isRegExp(value) {
  614. return toString.call(value) === '[object RegExp]';
  615. }
  616. /**
  617. * Checks if `obj` is a window object.
  618. *
  619. * @private
  620. * @param {*} obj Object to check
  621. * @returns {boolean} True if `obj` is a window obj.
  622. */
  623. function isWindow(obj) {
  624. return obj && obj.window === obj;
  625. }
  626. function isScope(obj) {
  627. return obj && obj.$evalAsync && obj.$watch;
  628. }
  629. function isFile(obj) {
  630. return toString.call(obj) === '[object File]';
  631. }
  632. function isFormData(obj) {
  633. return toString.call(obj) === '[object FormData]';
  634. }
  635. function isBlob(obj) {
  636. return toString.call(obj) === '[object Blob]';
  637. }
  638. function isBoolean(value) {
  639. return typeof value === 'boolean';
  640. }
  641. function isPromiseLike(obj) {
  642. return obj && isFunction(obj.then);
  643. }
  644. var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array\]$/;
  645. function isTypedArray(value) {
  646. return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
  647. }
  648. function isArrayBuffer(obj) {
  649. return toString.call(obj) === '[object ArrayBuffer]';
  650. }
  651. var trim = function(value) {
  652. return isString(value) ? value.trim() : value;
  653. };
  654. // Copied from:
  655. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  656. // Prereq: s is a string.
  657. var escapeForRegexp = function(s) {
  658. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  659. replace(/\x08/g, '\\x08');
  660. };
  661. /**
  662. * @ngdoc function
  663. * @name angular.isElement
  664. * @module ng
  665. * @kind function
  666. *
  667. * @description
  668. * Determines if a reference is a DOM element (or wrapped jQuery element).
  669. *
  670. * @param {*} value Reference to check.
  671. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  672. */
  673. function isElement(node) {
  674. return !!(node &&
  675. (node.nodeName // We are a direct element.
  676. || (node.prop && node.attr && node.find))); // We have an on and find method part of jQuery API.
  677. }
  678. /**
  679. * @param str 'key1,key2,...'
  680. * @returns {object} in the form of {key1:true, key2:true, ...}
  681. */
  682. function makeMap(str) {
  683. var obj = {}, items = str.split(','), i;
  684. for (i = 0; i < items.length; i++) {
  685. obj[items[i]] = true;
  686. }
  687. return obj;
  688. }
  689. function nodeName_(element) {
  690. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  691. }
  692. function includes(array, obj) {
  693. return Array.prototype.indexOf.call(array, obj) != -1;
  694. }
  695. function arrayRemove(array, value) {
  696. var index = array.indexOf(value);
  697. if (index >= 0) {
  698. array.splice(index, 1);
  699. }
  700. return index;
  701. }
  702. /**
  703. * @ngdoc function
  704. * @name angular.copy
  705. * @module ng
  706. * @kind function
  707. *
  708. * @description
  709. * Creates a deep copy of `source`, which should be an object or an array.
  710. *
  711. * * If no destination is supplied, a copy of the object or array is created.
  712. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  713. * are deleted and then all elements/properties from the source are copied to it.
  714. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  715. * * If `source` is identical to 'destination' an exception will be thrown.
  716. *
  717. * @param {*} source The source that will be used to make a copy.
  718. * Can be any type, including primitives, `null`, and `undefined`.
  719. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  720. * provided, must be of the same type as `source`.
  721. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  722. *
  723. * @example
  724. <example module="copyExample">
  725. <file name="index.html">
  726. <div ng-controller="ExampleController">
  727. <form novalidate class="simple-form">
  728. Name: <input type="text" ng-model="user.name" /><br />
  729. E-mail: <input type="email" ng-model="user.email" /><br />
  730. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  731. <input type="radio" ng-model="user.gender" value="female" />female<br />
  732. <button ng-click="reset()">RESET</button>
  733. <button ng-click="update(user)">SAVE</button>
  734. </form>
  735. <pre>form = {{user | json}}</pre>
  736. <pre>master = {{master | json}}</pre>
  737. </div>
  738. <script>
  739. angular.module('copyExample', [])
  740. .controller('ExampleController', ['$scope', function($scope) {
  741. $scope.master= {};
  742. $scope.update = function(user) {
  743. // Example with 1 argument
  744. $scope.master= angular.copy(user);
  745. };
  746. $scope.reset = function() {
  747. // Example with 2 arguments
  748. angular.copy($scope.master, $scope.user);
  749. };
  750. $scope.reset();
  751. }]);
  752. </script>
  753. </file>
  754. </example>
  755. */
  756. function copy(source, destination) {
  757. var stackSource = [];
  758. var stackDest = [];
  759. if (destination) {
  760. if (isTypedArray(destination) || isArrayBuffer(destination)) {
  761. throw ngMinErr('cpta', "Can't copy! TypedArray destination cannot be mutated.");
  762. }
  763. if (source === destination) {
  764. throw ngMinErr('cpi', "Can't copy! Source and destination are identical.");
  765. }
  766. // Empty the destination object
  767. if (isArray(destination)) {
  768. destination.length = 0;
  769. } else {
  770. forEach(destination, function(value, key) {
  771. if (key !== '$$hashKey') {
  772. delete destination[key];
  773. }
  774. });
  775. }
  776. stackSource.push(source);
  777. stackDest.push(destination);
  778. return copyRecurse(source, destination);
  779. }
  780. return copyElement(source);
  781. function copyRecurse(source, destination) {
  782. var h = destination.$$hashKey;
  783. var key;
  784. if (isArray(source)) {
  785. for (var i = 0, ii = source.length; i < ii; i++) {
  786. destination.push(copyElement(source[i]));
  787. }
  788. } else if (isBlankObject(source)) {
  789. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  790. for (key in source) {
  791. destination[key] = copyElement(source[key]);
  792. }
  793. } else if (source && typeof source.hasOwnProperty === 'function') {
  794. // Slow path, which must rely on hasOwnProperty
  795. for (key in source) {
  796. if (source.hasOwnProperty(key)) {
  797. destination[key] = copyElement(source[key]);
  798. }
  799. }
  800. } else {
  801. // Slowest path --- hasOwnProperty can't be called as a method
  802. for (key in source) {
  803. if (hasOwnProperty.call(source, key)) {
  804. destination[key] = copyElement(source[key]);
  805. }
  806. }
  807. }
  808. setHashKey(destination, h);
  809. return destination;
  810. }
  811. function copyElement(source) {
  812. // Simple values
  813. if (!isObject(source)) {
  814. return source;
  815. }
  816. // Already copied values
  817. var index = stackSource.indexOf(source);
  818. if (index !== -1) {
  819. return stackDest[index];
  820. }
  821. if (isWindow(source) || isScope(source)) {
  822. throw ngMinErr('cpws',
  823. "Can't copy! Making copies of Window or Scope instances is not supported.");
  824. }
  825. var needsRecurse = false;
  826. var destination = copyType(source);
  827. if (destination === undefined) {
  828. destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
  829. needsRecurse = true;
  830. }
  831. stackSource.push(source);
  832. stackDest.push(destination);
  833. return needsRecurse
  834. ? copyRecurse(source, destination)
  835. : destination;
  836. }
  837. function copyType(source) {
  838. switch (toString.call(source)) {
  839. case '[object Int8Array]':
  840. case '[object Int16Array]':
  841. case '[object Int32Array]':
  842. case '[object Float32Array]':
  843. case '[object Float64Array]':
  844. case '[object Uint8Array]':
  845. case '[object Uint8ClampedArray]':
  846. case '[object Uint16Array]':
  847. case '[object Uint32Array]':
  848. return new source.constructor(copyElement(source.buffer));
  849. case '[object ArrayBuffer]':
  850. //Support: IE10
  851. if (!source.slice) {
  852. var copied = new ArrayBuffer(source.byteLength);
  853. new Uint8Array(copied).set(new Uint8Array(source));
  854. return copied;
  855. }
  856. return source.slice(0);
  857. case '[object Boolean]':
  858. case '[object Number]':
  859. case '[object String]':
  860. case '[object Date]':
  861. return new source.constructor(source.valueOf());
  862. case '[object RegExp]':
  863. var re = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  864. re.lastIndex = source.lastIndex;
  865. return re;
  866. case '[object Blob]':
  867. return new source.constructor([source], {type: source.type});
  868. }
  869. if (isFunction(source.cloneNode)) {
  870. return source.cloneNode(true);
  871. }
  872. }
  873. }
  874. /**
  875. * @ngdoc function
  876. * @name angular.equals
  877. * @module ng
  878. * @kind function
  879. *
  880. * @description
  881. * Determines if two objects or two values are equivalent. Supports value types, regular
  882. * expressions, arrays and objects.
  883. *
  884. * Two objects or values are considered equivalent if at least one of the following is true:
  885. *
  886. * * Both objects or values pass `===` comparison.
  887. * * Both objects or values are of the same type and all of their properties are equal by
  888. * comparing them with `angular.equals`.
  889. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  890. * * Both values represent the same regular expression (In JavaScript,
  891. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  892. * representation matches).
  893. *
  894. * During a property comparison, properties of `function` type and properties with names
  895. * that begin with `$` are ignored.
  896. *
  897. * Scope and DOMWindow objects are being compared only by identify (`===`).
  898. *
  899. * @param {*} o1 Object or value to compare.
  900. * @param {*} o2 Object or value to compare.
  901. * @returns {boolean} True if arguments are equal.
  902. *
  903. * @example
  904. <example module="equalsExample" name="equalsExample">
  905. <file name="index.html">
  906. <div ng-controller="ExampleController">
  907. <form novalidate>
  908. <h3>User 1</h3>
  909. Name: <input type="text" ng-model="user1.name">
  910. Age: <input type="number" ng-model="user1.age">
  911. <h3>User 2</h3>
  912. Name: <input type="text" ng-model="user2.name">
  913. Age: <input type="number" ng-model="user2.age">
  914. <div>
  915. <br/>
  916. <input type="button" value="Compare" ng-click="compare()">
  917. </div>
  918. User 1: <pre>{{user1 | json}}</pre>
  919. User 2: <pre>{{user2 | json}}</pre>
  920. Equal: <pre>{{result}}</pre>
  921. </form>
  922. </div>
  923. </file>
  924. <file name="script.js">
  925. angular.module('equalsExample', []).controller('ExampleController', ['$scope', function($scope) {
  926. $scope.user1 = {};
  927. $scope.user2 = {};
  928. $scope.result;
  929. $scope.compare = function() {
  930. $scope.result = angular.equals($scope.user1, $scope.user2);
  931. };
  932. }]);
  933. </file>
  934. </example>
  935. */
  936. function equals(o1, o2) {
  937. if (o1 === o2) return true;
  938. if (o1 === null || o2 === null) return false;
  939. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  940. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  941. if (t1 == t2 && t1 == 'object') {
  942. if (isArray(o1)) {
  943. if (!isArray(o2)) return false;
  944. if ((length = o1.length) == o2.length) {
  945. for (key = 0; key < length; key++) {
  946. if (!equals(o1[key], o2[key])) return false;
  947. }
  948. return true;
  949. }
  950. } else if (isDate(o1)) {
  951. if (!isDate(o2)) return false;
  952. return equals(o1.getTime(), o2.getTime());
  953. } else if (isRegExp(o1)) {
  954. if (!isRegExp(o2)) return false;
  955. return o1.toString() == o2.toString();
  956. } else {
  957. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  958. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  959. keySet = createMap();
  960. for (key in o1) {
  961. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  962. if (!equals(o1[key], o2[key])) return false;
  963. keySet[key] = true;
  964. }
  965. for (key in o2) {
  966. if (!(key in keySet) &&
  967. key.charAt(0) !== '$' &&
  968. isDefined(o2[key]) &&
  969. !isFunction(o2[key])) return false;
  970. }
  971. return true;
  972. }
  973. }
  974. return false;
  975. }
  976. var csp = function() {
  977. if (!isDefined(csp.rules)) {
  978. var ngCspElement = (window.document.querySelector('[ng-csp]') ||
  979. window.document.querySelector('[data-ng-csp]'));
  980. if (ngCspElement) {
  981. var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
  982. ngCspElement.getAttribute('data-ng-csp');
  983. csp.rules = {
  984. noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
  985. noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
  986. };
  987. } else {
  988. csp.rules = {
  989. noUnsafeEval: noUnsafeEval(),
  990. noInlineStyle: false
  991. };
  992. }
  993. }
  994. return csp.rules;
  995. function noUnsafeEval() {
  996. try {
  997. /* jshint -W031, -W054 */
  998. new Function('');
  999. /* jshint +W031, +W054 */
  1000. return false;
  1001. } catch (e) {
  1002. return true;
  1003. }
  1004. }
  1005. };
  1006. /**
  1007. * @ngdoc directive
  1008. * @module ng
  1009. * @name ngJq
  1010. *
  1011. * @element ANY
  1012. * @param {string=} ngJq the name of the library available under `window`
  1013. * to be used for angular.element
  1014. * @description
  1015. * Use this directive to force the angular.element library. This should be
  1016. * used to force either jqLite by leaving ng-jq blank or setting the name of
  1017. * the jquery variable under window (eg. jQuery).
  1018. *
  1019. * Since angular looks for this directive when it is loaded (doesn't wait for the
  1020. * DOMContentLoaded event), it must be placed on an element that comes before the script
  1021. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  1022. * others ignored.
  1023. *
  1024. * @example
  1025. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  1026. ```html
  1027. <!doctype html>
  1028. <html ng-app ng-jq>
  1029. ...
  1030. ...
  1031. </html>
  1032. ```
  1033. * @example
  1034. * This example shows how to use a jQuery based library of a different name.
  1035. * The library name must be available at the top most 'window'.
  1036. ```html
  1037. <!doctype html>
  1038. <html ng-app ng-jq="jQueryLib">
  1039. ...
  1040. ...
  1041. </html>
  1042. ```
  1043. */
  1044. var jq = function() {
  1045. if (isDefined(jq.name_)) return jq.name_;
  1046. var el;
  1047. var i, ii = ngAttrPrefixes.length, prefix, name;
  1048. for (i = 0; i < ii; ++i) {
  1049. prefix = ngAttrPrefixes[i];
  1050. if (el = window.document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]')) {
  1051. name = el.getAttribute(prefix + 'jq');
  1052. break;
  1053. }
  1054. }
  1055. return (jq.name_ = name);
  1056. };
  1057. function concat(array1, array2, index) {
  1058. return array1.concat(slice.call(array2, index));
  1059. }
  1060. function sliceArgs(args, startIndex) {
  1061. return slice.call(args, startIndex || 0);
  1062. }
  1063. /* jshint -W101 */
  1064. /**
  1065. * @ngdoc function
  1066. * @name angular.bind
  1067. * @module ng
  1068. * @kind function
  1069. *
  1070. * @description
  1071. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  1072. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  1073. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  1074. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  1075. *
  1076. * @param {Object} self Context which `fn` should be evaluated in.
  1077. * @param {function()} fn Function to be bound.
  1078. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  1079. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  1080. */
  1081. /* jshint +W101 */
  1082. function bind(self, fn) {
  1083. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  1084. if (isFunction(fn) && !(fn instanceof RegExp)) {
  1085. return curryArgs.length
  1086. ? function() {
  1087. return arguments.length
  1088. ? fn.apply(self, concat(curryArgs, arguments, 0))
  1089. : fn.apply(self, curryArgs);
  1090. }
  1091. : function() {
  1092. return arguments.length
  1093. ? fn.apply(self, arguments)
  1094. : fn.call(self);
  1095. };
  1096. } else {
  1097. // In IE, native methods are not functions so they cannot be bound (note: they don't need to be).
  1098. return fn;
  1099. }
  1100. }
  1101. function toJsonReplacer(key, value) {
  1102. var val = value;
  1103. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  1104. val = undefined;
  1105. } else if (isWindow(value)) {
  1106. val = '$WINDOW';
  1107. } else if (value && window.document === value) {
  1108. val = '$DOCUMENT';
  1109. } else if (isScope(value)) {
  1110. val = '$SCOPE';
  1111. }
  1112. return val;
  1113. }
  1114. /**
  1115. * @ngdoc function
  1116. * @name angular.toJson
  1117. * @module ng
  1118. * @kind function
  1119. *
  1120. * @description
  1121. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  1122. * stripped since angular uses this notation internally.
  1123. *
  1124. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  1125. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  1126. * If set to an integer, the JSON output will contain that many spaces per indentation.
  1127. * @returns {string|undefined} JSON-ified string representing `obj`.
  1128. * @knownIssue
  1129. *
  1130. * The Safari browser throws a `RangeError` instead of returning `null` when it tries to stringify a `Date`
  1131. * object with an invalid date value. The only reliable way to prevent this is to monkeypatch the
  1132. * `Date.prototype.toJSON` method as follows:
  1133. *
  1134. * ```
  1135. * var _DatetoJSON = Date.prototype.toJSON;
  1136. * Date.prototype.toJSON = function() {
  1137. * try {
  1138. * return _DatetoJSON.call(this);
  1139. * } catch(e) {
  1140. * if (e instanceof RangeError) {
  1141. * return null;
  1142. * }
  1143. * throw e;
  1144. * }
  1145. * };
  1146. * ```
  1147. *
  1148. * See https://github.com/angular/angular.js/pull/14221 for more information.
  1149. */
  1150. function toJson(obj, pretty) {
  1151. if (isUndefined(obj)) return undefined;
  1152. if (!isNumber(pretty)) {
  1153. pretty = pretty ? 2 : null;
  1154. }
  1155. return JSON.stringify(obj, toJsonReplacer, pretty);
  1156. }
  1157. /**
  1158. * @ngdoc function
  1159. * @name angular.fromJson
  1160. * @module ng
  1161. * @kind function
  1162. *
  1163. * @description
  1164. * Deserializes a JSON string.
  1165. *
  1166. * @param {string} json JSON string to deserialize.
  1167. * @returns {Object|Array|string|number} Deserialized JSON string.
  1168. */
  1169. function fromJson(json) {
  1170. return isString(json)
  1171. ? JSON.parse(json)
  1172. : json;
  1173. }
  1174. var ALL_COLONS = /:/g;
  1175. function timezoneToOffset(timezone, fallback) {
  1176. // IE/Edge do not "understand" colon (`:`) in timezone
  1177. timezone = timezone.replace(ALL_COLONS, '');
  1178. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  1179. return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  1180. }
  1181. function addDateMinutes(date, minutes) {
  1182. date = new Date(date.getTime());
  1183. date.setMinutes(date.getMinutes() + minutes);
  1184. return date;
  1185. }
  1186. function convertTimezoneToLocal(date, timezone, reverse) {
  1187. reverse = reverse ? -1 : 1;
  1188. var dateTimezoneOffset = date.getTimezoneOffset();
  1189. var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  1190. return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));
  1191. }
  1192. /**
  1193. * @returns {string} Returns the string representation of the element.
  1194. */
  1195. function startingTag(element) {
  1196. element = jqLite(element).clone();
  1197. try {
  1198. // turns out IE does not let you set .html() on elements which
  1199. // are not allowed to have children. So we just ignore it.
  1200. element.empty();
  1201. } catch (e) {}
  1202. var elemHtml = jqLite('<div>').append(element).html();
  1203. try {
  1204. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  1205. elemHtml.
  1206. match(/^(<[^>]+>)/)[1].
  1207. replace(/^<([\w\-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
  1208. } catch (e) {
  1209. return lowercase(elemHtml);
  1210. }
  1211. }
  1212. /////////////////////////////////////////////////
  1213. /**
  1214. * Tries to decode the URI component without throwing an exception.
  1215. *
  1216. * @private
  1217. * @param str value potential URI component to check.
  1218. * @returns {boolean} True if `value` can be decoded
  1219. * with the decodeURIComponent function.
  1220. */
  1221. function tryDecodeURIComponent(value) {
  1222. try {
  1223. return decodeURIComponent(value);
  1224. } catch (e) {
  1225. // Ignore any invalid uri component.
  1226. }
  1227. }
  1228. /**
  1229. * Parses an escaped url query string into key-value pairs.
  1230. * @returns {Object.<string,boolean|Array>}
  1231. */
  1232. function parseKeyValue(/**string*/keyValue) {
  1233. var obj = {};
  1234. forEach((keyValue || "").split('&'), function(keyValue) {
  1235. var splitPoint, key, val;
  1236. if (keyValue) {
  1237. key = keyValue = keyValue.replace(/\+/g,'%20');
  1238. splitPoint = keyValue.indexOf('=');
  1239. if (splitPoint !== -1) {
  1240. key = keyValue.substring(0, splitPoint);
  1241. val = keyValue.substring(splitPoint + 1);
  1242. }
  1243. key = tryDecodeURIComponent(key);
  1244. if (isDefined(key)) {
  1245. val = isDefined(val) ? tryDecodeURIComponent(val) : true;
  1246. if (!hasOwnProperty.call(obj, key)) {
  1247. obj[key] = val;
  1248. } else if (isArray(obj[key])) {
  1249. obj[key].push(val);
  1250. } else {
  1251. obj[key] = [obj[key],val];
  1252. }
  1253. }
  1254. }
  1255. });
  1256. return obj;
  1257. }
  1258. function toKeyValue(obj) {
  1259. var parts = [];
  1260. forEach(obj, function(value, key) {
  1261. if (isArray(value)) {
  1262. forEach(value, function(arrayValue) {
  1263. parts.push(encodeUriQuery(key, true) +
  1264. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1265. });
  1266. } else {
  1267. parts.push(encodeUriQuery(key, true) +
  1268. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1269. }
  1270. });
  1271. return parts.length ? parts.join('&') : '';
  1272. }
  1273. /**
  1274. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1275. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1276. * segments:
  1277. * segment = *pchar
  1278. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1279. * pct-encoded = "%" HEXDIG HEXDIG
  1280. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1281. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1282. * / "*" / "+" / "," / ";" / "="
  1283. */
  1284. function encodeUriSegment(val) {
  1285. return encodeUriQuery(val, true).
  1286. replace(/%26/gi, '&').
  1287. replace(/%3D/gi, '=').
  1288. replace(/%2B/gi, '+');
  1289. }
  1290. /**
  1291. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1292. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1293. * encoded per http://tools.ietf.org/html/rfc3986:
  1294. * query = *( pchar / "/" / "?" )
  1295. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1296. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1297. * pct-encoded = "%" HEXDIG HEXDIG
  1298. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1299. * / "*" / "+" / "," / ";" / "="
  1300. */
  1301. function encodeUriQuery(val, pctEncodeSpaces) {
  1302. return encodeURIComponent(val).
  1303. replace(/%40/gi, '@').
  1304. replace(/%3A/gi, ':').
  1305. replace(/%24/g, '$').
  1306. replace(/%2C/gi, ',').
  1307. replace(/%3B/gi, ';').
  1308. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1309. }
  1310. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1311. function getNgAttribute(element, ngAttr) {
  1312. var attr, i, ii = ngAttrPrefixes.length;
  1313. for (i = 0; i < ii; ++i) {
  1314. attr = ngAttrPrefixes[i] + ngAttr;
  1315. if (isString(attr = element.getAttribute(attr))) {
  1316. return attr;
  1317. }
  1318. }
  1319. return null;
  1320. }
  1321. /**
  1322. * @ngdoc directive
  1323. * @name ngApp
  1324. * @module ng
  1325. *
  1326. * @element ANY
  1327. * @param {angular.Module} ngApp an optional application
  1328. * {@link angular.module module} name to load.
  1329. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1330. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1331. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1332. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1333. * tracking down the root of these bugs.
  1334. *
  1335. * @description
  1336. *
  1337. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1338. * designates the **root element** of the application and is typically placed near the root element
  1339. * of the page - e.g. on the `<body>` or `<html>` tags.
  1340. *
  1341. * There are a few things to keep in mind when using `ngApp`:
  1342. * - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1343. * found in the document will be used to define the root element to auto-bootstrap as an
  1344. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1345. * {@link angular.bootstrap} instead.
  1346. * - AngularJS applications cannot be nested within each other.
  1347. * - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`.
  1348. * This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and
  1349. * {@link ngRoute.ngView `ngView`}.
  1350. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1351. * causing animations to stop working and making the injector inaccessible from outside the app.
  1352. *
  1353. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1354. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1355. * should contain the application code needed or have dependencies on other modules that will
  1356. * contain the code. See {@link angular.module} for more information.
  1357. *
  1358. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1359. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1360. * would not be resolved to `3`.
  1361. *
  1362. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1363. *
  1364. <example module="ngAppDemo">
  1365. <file name="index.html">
  1366. <div ng-controller="ngAppDemoController">
  1367. I can add: {{a}} + {{b}} = {{ a+b }}
  1368. </div>
  1369. </file>
  1370. <file name="script.js">
  1371. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1372. $scope.a = 1;
  1373. $scope.b = 2;
  1374. });
  1375. </file>
  1376. </example>
  1377. *
  1378. * Using `ngStrictDi`, you would see something like this:
  1379. *
  1380. <example ng-app-included="true">
  1381. <file name="index.html">
  1382. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1383. <div ng-controller="GoodController1">
  1384. I can add: {{a}} + {{b}} = {{ a+b }}
  1385. <p>This renders because the controller does not fail to
  1386. instantiate, by using explicit annotation style (see
  1387. script.js for details)
  1388. </p>
  1389. </div>
  1390. <div ng-controller="GoodController2">
  1391. Name: <input ng-model="name"><br />
  1392. Hello, {{name}}!
  1393. <p>This renders because the controller does not fail to
  1394. instantiate, by using explicit annotation style
  1395. (see script.js for details)
  1396. </p>
  1397. </div>
  1398. <div ng-controller="BadController">
  1399. I can add: {{a}} + {{b}} = {{ a+b }}
  1400. <p>The controller could not be instantiated, due to relying
  1401. on automatic function annotations (which are disabled in
  1402. strict mode). As such, the content of this section is not
  1403. interpolated, and there should be an error in your web console.
  1404. </p>
  1405. </div>
  1406. </div>
  1407. </file>
  1408. <file name="script.js">
  1409. angular.module('ngAppStrictDemo', [])
  1410. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1411. // rather than an explicit annotation
  1412. .controller('BadController', function($scope) {
  1413. $scope.a = 1;
  1414. $scope.b = 2;
  1415. })
  1416. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1417. // due to using explicit annotations using the array style and $inject property, respectively.
  1418. .controller('GoodController1', ['$scope', function($scope) {
  1419. $scope.a = 1;
  1420. $scope.b = 2;
  1421. }])
  1422. .controller('GoodController2', GoodController2);
  1423. function GoodController2($scope) {
  1424. $scope.name = "World";
  1425. }
  1426. GoodController2.$inject = ['$scope'];
  1427. </file>
  1428. <file name="style.css">
  1429. div[ng-controller] {
  1430. margin-bottom: 1em;
  1431. -webkit-border-radius: 4px;
  1432. border-radius: 4px;
  1433. border: 1px solid;
  1434. padding: .5em;
  1435. }
  1436. div[ng-controller^=Good] {
  1437. border-color: #d6e9c6;
  1438. background-color: #dff0d8;
  1439. color: #3c763d;
  1440. }
  1441. div[ng-controller^=Bad] {
  1442. border-color: #ebccd1;
  1443. background-color: #f2dede;
  1444. color: #a94442;
  1445. margin-bottom: 0;
  1446. }
  1447. </file>
  1448. </example>
  1449. */
  1450. function angularInit(element, bootstrap) {
  1451. var appElement,
  1452. module,
  1453. config = {};
  1454. // The element `element` has priority over any other element.
  1455. forEach(ngAttrPrefixes, function(prefix) {
  1456. var name = prefix + 'app';
  1457. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1458. appElement = element;
  1459. module = element.getAttribute(name);
  1460. }
  1461. });
  1462. forEach(ngAttrPrefixes, function(prefix) {
  1463. var name = prefix + 'app';
  1464. var candidate;
  1465. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1466. appElement = candidate;
  1467. module = candidate.getAttribute(name);
  1468. }
  1469. });
  1470. if (appElement) {
  1471. config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
  1472. bootstrap(appElement, module ? [module] : [], config);
  1473. }
  1474. }
  1475. /**
  1476. * @ngdoc function
  1477. * @name angular.bootstrap
  1478. * @module ng
  1479. * @description
  1480. * Use this function to manually start up angular application.
  1481. *
  1482. * For more information, see the {@link guide/bootstrap Bootstrap guide}.
  1483. *
  1484. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1485. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1486. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1487. * multiple instances of Angular try to work on the DOM.
  1488. *
  1489. * <div class="alert alert-warning">
  1490. * **Note:** Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1491. * They must use {@link ng.directive:ngApp ngApp}.
  1492. * </div>
  1493. *
  1494. * <div class="alert alert-warning">
  1495. * **Note:** Do not bootstrap the app on an element with a directive that uses {@link ng.$compile#transclusion transclusion},
  1496. * such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and {@link ngRoute.ngView `ngView`}.
  1497. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  1498. * causing animations to stop working and making the injector inaccessible from outside the app.
  1499. * </div>
  1500. *
  1501. * ```html
  1502. * <!doctype html>
  1503. * <html>
  1504. * <body>
  1505. * <div ng-controller="WelcomeController">
  1506. * {{greeting}}
  1507. * </div>
  1508. *
  1509. * <script src="angular.js"></script>
  1510. * <script>
  1511. * var app = angular.module('demo', [])
  1512. * .controller('WelcomeController', function($scope) {
  1513. * $scope.greeting = 'Welcome!';
  1514. * });
  1515. * angular.bootstrap(document, ['demo']);
  1516. * </script>
  1517. * </body>
  1518. * </html>
  1519. * ```
  1520. *
  1521. * @param {DOMElement} element DOM element which is the root of angular application.
  1522. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1523. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1524. * function that will be invoked by the injector as a `config` block.
  1525. * See: {@link angular.module modules}
  1526. * @param {Object=} config an object for defining configuration options for the application. The
  1527. * following keys are supported:
  1528. *
  1529. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1530. * assist in finding bugs which break minified code. Defaults to `false`.
  1531. *
  1532. * @returns {auto.$injector} Returns the newly created injector for this app.
  1533. */
  1534. function bootstrap(element, modules, config) {
  1535. if (!isObject(config)) config = {};
  1536. var defaultConfig = {
  1537. strictDi: false
  1538. };
  1539. config = extend(defaultConfig, config);
  1540. var doBootstrap = function() {
  1541. element = jqLite(element);
  1542. if (element.injector()) {
  1543. var tag = (element[0] === window.document) ? 'document' : startingTag(element);
  1544. // Encode angle brackets to prevent input from being sanitized to empty string #8683.
  1545. throw ngMinErr(
  1546. 'btstrpd',
  1547. "App already bootstrapped with this element '{0}'",
  1548. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1549. }
  1550. modules = modules || [];
  1551. modules.unshift(['$provide', function($provide) {
  1552. $provide.value('$rootElement', element);
  1553. }]);
  1554. if (config.debugInfoEnabled) {
  1555. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1556. modules.push(['$compileProvider', function($compileProvider) {
  1557. $compileProvider.debugInfoEnabled(true);
  1558. }]);
  1559. }
  1560. modules.unshift('ng');
  1561. var injector = createInjector(modules, config.strictDi);
  1562. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1563. function bootstrapApply(scope, element, compile, injector) {
  1564. scope.$apply(function() {
  1565. element.data('$injector', injector);
  1566. compile(element)(scope);
  1567. });
  1568. }]
  1569. );
  1570. return injector;
  1571. };
  1572. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1573. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1574. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1575. config.debugInfoEnabled = true;
  1576. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1577. }
  1578. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1579. return doBootstrap();
  1580. }
  1581. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1582. angular.resumeBootstrap = function(extraModules) {
  1583. forEach(extraModules, function(module) {
  1584. modules.push(module);
  1585. });
  1586. return doBootstrap();
  1587. };
  1588. if (isFunction(angular.resumeDeferredBootstrap)) {
  1589. angular.resumeDeferredBootstrap();
  1590. }
  1591. }
  1592. /**
  1593. * @ngdoc function
  1594. * @name angular.reloadWithDebugInfo
  1595. * @module ng
  1596. * @description
  1597. * Use this function to reload the current application with debug information turned on.
  1598. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1599. *
  1600. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1601. */
  1602. function reloadWithDebugInfo() {
  1603. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1604. window.location.reload();
  1605. }
  1606. /**
  1607. * @name angular.getTestability
  1608. * @module ng
  1609. * @description
  1610. * Get the testability service for the instance of Angular on the given
  1611. * element.
  1612. * @param {DOMElement} element DOM element which is the root of angular application.
  1613. */
  1614. function getTestability(rootElement) {
  1615. var injector = angular.element(rootElement).injector();
  1616. if (!injector) {
  1617. throw ngMinErr('test',
  1618. 'no injector found for element argument to getTestability');
  1619. }
  1620. return injector.get('$$testability');
  1621. }
  1622. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1623. function snake_case(name, separator) {
  1624. separator = separator || '_';
  1625. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1626. return (pos ? separator : '') + letter.toLowerCase();
  1627. });
  1628. }
  1629. var bindJQueryFired = false;
  1630. function bindJQuery() {
  1631. var originalCleanData;
  1632. if (bindJQueryFired) {
  1633. return;
  1634. }
  1635. // bind to jQuery if present;
  1636. var jqName = jq();
  1637. jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
  1638. !jqName ? undefined : // use jqLite
  1639. window[jqName]; // use jQuery specified by `ngJq`
  1640. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1641. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1642. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1643. // versions. It will not work for sure with jQuery <1.7, though.
  1644. if (jQuery && jQuery.fn.on) {
  1645. jqLite = jQuery;
  1646. extend(jQuery.fn, {
  1647. scope: JQLitePrototype.scope,
  1648. isolateScope: JQLitePrototype.isolateScope,
  1649. controller: JQLitePrototype.controller,
  1650. injector: JQLitePrototype.injector,
  1651. inheritedData: JQLitePrototype.inheritedData
  1652. });
  1653. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1654. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1655. // the $destroy event on all removed nodes.
  1656. originalCleanData = jQuery.cleanData;
  1657. jQuery.cleanData = function(elems) {
  1658. var events;
  1659. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1660. events = jQuery._data(elem, "events");
  1661. if (events && events.$destroy) {
  1662. jQuery(elem).triggerHandler('$destroy');
  1663. }
  1664. }
  1665. originalCleanData(elems);
  1666. };
  1667. } else {
  1668. jqLite = JQLite;
  1669. }
  1670. angular.element = jqLite;
  1671. // Prevent double-proxying.
  1672. bindJQueryFired = true;
  1673. }
  1674. /**
  1675. * throw error if the argument is falsy.
  1676. */
  1677. function assertArg(arg, name, reason) {
  1678. if (!arg) {
  1679. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1680. }
  1681. return arg;
  1682. }
  1683. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1684. if (acceptArrayAnnotation && isArray(arg)) {
  1685. arg = arg[arg.length - 1];
  1686. }
  1687. assertArg(isFunction(arg), name, 'not a function, got ' +
  1688. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1689. return arg;
  1690. }
  1691. /**
  1692. * throw error if the name given is hasOwnProperty
  1693. * @param {String} name the name to test
  1694. * @param {String} context the context in which the name is used, such as module or directive
  1695. */
  1696. function assertNotHasOwnProperty(name, context) {
  1697. if (name === 'hasOwnProperty') {
  1698. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1699. }
  1700. }
  1701. /**
  1702. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1703. * @param {Object} obj starting object
  1704. * @param {String} path path to traverse
  1705. * @param {boolean} [bindFnToScope=true]
  1706. * @returns {Object} value as accessible by path
  1707. */
  1708. //TODO(misko): this function needs to be removed
  1709. function getter(obj, path, bindFnToScope) {
  1710. if (!path) return obj;
  1711. var keys = path.split('.');
  1712. var key;
  1713. var lastInstance = obj;
  1714. var len = keys.length;
  1715. for (var i = 0; i < len; i++) {
  1716. key = keys[i];
  1717. if (obj) {
  1718. obj = (lastInstance = obj)[key];
  1719. }
  1720. }
  1721. if (!bindFnToScope && isFunction(obj)) {
  1722. return bind(lastInstance, obj);
  1723. }
  1724. return obj;
  1725. }
  1726. /**
  1727. * Return the DOM siblings between the first and last node in the given array.
  1728. * @param {Array} array like object
  1729. * @returns {Array} the inputted object or a jqLite collection containing the nodes
  1730. */
  1731. function getBlockNodes(nodes) {
  1732. // TODO(perf): update `nodes` instead of creating a new object?
  1733. var node = nodes[0];
  1734. var endNode = nodes[nodes.length - 1];
  1735. var blockNodes;
  1736. for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
  1737. if (blockNodes || nodes[i] !== node) {
  1738. if (!blockNodes) {
  1739. blockNodes = jqLite(slice.call(nodes, 0, i));
  1740. }
  1741. blockNodes.push(node);
  1742. }
  1743. }
  1744. return blockNodes || nodes;
  1745. }
  1746. /**
  1747. * Creates a new object without a prototype. This object is useful for lookup without having to
  1748. * guard against prototypically inherited properties via hasOwnProperty.
  1749. *
  1750. * Related micro-benchmarks:
  1751. * - http://jsperf.com/object-create2
  1752. * - http://jsperf.com/proto-map-lookup/2
  1753. * - http://jsperf.com/for-in-vs-object-keys2
  1754. *
  1755. * @returns {Object}
  1756. */
  1757. function createMap() {
  1758. return Object.create(null);
  1759. }
  1760. var NODE_TYPE_ELEMENT = 1;
  1761. var NODE_TYPE_ATTRIBUTE = 2;
  1762. var NODE_TYPE_TEXT = 3;
  1763. var NODE_TYPE_COMMENT = 8;
  1764. var NODE_TYPE_DOCUMENT = 9;
  1765. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1766. /**
  1767. * @ngdoc type
  1768. * @name angular.Module
  1769. * @module ng
  1770. * @description
  1771. *
  1772. * Interface for configuring angular {@link angular.module modules}.
  1773. */
  1774. function setupModuleLoader(window) {
  1775. var $injectorMinErr = minErr('$injector');
  1776. var ngMinErr = minErr('ng');
  1777. function ensure(obj, name, factory) {
  1778. return obj[name] || (obj[name] = factory());
  1779. }
  1780. var angular = ensure(window, 'angular', Object);
  1781. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1782. angular.$$minErr = angular.$$minErr || minErr;
  1783. return ensure(angular, 'module', function() {
  1784. /** @type {Object.<string, angular.Module>} */
  1785. var modules = {};
  1786. /**
  1787. * @ngdoc function
  1788. * @name angular.module
  1789. * @module ng
  1790. * @description
  1791. *
  1792. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1793. * modules.
  1794. * All modules (angular core or 3rd party) that should be available to an application must be
  1795. * registered using this mechanism.
  1796. *
  1797. * Passing one argument retrieves an existing {@link angular.Module},
  1798. * whereas passing more than one argument creates a new {@link angular.Module}
  1799. *
  1800. *
  1801. * # Module
  1802. *
  1803. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1804. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1805. *
  1806. * ```js
  1807. * // Create a new module
  1808. * var myModule = angular.module('myModule', []);
  1809. *
  1810. * // register a new service
  1811. * myModule.value('appName', 'MyCoolApp');
  1812. *
  1813. * // configure existing services inside initialization blocks.
  1814. * myModule.config(['$locationProvider', function($locationProvider) {
  1815. * // Configure existing providers
  1816. * $locationProvider.hashPrefix('!');
  1817. * }]);
  1818. * ```
  1819. *
  1820. * Then you can create an injector and load your modules like this:
  1821. *
  1822. * ```js
  1823. * var injector = angular.injector(['ng', 'myModule'])
  1824. * ```
  1825. *
  1826. * However it's more likely that you'll just use
  1827. * {@link ng.directive:ngApp ngApp} or
  1828. * {@link angular.bootstrap} to simplify this process for you.
  1829. *
  1830. * @param {!string} name The name of the module to create or retrieve.
  1831. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1832. * unspecified then the module is being retrieved for further configuration.
  1833. * @param {Function=} configFn Optional configuration function for the module. Same as
  1834. * {@link angular.Module#config Module#config()}.
  1835. * @returns {angular.Module} new module with the {@link angular.Module} api.
  1836. */
  1837. return function module(name, requires, configFn) {
  1838. var assertNotHasOwnProperty = function(name, context) {
  1839. if (name === 'hasOwnProperty') {
  1840. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1841. }
  1842. };
  1843. assertNotHasOwnProperty(name, 'module');
  1844. if (requires && modules.hasOwnProperty(name)) {
  1845. modules[name] = null;
  1846. }
  1847. return ensure(modules, name, function() {
  1848. if (!requires) {
  1849. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1850. "the module name or forgot to load it. If registering a module ensure that you " +
  1851. "specify the dependencies as the second argument.", name);
  1852. }
  1853. /** @type {!Array.<Array.<*>>} */
  1854. var invokeQueue = [];
  1855. /** @type {!Array.<Function>} */
  1856. var configBlocks = [];
  1857. /** @type {!Array.<Function>} */
  1858. var runBlocks = [];
  1859. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  1860. /** @type {angular.Module} */
  1861. var moduleInstance = {
  1862. // Private state
  1863. _invokeQueue: invokeQueue,
  1864. _configBlocks: configBlocks,
  1865. _runBlocks: runBlocks,
  1866. /**
  1867. * @ngdoc property
  1868. * @name angular.Module#requires
  1869. * @module ng
  1870. *
  1871. * @description
  1872. * Holds the list of modules which the injector will load before the current module is
  1873. * loaded.
  1874. */
  1875. requires: requires,
  1876. /**
  1877. * @ngdoc property
  1878. * @name angular.Module#name
  1879. * @module ng
  1880. *
  1881. * @description
  1882. * Name of the module.
  1883. */
  1884. name: name,
  1885. /**
  1886. * @ngdoc method
  1887. * @name angular.Module#provider
  1888. * @module ng
  1889. * @param {string} name service name
  1890. * @param {Function} providerType Construction function for creating new instance of the
  1891. * service.
  1892. * @description
  1893. * See {@link auto.$provide#provider $provide.provider()}.
  1894. */
  1895. provider: invokeLaterAndSetModuleName('$provide', 'provider'),
  1896. /**
  1897. * @ngdoc method
  1898. * @name angular.Module#factory
  1899. * @module ng
  1900. * @param {string} name service name
  1901. * @param {Function} providerFunction Function for creating new instance of the service.
  1902. * @description
  1903. * See {@link auto.$provide#factory $provide.factory()}.
  1904. */
  1905. factory: invokeLaterAndSetModuleName('$provide', 'factory'),
  1906. /**
  1907. * @ngdoc method
  1908. * @name angular.Module#service
  1909. * @module ng
  1910. * @param {string} name service name
  1911. * @param {Function} constructor A constructor function that will be instantiated.
  1912. * @description
  1913. * See {@link auto.$provide#service $provide.service()}.
  1914. */
  1915. service: invokeLaterAndSetModuleName('$provide', 'service'),
  1916. /**
  1917. * @ngdoc method
  1918. * @name angular.Module#value
  1919. * @module ng
  1920. * @param {string} name service name
  1921. * @param {*} object Service instance object.
  1922. * @description
  1923. * See {@link auto.$provide#value $provide.value()}.
  1924. */
  1925. value: invokeLater('$provide', 'value'),
  1926. /**
  1927. * @ngdoc method
  1928. * @name angular.Module#constant
  1929. * @module ng
  1930. * @param {string} name constant name
  1931. * @param {*} object Constant value.
  1932. * @description
  1933. * Because the constants are fixed, they get applied before other provide methods.
  1934. * See {@link auto.$provide#constant $provide.constant()}.
  1935. */
  1936. constant: invokeLater('$provide', 'constant', 'unshift'),
  1937. /**
  1938. * @ngdoc method
  1939. * @name angular.Module#decorator
  1940. * @module ng
  1941. * @param {string} name The name of the service to decorate.
  1942. * @param {Function} decorFn This function will be invoked when the service needs to be
  1943. * instantiated and should return the decorated service instance.
  1944. * @description
  1945. * See {@link auto.$provide#decorator $provide.decorator()}.
  1946. */
  1947. decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
  1948. /**
  1949. * @ngdoc method
  1950. * @name angular.Module#animation
  1951. * @module ng
  1952. * @param {string} name animation name
  1953. * @param {Function} animationFactory Factory function for creating new instance of an
  1954. * animation.
  1955. * @description
  1956. *
  1957. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1958. *
  1959. *
  1960. * Defines an animation hook that can be later used with
  1961. * {@link $animate $animate} service and directives that use this service.
  1962. *
  1963. * ```js
  1964. * module.animation('.animation-name', function($inject1, $inject2) {
  1965. * return {
  1966. * eventName : function(element, done) {
  1967. * //code to run the animation
  1968. * //once complete, then run done()
  1969. * return function cancellationFunction(element) {
  1970. * //code to cancel the animation
  1971. * }
  1972. * }
  1973. * }
  1974. * })
  1975. * ```
  1976. *
  1977. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  1978. * {@link ngAnimate ngAnimate module} for more information.
  1979. */
  1980. animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
  1981. /**
  1982. * @ngdoc method
  1983. * @name angular.Module#filter
  1984. * @module ng
  1985. * @param {string} name Filter name - this must be a valid angular expression identifier
  1986. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1987. * @description
  1988. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1989. *
  1990. * <div class="alert alert-warning">
  1991. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  1992. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  1993. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  1994. * (`myapp_subsection_filterx`).
  1995. * </div>
  1996. */
  1997. filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
  1998. /**
  1999. * @ngdoc method
  2000. * @name angular.Module#controller
  2001. * @module ng
  2002. * @param {string|Object} name Controller name, or an object map of controllers where the
  2003. * keys are the names and the values are the constructors.
  2004. * @param {Function} constructor Controller constructor function.
  2005. * @description
  2006. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  2007. */
  2008. controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
  2009. /**
  2010. * @ngdoc method
  2011. * @name angular.Module#directive
  2012. * @module ng
  2013. * @param {string|Object} name Directive name, or an object map of directives where the
  2014. * keys are the names and the values are the factories.
  2015. * @param {Function} directiveFactory Factory function for creating new instance of
  2016. * directives.
  2017. * @description
  2018. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  2019. */
  2020. directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
  2021. /**
  2022. * @ngdoc method
  2023. * @name angular.Module#component
  2024. * @module ng
  2025. * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp)
  2026. * @param {Object} options Component definition object (a simplified
  2027. * {@link ng.$compile#directive-definition-object directive definition object})
  2028. *
  2029. * @description
  2030. * See {@link ng.$compileProvider#component $compileProvider.component()}.
  2031. */
  2032. component: invokeLaterAndSetModuleName('$compileProvider', 'component'),
  2033. /**
  2034. * @ngdoc method
  2035. * @name angular.Module#config
  2036. * @module ng
  2037. * @param {Function} configFn Execute this function on module load. Useful for service
  2038. * configuration.
  2039. * @description
  2040. * Use this method to register work which needs to be performed on module loading.
  2041. * For more about how to configure services, see
  2042. * {@link providers#provider-recipe Provider Recipe}.
  2043. */
  2044. config: config,
  2045. /**
  2046. * @ngdoc method
  2047. * @name angular.Module#run
  2048. * @module ng
  2049. * @param {Function} initializationFn Execute this function after injector creation.
  2050. * Useful for application initialization.
  2051. * @description
  2052. * Use this method to register work which should be performed when the injector is done
  2053. * loading all modules.
  2054. */
  2055. run: function(block) {
  2056. runBlocks.push(block);
  2057. return this;
  2058. }
  2059. };
  2060. if (configFn) {
  2061. config(configFn);
  2062. }
  2063. return moduleInstance;
  2064. /**
  2065. * @param {string} provider
  2066. * @param {string} method
  2067. * @param {String=} insertMethod
  2068. * @returns {angular.Module}
  2069. */
  2070. function invokeLater(provider, method, insertMethod, queue) {
  2071. if (!queue) queue = invokeQueue;
  2072. return function() {
  2073. queue[insertMethod || 'push']([provider, method, arguments]);
  2074. return moduleInstance;
  2075. };
  2076. }
  2077. /**
  2078. * @param {string} provider
  2079. * @param {string} method
  2080. * @returns {angular.Module}
  2081. */
  2082. function invokeLaterAndSetModuleName(provider, method) {
  2083. return function(recipeName, factoryFunction) {
  2084. if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
  2085. invokeQueue.push([provider, method, arguments]);
  2086. return moduleInstance;
  2087. };
  2088. }
  2089. });
  2090. };
  2091. });
  2092. }
  2093. /* global shallowCopy: true */
  2094. /**
  2095. * Creates a shallow copy of an object, an array or a primitive.
  2096. *
  2097. * Assumes that there are no proto properties for objects.
  2098. */
  2099. function shallowCopy(src, dst) {
  2100. if (isArray(src)) {
  2101. dst = dst || [];
  2102. for (var i = 0, ii = src.length; i < ii; i++) {
  2103. dst[i] = src[i];
  2104. }
  2105. } else if (isObject(src)) {
  2106. dst = dst || {};
  2107. for (var key in src) {
  2108. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  2109. dst[key] = src[key];
  2110. }
  2111. }
  2112. }
  2113. return dst || src;
  2114. }
  2115. /* global toDebugString: true */
  2116. function serializeObject(obj) {
  2117. var seen = [];
  2118. return JSON.stringify(obj, function(key, val) {
  2119. val = toJsonReplacer(key, val);
  2120. if (isObject(val)) {
  2121. if (seen.indexOf(val) >= 0) return '...';
  2122. seen.push(val);
  2123. }
  2124. return val;
  2125. });
  2126. }
  2127. function toDebugString(obj) {
  2128. if (typeof obj === 'function') {
  2129. return obj.toString().replace(/ \{[\s\S]*$/, '');
  2130. } else if (isUndefined(obj)) {
  2131. return 'undefined';
  2132. } else if (typeof obj !== 'string') {
  2133. return serializeObject(obj);
  2134. }
  2135. return obj;
  2136. }
  2137. /* global angularModule: true,
  2138. version: true,
  2139. $CompileProvider,
  2140. htmlAnchorDirective,
  2141. inputDirective,
  2142. inputDirective,
  2143. formDirective,
  2144. scriptDirective,
  2145. selectDirective,
  2146. styleDirective,
  2147. optionDirective,
  2148. ngBindDirective,
  2149. ngBindHtmlDirective,
  2150. ngBindTemplateDirective,
  2151. ngClassDirective,
  2152. ngClassEvenDirective,
  2153. ngClassOddDirective,
  2154. ngCloakDirective,
  2155. ngControllerDirective,
  2156. ngFormDirective,
  2157. ngHideDirective,
  2158. ngIfDirective,
  2159. ngIncludeDirective,
  2160. ngIncludeFillContentDirective,
  2161. ngInitDirective,
  2162. ngNonBindableDirective,
  2163. ngPluralizeDirective,
  2164. ngRepeatDirective,
  2165. ngShowDirective,
  2166. ngStyleDirective,
  2167. ngSwitchDirective,
  2168. ngSwitchWhenDirective,
  2169. ngSwitchDefaultDirective,
  2170. ngOptionsDirective,
  2171. ngTranscludeDirective,
  2172. ngModelDirective,
  2173. ngListDirective,
  2174. ngChangeDirective,
  2175. patternDirective,
  2176. patternDirective,
  2177. requiredDirective,
  2178. requiredDirective,
  2179. minlengthDirective,
  2180. minlengthDirective,
  2181. maxlengthDirective,
  2182. maxlengthDirective,
  2183. ngValueDirective,
  2184. ngModelOptionsDirective,
  2185. ngAttributeAliasDirectives,
  2186. ngEventDirectives,
  2187. $AnchorScrollProvider,
  2188. $AnimateProvider,
  2189. $CoreAnimateCssProvider,
  2190. $$CoreAnimateJsProvider,
  2191. $$CoreAnimateQueueProvider,
  2192. $$AnimateRunnerFactoryProvider,
  2193. $$AnimateAsyncRunFactoryProvider,
  2194. $BrowserProvider,
  2195. $CacheFactoryProvider,
  2196. $ControllerProvider,
  2197. $DateProvider,
  2198. $DocumentProvider,
  2199. $ExceptionHandlerProvider,
  2200. $FilterProvider,
  2201. $$ForceReflowProvider,
  2202. $InterpolateProvider,
  2203. $IntervalProvider,
  2204. $$HashMapProvider,
  2205. $HttpProvider,
  2206. $HttpParamSerializerProvider,
  2207. $HttpParamSerializerJQLikeProvider,
  2208. $HttpBackendProvider,
  2209. $xhrFactoryProvider,
  2210. $LocationProvider,
  2211. $LogProvider,
  2212. $ParseProvider,
  2213. $RootScopeProvider,
  2214. $QProvider,
  2215. $$QProvider,
  2216. $$SanitizeUriProvider,
  2217. $SceProvider,
  2218. $SceDelegateProvider,
  2219. $SnifferProvider,
  2220. $TemplateCacheProvider,
  2221. $TemplateRequestProvider,
  2222. $$TestabilityProvider,
  2223. $TimeoutProvider,
  2224. $$RAFProvider,
  2225. $WindowProvider,
  2226. $$jqLiteProvider,
  2227. $$CookieReaderProvider
  2228. */
  2229. /**
  2230. * @ngdoc object
  2231. * @name angular.version
  2232. * @module ng
  2233. * @description
  2234. * An object that contains information about the current AngularJS version.
  2235. *
  2236. * This object has the following properties:
  2237. *
  2238. * - `full` – `{string}` – Full version string, such as "0.9.18".
  2239. * - `major` – `{number}` – Major version number, such as "0".
  2240. * - `minor` – `{number}` – Minor version number, such as "9".
  2241. * - `dot` – `{number}` – Dot version number, such as "18".
  2242. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  2243. */
  2244. var version = {
  2245. full: '1.5.7', // all of these placeholder strings will be replaced by grunt's
  2246. major: 1, // package task
  2247. minor: 5,
  2248. dot: 7,
  2249. codeName: 'hexagonal-circumvolution'
  2250. };
  2251. function publishExternalAPI(angular) {
  2252. extend(angular, {
  2253. 'bootstrap': bootstrap,
  2254. 'copy': copy,
  2255. 'extend': extend,
  2256. 'merge': merge,
  2257. 'equals': equals,
  2258. 'element': jqLite,
  2259. 'forEach': forEach,
  2260. 'injector': createInjector,
  2261. 'noop': noop,
  2262. 'bind': bind,
  2263. 'toJson': toJson,
  2264. 'fromJson': fromJson,
  2265. 'identity': identity,
  2266. 'isUndefined': isUndefined,
  2267. 'isDefined': isDefined,
  2268. 'isString': isString,
  2269. 'isFunction': isFunction,
  2270. 'isObject': isObject,
  2271. 'isNumber': isNumber,
  2272. 'isElement': isElement,
  2273. 'isArray': isArray,
  2274. 'version': version,
  2275. 'isDate': isDate,
  2276. 'lowercase': lowercase,
  2277. 'uppercase': uppercase,
  2278. 'callbacks': {counter: 0},
  2279. 'getTestability': getTestability,
  2280. '$$minErr': minErr,
  2281. '$$csp': csp,
  2282. 'reloadWithDebugInfo': reloadWithDebugInfo
  2283. });
  2284. angularModule = setupModuleLoader(window);
  2285. angularModule('ng', ['ngLocale'], ['$provide',
  2286. function ngModule($provide) {
  2287. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  2288. $provide.provider({
  2289. $$sanitizeUri: $$SanitizeUriProvider
  2290. });
  2291. $provide.provider('$compile', $CompileProvider).
  2292. directive({
  2293. a: htmlAnchorDirective,
  2294. input: inputDirective,
  2295. textarea: inputDirective,
  2296. form: formDirective,
  2297. script: scriptDirective,
  2298. select: selectDirective,
  2299. style: styleDirective,
  2300. option: optionDirective,
  2301. ngBind: ngBindDirective,
  2302. ngBindHtml: ngBindHtmlDirective,
  2303. ngBindTemplate: ngBindTemplateDirective,
  2304. ngClass: ngClassDirective,
  2305. ngClassEven: ngClassEvenDirective,
  2306. ngClassOdd: ngClassOddDirective,
  2307. ngCloak: ngCloakDirective,
  2308. ngController: ngControllerDirective,
  2309. ngForm: ngFormDirective,
  2310. ngHide: ngHideDirective,
  2311. ngIf: ngIfDirective,
  2312. ngInclude: ngIncludeDirective,
  2313. ngInit: ngInitDirective,
  2314. ngNonBindable: ngNonBindableDirective,
  2315. ngPluralize: ngPluralizeDirective,
  2316. ngRepeat: ngRepeatDirective,
  2317. ngShow: ngShowDirective,
  2318. ngStyle: ngStyleDirective,
  2319. ngSwitch: ngSwitchDirective,
  2320. ngSwitchWhen: ngSwitchWhenDirective,
  2321. ngSwitchDefault: ngSwitchDefaultDirective,
  2322. ngOptions: ngOptionsDirective,
  2323. ngTransclude: ngTranscludeDirective,
  2324. ngModel: ngModelDirective,
  2325. ngList: ngListDirective,
  2326. ngChange: ngChangeDirective,
  2327. pattern: patternDirective,
  2328. ngPattern: patternDirective,
  2329. required: requiredDirective,
  2330. ngRequired: requiredDirective,
  2331. minlength: minlengthDirective,
  2332. ngMinlength: minlengthDirective,
  2333. maxlength: maxlengthDirective,
  2334. ngMaxlength: maxlengthDirective,
  2335. ngValue: ngValueDirective,
  2336. ngModelOptions: ngModelOptionsDirective
  2337. }).
  2338. directive({
  2339. ngInclude: ngIncludeFillContentDirective
  2340. }).
  2341. directive(ngAttributeAliasDirectives).
  2342. directive(ngEventDirectives);
  2343. $provide.provider({
  2344. $anchorScroll: $AnchorScrollProvider,
  2345. $animate: $AnimateProvider,
  2346. $animateCss: $CoreAnimateCssProvider,
  2347. $$animateJs: $$CoreAnimateJsProvider,
  2348. $$animateQueue: $$CoreAnimateQueueProvider,
  2349. $$AnimateRunner: $$AnimateRunnerFactoryProvider,
  2350. $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,
  2351. $browser: $BrowserProvider,
  2352. $cacheFactory: $CacheFactoryProvider,
  2353. $controller: $ControllerProvider,
  2354. $document: $DocumentProvider,
  2355. $exceptionHandler: $ExceptionHandlerProvider,
  2356. $filter: $FilterProvider,
  2357. $$forceReflow: $$ForceReflowProvider,
  2358. $interpolate: $InterpolateProvider,
  2359. $interval: $IntervalProvider,
  2360. $http: $HttpProvider,
  2361. $httpParamSerializer: $HttpParamSerializerProvider,
  2362. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  2363. $httpBackend: $HttpBackendProvider,
  2364. $xhrFactory: $xhrFactoryProvider,
  2365. $location: $LocationProvider,
  2366. $log: $LogProvider,
  2367. $parse: $ParseProvider,
  2368. $rootScope: $RootScopeProvider,
  2369. $q: $QProvider,
  2370. $$q: $$QProvider,
  2371. $sce: $SceProvider,
  2372. $sceDelegate: $SceDelegateProvider,
  2373. $sniffer: $SnifferProvider,
  2374. $templateCache: $TemplateCacheProvider,
  2375. $templateRequest: $TemplateRequestProvider,
  2376. $$testability: $$TestabilityProvider,
  2377. $timeout: $TimeoutProvider,
  2378. $window: $WindowProvider,
  2379. $$rAF: $$RAFProvider,
  2380. $$jqLite: $$jqLiteProvider,
  2381. $$HashMap: $$HashMapProvider,
  2382. $$cookieReader: $$CookieReaderProvider
  2383. });
  2384. }
  2385. ]);
  2386. }
  2387. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2388. * Any commits to this file should be reviewed with security in mind. *
  2389. * Changes to this file can potentially create security vulnerabilities. *
  2390. * An approval from 2 Core members with history of modifying *
  2391. * this file is required. *
  2392. * *
  2393. * Does the change somehow allow for arbitrary javascript to be executed? *
  2394. * Or allows for someone to change the prototype of built-in objects? *
  2395. * Or gives undesired access to variables likes document or window? *
  2396. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2397. /* global JQLitePrototype: true,
  2398. addEventListenerFn: true,
  2399. removeEventListenerFn: true,
  2400. BOOLEAN_ATTR: true,
  2401. ALIASED_ATTR: true,
  2402. */
  2403. //////////////////////////////////
  2404. //JQLite
  2405. //////////////////////////////////
  2406. /**
  2407. * @ngdoc function
  2408. * @name angular.element
  2409. * @module ng
  2410. * @kind function
  2411. *
  2412. * @description
  2413. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2414. *
  2415. * If jQuery is available, `angular.element` is an alias for the
  2416. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2417. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
  2418. *
  2419. * jqLite is a tiny, API-compatible subset of jQuery that allows
  2420. * Angular to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
  2421. * commonly needed functionality with the goal of having a very small footprint.
  2422. *
  2423. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
  2424. * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
  2425. * specific version of jQuery if multiple versions exist on the page.
  2426. *
  2427. * <div class="alert alert-info">**Note:** All element references in Angular are always wrapped with jQuery or
  2428. * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div>
  2429. *
  2430. * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements
  2431. * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
  2432. * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.</div>
  2433. *
  2434. * ## Angular's jqLite
  2435. * jqLite provides only the following jQuery methods:
  2436. *
  2437. * - [`addClass()`](http://api.jquery.com/addClass/) - Does not support a function as first argument
  2438. * - [`after()`](http://api.jquery.com/after/)
  2439. * - [`append()`](http://api.jquery.com/append/)
  2440. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2441. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  2442. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2443. * - [`clone()`](http://api.jquery.com/clone/)
  2444. * - [`contents()`](http://api.jquery.com/contents/)
  2445. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
  2446. * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
  2447. * - [`data()`](http://api.jquery.com/data/)
  2448. * - [`detach()`](http://api.jquery.com/detach/)
  2449. * - [`empty()`](http://api.jquery.com/empty/)
  2450. * - [`eq()`](http://api.jquery.com/eq/)
  2451. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2452. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2453. * - [`html()`](http://api.jquery.com/html/)
  2454. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2455. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2456. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
  2457. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2458. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2459. * - [`prepend()`](http://api.jquery.com/prepend/)
  2460. * - [`prop()`](http://api.jquery.com/prop/)
  2461. * - [`ready()`](http://api.jquery.com/ready/)
  2462. * - [`remove()`](http://api.jquery.com/remove/)
  2463. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  2464. * - [`removeClass()`](http://api.jquery.com/removeClass/) - Does not support a function as first argument
  2465. * - [`removeData()`](http://api.jquery.com/removeData/)
  2466. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2467. * - [`text()`](http://api.jquery.com/text/)
  2468. * - [`toggleClass()`](http://api.jquery.com/toggleClass/) - Does not support a function as first argument
  2469. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers
  2470. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces or event object as parameter
  2471. * - [`val()`](http://api.jquery.com/val/)
  2472. * - [`wrap()`](http://api.jquery.com/wrap/)
  2473. *
  2474. * ## jQuery/jqLite Extras
  2475. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2476. *
  2477. * ### Events
  2478. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2479. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2480. * element before it is removed.
  2481. *
  2482. * ### Methods
  2483. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2484. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2485. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2486. * `'ngModel'`).
  2487. * - `injector()` - retrieves the injector of the current element or its parent.
  2488. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2489. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2490. * be enabled.
  2491. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2492. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2493. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2494. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2495. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2496. * parent element is reached.
  2497. *
  2498. * @knownIssue You cannot spy on `angular.element` if you are using Jasmine version 1.x. See
  2499. * https://github.com/angular/angular.js/issues/14251 for more information.
  2500. *
  2501. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2502. * @returns {Object} jQuery object.
  2503. */
  2504. JQLite.expando = 'ng339';
  2505. var jqCache = JQLite.cache = {},
  2506. jqId = 1,
  2507. addEventListenerFn = function(element, type, fn) {
  2508. element.addEventListener(type, fn, false);
  2509. },
  2510. removeEventListenerFn = function(element, type, fn) {
  2511. element.removeEventListener(type, fn, false);
  2512. };
  2513. /*
  2514. * !!! This is an undocumented "private" function !!!
  2515. */
  2516. JQLite._data = function(node) {
  2517. //jQuery always returns an object on cache miss
  2518. return this.cache[node[this.expando]] || {};
  2519. };
  2520. function jqNextId() { return ++jqId; }
  2521. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  2522. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  2523. var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
  2524. var jqLiteMinErr = minErr('jqLite');
  2525. /**
  2526. * Converts snake_case to camelCase.
  2527. * Also there is special case for Moz prefix starting with upper case letter.
  2528. * @param name Name to normalize
  2529. */
  2530. function camelCase(name) {
  2531. return name.
  2532. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2533. return offset ? letter.toUpperCase() : letter;
  2534. }).
  2535. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2536. }
  2537. var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
  2538. var HTML_REGEXP = /<|&#?\w+;/;
  2539. var TAG_NAME_REGEXP = /<([\w:-]+)/;
  2540. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
  2541. var wrapMap = {
  2542. 'option': [1, '<select multiple="multiple">', '</select>'],
  2543. 'thead': [1, '<table>', '</table>'],
  2544. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2545. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2546. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2547. '_default': [0, "", ""]
  2548. };
  2549. wrapMap.optgroup = wrapMap.option;
  2550. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2551. wrapMap.th = wrapMap.td;
  2552. function jqLiteIsTextNode(html) {
  2553. return !HTML_REGEXP.test(html);
  2554. }
  2555. function jqLiteAcceptsData(node) {
  2556. // The window object can accept data but has no nodeType
  2557. // Otherwise we are only interested in elements (1) and documents (9)
  2558. var nodeType = node.nodeType;
  2559. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2560. }
  2561. function jqLiteHasData(node) {
  2562. for (var key in jqCache[node.ng339]) {
  2563. return true;
  2564. }
  2565. return false;
  2566. }
  2567. function jqLiteCleanData(nodes) {
  2568. for (var i = 0, ii = nodes.length; i < ii; i++) {
  2569. jqLiteRemoveData(nodes[i]);
  2570. }
  2571. }
  2572. function jqLiteBuildFragment(html, context) {
  2573. var tmp, tag, wrap,
  2574. fragment = context.createDocumentFragment(),
  2575. nodes = [], i;
  2576. if (jqLiteIsTextNode(html)) {
  2577. // Convert non-html into a text node
  2578. nodes.push(context.createTextNode(html));
  2579. } else {
  2580. // Convert html into DOM nodes
  2581. tmp = tmp || fragment.appendChild(context.createElement("div"));
  2582. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2583. wrap = wrapMap[tag] || wrapMap._default;
  2584. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2585. // Descend through wrappers to the right content
  2586. i = wrap[0];
  2587. while (i--) {
  2588. tmp = tmp.lastChild;
  2589. }
  2590. nodes = concat(nodes, tmp.childNodes);
  2591. tmp = fragment.firstChild;
  2592. tmp.textContent = "";
  2593. }
  2594. // Remove wrapper from fragment
  2595. fragment.textContent = "";
  2596. fragment.innerHTML = ""; // Clear inner HTML
  2597. forEach(nodes, function(node) {
  2598. fragment.appendChild(node);
  2599. });
  2600. return fragment;
  2601. }
  2602. function jqLiteParseHTML(html, context) {
  2603. context = context || window.document;
  2604. var parsed;
  2605. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2606. return [context.createElement(parsed[1])];
  2607. }
  2608. if ((parsed = jqLiteBuildFragment(html, context))) {
  2609. return parsed.childNodes;
  2610. }
  2611. return [];
  2612. }
  2613. function jqLiteWrapNode(node, wrapper) {
  2614. var parent = node.parentNode;
  2615. if (parent) {
  2616. parent.replaceChild(wrapper, node);
  2617. }
  2618. wrapper.appendChild(node);
  2619. }
  2620. // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
  2621. var jqLiteContains = window.Node.prototype.contains || function(arg) {
  2622. // jshint bitwise: false
  2623. return !!(this.compareDocumentPosition(arg) & 16);
  2624. // jshint bitwise: true
  2625. };
  2626. /////////////////////////////////////////////
  2627. function JQLite(element) {
  2628. if (element instanceof JQLite) {
  2629. return element;
  2630. }
  2631. var argIsString;
  2632. if (isString(element)) {
  2633. element = trim(element);
  2634. argIsString = true;
  2635. }
  2636. if (!(this instanceof JQLite)) {
  2637. if (argIsString && element.charAt(0) != '<') {
  2638. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2639. }
  2640. return new JQLite(element);
  2641. }
  2642. if (argIsString) {
  2643. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2644. } else {
  2645. jqLiteAddNodes(this, element);
  2646. }
  2647. }
  2648. function jqLiteClone(element) {
  2649. return element.cloneNode(true);
  2650. }
  2651. function jqLiteDealoc(element, onlyDescendants) {
  2652. if (!onlyDescendants) jqLiteRemoveData(element);
  2653. if (element.querySelectorAll) {
  2654. var descendants = element.querySelectorAll('*');
  2655. for (var i = 0, l = descendants.length; i < l; i++) {
  2656. jqLiteRemoveData(descendants[i]);
  2657. }
  2658. }
  2659. }
  2660. function jqLiteOff(element, type, fn, unsupported) {
  2661. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2662. var expandoStore = jqLiteExpandoStore(element);
  2663. var events = expandoStore && expandoStore.events;
  2664. var handle = expandoStore && expandoStore.handle;
  2665. if (!handle) return; //no listeners registered
  2666. if (!type) {
  2667. for (type in events) {
  2668. if (type !== '$destroy') {
  2669. removeEventListenerFn(element, type, handle);
  2670. }
  2671. delete events[type];
  2672. }
  2673. } else {
  2674. var removeHandler = function(type) {
  2675. var listenerFns = events[type];
  2676. if (isDefined(fn)) {
  2677. arrayRemove(listenerFns || [], fn);
  2678. }
  2679. if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
  2680. removeEventListenerFn(element, type, handle);
  2681. delete events[type];
  2682. }
  2683. };
  2684. forEach(type.split(' '), function(type) {
  2685. removeHandler(type);
  2686. if (MOUSE_EVENT_MAP[type]) {
  2687. removeHandler(MOUSE_EVENT_MAP[type]);
  2688. }
  2689. });
  2690. }
  2691. }
  2692. function jqLiteRemoveData(element, name) {
  2693. var expandoId = element.ng339;
  2694. var expandoStore = expandoId && jqCache[expandoId];
  2695. if (expandoStore) {
  2696. if (name) {
  2697. delete expandoStore.data[name];
  2698. return;
  2699. }
  2700. if (expandoStore.handle) {
  2701. if (expandoStore.events.$destroy) {
  2702. expandoStore.handle({}, '$destroy');
  2703. }
  2704. jqLiteOff(element);
  2705. }
  2706. delete jqCache[expandoId];
  2707. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2708. }
  2709. }
  2710. function jqLiteExpandoStore(element, createIfNecessary) {
  2711. var expandoId = element.ng339,
  2712. expandoStore = expandoId && jqCache[expandoId];
  2713. if (createIfNecessary && !expandoStore) {
  2714. element.ng339 = expandoId = jqNextId();
  2715. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2716. }
  2717. return expandoStore;
  2718. }
  2719. function jqLiteData(element, key, value) {
  2720. if (jqLiteAcceptsData(element)) {
  2721. var isSimpleSetter = isDefined(value);
  2722. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2723. var massGetter = !key;
  2724. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2725. var data = expandoStore && expandoStore.data;
  2726. if (isSimpleSetter) { // data('key', value)
  2727. data[key] = value;
  2728. } else {
  2729. if (massGetter) { // data()
  2730. return data;
  2731. } else {
  2732. if (isSimpleGetter) { // data('key')
  2733. // don't force creation of expandoStore if it doesn't exist yet
  2734. return data && data[key];
  2735. } else { // mass-setter: data({key1: val1, key2: val2})
  2736. extend(data, key);
  2737. }
  2738. }
  2739. }
  2740. }
  2741. }
  2742. function jqLiteHasClass(element, selector) {
  2743. if (!element.getAttribute) return false;
  2744. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2745. indexOf(" " + selector + " ") > -1);
  2746. }
  2747. function jqLiteRemoveClass(element, cssClasses) {
  2748. if (cssClasses && element.setAttribute) {
  2749. forEach(cssClasses.split(' '), function(cssClass) {
  2750. element.setAttribute('class', trim(
  2751. (" " + (element.getAttribute('class') || '') + " ")
  2752. .replace(/[\n\t]/g, " ")
  2753. .replace(" " + trim(cssClass) + " ", " "))
  2754. );
  2755. });
  2756. }
  2757. }
  2758. function jqLiteAddClass(element, cssClasses) {
  2759. if (cssClasses && element.setAttribute) {
  2760. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2761. .replace(/[\n\t]/g, " ");
  2762. forEach(cssClasses.split(' '), function(cssClass) {
  2763. cssClass = trim(cssClass);
  2764. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2765. existingClasses += cssClass + ' ';
  2766. }
  2767. });
  2768. element.setAttribute('class', trim(existingClasses));
  2769. }
  2770. }
  2771. function jqLiteAddNodes(root, elements) {
  2772. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2773. if (elements) {
  2774. // if a Node (the most common case)
  2775. if (elements.nodeType) {
  2776. root[root.length++] = elements;
  2777. } else {
  2778. var length = elements.length;
  2779. // if an Array or NodeList and not a Window
  2780. if (typeof length === 'number' && elements.window !== elements) {
  2781. if (length) {
  2782. for (var i = 0; i < length; i++) {
  2783. root[root.length++] = elements[i];
  2784. }
  2785. }
  2786. } else {
  2787. root[root.length++] = elements;
  2788. }
  2789. }
  2790. }
  2791. }
  2792. function jqLiteController(element, name) {
  2793. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  2794. }
  2795. function jqLiteInheritedData(element, name, value) {
  2796. // if element is the document object work with the html element instead
  2797. // this makes $(document).scope() possible
  2798. if (element.nodeType == NODE_TYPE_DOCUMENT) {
  2799. element = element.documentElement;
  2800. }
  2801. var names = isArray(name) ? name : [name];
  2802. while (element) {
  2803. for (var i = 0, ii = names.length; i < ii; i++) {
  2804. if (isDefined(value = jqLite.data(element, names[i]))) return value;
  2805. }
  2806. // If dealing with a document fragment node with a host element, and no parent, use the host
  2807. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2808. // to lookup parent controllers.
  2809. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  2810. }
  2811. }
  2812. function jqLiteEmpty(element) {
  2813. jqLiteDealoc(element, true);
  2814. while (element.firstChild) {
  2815. element.removeChild(element.firstChild);
  2816. }
  2817. }
  2818. function jqLiteRemove(element, keepData) {
  2819. if (!keepData) jqLiteDealoc(element);
  2820. var parent = element.parentNode;
  2821. if (parent) parent.removeChild(element);
  2822. }
  2823. function jqLiteDocumentLoaded(action, win) {
  2824. win = win || window;
  2825. if (win.document.readyState === 'complete') {
  2826. // Force the action to be run async for consistent behavior
  2827. // from the action's point of view
  2828. // i.e. it will definitely not be in a $apply
  2829. win.setTimeout(action);
  2830. } else {
  2831. // No need to unbind this handler as load is only ever called once
  2832. jqLite(win).on('load', action);
  2833. }
  2834. }
  2835. //////////////////////////////////////////
  2836. // Functions which are declared directly.
  2837. //////////////////////////////////////////
  2838. var JQLitePrototype = JQLite.prototype = {
  2839. ready: function(fn) {
  2840. var fired = false;
  2841. function trigger() {
  2842. if (fired) return;
  2843. fired = true;
  2844. fn();
  2845. }
  2846. // check if document is already loaded
  2847. if (window.document.readyState === 'complete') {
  2848. window.setTimeout(trigger);
  2849. } else {
  2850. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2851. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2852. // jshint -W064
  2853. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2854. // jshint +W064
  2855. }
  2856. },
  2857. toString: function() {
  2858. var value = [];
  2859. forEach(this, function(e) { value.push('' + e);});
  2860. return '[' + value.join(', ') + ']';
  2861. },
  2862. eq: function(index) {
  2863. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2864. },
  2865. length: 0,
  2866. push: push,
  2867. sort: [].sort,
  2868. splice: [].splice
  2869. };
  2870. //////////////////////////////////////////
  2871. // Functions iterating getter/setters.
  2872. // these functions return self on setter and
  2873. // value on get.
  2874. //////////////////////////////////////////
  2875. var BOOLEAN_ATTR = {};
  2876. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2877. BOOLEAN_ATTR[lowercase(value)] = value;
  2878. });
  2879. var BOOLEAN_ELEMENTS = {};
  2880. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2881. BOOLEAN_ELEMENTS[value] = true;
  2882. });
  2883. var ALIASED_ATTR = {
  2884. 'ngMinlength': 'minlength',
  2885. 'ngMaxlength': 'maxlength',
  2886. 'ngMin': 'min',
  2887. 'ngMax': 'max',
  2888. 'ngPattern': 'pattern'
  2889. };
  2890. function getBooleanAttrName(element, name) {
  2891. // check dom last since we will most likely fail on name
  2892. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2893. // booleanAttr is here twice to minimize DOM access
  2894. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  2895. }
  2896. function getAliasedAttrName(name) {
  2897. return ALIASED_ATTR[name];
  2898. }
  2899. forEach({
  2900. data: jqLiteData,
  2901. removeData: jqLiteRemoveData,
  2902. hasData: jqLiteHasData,
  2903. cleanData: jqLiteCleanData
  2904. }, function(fn, name) {
  2905. JQLite[name] = fn;
  2906. });
  2907. forEach({
  2908. data: jqLiteData,
  2909. inheritedData: jqLiteInheritedData,
  2910. scope: function(element) {
  2911. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2912. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2913. },
  2914. isolateScope: function(element) {
  2915. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2916. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  2917. },
  2918. controller: jqLiteController,
  2919. injector: function(element) {
  2920. return jqLiteInheritedData(element, '$injector');
  2921. },
  2922. removeAttr: function(element, name) {
  2923. element.removeAttribute(name);
  2924. },
  2925. hasClass: jqLiteHasClass,
  2926. css: function(element, name, value) {
  2927. name = camelCase(name);
  2928. if (isDefined(value)) {
  2929. element.style[name] = value;
  2930. } else {
  2931. return element.style[name];
  2932. }
  2933. },
  2934. attr: function(element, name, value) {
  2935. var nodeType = element.nodeType;
  2936. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
  2937. return;
  2938. }
  2939. var lowercasedName = lowercase(name);
  2940. if (BOOLEAN_ATTR[lowercasedName]) {
  2941. if (isDefined(value)) {
  2942. if (!!value) {
  2943. element[name] = true;
  2944. element.setAttribute(name, lowercasedName);
  2945. } else {
  2946. element[name] = false;
  2947. element.removeAttribute(lowercasedName);
  2948. }
  2949. } else {
  2950. return (element[name] ||
  2951. (element.attributes.getNamedItem(name) || noop).specified)
  2952. ? lowercasedName
  2953. : undefined;
  2954. }
  2955. } else if (isDefined(value)) {
  2956. element.setAttribute(name, value);
  2957. } else if (element.getAttribute) {
  2958. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2959. // some elements (e.g. Document) don't have get attribute, so return undefined
  2960. var ret = element.getAttribute(name, 2);
  2961. // normalize non-existing attributes to undefined (as jQuery)
  2962. return ret === null ? undefined : ret;
  2963. }
  2964. },
  2965. prop: function(element, name, value) {
  2966. if (isDefined(value)) {
  2967. element[name] = value;
  2968. } else {
  2969. return element[name];
  2970. }
  2971. },
  2972. text: (function() {
  2973. getText.$dv = '';
  2974. return getText;
  2975. function getText(element, value) {
  2976. if (isUndefined(value)) {
  2977. var nodeType = element.nodeType;
  2978. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  2979. }
  2980. element.textContent = value;
  2981. }
  2982. })(),
  2983. val: function(element, value) {
  2984. if (isUndefined(value)) {
  2985. if (element.multiple && nodeName_(element) === 'select') {
  2986. var result = [];
  2987. forEach(element.options, function(option) {
  2988. if (option.selected) {
  2989. result.push(option.value || option.text);
  2990. }
  2991. });
  2992. return result.length === 0 ? null : result;
  2993. }
  2994. return element.value;
  2995. }
  2996. element.value = value;
  2997. },
  2998. html: function(element, value) {
  2999. if (isUndefined(value)) {
  3000. return element.innerHTML;
  3001. }
  3002. jqLiteDealoc(element, true);
  3003. element.innerHTML = value;
  3004. },
  3005. empty: jqLiteEmpty
  3006. }, function(fn, name) {
  3007. /**
  3008. * Properties: writes return selection, reads return first value
  3009. */
  3010. JQLite.prototype[name] = function(arg1, arg2) {
  3011. var i, key;
  3012. var nodeCount = this.length;
  3013. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  3014. // in a way that survives minification.
  3015. // jqLiteEmpty takes no arguments but is a setter.
  3016. if (fn !== jqLiteEmpty &&
  3017. (isUndefined((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
  3018. if (isObject(arg1)) {
  3019. // we are a write, but the object properties are the key/values
  3020. for (i = 0; i < nodeCount; i++) {
  3021. if (fn === jqLiteData) {
  3022. // data() takes the whole object in jQuery
  3023. fn(this[i], arg1);
  3024. } else {
  3025. for (key in arg1) {
  3026. fn(this[i], key, arg1[key]);
  3027. }
  3028. }
  3029. }
  3030. // return self for chaining
  3031. return this;
  3032. } else {
  3033. // we are a read, so read the first child.
  3034. // TODO: do we still need this?
  3035. var value = fn.$dv;
  3036. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  3037. var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
  3038. for (var j = 0; j < jj; j++) {
  3039. var nodeValue = fn(this[j], arg1, arg2);
  3040. value = value ? value + nodeValue : nodeValue;
  3041. }
  3042. return value;
  3043. }
  3044. } else {
  3045. // we are a write, so apply to all children
  3046. for (i = 0; i < nodeCount; i++) {
  3047. fn(this[i], arg1, arg2);
  3048. }
  3049. // return self for chaining
  3050. return this;
  3051. }
  3052. };
  3053. });
  3054. function createEventHandler(element, events) {
  3055. var eventHandler = function(event, type) {
  3056. // jQuery specific api
  3057. event.isDefaultPrevented = function() {
  3058. return event.defaultPrevented;
  3059. };
  3060. var eventFns = events[type || event.type];
  3061. var eventFnsLength = eventFns ? eventFns.length : 0;
  3062. if (!eventFnsLength) return;
  3063. if (isUndefined(event.immediatePropagationStopped)) {
  3064. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  3065. event.stopImmediatePropagation = function() {
  3066. event.immediatePropagationStopped = true;
  3067. if (event.stopPropagation) {
  3068. event.stopPropagation();
  3069. }
  3070. if (originalStopImmediatePropagation) {
  3071. originalStopImmediatePropagation.call(event);
  3072. }
  3073. };
  3074. }
  3075. event.isImmediatePropagationStopped = function() {
  3076. return event.immediatePropagationStopped === true;
  3077. };
  3078. // Some events have special handlers that wrap the real handler
  3079. var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
  3080. // Copy event handlers in case event handlers array is modified during execution.
  3081. if ((eventFnsLength > 1)) {
  3082. eventFns = shallowCopy(eventFns);
  3083. }
  3084. for (var i = 0; i < eventFnsLength; i++) {
  3085. if (!event.isImmediatePropagationStopped()) {
  3086. handlerWrapper(element, event, eventFns[i]);
  3087. }
  3088. }
  3089. };
  3090. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  3091. // events on `element`
  3092. eventHandler.elem = element;
  3093. return eventHandler;
  3094. }
  3095. function defaultHandlerWrapper(element, event, handler) {
  3096. handler.call(element, event);
  3097. }
  3098. function specialMouseHandlerWrapper(target, event, handler) {
  3099. // Refer to jQuery's implementation of mouseenter & mouseleave
  3100. // Read about mouseenter and mouseleave:
  3101. // http://www.quirksmode.org/js/events_mouse.html#link8
  3102. var related = event.relatedTarget;
  3103. // For mousenter/leave call the handler if related is outside the target.
  3104. // NB: No relatedTarget if the mouse left/entered the browser window
  3105. if (!related || (related !== target && !jqLiteContains.call(target, related))) {
  3106. handler.call(target, event);
  3107. }
  3108. }
  3109. //////////////////////////////////////////
  3110. // Functions iterating traversal.
  3111. // These functions chain results into a single
  3112. // selector.
  3113. //////////////////////////////////////////
  3114. forEach({
  3115. removeData: jqLiteRemoveData,
  3116. on: function jqLiteOn(element, type, fn, unsupported) {
  3117. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  3118. // Do not add event handlers to non-elements because they will not be cleaned up.
  3119. if (!jqLiteAcceptsData(element)) {
  3120. return;
  3121. }
  3122. var expandoStore = jqLiteExpandoStore(element, true);
  3123. var events = expandoStore.events;
  3124. var handle = expandoStore.handle;
  3125. if (!handle) {
  3126. handle = expandoStore.handle = createEventHandler(element, events);
  3127. }
  3128. // http://jsperf.com/string-indexof-vs-split
  3129. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  3130. var i = types.length;
  3131. var addHandler = function(type, specialHandlerWrapper, noEventListener) {
  3132. var eventFns = events[type];
  3133. if (!eventFns) {
  3134. eventFns = events[type] = [];
  3135. eventFns.specialHandlerWrapper = specialHandlerWrapper;
  3136. if (type !== '$destroy' && !noEventListener) {
  3137. addEventListenerFn(element, type, handle);
  3138. }
  3139. }
  3140. eventFns.push(fn);
  3141. };
  3142. while (i--) {
  3143. type = types[i];
  3144. if (MOUSE_EVENT_MAP[type]) {
  3145. addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
  3146. addHandler(type, undefined, true);
  3147. } else {
  3148. addHandler(type);
  3149. }
  3150. }
  3151. },
  3152. off: jqLiteOff,
  3153. one: function(element, type, fn) {
  3154. element = jqLite(element);
  3155. //add the listener twice so that when it is called
  3156. //you can remove the original function and still be
  3157. //able to call element.off(ev, fn) normally
  3158. element.on(type, function onFn() {
  3159. element.off(type, fn);
  3160. element.off(type, onFn);
  3161. });
  3162. element.on(type, fn);
  3163. },
  3164. replaceWith: function(element, replaceNode) {
  3165. var index, parent = element.parentNode;
  3166. jqLiteDealoc(element);
  3167. forEach(new JQLite(replaceNode), function(node) {
  3168. if (index) {
  3169. parent.insertBefore(node, index.nextSibling);
  3170. } else {
  3171. parent.replaceChild(node, element);
  3172. }
  3173. index = node;
  3174. });
  3175. },
  3176. children: function(element) {
  3177. var children = [];
  3178. forEach(element.childNodes, function(element) {
  3179. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3180. children.push(element);
  3181. }
  3182. });
  3183. return children;
  3184. },
  3185. contents: function(element) {
  3186. return element.contentDocument || element.childNodes || [];
  3187. },
  3188. append: function(element, node) {
  3189. var nodeType = element.nodeType;
  3190. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  3191. node = new JQLite(node);
  3192. for (var i = 0, ii = node.length; i < ii; i++) {
  3193. var child = node[i];
  3194. element.appendChild(child);
  3195. }
  3196. },
  3197. prepend: function(element, node) {
  3198. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3199. var index = element.firstChild;
  3200. forEach(new JQLite(node), function(child) {
  3201. element.insertBefore(child, index);
  3202. });
  3203. }
  3204. },
  3205. wrap: function(element, wrapNode) {
  3206. jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);
  3207. },
  3208. remove: jqLiteRemove,
  3209. detach: function(element) {
  3210. jqLiteRemove(element, true);
  3211. },
  3212. after: function(element, newElement) {
  3213. var index = element, parent = element.parentNode;
  3214. newElement = new JQLite(newElement);
  3215. for (var i = 0, ii = newElement.length; i < ii; i++) {
  3216. var node = newElement[i];
  3217. parent.insertBefore(node, index.nextSibling);
  3218. index = node;
  3219. }
  3220. },
  3221. addClass: jqLiteAddClass,
  3222. removeClass: jqLiteRemoveClass,
  3223. toggleClass: function(element, selector, condition) {
  3224. if (selector) {
  3225. forEach(selector.split(' '), function(className) {
  3226. var classCondition = condition;
  3227. if (isUndefined(classCondition)) {
  3228. classCondition = !jqLiteHasClass(element, className);
  3229. }
  3230. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  3231. });
  3232. }
  3233. },
  3234. parent: function(element) {
  3235. var parent = element.parentNode;
  3236. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  3237. },
  3238. next: function(element) {
  3239. return element.nextElementSibling;
  3240. },
  3241. find: function(element, selector) {
  3242. if (element.getElementsByTagName) {
  3243. return element.getElementsByTagName(selector);
  3244. } else {
  3245. return [];
  3246. }
  3247. },
  3248. clone: jqLiteClone,
  3249. triggerHandler: function(element, event, extraParameters) {
  3250. var dummyEvent, eventFnsCopy, handlerArgs;
  3251. var eventName = event.type || event;
  3252. var expandoStore = jqLiteExpandoStore(element);
  3253. var events = expandoStore && expandoStore.events;
  3254. var eventFns = events && events[eventName];
  3255. if (eventFns) {
  3256. // Create a dummy event to pass to the handlers
  3257. dummyEvent = {
  3258. preventDefault: function() { this.defaultPrevented = true; },
  3259. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  3260. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  3261. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  3262. stopPropagation: noop,
  3263. type: eventName,
  3264. target: element
  3265. };
  3266. // If a custom event was provided then extend our dummy event with it
  3267. if (event.type) {
  3268. dummyEvent = extend(dummyEvent, event);
  3269. }
  3270. // Copy event handlers in case event handlers array is modified during execution.
  3271. eventFnsCopy = shallowCopy(eventFns);
  3272. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  3273. forEach(eventFnsCopy, function(fn) {
  3274. if (!dummyEvent.isImmediatePropagationStopped()) {
  3275. fn.apply(element, handlerArgs);
  3276. }
  3277. });
  3278. }
  3279. }
  3280. }, function(fn, name) {
  3281. /**
  3282. * chaining functions
  3283. */
  3284. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  3285. var value;
  3286. for (var i = 0, ii = this.length; i < ii; i++) {
  3287. if (isUndefined(value)) {
  3288. value = fn(this[i], arg1, arg2, arg3);
  3289. if (isDefined(value)) {
  3290. // any function which returns a value needs to be wrapped
  3291. value = jqLite(value);
  3292. }
  3293. } else {
  3294. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  3295. }
  3296. }
  3297. return isDefined(value) ? value : this;
  3298. };
  3299. // bind legacy bind/unbind to on/off
  3300. JQLite.prototype.bind = JQLite.prototype.on;
  3301. JQLite.prototype.unbind = JQLite.prototype.off;
  3302. });
  3303. // Provider for private $$jqLite service
  3304. function $$jqLiteProvider() {
  3305. this.$get = function $$jqLite() {
  3306. return extend(JQLite, {
  3307. hasClass: function(node, classes) {
  3308. if (node.attr) node = node[0];
  3309. return jqLiteHasClass(node, classes);
  3310. },
  3311. addClass: function(node, classes) {
  3312. if (node.attr) node = node[0];
  3313. return jqLiteAddClass(node, classes);
  3314. },
  3315. removeClass: function(node, classes) {
  3316. if (node.attr) node = node[0];
  3317. return jqLiteRemoveClass(node, classes);
  3318. }
  3319. });
  3320. };
  3321. }
  3322. /**
  3323. * Computes a hash of an 'obj'.
  3324. * Hash of a:
  3325. * string is string
  3326. * number is number as string
  3327. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  3328. * that is also assigned to the $$hashKey property of the object.
  3329. *
  3330. * @param obj
  3331. * @returns {string} hash string such that the same input will have the same hash string.
  3332. * The resulting string key is in 'type:hashKey' format.
  3333. */
  3334. function hashKey(obj, nextUidFn) {
  3335. var key = obj && obj.$$hashKey;
  3336. if (key) {
  3337. if (typeof key === 'function') {
  3338. key = obj.$$hashKey();
  3339. }
  3340. return key;
  3341. }
  3342. var objType = typeof obj;
  3343. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  3344. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  3345. } else {
  3346. key = objType + ':' + obj;
  3347. }
  3348. return key;
  3349. }
  3350. /**
  3351. * HashMap which can use objects as keys
  3352. */
  3353. function HashMap(array, isolatedUid) {
  3354. if (isolatedUid) {
  3355. var uid = 0;
  3356. this.nextUid = function() {
  3357. return ++uid;
  3358. };
  3359. }
  3360. forEach(array, this.put, this);
  3361. }
  3362. HashMap.prototype = {
  3363. /**
  3364. * Store key value pair
  3365. * @param key key to store can be any type
  3366. * @param value value to store can be any type
  3367. */
  3368. put: function(key, value) {
  3369. this[hashKey(key, this.nextUid)] = value;
  3370. },
  3371. /**
  3372. * @param key
  3373. * @returns {Object} the value for the key
  3374. */
  3375. get: function(key) {
  3376. return this[hashKey(key, this.nextUid)];
  3377. },
  3378. /**
  3379. * Remove the key/value pair
  3380. * @param key
  3381. */
  3382. remove: function(key) {
  3383. var value = this[key = hashKey(key, this.nextUid)];
  3384. delete this[key];
  3385. return value;
  3386. }
  3387. };
  3388. var $$HashMapProvider = [function() {
  3389. this.$get = [function() {
  3390. return HashMap;
  3391. }];
  3392. }];
  3393. /**
  3394. * @ngdoc function
  3395. * @module ng
  3396. * @name angular.injector
  3397. * @kind function
  3398. *
  3399. * @description
  3400. * Creates an injector object that can be used for retrieving services as well as for
  3401. * dependency injection (see {@link guide/di dependency injection}).
  3402. *
  3403. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3404. * {@link angular.module}. The `ng` module must be explicitly added.
  3405. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3406. * disallows argument name annotation inference.
  3407. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3408. *
  3409. * @example
  3410. * Typical usage
  3411. * ```js
  3412. * // create an injector
  3413. * var $injector = angular.injector(['ng']);
  3414. *
  3415. * // use the injector to kick off your application
  3416. * // use the type inference to auto inject arguments, or use implicit injection
  3417. * $injector.invoke(function($rootScope, $compile, $document) {
  3418. * $compile($document)($rootScope);
  3419. * $rootScope.$digest();
  3420. * });
  3421. * ```
  3422. *
  3423. * Sometimes you want to get access to the injector of a currently running Angular app
  3424. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  3425. * application has been bootstrapped. You can do this using the extra `injector()` added
  3426. * to JQuery/jqLite elements. See {@link angular.element}.
  3427. *
  3428. * *This is fairly rare but could be the case if a third party library is injecting the
  3429. * markup.*
  3430. *
  3431. * In the following example a new block of HTML containing a `ng-controller`
  3432. * directive is added to the end of the document body by JQuery. We then compile and link
  3433. * it into the current AngularJS scope.
  3434. *
  3435. * ```js
  3436. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3437. * $(document.body).append($div);
  3438. *
  3439. * angular.element(document).injector().invoke(function($compile) {
  3440. * var scope = angular.element($div).scope();
  3441. * $compile($div)(scope);
  3442. * });
  3443. * ```
  3444. */
  3445. /**
  3446. * @ngdoc module
  3447. * @name auto
  3448. * @installation
  3449. * @description
  3450. *
  3451. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3452. */
  3453. var ARROW_ARG = /^([^\(]+?)=>/;
  3454. var FN_ARGS = /^[^\(]*\(\s*([^\)]*)\)/m;
  3455. var FN_ARG_SPLIT = /,/;
  3456. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3457. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3458. var $injectorMinErr = minErr('$injector');
  3459. function stringifyFn(fn) {
  3460. // Support: Chrome 50-51 only
  3461. // Creating a new string by adding `' '` at the end, to hack around some bug in Chrome v50/51
  3462. // (See https://github.com/angular/angular.js/issues/14487.)
  3463. // TODO (gkalpak): Remove workaround when Chrome v52 is released
  3464. return Function.prototype.toString.call(fn) + ' ';
  3465. }
  3466. function extractArgs(fn) {
  3467. var fnText = stringifyFn(fn).replace(STRIP_COMMENTS, ''),
  3468. args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
  3469. return args;
  3470. }
  3471. function anonFn(fn) {
  3472. // For anonymous functions, showing at the very least the function signature can help in
  3473. // debugging.
  3474. var args = extractArgs(fn);
  3475. if (args) {
  3476. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3477. }
  3478. return 'fn';
  3479. }
  3480. function annotate(fn, strictDi, name) {
  3481. var $inject,
  3482. argDecl,
  3483. last;
  3484. if (typeof fn === 'function') {
  3485. if (!($inject = fn.$inject)) {
  3486. $inject = [];
  3487. if (fn.length) {
  3488. if (strictDi) {
  3489. if (!isString(name) || !name) {
  3490. name = fn.name || anonFn(fn);
  3491. }
  3492. throw $injectorMinErr('strictdi',
  3493. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3494. }
  3495. argDecl = extractArgs(fn);
  3496. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3497. arg.replace(FN_ARG, function(all, underscore, name) {
  3498. $inject.push(name);
  3499. });
  3500. });
  3501. }
  3502. fn.$inject = $inject;
  3503. }
  3504. } else if (isArray(fn)) {
  3505. last = fn.length - 1;
  3506. assertArgFn(fn[last], 'fn');
  3507. $inject = fn.slice(0, last);
  3508. } else {
  3509. assertArgFn(fn, 'fn', true);
  3510. }
  3511. return $inject;
  3512. }
  3513. ///////////////////////////////////////
  3514. /**
  3515. * @ngdoc service
  3516. * @name $injector
  3517. *
  3518. * @description
  3519. *
  3520. * `$injector` is used to retrieve object instances as defined by
  3521. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3522. * and load modules.
  3523. *
  3524. * The following always holds true:
  3525. *
  3526. * ```js
  3527. * var $injector = angular.injector();
  3528. * expect($injector.get('$injector')).toBe($injector);
  3529. * expect($injector.invoke(function($injector) {
  3530. * return $injector;
  3531. * })).toBe($injector);
  3532. * ```
  3533. *
  3534. * # Injection Function Annotation
  3535. *
  3536. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3537. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3538. *
  3539. * ```js
  3540. * // inferred (only works if code not minified/obfuscated)
  3541. * $injector.invoke(function(serviceA){});
  3542. *
  3543. * // annotated
  3544. * function explicit(serviceA) {};
  3545. * explicit.$inject = ['serviceA'];
  3546. * $injector.invoke(explicit);
  3547. *
  3548. * // inline
  3549. * $injector.invoke(['serviceA', function(serviceA){}]);
  3550. * ```
  3551. *
  3552. * ## Inference
  3553. *
  3554. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3555. * can then be parsed and the function arguments can be extracted. This method of discovering
  3556. * annotations is disallowed when the injector is in strict mode.
  3557. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3558. * argument names.
  3559. *
  3560. * ## `$inject` Annotation
  3561. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3562. *
  3563. * ## Inline
  3564. * As an array of injection names, where the last item in the array is the function to call.
  3565. */
  3566. /**
  3567. * @ngdoc method
  3568. * @name $injector#get
  3569. *
  3570. * @description
  3571. * Return an instance of the service.
  3572. *
  3573. * @param {string} name The name of the instance to retrieve.
  3574. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  3575. * @return {*} The instance.
  3576. */
  3577. /**
  3578. * @ngdoc method
  3579. * @name $injector#invoke
  3580. *
  3581. * @description
  3582. * Invoke the method and supply the method arguments from the `$injector`.
  3583. *
  3584. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  3585. * injected according to the {@link guide/di $inject Annotation} rules.
  3586. * @param {Object=} self The `this` for the invoked method.
  3587. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3588. * object first, before the `$injector` is consulted.
  3589. * @returns {*} the value returned by the invoked `fn` function.
  3590. */
  3591. /**
  3592. * @ngdoc method
  3593. * @name $injector#has
  3594. *
  3595. * @description
  3596. * Allows the user to query if the particular service exists.
  3597. *
  3598. * @param {string} name Name of the service to query.
  3599. * @returns {boolean} `true` if injector has given service.
  3600. */
  3601. /**
  3602. * @ngdoc method
  3603. * @name $injector#instantiate
  3604. * @description
  3605. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3606. * operator, and supplies all of the arguments to the constructor function as specified by the
  3607. * constructor annotation.
  3608. *
  3609. * @param {Function} Type Annotated constructor function.
  3610. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3611. * object first, before the `$injector` is consulted.
  3612. * @returns {Object} new instance of `Type`.
  3613. */
  3614. /**
  3615. * @ngdoc method
  3616. * @name $injector#annotate
  3617. *
  3618. * @description
  3619. * Returns an array of service names which the function is requesting for injection. This API is
  3620. * used by the injector to determine which services need to be injected into the function when the
  3621. * function is invoked. There are three ways in which the function can be annotated with the needed
  3622. * dependencies.
  3623. *
  3624. * # Argument names
  3625. *
  3626. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3627. * by converting the function into a string using `toString()` method and extracting the argument
  3628. * names.
  3629. * ```js
  3630. * // Given
  3631. * function MyController($scope, $route) {
  3632. * // ...
  3633. * }
  3634. *
  3635. * // Then
  3636. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3637. * ```
  3638. *
  3639. * You can disallow this method by using strict injection mode.
  3640. *
  3641. * This method does not work with code minification / obfuscation. For this reason the following
  3642. * annotation strategies are supported.
  3643. *
  3644. * # The `$inject` property
  3645. *
  3646. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3647. * represent names of services to be injected into the function.
  3648. * ```js
  3649. * // Given
  3650. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3651. * // ...
  3652. * }
  3653. * // Define function dependencies
  3654. * MyController['$inject'] = ['$scope', '$route'];
  3655. *
  3656. * // Then
  3657. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3658. * ```
  3659. *
  3660. * # The array notation
  3661. *
  3662. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3663. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3664. * a way that survives minification is a better choice:
  3665. *
  3666. * ```js
  3667. * // We wish to write this (not minification / obfuscation safe)
  3668. * injector.invoke(function($compile, $rootScope) {
  3669. * // ...
  3670. * });
  3671. *
  3672. * // We are forced to write break inlining
  3673. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3674. * // ...
  3675. * };
  3676. * tmpFn.$inject = ['$compile', '$rootScope'];
  3677. * injector.invoke(tmpFn);
  3678. *
  3679. * // To better support inline function the inline annotation is supported
  3680. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3681. * // ...
  3682. * }]);
  3683. *
  3684. * // Therefore
  3685. * expect(injector.annotate(
  3686. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3687. * ).toEqual(['$compile', '$rootScope']);
  3688. * ```
  3689. *
  3690. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3691. * be retrieved as described above.
  3692. *
  3693. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3694. *
  3695. * @returns {Array.<string>} The names of the services which the function requires.
  3696. */
  3697. /**
  3698. * @ngdoc service
  3699. * @name $provide
  3700. *
  3701. * @description
  3702. *
  3703. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3704. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3705. * {@link angular.Module}.
  3706. *
  3707. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3708. * factories** are functions which, in turn, are created by a **service provider**.
  3709. * The **service providers** are constructor functions. When instantiated they must contain a
  3710. * property called `$get`, which holds the **service factory** function.
  3711. *
  3712. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3713. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3714. * function to get the instance of the **service**.
  3715. *
  3716. * Often services have no configuration options and there is no need to add methods to the service
  3717. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3718. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3719. * services without specifying a provider.
  3720. *
  3721. * * {@link auto.$provide#provider provider(name, provider)} - registers a **service provider** with the
  3722. * {@link auto.$injector $injector}
  3723. * * {@link auto.$provide#constant constant(name, obj)} - registers a value/object that can be accessed by
  3724. * providers and services.
  3725. * * {@link auto.$provide#value value(name, obj)} - registers a value/object that can only be accessed by
  3726. * services, not providers.
  3727. * * {@link auto.$provide#factory factory(name, fn)} - registers a service **factory function**
  3728. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3729. * given factory function.
  3730. * * {@link auto.$provide#service service(name, Fn)} - registers a **constructor function**
  3731. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3732. * a new object using the given constructor function.
  3733. * * {@link auto.$provide#decorator decorator(name, decorFn)} - registers a **decorator function** that
  3734. * will be able to modify or replace the implementation of another service.
  3735. *
  3736. * See the individual methods for more information and examples.
  3737. */
  3738. /**
  3739. * @ngdoc method
  3740. * @name $provide#provider
  3741. * @description
  3742. *
  3743. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3744. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3745. * service.
  3746. *
  3747. * Service provider names start with the name of the service they provide followed by `Provider`.
  3748. * For example, the {@link ng.$log $log} service has a provider called
  3749. * {@link ng.$logProvider $logProvider}.
  3750. *
  3751. * Service provider objects can have additional methods which allow configuration of the provider
  3752. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3753. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3754. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3755. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3756. * console or not.
  3757. *
  3758. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3759. 'Provider'` key.
  3760. * @param {(Object|function())} provider If the provider is:
  3761. *
  3762. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3763. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3764. * - `Constructor`: a new instance of the provider will be created using
  3765. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3766. *
  3767. * @returns {Object} registered provider instance
  3768. * @example
  3769. *
  3770. * The following example shows how to create a simple event tracking service and register it using
  3771. * {@link auto.$provide#provider $provide.provider()}.
  3772. *
  3773. * ```js
  3774. * // Define the eventTracker provider
  3775. * function EventTrackerProvider() {
  3776. * var trackingUrl = '/track';
  3777. *
  3778. * // A provider method for configuring where the tracked events should been saved
  3779. * this.setTrackingUrl = function(url) {
  3780. * trackingUrl = url;
  3781. * };
  3782. *
  3783. * // The service factory function
  3784. * this.$get = ['$http', function($http) {
  3785. * var trackedEvents = {};
  3786. * return {
  3787. * // Call this to track an event
  3788. * event: function(event) {
  3789. * var count = trackedEvents[event] || 0;
  3790. * count += 1;
  3791. * trackedEvents[event] = count;
  3792. * return count;
  3793. * },
  3794. * // Call this to save the tracked events to the trackingUrl
  3795. * save: function() {
  3796. * $http.post(trackingUrl, trackedEvents);
  3797. * }
  3798. * };
  3799. * }];
  3800. * }
  3801. *
  3802. * describe('eventTracker', function() {
  3803. * var postSpy;
  3804. *
  3805. * beforeEach(module(function($provide) {
  3806. * // Register the eventTracker provider
  3807. * $provide.provider('eventTracker', EventTrackerProvider);
  3808. * }));
  3809. *
  3810. * beforeEach(module(function(eventTrackerProvider) {
  3811. * // Configure eventTracker provider
  3812. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3813. * }));
  3814. *
  3815. * it('tracks events', inject(function(eventTracker) {
  3816. * expect(eventTracker.event('login')).toEqual(1);
  3817. * expect(eventTracker.event('login')).toEqual(2);
  3818. * }));
  3819. *
  3820. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3821. * postSpy = spyOn($http, 'post');
  3822. * eventTracker.event('login');
  3823. * eventTracker.save();
  3824. * expect(postSpy).toHaveBeenCalled();
  3825. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3826. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3827. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3828. * }));
  3829. * });
  3830. * ```
  3831. */
  3832. /**
  3833. * @ngdoc method
  3834. * @name $provide#factory
  3835. * @description
  3836. *
  3837. * Register a **service factory**, which will be called to return the service instance.
  3838. * This is short for registering a service where its provider consists of only a `$get` property,
  3839. * which is the given service factory function.
  3840. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3841. * configure your service in a provider.
  3842. *
  3843. * @param {string} name The name of the instance.
  3844. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  3845. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  3846. * @returns {Object} registered provider instance
  3847. *
  3848. * @example
  3849. * Here is an example of registering a service
  3850. * ```js
  3851. * $provide.factory('ping', ['$http', function($http) {
  3852. * return function ping() {
  3853. * return $http.send('/ping');
  3854. * };
  3855. * }]);
  3856. * ```
  3857. * You would then inject and use this service like this:
  3858. * ```js
  3859. * someModule.controller('Ctrl', ['ping', function(ping) {
  3860. * ping();
  3861. * }]);
  3862. * ```
  3863. */
  3864. /**
  3865. * @ngdoc method
  3866. * @name $provide#service
  3867. * @description
  3868. *
  3869. * Register a **service constructor**, which will be invoked with `new` to create the service
  3870. * instance.
  3871. * This is short for registering a service where its provider's `$get` property is a factory
  3872. * function that returns an instance instantiated by the injector from the service constructor
  3873. * function.
  3874. *
  3875. * Internally it looks a bit like this:
  3876. *
  3877. * ```
  3878. * {
  3879. * $get: function() {
  3880. * return $injector.instantiate(constructor);
  3881. * }
  3882. * }
  3883. * ```
  3884. *
  3885. *
  3886. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3887. * as a type/class.
  3888. *
  3889. * @param {string} name The name of the instance.
  3890. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  3891. * that will be instantiated.
  3892. * @returns {Object} registered provider instance
  3893. *
  3894. * @example
  3895. * Here is an example of registering a service using
  3896. * {@link auto.$provide#service $provide.service(class)}.
  3897. * ```js
  3898. * var Ping = function($http) {
  3899. * this.$http = $http;
  3900. * };
  3901. *
  3902. * Ping.$inject = ['$http'];
  3903. *
  3904. * Ping.prototype.send = function() {
  3905. * return this.$http.get('/ping');
  3906. * };
  3907. * $provide.service('ping', Ping);
  3908. * ```
  3909. * You would then inject and use this service like this:
  3910. * ```js
  3911. * someModule.controller('Ctrl', ['ping', function(ping) {
  3912. * ping.send();
  3913. * }]);
  3914. * ```
  3915. */
  3916. /**
  3917. * @ngdoc method
  3918. * @name $provide#value
  3919. * @description
  3920. *
  3921. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3922. * number, an array, an object or a function. This is short for registering a service where its
  3923. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3924. * service**. That also means it is not possible to inject other services into a value service.
  3925. *
  3926. * Value services are similar to constant services, except that they cannot be injected into a
  3927. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3928. * an Angular {@link auto.$provide#decorator decorator}.
  3929. *
  3930. * @param {string} name The name of the instance.
  3931. * @param {*} value The value.
  3932. * @returns {Object} registered provider instance
  3933. *
  3934. * @example
  3935. * Here are some examples of creating value services.
  3936. * ```js
  3937. * $provide.value('ADMIN_USER', 'admin');
  3938. *
  3939. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3940. *
  3941. * $provide.value('halfOf', function(value) {
  3942. * return value / 2;
  3943. * });
  3944. * ```
  3945. */
  3946. /**
  3947. * @ngdoc method
  3948. * @name $provide#constant
  3949. * @description
  3950. *
  3951. * Register a **constant service** with the {@link auto.$injector $injector}, such as a string,
  3952. * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not
  3953. * possible to inject other services into a constant.
  3954. *
  3955. * But unlike {@link auto.$provide#value value}, a constant can be
  3956. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3957. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3958. *
  3959. * @param {string} name The name of the constant.
  3960. * @param {*} value The constant value.
  3961. * @returns {Object} registered instance
  3962. *
  3963. * @example
  3964. * Here a some examples of creating constants:
  3965. * ```js
  3966. * $provide.constant('SHARD_HEIGHT', 306);
  3967. *
  3968. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3969. *
  3970. * $provide.constant('double', function(value) {
  3971. * return value * 2;
  3972. * });
  3973. * ```
  3974. */
  3975. /**
  3976. * @ngdoc method
  3977. * @name $provide#decorator
  3978. * @description
  3979. *
  3980. * Register a **decorator function** with the {@link auto.$injector $injector}. A decorator function
  3981. * intercepts the creation of a service, allowing it to override or modify the behavior of the
  3982. * service. The return value of the decorator function may be the original service, or a new service
  3983. * that replaces (or wraps and delegates to) the original service.
  3984. *
  3985. * You can find out more about using decorators in the {@link guide/decorators} guide.
  3986. *
  3987. * @param {string} name The name of the service to decorate.
  3988. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  3989. * provided and should return the decorated service instance. The function is called using
  3990. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3991. * Local injection arguments:
  3992. *
  3993. * * `$delegate` - The original service instance, which can be replaced, monkey patched, configured,
  3994. * decorated or delegated to.
  3995. *
  3996. * @example
  3997. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3998. * calls to {@link ng.$log#error $log.warn()}.
  3999. * ```js
  4000. * $provide.decorator('$log', ['$delegate', function($delegate) {
  4001. * $delegate.warn = $delegate.error;
  4002. * return $delegate;
  4003. * }]);
  4004. * ```
  4005. */
  4006. function createInjector(modulesToLoad, strictDi) {
  4007. strictDi = (strictDi === true);
  4008. var INSTANTIATING = {},
  4009. providerSuffix = 'Provider',
  4010. path = [],
  4011. loadedModules = new HashMap([], true),
  4012. providerCache = {
  4013. $provide: {
  4014. provider: supportObject(provider),
  4015. factory: supportObject(factory),
  4016. service: supportObject(service),
  4017. value: supportObject(value),
  4018. constant: supportObject(constant),
  4019. decorator: decorator
  4020. }
  4021. },
  4022. providerInjector = (providerCache.$injector =
  4023. createInternalInjector(providerCache, function(serviceName, caller) {
  4024. if (angular.isString(caller)) {
  4025. path.push(caller);
  4026. }
  4027. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  4028. })),
  4029. instanceCache = {},
  4030. protoInstanceInjector =
  4031. createInternalInjector(instanceCache, function(serviceName, caller) {
  4032. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  4033. return instanceInjector.invoke(
  4034. provider.$get, provider, undefined, serviceName);
  4035. }),
  4036. instanceInjector = protoInstanceInjector;
  4037. providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
  4038. var runBlocks = loadModules(modulesToLoad);
  4039. instanceInjector = protoInstanceInjector.get('$injector');
  4040. instanceInjector.strictDi = strictDi;
  4041. forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
  4042. return instanceInjector;
  4043. ////////////////////////////////////
  4044. // $provider
  4045. ////////////////////////////////////
  4046. function supportObject(delegate) {
  4047. return function(key, value) {
  4048. if (isObject(key)) {
  4049. forEach(key, reverseParams(delegate));
  4050. } else {
  4051. return delegate(key, value);
  4052. }
  4053. };
  4054. }
  4055. function provider(name, provider_) {
  4056. assertNotHasOwnProperty(name, 'service');
  4057. if (isFunction(provider_) || isArray(provider_)) {
  4058. provider_ = providerInjector.instantiate(provider_);
  4059. }
  4060. if (!provider_.$get) {
  4061. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  4062. }
  4063. return providerCache[name + providerSuffix] = provider_;
  4064. }
  4065. function enforceReturnValue(name, factory) {
  4066. return function enforcedReturnValue() {
  4067. var result = instanceInjector.invoke(factory, this);
  4068. if (isUndefined(result)) {
  4069. throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
  4070. }
  4071. return result;
  4072. };
  4073. }
  4074. function factory(name, factoryFn, enforce) {
  4075. return provider(name, {
  4076. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  4077. });
  4078. }
  4079. function service(name, constructor) {
  4080. return factory(name, ['$injector', function($injector) {
  4081. return $injector.instantiate(constructor);
  4082. }]);
  4083. }
  4084. function value(name, val) { return factory(name, valueFn(val), false); }
  4085. function constant(name, value) {
  4086. assertNotHasOwnProperty(name, 'constant');
  4087. providerCache[name] = value;
  4088. instanceCache[name] = value;
  4089. }
  4090. function decorator(serviceName, decorFn) {
  4091. var origProvider = providerInjector.get(serviceName + providerSuffix),
  4092. orig$get = origProvider.$get;
  4093. origProvider.$get = function() {
  4094. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  4095. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  4096. };
  4097. }
  4098. ////////////////////////////////////
  4099. // Module Loading
  4100. ////////////////////////////////////
  4101. function loadModules(modulesToLoad) {
  4102. assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
  4103. var runBlocks = [], moduleFn;
  4104. forEach(modulesToLoad, function(module) {
  4105. if (loadedModules.get(module)) return;
  4106. loadedModules.put(module, true);
  4107. function runInvokeQueue(queue) {
  4108. var i, ii;
  4109. for (i = 0, ii = queue.length; i < ii; i++) {
  4110. var invokeArgs = queue[i],
  4111. provider = providerInjector.get(invokeArgs[0]);
  4112. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  4113. }
  4114. }
  4115. try {
  4116. if (isString(module)) {
  4117. moduleFn = angularModule(module);
  4118. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  4119. runInvokeQueue(moduleFn._invokeQueue);
  4120. runInvokeQueue(moduleFn._configBlocks);
  4121. } else if (isFunction(module)) {
  4122. runBlocks.push(providerInjector.invoke(module));
  4123. } else if (isArray(module)) {
  4124. runBlocks.push(providerInjector.invoke(module));
  4125. } else {
  4126. assertArgFn(module, 'module');
  4127. }
  4128. } catch (e) {
  4129. if (isArray(module)) {
  4130. module = module[module.length - 1];
  4131. }
  4132. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  4133. // Safari & FF's stack traces don't contain error.message content
  4134. // unlike those of Chrome and IE
  4135. // So if stack doesn't contain message, we create a new string that contains both.
  4136. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  4137. /* jshint -W022 */
  4138. e = e.message + '\n' + e.stack;
  4139. }
  4140. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  4141. module, e.stack || e.message || e);
  4142. }
  4143. });
  4144. return runBlocks;
  4145. }
  4146. ////////////////////////////////////
  4147. // internal Injector
  4148. ////////////////////////////////////
  4149. function createInternalInjector(cache, factory) {
  4150. function getService(serviceName, caller) {
  4151. if (cache.hasOwnProperty(serviceName)) {
  4152. if (cache[serviceName] === INSTANTIATING) {
  4153. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  4154. serviceName + ' <- ' + path.join(' <- '));
  4155. }
  4156. return cache[serviceName];
  4157. } else {
  4158. try {
  4159. path.unshift(serviceName);
  4160. cache[serviceName] = INSTANTIATING;
  4161. return cache[serviceName] = factory(serviceName, caller);
  4162. } catch (err) {
  4163. if (cache[serviceName] === INSTANTIATING) {
  4164. delete cache[serviceName];
  4165. }
  4166. throw err;
  4167. } finally {
  4168. path.shift();
  4169. }
  4170. }
  4171. }
  4172. function injectionArgs(fn, locals, serviceName) {
  4173. var args = [],
  4174. $inject = createInjector.$$annotate(fn, strictDi, serviceName);
  4175. for (var i = 0, length = $inject.length; i < length; i++) {
  4176. var key = $inject[i];
  4177. if (typeof key !== 'string') {
  4178. throw $injectorMinErr('itkn',
  4179. 'Incorrect injection token! Expected service name as string, got {0}', key);
  4180. }
  4181. args.push(locals && locals.hasOwnProperty(key) ? locals[key] :
  4182. getService(key, serviceName));
  4183. }
  4184. return args;
  4185. }
  4186. function isClass(func) {
  4187. // IE 9-11 do not support classes and IE9 leaks with the code below.
  4188. if (msie <= 11) {
  4189. return false;
  4190. }
  4191. // Workaround for MS Edge.
  4192. // Check https://connect.microsoft.com/IE/Feedback/Details/2211653
  4193. return typeof func === 'function'
  4194. && /^(?:class\s|constructor\()/.test(stringifyFn(func));
  4195. }
  4196. function invoke(fn, self, locals, serviceName) {
  4197. if (typeof locals === 'string') {
  4198. serviceName = locals;
  4199. locals = null;
  4200. }
  4201. var args = injectionArgs(fn, locals, serviceName);
  4202. if (isArray(fn)) {
  4203. fn = fn[fn.length - 1];
  4204. }
  4205. if (!isClass(fn)) {
  4206. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  4207. // #5388
  4208. return fn.apply(self, args);
  4209. } else {
  4210. args.unshift(null);
  4211. return new (Function.prototype.bind.apply(fn, args))();
  4212. }
  4213. }
  4214. function instantiate(Type, locals, serviceName) {
  4215. // Check if Type is annotated and use just the given function at n-1 as parameter
  4216. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  4217. var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
  4218. var args = injectionArgs(Type, locals, serviceName);
  4219. // Empty object at position 0 is ignored for invocation with `new`, but required.
  4220. args.unshift(null);
  4221. return new (Function.prototype.bind.apply(ctor, args))();
  4222. }
  4223. return {
  4224. invoke: invoke,
  4225. instantiate: instantiate,
  4226. get: getService,
  4227. annotate: createInjector.$$annotate,
  4228. has: function(name) {
  4229. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  4230. }
  4231. };
  4232. }
  4233. }
  4234. createInjector.$$annotate = annotate;
  4235. /**
  4236. * @ngdoc provider
  4237. * @name $anchorScrollProvider
  4238. *
  4239. * @description
  4240. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  4241. * {@link ng.$location#hash $location.hash()} changes.
  4242. */
  4243. function $AnchorScrollProvider() {
  4244. var autoScrollingEnabled = true;
  4245. /**
  4246. * @ngdoc method
  4247. * @name $anchorScrollProvider#disableAutoScrolling
  4248. *
  4249. * @description
  4250. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  4251. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  4252. * Use this method to disable automatic scrolling.
  4253. *
  4254. * If automatic scrolling is disabled, one must explicitly call
  4255. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  4256. * current hash.
  4257. */
  4258. this.disableAutoScrolling = function() {
  4259. autoScrollingEnabled = false;
  4260. };
  4261. /**
  4262. * @ngdoc service
  4263. * @name $anchorScroll
  4264. * @kind function
  4265. * @requires $window
  4266. * @requires $location
  4267. * @requires $rootScope
  4268. *
  4269. * @description
  4270. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  4271. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  4272. * in the
  4273. * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#an-indicated-part-of-the-document).
  4274. *
  4275. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  4276. * match any anchor whenever it changes. This can be disabled by calling
  4277. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  4278. *
  4279. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  4280. * vertical scroll-offset (either fixed or dynamic).
  4281. *
  4282. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  4283. * {@link ng.$location#hash $location.hash()} will be used.
  4284. *
  4285. * @property {(number|function|jqLite)} yOffset
  4286. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  4287. * positioned elements at the top of the page, such as navbars, headers etc.
  4288. *
  4289. * `yOffset` can be specified in various ways:
  4290. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  4291. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  4292. * a number representing the offset (in pixels).<br /><br />
  4293. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  4294. * the top of the page to the element's bottom will be used as offset.<br />
  4295. * **Note**: The element will be taken into account only as long as its `position` is set to
  4296. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  4297. * their height and/or positioning according to the viewport's size.
  4298. *
  4299. * <br />
  4300. * <div class="alert alert-warning">
  4301. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  4302. * not some child element.
  4303. * </div>
  4304. *
  4305. * @example
  4306. <example module="anchorScrollExample">
  4307. <file name="index.html">
  4308. <div id="scrollArea" ng-controller="ScrollController">
  4309. <a ng-click="gotoBottom()">Go to bottom</a>
  4310. <a id="bottom"></a> You're at the bottom!
  4311. </div>
  4312. </file>
  4313. <file name="script.js">
  4314. angular.module('anchorScrollExample', [])
  4315. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  4316. function ($scope, $location, $anchorScroll) {
  4317. $scope.gotoBottom = function() {
  4318. // set the location.hash to the id of
  4319. // the element you wish to scroll to.
  4320. $location.hash('bottom');
  4321. // call $anchorScroll()
  4322. $anchorScroll();
  4323. };
  4324. }]);
  4325. </file>
  4326. <file name="style.css">
  4327. #scrollArea {
  4328. height: 280px;
  4329. overflow: auto;
  4330. }
  4331. #bottom {
  4332. display: block;
  4333. margin-top: 2000px;
  4334. }
  4335. </file>
  4336. </example>
  4337. *
  4338. * <hr />
  4339. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  4340. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  4341. *
  4342. * @example
  4343. <example module="anchorScrollOffsetExample">
  4344. <file name="index.html">
  4345. <div class="fixed-header" ng-controller="headerCtrl">
  4346. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  4347. Go to anchor {{x}}
  4348. </a>
  4349. </div>
  4350. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  4351. Anchor {{x}} of 5
  4352. </div>
  4353. </file>
  4354. <file name="script.js">
  4355. angular.module('anchorScrollOffsetExample', [])
  4356. .run(['$anchorScroll', function($anchorScroll) {
  4357. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  4358. }])
  4359. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  4360. function ($anchorScroll, $location, $scope) {
  4361. $scope.gotoAnchor = function(x) {
  4362. var newHash = 'anchor' + x;
  4363. if ($location.hash() !== newHash) {
  4364. // set the $location.hash to `newHash` and
  4365. // $anchorScroll will automatically scroll to it
  4366. $location.hash('anchor' + x);
  4367. } else {
  4368. // call $anchorScroll() explicitly,
  4369. // since $location.hash hasn't changed
  4370. $anchorScroll();
  4371. }
  4372. };
  4373. }
  4374. ]);
  4375. </file>
  4376. <file name="style.css">
  4377. body {
  4378. padding-top: 50px;
  4379. }
  4380. .anchor {
  4381. border: 2px dashed DarkOrchid;
  4382. padding: 10px 10px 200px 10px;
  4383. }
  4384. .fixed-header {
  4385. background-color: rgba(0, 0, 0, 0.2);
  4386. height: 50px;
  4387. position: fixed;
  4388. top: 0; left: 0; right: 0;
  4389. }
  4390. .fixed-header > a {
  4391. display: inline-block;
  4392. margin: 5px 15px;
  4393. }
  4394. </file>
  4395. </example>
  4396. */
  4397. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  4398. var document = $window.document;
  4399. // Helper function to get first anchor from a NodeList
  4400. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  4401. // and working in all supported browsers.)
  4402. function getFirstAnchor(list) {
  4403. var result = null;
  4404. Array.prototype.some.call(list, function(element) {
  4405. if (nodeName_(element) === 'a') {
  4406. result = element;
  4407. return true;
  4408. }
  4409. });
  4410. return result;
  4411. }
  4412. function getYOffset() {
  4413. var offset = scroll.yOffset;
  4414. if (isFunction(offset)) {
  4415. offset = offset();
  4416. } else if (isElement(offset)) {
  4417. var elem = offset[0];
  4418. var style = $window.getComputedStyle(elem);
  4419. if (style.position !== 'fixed') {
  4420. offset = 0;
  4421. } else {
  4422. offset = elem.getBoundingClientRect().bottom;
  4423. }
  4424. } else if (!isNumber(offset)) {
  4425. offset = 0;
  4426. }
  4427. return offset;
  4428. }
  4429. function scrollTo(elem) {
  4430. if (elem) {
  4431. elem.scrollIntoView();
  4432. var offset = getYOffset();
  4433. if (offset) {
  4434. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  4435. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  4436. // top of the viewport.
  4437. //
  4438. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  4439. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  4440. // way down the page.
  4441. //
  4442. // This is often the case for elements near the bottom of the page.
  4443. //
  4444. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  4445. // the top of the element and the offset, which is enough to align the top of `elem` at the
  4446. // desired position.
  4447. var elemTop = elem.getBoundingClientRect().top;
  4448. $window.scrollBy(0, elemTop - offset);
  4449. }
  4450. } else {
  4451. $window.scrollTo(0, 0);
  4452. }
  4453. }
  4454. function scroll(hash) {
  4455. hash = isString(hash) ? hash : $location.hash();
  4456. var elm;
  4457. // empty hash, scroll to the top of the page
  4458. if (!hash) scrollTo(null);
  4459. // element with given id
  4460. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4461. // first anchor with given name :-D
  4462. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4463. // no element and hash == 'top', scroll to the top of the page
  4464. else if (hash === 'top') scrollTo(null);
  4465. }
  4466. // does not scroll when user clicks on anchor link that is currently on
  4467. // (no url change, no $location.hash() change), browser native does scroll
  4468. if (autoScrollingEnabled) {
  4469. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4470. function autoScrollWatchAction(newVal, oldVal) {
  4471. // skip the initial scroll if $location.hash is empty
  4472. if (newVal === oldVal && newVal === '') return;
  4473. jqLiteDocumentLoaded(function() {
  4474. $rootScope.$evalAsync(scroll);
  4475. });
  4476. });
  4477. }
  4478. return scroll;
  4479. }];
  4480. }
  4481. var $animateMinErr = minErr('$animate');
  4482. var ELEMENT_NODE = 1;
  4483. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  4484. function mergeClasses(a,b) {
  4485. if (!a && !b) return '';
  4486. if (!a) return b;
  4487. if (!b) return a;
  4488. if (isArray(a)) a = a.join(' ');
  4489. if (isArray(b)) b = b.join(' ');
  4490. return a + ' ' + b;
  4491. }
  4492. function extractElementNode(element) {
  4493. for (var i = 0; i < element.length; i++) {
  4494. var elm = element[i];
  4495. if (elm.nodeType === ELEMENT_NODE) {
  4496. return elm;
  4497. }
  4498. }
  4499. }
  4500. function splitClasses(classes) {
  4501. if (isString(classes)) {
  4502. classes = classes.split(' ');
  4503. }
  4504. // Use createMap() to prevent class assumptions involving property names in
  4505. // Object.prototype
  4506. var obj = createMap();
  4507. forEach(classes, function(klass) {
  4508. // sometimes the split leaves empty string values
  4509. // incase extra spaces were applied to the options
  4510. if (klass.length) {
  4511. obj[klass] = true;
  4512. }
  4513. });
  4514. return obj;
  4515. }
  4516. // if any other type of options value besides an Object value is
  4517. // passed into the $animate.method() animation then this helper code
  4518. // will be run which will ignore it. While this patch is not the
  4519. // greatest solution to this, a lot of existing plugins depend on
  4520. // $animate to either call the callback (< 1.2) or return a promise
  4521. // that can be changed. This helper function ensures that the options
  4522. // are wiped clean incase a callback function is provided.
  4523. function prepareAnimateOptions(options) {
  4524. return isObject(options)
  4525. ? options
  4526. : {};
  4527. }
  4528. var $$CoreAnimateJsProvider = function() {
  4529. this.$get = noop;
  4530. };
  4531. // this is prefixed with Core since it conflicts with
  4532. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  4533. var $$CoreAnimateQueueProvider = function() {
  4534. var postDigestQueue = new HashMap();
  4535. var postDigestElements = [];
  4536. this.$get = ['$$AnimateRunner', '$rootScope',
  4537. function($$AnimateRunner, $rootScope) {
  4538. return {
  4539. enabled: noop,
  4540. on: noop,
  4541. off: noop,
  4542. pin: noop,
  4543. push: function(element, event, options, domOperation) {
  4544. domOperation && domOperation();
  4545. options = options || {};
  4546. options.from && element.css(options.from);
  4547. options.to && element.css(options.to);
  4548. if (options.addClass || options.removeClass) {
  4549. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  4550. }
  4551. var runner = new $$AnimateRunner(); // jshint ignore:line
  4552. // since there are no animations to run the runner needs to be
  4553. // notified that the animation call is complete.
  4554. runner.complete();
  4555. return runner;
  4556. }
  4557. };
  4558. function updateData(data, classes, value) {
  4559. var changed = false;
  4560. if (classes) {
  4561. classes = isString(classes) ? classes.split(' ') :
  4562. isArray(classes) ? classes : [];
  4563. forEach(classes, function(className) {
  4564. if (className) {
  4565. changed = true;
  4566. data[className] = value;
  4567. }
  4568. });
  4569. }
  4570. return changed;
  4571. }
  4572. function handleCSSClassChanges() {
  4573. forEach(postDigestElements, function(element) {
  4574. var data = postDigestQueue.get(element);
  4575. if (data) {
  4576. var existing = splitClasses(element.attr('class'));
  4577. var toAdd = '';
  4578. var toRemove = '';
  4579. forEach(data, function(status, className) {
  4580. var hasClass = !!existing[className];
  4581. if (status !== hasClass) {
  4582. if (status) {
  4583. toAdd += (toAdd.length ? ' ' : '') + className;
  4584. } else {
  4585. toRemove += (toRemove.length ? ' ' : '') + className;
  4586. }
  4587. }
  4588. });
  4589. forEach(element, function(elm) {
  4590. toAdd && jqLiteAddClass(elm, toAdd);
  4591. toRemove && jqLiteRemoveClass(elm, toRemove);
  4592. });
  4593. postDigestQueue.remove(element);
  4594. }
  4595. });
  4596. postDigestElements.length = 0;
  4597. }
  4598. function addRemoveClassesPostDigest(element, add, remove) {
  4599. var data = postDigestQueue.get(element) || {};
  4600. var classesAdded = updateData(data, add, true);
  4601. var classesRemoved = updateData(data, remove, false);
  4602. if (classesAdded || classesRemoved) {
  4603. postDigestQueue.put(element, data);
  4604. postDigestElements.push(element);
  4605. if (postDigestElements.length === 1) {
  4606. $rootScope.$$postDigest(handleCSSClassChanges);
  4607. }
  4608. }
  4609. }
  4610. }];
  4611. };
  4612. /**
  4613. * @ngdoc provider
  4614. * @name $animateProvider
  4615. *
  4616. * @description
  4617. * Default implementation of $animate that doesn't perform any animations, instead just
  4618. * synchronously performs DOM updates and resolves the returned runner promise.
  4619. *
  4620. * In order to enable animations the `ngAnimate` module has to be loaded.
  4621. *
  4622. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  4623. */
  4624. var $AnimateProvider = ['$provide', function($provide) {
  4625. var provider = this;
  4626. this.$$registeredAnimations = Object.create(null);
  4627. /**
  4628. * @ngdoc method
  4629. * @name $animateProvider#register
  4630. *
  4631. * @description
  4632. * Registers a new injectable animation factory function. The factory function produces the
  4633. * animation object which contains callback functions for each event that is expected to be
  4634. * animated.
  4635. *
  4636. * * `eventFn`: `function(element, ... , doneFunction, options)`
  4637. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  4638. * on the type of animation additional arguments will be injected into the animation function. The
  4639. * list below explains the function signatures for the different animation methods:
  4640. *
  4641. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  4642. * - addClass: function(element, addedClasses, doneFunction, options)
  4643. * - removeClass: function(element, removedClasses, doneFunction, options)
  4644. * - enter, leave, move: function(element, doneFunction, options)
  4645. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  4646. *
  4647. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  4648. *
  4649. * ```js
  4650. * return {
  4651. * //enter, leave, move signature
  4652. * eventFn : function(element, done, options) {
  4653. * //code to run the animation
  4654. * //once complete, then run done()
  4655. * return function endFunction(wasCancelled) {
  4656. * //code to cancel the animation
  4657. * }
  4658. * }
  4659. * }
  4660. * ```
  4661. *
  4662. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  4663. * @param {Function} factory The factory function that will be executed to return the animation
  4664. * object.
  4665. */
  4666. this.register = function(name, factory) {
  4667. if (name && name.charAt(0) !== '.') {
  4668. throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name);
  4669. }
  4670. var key = name + '-animation';
  4671. provider.$$registeredAnimations[name.substr(1)] = key;
  4672. $provide.factory(key, factory);
  4673. };
  4674. /**
  4675. * @ngdoc method
  4676. * @name $animateProvider#classNameFilter
  4677. *
  4678. * @description
  4679. * Sets and/or returns the CSS class regular expression that is checked when performing
  4680. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4681. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  4682. * When setting the `classNameFilter` value, animations will only be performed on elements
  4683. * that successfully match the filter expression. This in turn can boost performance
  4684. * for low-powered devices as well as applications containing a lot of structural operations.
  4685. * @param {RegExp=} expression The className expression which will be checked against all animations
  4686. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4687. */
  4688. this.classNameFilter = function(expression) {
  4689. if (arguments.length === 1) {
  4690. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  4691. if (this.$$classNameFilter) {
  4692. var reservedRegex = new RegExp("(\\s+|\\/)" + NG_ANIMATE_CLASSNAME + "(\\s+|\\/)");
  4693. if (reservedRegex.test(this.$$classNameFilter.toString())) {
  4694. throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  4695. }
  4696. }
  4697. }
  4698. return this.$$classNameFilter;
  4699. };
  4700. this.$get = ['$$animateQueue', function($$animateQueue) {
  4701. function domInsert(element, parentElement, afterElement) {
  4702. // if for some reason the previous element was removed
  4703. // from the dom sometime before this code runs then let's
  4704. // just stick to using the parent element as the anchor
  4705. if (afterElement) {
  4706. var afterNode = extractElementNode(afterElement);
  4707. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  4708. afterElement = null;
  4709. }
  4710. }
  4711. afterElement ? afterElement.after(element) : parentElement.prepend(element);
  4712. }
  4713. /**
  4714. * @ngdoc service
  4715. * @name $animate
  4716. * @description The $animate service exposes a series of DOM utility methods that provide support
  4717. * for animation hooks. The default behavior is the application of DOM operations, however,
  4718. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  4719. * to ensure that animation runs with the triggered DOM operation.
  4720. *
  4721. * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
  4722. * included and only when it is active then the animation hooks that `$animate` triggers will be
  4723. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  4724. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  4725. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  4726. *
  4727. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  4728. *
  4729. * To learn more about enabling animation support, click here to visit the
  4730. * {@link ngAnimate ngAnimate module page}.
  4731. */
  4732. return {
  4733. // we don't call it directly since non-existant arguments may
  4734. // be interpreted as null within the sub enabled function
  4735. /**
  4736. *
  4737. * @ngdoc method
  4738. * @name $animate#on
  4739. * @kind function
  4740. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  4741. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  4742. * is fired with the following params:
  4743. *
  4744. * ```js
  4745. * $animate.on('enter', container,
  4746. * function callback(element, phase) {
  4747. * // cool we detected an enter animation within the container
  4748. * }
  4749. * );
  4750. * ```
  4751. *
  4752. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  4753. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  4754. * as well as among its children
  4755. * @param {Function} callback the callback function that will be fired when the listener is triggered
  4756. *
  4757. * The arguments present in the callback function are:
  4758. * * `element` - The captured DOM element that the animation was fired on.
  4759. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  4760. */
  4761. on: $$animateQueue.on,
  4762. /**
  4763. *
  4764. * @ngdoc method
  4765. * @name $animate#off
  4766. * @kind function
  4767. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  4768. * can be used in three different ways depending on the arguments:
  4769. *
  4770. * ```js
  4771. * // remove all the animation event listeners listening for `enter`
  4772. * $animate.off('enter');
  4773. *
  4774. * // remove listeners for all animation events from the container element
  4775. * $animate.off(container);
  4776. *
  4777. * // remove all the animation event listeners listening for `enter` on the given element and its children
  4778. * $animate.off('enter', container);
  4779. *
  4780. * // remove the event listener function provided by `callback` that is set
  4781. * // to listen for `enter` on the given `container` as well as its children
  4782. * $animate.off('enter', container, callback);
  4783. * ```
  4784. *
  4785. * @param {string|DOMElement} event|container the animation event (e.g. enter, leave, move,
  4786. * addClass, removeClass, etc...), or the container element. If it is the element, all other
  4787. * arguments are ignored.
  4788. * @param {DOMElement=} container the container element the event listener was placed on
  4789. * @param {Function=} callback the callback function that was registered as the listener
  4790. */
  4791. off: $$animateQueue.off,
  4792. /**
  4793. * @ngdoc method
  4794. * @name $animate#pin
  4795. * @kind function
  4796. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  4797. * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
  4798. * element despite being outside the realm of the application or within another application. Say for example if the application
  4799. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  4800. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  4801. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  4802. *
  4803. * Note that this feature is only active when the `ngAnimate` module is used.
  4804. *
  4805. * @param {DOMElement} element the external element that will be pinned
  4806. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  4807. */
  4808. pin: $$animateQueue.pin,
  4809. /**
  4810. *
  4811. * @ngdoc method
  4812. * @name $animate#enabled
  4813. * @kind function
  4814. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  4815. * function can be called in four ways:
  4816. *
  4817. * ```js
  4818. * // returns true or false
  4819. * $animate.enabled();
  4820. *
  4821. * // changes the enabled state for all animations
  4822. * $animate.enabled(false);
  4823. * $animate.enabled(true);
  4824. *
  4825. * // returns true or false if animations are enabled for an element
  4826. * $animate.enabled(element);
  4827. *
  4828. * // changes the enabled state for an element and its children
  4829. * $animate.enabled(element, true);
  4830. * $animate.enabled(element, false);
  4831. * ```
  4832. *
  4833. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  4834. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  4835. *
  4836. * @return {boolean} whether or not animations are enabled
  4837. */
  4838. enabled: $$animateQueue.enabled,
  4839. /**
  4840. * @ngdoc method
  4841. * @name $animate#cancel
  4842. * @kind function
  4843. * @description Cancels the provided animation.
  4844. *
  4845. * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
  4846. */
  4847. cancel: function(runner) {
  4848. runner.end && runner.end();
  4849. },
  4850. /**
  4851. *
  4852. * @ngdoc method
  4853. * @name $animate#enter
  4854. * @kind function
  4855. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  4856. * as the first child within the `parent` element and then triggers an animation.
  4857. * A promise is returned that will be resolved during the next digest once the animation
  4858. * has completed.
  4859. *
  4860. * @param {DOMElement} element the element which will be inserted into the DOM
  4861. * @param {DOMElement} parent the parent element which will append the element as
  4862. * a child (so long as the after element is not present)
  4863. * @param {DOMElement=} after the sibling element after which the element will be appended
  4864. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  4865. * The object can have the following properties:
  4866. *
  4867. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  4868. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  4869. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  4870. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  4871. *
  4872. * @return {Promise} the animation callback promise
  4873. */
  4874. enter: function(element, parent, after, options) {
  4875. parent = parent && jqLite(parent);
  4876. after = after && jqLite(after);
  4877. parent = parent || after.parent();
  4878. domInsert(element, parent, after);
  4879. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  4880. },
  4881. /**
  4882. *
  4883. * @ngdoc method
  4884. * @name $animate#move
  4885. * @kind function
  4886. * @description Inserts (moves) the element into its new position in the DOM either after
  4887. * the `after` element (if provided) or as the first child within the `parent` element
  4888. * and then triggers an animation. A promise is returned that will be resolved
  4889. * during the next digest once the animation has completed.
  4890. *
  4891. * @param {DOMElement} element the element which will be moved into the new DOM position
  4892. * @param {DOMElement} parent the parent element which will append the element as
  4893. * a child (so long as the after element is not present)
  4894. * @param {DOMElement=} after the sibling element after which the element will be appended
  4895. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  4896. * The object can have the following properties:
  4897. *
  4898. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  4899. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  4900. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  4901. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  4902. *
  4903. * @return {Promise} the animation callback promise
  4904. */
  4905. move: function(element, parent, after, options) {
  4906. parent = parent && jqLite(parent);
  4907. after = after && jqLite(after);
  4908. parent = parent || after.parent();
  4909. domInsert(element, parent, after);
  4910. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  4911. },
  4912. /**
  4913. * @ngdoc method
  4914. * @name $animate#leave
  4915. * @kind function
  4916. * @description Triggers an animation and then removes the element from the DOM.
  4917. * When the function is called a promise is returned that will be resolved during the next
  4918. * digest once the animation has completed.
  4919. *
  4920. * @param {DOMElement} element the element which will be removed from the DOM
  4921. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  4922. * The object can have the following properties:
  4923. *
  4924. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  4925. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  4926. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  4927. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  4928. *
  4929. * @return {Promise} the animation callback promise
  4930. */
  4931. leave: function(element, options) {
  4932. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  4933. element.remove();
  4934. });
  4935. },
  4936. /**
  4937. * @ngdoc method
  4938. * @name $animate#addClass
  4939. * @kind function
  4940. *
  4941. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  4942. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  4943. * animation if element already contains the CSS class or if the class is removed at a later step.
  4944. * Note that class-based animations are treated differently compared to structural animations
  4945. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4946. * depending if CSS or JavaScript animations are used.
  4947. *
  4948. * @param {DOMElement} element the element which the CSS classes will be applied to
  4949. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  4950. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  4951. * The object can have the following properties:
  4952. *
  4953. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  4954. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  4955. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  4956. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  4957. *
  4958. * @return {Promise} the animation callback promise
  4959. */
  4960. addClass: function(element, className, options) {
  4961. options = prepareAnimateOptions(options);
  4962. options.addClass = mergeClasses(options.addclass, className);
  4963. return $$animateQueue.push(element, 'addClass', options);
  4964. },
  4965. /**
  4966. * @ngdoc method
  4967. * @name $animate#removeClass
  4968. * @kind function
  4969. *
  4970. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  4971. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  4972. * animation if element does not contain the CSS class or if the class is added at a later step.
  4973. * Note that class-based animations are treated differently compared to structural animations
  4974. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4975. * depending if CSS or JavaScript animations are used.
  4976. *
  4977. * @param {DOMElement} element the element which the CSS classes will be applied to
  4978. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  4979. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  4980. * The object can have the following properties:
  4981. *
  4982. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  4983. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  4984. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  4985. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  4986. *
  4987. * @return {Promise} the animation callback promise
  4988. */
  4989. removeClass: function(element, className, options) {
  4990. options = prepareAnimateOptions(options);
  4991. options.removeClass = mergeClasses(options.removeClass, className);
  4992. return $$animateQueue.push(element, 'removeClass', options);
  4993. },
  4994. /**
  4995. * @ngdoc method
  4996. * @name $animate#setClass
  4997. * @kind function
  4998. *
  4999. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  5000. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  5001. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  5002. * passed. Note that class-based animations are treated differently compared to structural animations
  5003. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  5004. * depending if CSS or JavaScript animations are used.
  5005. *
  5006. * @param {DOMElement} element the element which the CSS classes will be applied to
  5007. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  5008. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  5009. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5010. * The object can have the following properties:
  5011. *
  5012. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5013. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5014. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5015. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5016. *
  5017. * @return {Promise} the animation callback promise
  5018. */
  5019. setClass: function(element, add, remove, options) {
  5020. options = prepareAnimateOptions(options);
  5021. options.addClass = mergeClasses(options.addClass, add);
  5022. options.removeClass = mergeClasses(options.removeClass, remove);
  5023. return $$animateQueue.push(element, 'setClass', options);
  5024. },
  5025. /**
  5026. * @ngdoc method
  5027. * @name $animate#animate
  5028. * @kind function
  5029. *
  5030. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  5031. * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take
  5032. * on the provided styles. For example, if a transition animation is set for the given classNamem, then the provided `from` and
  5033. * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding
  5034. * style in `to`, the style in `from` is applied immediately, and no animation is run.
  5035. * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`
  5036. * method (or as part of the `options` parameter):
  5037. *
  5038. * ```js
  5039. * ngModule.animation('.my-inline-animation', function() {
  5040. * return {
  5041. * animate : function(element, from, to, done, options) {
  5042. * //animation
  5043. * done();
  5044. * }
  5045. * }
  5046. * });
  5047. * ```
  5048. *
  5049. * @param {DOMElement} element the element which the CSS styles will be applied to
  5050. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  5051. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  5052. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  5053. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  5054. * (Note that if no animation is detected then this value will not be applied to the element.)
  5055. * @param {object=} options an optional collection of options/styles that will be applied to the element.
  5056. * The object can have the following properties:
  5057. *
  5058. * - **addClass** - `{string}` - space-separated CSS classes to add to element
  5059. * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to`
  5060. * - **removeClass** - `{string}` - space-separated CSS classes to remove from element
  5061. * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from`
  5062. *
  5063. * @return {Promise} the animation callback promise
  5064. */
  5065. animate: function(element, from, to, className, options) {
  5066. options = prepareAnimateOptions(options);
  5067. options.from = options.from ? extend(options.from, from) : from;
  5068. options.to = options.to ? extend(options.to, to) : to;
  5069. className = className || 'ng-inline-animate';
  5070. options.tempClasses = mergeClasses(options.tempClasses, className);
  5071. return $$animateQueue.push(element, 'animate', options);
  5072. }
  5073. };
  5074. }];
  5075. }];
  5076. var $$AnimateAsyncRunFactoryProvider = function() {
  5077. this.$get = ['$$rAF', function($$rAF) {
  5078. var waitQueue = [];
  5079. function waitForTick(fn) {
  5080. waitQueue.push(fn);
  5081. if (waitQueue.length > 1) return;
  5082. $$rAF(function() {
  5083. for (var i = 0; i < waitQueue.length; i++) {
  5084. waitQueue[i]();
  5085. }
  5086. waitQueue = [];
  5087. });
  5088. }
  5089. return function() {
  5090. var passed = false;
  5091. waitForTick(function() {
  5092. passed = true;
  5093. });
  5094. return function(callback) {
  5095. passed ? callback() : waitForTick(callback);
  5096. };
  5097. };
  5098. }];
  5099. };
  5100. var $$AnimateRunnerFactoryProvider = function() {
  5101. this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$document', '$timeout',
  5102. function($q, $sniffer, $$animateAsyncRun, $document, $timeout) {
  5103. var INITIAL_STATE = 0;
  5104. var DONE_PENDING_STATE = 1;
  5105. var DONE_COMPLETE_STATE = 2;
  5106. AnimateRunner.chain = function(chain, callback) {
  5107. var index = 0;
  5108. next();
  5109. function next() {
  5110. if (index === chain.length) {
  5111. callback(true);
  5112. return;
  5113. }
  5114. chain[index](function(response) {
  5115. if (response === false) {
  5116. callback(false);
  5117. return;
  5118. }
  5119. index++;
  5120. next();
  5121. });
  5122. }
  5123. };
  5124. AnimateRunner.all = function(runners, callback) {
  5125. var count = 0;
  5126. var status = true;
  5127. forEach(runners, function(runner) {
  5128. runner.done(onProgress);
  5129. });
  5130. function onProgress(response) {
  5131. status = status && response;
  5132. if (++count === runners.length) {
  5133. callback(status);
  5134. }
  5135. }
  5136. };
  5137. function AnimateRunner(host) {
  5138. this.setHost(host);
  5139. var rafTick = $$animateAsyncRun();
  5140. var timeoutTick = function(fn) {
  5141. $timeout(fn, 0, false);
  5142. };
  5143. this._doneCallbacks = [];
  5144. this._tick = function(fn) {
  5145. var doc = $document[0];
  5146. // the document may not be ready or attached
  5147. // to the module for some internal tests
  5148. if (doc && doc.hidden) {
  5149. timeoutTick(fn);
  5150. } else {
  5151. rafTick(fn);
  5152. }
  5153. };
  5154. this._state = 0;
  5155. }
  5156. AnimateRunner.prototype = {
  5157. setHost: function(host) {
  5158. this.host = host || {};
  5159. },
  5160. done: function(fn) {
  5161. if (this._state === DONE_COMPLETE_STATE) {
  5162. fn();
  5163. } else {
  5164. this._doneCallbacks.push(fn);
  5165. }
  5166. },
  5167. progress: noop,
  5168. getPromise: function() {
  5169. if (!this.promise) {
  5170. var self = this;
  5171. this.promise = $q(function(resolve, reject) {
  5172. self.done(function(status) {
  5173. status === false ? reject() : resolve();
  5174. });
  5175. });
  5176. }
  5177. return this.promise;
  5178. },
  5179. then: function(resolveHandler, rejectHandler) {
  5180. return this.getPromise().then(resolveHandler, rejectHandler);
  5181. },
  5182. 'catch': function(handler) {
  5183. return this.getPromise()['catch'](handler);
  5184. },
  5185. 'finally': function(handler) {
  5186. return this.getPromise()['finally'](handler);
  5187. },
  5188. pause: function() {
  5189. if (this.host.pause) {
  5190. this.host.pause();
  5191. }
  5192. },
  5193. resume: function() {
  5194. if (this.host.resume) {
  5195. this.host.resume();
  5196. }
  5197. },
  5198. end: function() {
  5199. if (this.host.end) {
  5200. this.host.end();
  5201. }
  5202. this._resolve(true);
  5203. },
  5204. cancel: function() {
  5205. if (this.host.cancel) {
  5206. this.host.cancel();
  5207. }
  5208. this._resolve(false);
  5209. },
  5210. complete: function(response) {
  5211. var self = this;
  5212. if (self._state === INITIAL_STATE) {
  5213. self._state = DONE_PENDING_STATE;
  5214. self._tick(function() {
  5215. self._resolve(response);
  5216. });
  5217. }
  5218. },
  5219. _resolve: function(response) {
  5220. if (this._state !== DONE_COMPLETE_STATE) {
  5221. forEach(this._doneCallbacks, function(fn) {
  5222. fn(response);
  5223. });
  5224. this._doneCallbacks.length = 0;
  5225. this._state = DONE_COMPLETE_STATE;
  5226. }
  5227. }
  5228. };
  5229. return AnimateRunner;
  5230. }];
  5231. };
  5232. /**
  5233. * @ngdoc service
  5234. * @name $animateCss
  5235. * @kind object
  5236. *
  5237. * @description
  5238. * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
  5239. * then the `$animateCss` service will actually perform animations.
  5240. *
  5241. * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
  5242. */
  5243. var $CoreAnimateCssProvider = function() {
  5244. this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
  5245. return function(element, initialOptions) {
  5246. // all of the animation functions should create
  5247. // a copy of the options data, however, if a
  5248. // parent service has already created a copy then
  5249. // we should stick to using that
  5250. var options = initialOptions || {};
  5251. if (!options.$$prepared) {
  5252. options = copy(options);
  5253. }
  5254. // there is no point in applying the styles since
  5255. // there is no animation that goes on at all in
  5256. // this version of $animateCss.
  5257. if (options.cleanupStyles) {
  5258. options.from = options.to = null;
  5259. }
  5260. if (options.from) {
  5261. element.css(options.from);
  5262. options.from = null;
  5263. }
  5264. /* jshint newcap: false */
  5265. var closed, runner = new $$AnimateRunner();
  5266. return {
  5267. start: run,
  5268. end: run
  5269. };
  5270. function run() {
  5271. $$rAF(function() {
  5272. applyAnimationContents();
  5273. if (!closed) {
  5274. runner.complete();
  5275. }
  5276. closed = true;
  5277. });
  5278. return runner;
  5279. }
  5280. function applyAnimationContents() {
  5281. if (options.addClass) {
  5282. element.addClass(options.addClass);
  5283. options.addClass = null;
  5284. }
  5285. if (options.removeClass) {
  5286. element.removeClass(options.removeClass);
  5287. options.removeClass = null;
  5288. }
  5289. if (options.to) {
  5290. element.css(options.to);
  5291. options.to = null;
  5292. }
  5293. }
  5294. };
  5295. }];
  5296. };
  5297. /* global stripHash: true */
  5298. /**
  5299. * ! This is a private undocumented service !
  5300. *
  5301. * @name $browser
  5302. * @requires $log
  5303. * @description
  5304. * This object has two goals:
  5305. *
  5306. * - hide all the global state in the browser caused by the window object
  5307. * - abstract away all the browser specific features and inconsistencies
  5308. *
  5309. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  5310. * service, which can be used for convenient testing of the application without the interaction with
  5311. * the real browser apis.
  5312. */
  5313. /**
  5314. * @param {object} window The global window object.
  5315. * @param {object} document jQuery wrapped document.
  5316. * @param {object} $log window.console or an object with the same interface.
  5317. * @param {object} $sniffer $sniffer service
  5318. */
  5319. function Browser(window, document, $log, $sniffer) {
  5320. var self = this,
  5321. location = window.location,
  5322. history = window.history,
  5323. setTimeout = window.setTimeout,
  5324. clearTimeout = window.clearTimeout,
  5325. pendingDeferIds = {};
  5326. self.isMock = false;
  5327. var outstandingRequestCount = 0;
  5328. var outstandingRequestCallbacks = [];
  5329. // TODO(vojta): remove this temporary api
  5330. self.$$completeOutstandingRequest = completeOutstandingRequest;
  5331. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  5332. /**
  5333. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  5334. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  5335. */
  5336. function completeOutstandingRequest(fn) {
  5337. try {
  5338. fn.apply(null, sliceArgs(arguments, 1));
  5339. } finally {
  5340. outstandingRequestCount--;
  5341. if (outstandingRequestCount === 0) {
  5342. while (outstandingRequestCallbacks.length) {
  5343. try {
  5344. outstandingRequestCallbacks.pop()();
  5345. } catch (e) {
  5346. $log.error(e);
  5347. }
  5348. }
  5349. }
  5350. }
  5351. }
  5352. function getHash(url) {
  5353. var index = url.indexOf('#');
  5354. return index === -1 ? '' : url.substr(index);
  5355. }
  5356. /**
  5357. * @private
  5358. * Note: this method is used only by scenario runner
  5359. * TODO(vojta): prefix this method with $$ ?
  5360. * @param {function()} callback Function that will be called when no outstanding request
  5361. */
  5362. self.notifyWhenNoOutstandingRequests = function(callback) {
  5363. if (outstandingRequestCount === 0) {
  5364. callback();
  5365. } else {
  5366. outstandingRequestCallbacks.push(callback);
  5367. }
  5368. };
  5369. //////////////////////////////////////////////////////////////
  5370. // URL API
  5371. //////////////////////////////////////////////////////////////
  5372. var cachedState, lastHistoryState,
  5373. lastBrowserUrl = location.href,
  5374. baseElement = document.find('base'),
  5375. pendingLocation = null,
  5376. getCurrentState = !$sniffer.history ? noop : function getCurrentState() {
  5377. try {
  5378. return history.state;
  5379. } catch (e) {
  5380. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  5381. }
  5382. };
  5383. cacheState();
  5384. lastHistoryState = cachedState;
  5385. /**
  5386. * @name $browser#url
  5387. *
  5388. * @description
  5389. * GETTER:
  5390. * Without any argument, this method just returns current value of location.href.
  5391. *
  5392. * SETTER:
  5393. * With at least one argument, this method sets url to new value.
  5394. * If html5 history api supported, pushState/replaceState is used, otherwise
  5395. * location.href/location.replace is used.
  5396. * Returns its own instance to allow chaining
  5397. *
  5398. * NOTE: this api is intended for use only by the $location service. Please use the
  5399. * {@link ng.$location $location service} to change url.
  5400. *
  5401. * @param {string} url New url (when used as setter)
  5402. * @param {boolean=} replace Should new url replace current history record?
  5403. * @param {object=} state object to use with pushState/replaceState
  5404. */
  5405. self.url = function(url, replace, state) {
  5406. // In modern browsers `history.state` is `null` by default; treating it separately
  5407. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  5408. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  5409. if (isUndefined(state)) {
  5410. state = null;
  5411. }
  5412. // Android Browser BFCache causes location, history reference to become stale.
  5413. if (location !== window.location) location = window.location;
  5414. if (history !== window.history) history = window.history;
  5415. // setter
  5416. if (url) {
  5417. var sameState = lastHistoryState === state;
  5418. // Don't change anything if previous and current URLs and states match. This also prevents
  5419. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  5420. // See https://github.com/angular/angular.js/commit/ffb2701
  5421. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  5422. return self;
  5423. }
  5424. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  5425. lastBrowserUrl = url;
  5426. lastHistoryState = state;
  5427. // Don't use history API if only the hash changed
  5428. // due to a bug in IE10/IE11 which leads
  5429. // to not firing a `hashchange` nor `popstate` event
  5430. // in some cases (see #9143).
  5431. if ($sniffer.history && (!sameBase || !sameState)) {
  5432. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  5433. cacheState();
  5434. // Do the assignment again so that those two variables are referentially identical.
  5435. lastHistoryState = cachedState;
  5436. } else {
  5437. if (!sameBase) {
  5438. pendingLocation = url;
  5439. }
  5440. if (replace) {
  5441. location.replace(url);
  5442. } else if (!sameBase) {
  5443. location.href = url;
  5444. } else {
  5445. location.hash = getHash(url);
  5446. }
  5447. if (location.href !== url) {
  5448. pendingLocation = url;
  5449. }
  5450. }
  5451. if (pendingLocation) {
  5452. pendingLocation = url;
  5453. }
  5454. return self;
  5455. // getter
  5456. } else {
  5457. // - pendingLocation is needed as browsers don't allow to read out
  5458. // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
  5459. // https://openradar.appspot.com/22186109).
  5460. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  5461. return pendingLocation || location.href.replace(/%27/g,"'");
  5462. }
  5463. };
  5464. /**
  5465. * @name $browser#state
  5466. *
  5467. * @description
  5468. * This method is a getter.
  5469. *
  5470. * Return history.state or null if history.state is undefined.
  5471. *
  5472. * @returns {object} state
  5473. */
  5474. self.state = function() {
  5475. return cachedState;
  5476. };
  5477. var urlChangeListeners = [],
  5478. urlChangeInit = false;
  5479. function cacheStateAndFireUrlChange() {
  5480. pendingLocation = null;
  5481. cacheState();
  5482. fireUrlChange();
  5483. }
  5484. // This variable should be used *only* inside the cacheState function.
  5485. var lastCachedState = null;
  5486. function cacheState() {
  5487. // This should be the only place in $browser where `history.state` is read.
  5488. cachedState = getCurrentState();
  5489. cachedState = isUndefined(cachedState) ? null : cachedState;
  5490. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  5491. if (equals(cachedState, lastCachedState)) {
  5492. cachedState = lastCachedState;
  5493. }
  5494. lastCachedState = cachedState;
  5495. }
  5496. function fireUrlChange() {
  5497. if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
  5498. return;
  5499. }
  5500. lastBrowserUrl = self.url();
  5501. lastHistoryState = cachedState;
  5502. forEach(urlChangeListeners, function(listener) {
  5503. listener(self.url(), cachedState);
  5504. });
  5505. }
  5506. /**
  5507. * @name $browser#onUrlChange
  5508. *
  5509. * @description
  5510. * Register callback function that will be called, when url changes.
  5511. *
  5512. * It's only called when the url is changed from outside of angular:
  5513. * - user types different url into address bar
  5514. * - user clicks on history (forward/back) button
  5515. * - user clicks on a link
  5516. *
  5517. * It's not called when url is changed by $browser.url() method
  5518. *
  5519. * The listener gets called with new url as parameter.
  5520. *
  5521. * NOTE: this api is intended for use only by the $location service. Please use the
  5522. * {@link ng.$location $location service} to monitor url changes in angular apps.
  5523. *
  5524. * @param {function(string)} listener Listener function to be called when url changes.
  5525. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  5526. */
  5527. self.onUrlChange = function(callback) {
  5528. // TODO(vojta): refactor to use node's syntax for events
  5529. if (!urlChangeInit) {
  5530. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  5531. // don't fire popstate when user change the address bar and don't fire hashchange when url
  5532. // changed by push/replaceState
  5533. // html5 history api - popstate event
  5534. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  5535. // hashchange event
  5536. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  5537. urlChangeInit = true;
  5538. }
  5539. urlChangeListeners.push(callback);
  5540. return callback;
  5541. };
  5542. /**
  5543. * @private
  5544. * Remove popstate and hashchange handler from window.
  5545. *
  5546. * NOTE: this api is intended for use only by $rootScope.
  5547. */
  5548. self.$$applicationDestroyed = function() {
  5549. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  5550. };
  5551. /**
  5552. * Checks whether the url has changed outside of Angular.
  5553. * Needs to be exported to be able to check for changes that have been done in sync,
  5554. * as hashchange/popstate events fire in async.
  5555. */
  5556. self.$$checkUrlChange = fireUrlChange;
  5557. //////////////////////////////////////////////////////////////
  5558. // Misc API
  5559. //////////////////////////////////////////////////////////////
  5560. /**
  5561. * @name $browser#baseHref
  5562. *
  5563. * @description
  5564. * Returns current <base href>
  5565. * (always relative - without domain)
  5566. *
  5567. * @returns {string} The current base href
  5568. */
  5569. self.baseHref = function() {
  5570. var href = baseElement.attr('href');
  5571. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  5572. };
  5573. /**
  5574. * @name $browser#defer
  5575. * @param {function()} fn A function, who's execution should be deferred.
  5576. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  5577. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  5578. *
  5579. * @description
  5580. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  5581. *
  5582. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  5583. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  5584. * via `$browser.defer.flush()`.
  5585. *
  5586. */
  5587. self.defer = function(fn, delay) {
  5588. var timeoutId;
  5589. outstandingRequestCount++;
  5590. timeoutId = setTimeout(function() {
  5591. delete pendingDeferIds[timeoutId];
  5592. completeOutstandingRequest(fn);
  5593. }, delay || 0);
  5594. pendingDeferIds[timeoutId] = true;
  5595. return timeoutId;
  5596. };
  5597. /**
  5598. * @name $browser#defer.cancel
  5599. *
  5600. * @description
  5601. * Cancels a deferred task identified with `deferId`.
  5602. *
  5603. * @param {*} deferId Token returned by the `$browser.defer` function.
  5604. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  5605. * canceled.
  5606. */
  5607. self.defer.cancel = function(deferId) {
  5608. if (pendingDeferIds[deferId]) {
  5609. delete pendingDeferIds[deferId];
  5610. clearTimeout(deferId);
  5611. completeOutstandingRequest(noop);
  5612. return true;
  5613. }
  5614. return false;
  5615. };
  5616. }
  5617. function $BrowserProvider() {
  5618. this.$get = ['$window', '$log', '$sniffer', '$document',
  5619. function($window, $log, $sniffer, $document) {
  5620. return new Browser($window, $document, $log, $sniffer);
  5621. }];
  5622. }
  5623. /**
  5624. * @ngdoc service
  5625. * @name $cacheFactory
  5626. *
  5627. * @description
  5628. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  5629. * them.
  5630. *
  5631. * ```js
  5632. *
  5633. * var cache = $cacheFactory('cacheId');
  5634. * expect($cacheFactory.get('cacheId')).toBe(cache);
  5635. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  5636. *
  5637. * cache.put("key", "value");
  5638. * cache.put("another key", "another value");
  5639. *
  5640. * // We've specified no options on creation
  5641. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  5642. *
  5643. * ```
  5644. *
  5645. *
  5646. * @param {string} cacheId Name or id of the newly created cache.
  5647. * @param {object=} options Options object that specifies the cache behavior. Properties:
  5648. *
  5649. * - `{number=}` `capacity` — turns the cache into LRU cache.
  5650. *
  5651. * @returns {object} Newly created cache object with the following set of methods:
  5652. *
  5653. * - `{object}` `info()` — Returns id, size, and options of cache.
  5654. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  5655. * it.
  5656. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  5657. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  5658. * - `{void}` `removeAll()` — Removes all cached values.
  5659. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  5660. *
  5661. * @example
  5662. <example module="cacheExampleApp">
  5663. <file name="index.html">
  5664. <div ng-controller="CacheController">
  5665. <input ng-model="newCacheKey" placeholder="Key">
  5666. <input ng-model="newCacheValue" placeholder="Value">
  5667. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  5668. <p ng-if="keys.length">Cached Values</p>
  5669. <div ng-repeat="key in keys">
  5670. <span ng-bind="key"></span>
  5671. <span>: </span>
  5672. <b ng-bind="cache.get(key)"></b>
  5673. </div>
  5674. <p>Cache Info</p>
  5675. <div ng-repeat="(key, value) in cache.info()">
  5676. <span ng-bind="key"></span>
  5677. <span>: </span>
  5678. <b ng-bind="value"></b>
  5679. </div>
  5680. </div>
  5681. </file>
  5682. <file name="script.js">
  5683. angular.module('cacheExampleApp', []).
  5684. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  5685. $scope.keys = [];
  5686. $scope.cache = $cacheFactory('cacheId');
  5687. $scope.put = function(key, value) {
  5688. if (angular.isUndefined($scope.cache.get(key))) {
  5689. $scope.keys.push(key);
  5690. }
  5691. $scope.cache.put(key, angular.isUndefined(value) ? null : value);
  5692. };
  5693. }]);
  5694. </file>
  5695. <file name="style.css">
  5696. p {
  5697. margin: 10px 0 3px;
  5698. }
  5699. </file>
  5700. </example>
  5701. */
  5702. function $CacheFactoryProvider() {
  5703. this.$get = function() {
  5704. var caches = {};
  5705. function cacheFactory(cacheId, options) {
  5706. if (cacheId in caches) {
  5707. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  5708. }
  5709. var size = 0,
  5710. stats = extend({}, options, {id: cacheId}),
  5711. data = createMap(),
  5712. capacity = (options && options.capacity) || Number.MAX_VALUE,
  5713. lruHash = createMap(),
  5714. freshEnd = null,
  5715. staleEnd = null;
  5716. /**
  5717. * @ngdoc type
  5718. * @name $cacheFactory.Cache
  5719. *
  5720. * @description
  5721. * A cache object used to store and retrieve data, primarily used by
  5722. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  5723. * templates and other data.
  5724. *
  5725. * ```js
  5726. * angular.module('superCache')
  5727. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  5728. * return $cacheFactory('super-cache');
  5729. * }]);
  5730. * ```
  5731. *
  5732. * Example test:
  5733. *
  5734. * ```js
  5735. * it('should behave like a cache', inject(function(superCache) {
  5736. * superCache.put('key', 'value');
  5737. * superCache.put('another key', 'another value');
  5738. *
  5739. * expect(superCache.info()).toEqual({
  5740. * id: 'super-cache',
  5741. * size: 2
  5742. * });
  5743. *
  5744. * superCache.remove('another key');
  5745. * expect(superCache.get('another key')).toBeUndefined();
  5746. *
  5747. * superCache.removeAll();
  5748. * expect(superCache.info()).toEqual({
  5749. * id: 'super-cache',
  5750. * size: 0
  5751. * });
  5752. * }));
  5753. * ```
  5754. */
  5755. return caches[cacheId] = {
  5756. /**
  5757. * @ngdoc method
  5758. * @name $cacheFactory.Cache#put
  5759. * @kind function
  5760. *
  5761. * @description
  5762. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  5763. * retrieved later, and incrementing the size of the cache if the key was not already
  5764. * present in the cache. If behaving like an LRU cache, it will also remove stale
  5765. * entries from the set.
  5766. *
  5767. * It will not insert undefined values into the cache.
  5768. *
  5769. * @param {string} key the key under which the cached data is stored.
  5770. * @param {*} value the value to store alongside the key. If it is undefined, the key
  5771. * will not be stored.
  5772. * @returns {*} the value stored.
  5773. */
  5774. put: function(key, value) {
  5775. if (isUndefined(value)) return;
  5776. if (capacity < Number.MAX_VALUE) {
  5777. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  5778. refresh(lruEntry);
  5779. }
  5780. if (!(key in data)) size++;
  5781. data[key] = value;
  5782. if (size > capacity) {
  5783. this.remove(staleEnd.key);
  5784. }
  5785. return value;
  5786. },
  5787. /**
  5788. * @ngdoc method
  5789. * @name $cacheFactory.Cache#get
  5790. * @kind function
  5791. *
  5792. * @description
  5793. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  5794. *
  5795. * @param {string} key the key of the data to be retrieved
  5796. * @returns {*} the value stored.
  5797. */
  5798. get: function(key) {
  5799. if (capacity < Number.MAX_VALUE) {
  5800. var lruEntry = lruHash[key];
  5801. if (!lruEntry) return;
  5802. refresh(lruEntry);
  5803. }
  5804. return data[key];
  5805. },
  5806. /**
  5807. * @ngdoc method
  5808. * @name $cacheFactory.Cache#remove
  5809. * @kind function
  5810. *
  5811. * @description
  5812. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  5813. *
  5814. * @param {string} key the key of the entry to be removed
  5815. */
  5816. remove: function(key) {
  5817. if (capacity < Number.MAX_VALUE) {
  5818. var lruEntry = lruHash[key];
  5819. if (!lruEntry) return;
  5820. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  5821. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  5822. link(lruEntry.n,lruEntry.p);
  5823. delete lruHash[key];
  5824. }
  5825. if (!(key in data)) return;
  5826. delete data[key];
  5827. size--;
  5828. },
  5829. /**
  5830. * @ngdoc method
  5831. * @name $cacheFactory.Cache#removeAll
  5832. * @kind function
  5833. *
  5834. * @description
  5835. * Clears the cache object of any entries.
  5836. */
  5837. removeAll: function() {
  5838. data = createMap();
  5839. size = 0;
  5840. lruHash = createMap();
  5841. freshEnd = staleEnd = null;
  5842. },
  5843. /**
  5844. * @ngdoc method
  5845. * @name $cacheFactory.Cache#destroy
  5846. * @kind function
  5847. *
  5848. * @description
  5849. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  5850. * removing it from the {@link $cacheFactory $cacheFactory} set.
  5851. */
  5852. destroy: function() {
  5853. data = null;
  5854. stats = null;
  5855. lruHash = null;
  5856. delete caches[cacheId];
  5857. },
  5858. /**
  5859. * @ngdoc method
  5860. * @name $cacheFactory.Cache#info
  5861. * @kind function
  5862. *
  5863. * @description
  5864. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  5865. *
  5866. * @returns {object} an object with the following properties:
  5867. * <ul>
  5868. * <li>**id**: the id of the cache instance</li>
  5869. * <li>**size**: the number of entries kept in the cache instance</li>
  5870. * <li>**...**: any additional properties from the options object when creating the
  5871. * cache.</li>
  5872. * </ul>
  5873. */
  5874. info: function() {
  5875. return extend({}, stats, {size: size});
  5876. }
  5877. };
  5878. /**
  5879. * makes the `entry` the freshEnd of the LRU linked list
  5880. */
  5881. function refresh(entry) {
  5882. if (entry != freshEnd) {
  5883. if (!staleEnd) {
  5884. staleEnd = entry;
  5885. } else if (staleEnd == entry) {
  5886. staleEnd = entry.n;
  5887. }
  5888. link(entry.n, entry.p);
  5889. link(entry, freshEnd);
  5890. freshEnd = entry;
  5891. freshEnd.n = null;
  5892. }
  5893. }
  5894. /**
  5895. * bidirectionally links two entries of the LRU linked list
  5896. */
  5897. function link(nextEntry, prevEntry) {
  5898. if (nextEntry != prevEntry) {
  5899. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  5900. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  5901. }
  5902. }
  5903. }
  5904. /**
  5905. * @ngdoc method
  5906. * @name $cacheFactory#info
  5907. *
  5908. * @description
  5909. * Get information about all the caches that have been created
  5910. *
  5911. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  5912. */
  5913. cacheFactory.info = function() {
  5914. var info = {};
  5915. forEach(caches, function(cache, cacheId) {
  5916. info[cacheId] = cache.info();
  5917. });
  5918. return info;
  5919. };
  5920. /**
  5921. * @ngdoc method
  5922. * @name $cacheFactory#get
  5923. *
  5924. * @description
  5925. * Get access to a cache object by the `cacheId` used when it was created.
  5926. *
  5927. * @param {string} cacheId Name or id of a cache to access.
  5928. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  5929. */
  5930. cacheFactory.get = function(cacheId) {
  5931. return caches[cacheId];
  5932. };
  5933. return cacheFactory;
  5934. };
  5935. }
  5936. /**
  5937. * @ngdoc service
  5938. * @name $templateCache
  5939. *
  5940. * @description
  5941. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  5942. * can load templates directly into the cache in a `script` tag, or by consuming the
  5943. * `$templateCache` service directly.
  5944. *
  5945. * Adding via the `script` tag:
  5946. *
  5947. * ```html
  5948. * <script type="text/ng-template" id="templateId.html">
  5949. * <p>This is the content of the template</p>
  5950. * </script>
  5951. * ```
  5952. *
  5953. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  5954. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  5955. * element with ng-app attribute), otherwise the template will be ignored.
  5956. *
  5957. * Adding via the `$templateCache` service:
  5958. *
  5959. * ```js
  5960. * var myApp = angular.module('myApp', []);
  5961. * myApp.run(function($templateCache) {
  5962. * $templateCache.put('templateId.html', 'This is the content of the template');
  5963. * });
  5964. * ```
  5965. *
  5966. * To retrieve the template later, simply use it in your HTML:
  5967. * ```html
  5968. * <div ng-include=" 'templateId.html' "></div>
  5969. * ```
  5970. *
  5971. * or get it via Javascript:
  5972. * ```js
  5973. * $templateCache.get('templateId.html')
  5974. * ```
  5975. *
  5976. * See {@link ng.$cacheFactory $cacheFactory}.
  5977. *
  5978. */
  5979. function $TemplateCacheProvider() {
  5980. this.$get = ['$cacheFactory', function($cacheFactory) {
  5981. return $cacheFactory('templates');
  5982. }];
  5983. }
  5984. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  5985. * Any commits to this file should be reviewed with security in mind. *
  5986. * Changes to this file can potentially create security vulnerabilities. *
  5987. * An approval from 2 Core members with history of modifying *
  5988. * this file is required. *
  5989. * *
  5990. * Does the change somehow allow for arbitrary javascript to be executed? *
  5991. * Or allows for someone to change the prototype of built-in objects? *
  5992. * Or gives undesired access to variables likes document or window? *
  5993. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  5994. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  5995. *
  5996. * DOM-related variables:
  5997. *
  5998. * - "node" - DOM Node
  5999. * - "element" - DOM Element or Node
  6000. * - "$node" or "$element" - jqLite-wrapped node or element
  6001. *
  6002. *
  6003. * Compiler related stuff:
  6004. *
  6005. * - "linkFn" - linking fn of a single directive
  6006. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  6007. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  6008. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  6009. */
  6010. /**
  6011. * @ngdoc service
  6012. * @name $compile
  6013. * @kind function
  6014. *
  6015. * @description
  6016. * Compiles an HTML string or DOM into a template and produces a template function, which
  6017. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  6018. *
  6019. * The compilation is a process of walking the DOM tree and matching DOM elements to
  6020. * {@link ng.$compileProvider#directive directives}.
  6021. *
  6022. * <div class="alert alert-warning">
  6023. * **Note:** This document is an in-depth reference of all directive options.
  6024. * For a gentle introduction to directives with examples of common use cases,
  6025. * see the {@link guide/directive directive guide}.
  6026. * </div>
  6027. *
  6028. * ## Comprehensive Directive API
  6029. *
  6030. * There are many different options for a directive.
  6031. *
  6032. * The difference resides in the return value of the factory function.
  6033. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  6034. * or just the `postLink` function (all other properties will have the default values).
  6035. *
  6036. * <div class="alert alert-success">
  6037. * **Best Practice:** It's recommended to use the "directive definition object" form.
  6038. * </div>
  6039. *
  6040. * Here's an example directive declared with a Directive Definition Object:
  6041. *
  6042. * ```js
  6043. * var myModule = angular.module(...);
  6044. *
  6045. * myModule.directive('directiveName', function factory(injectables) {
  6046. * var directiveDefinitionObject = {
  6047. * priority: 0,
  6048. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  6049. * // or
  6050. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  6051. * transclude: false,
  6052. * restrict: 'A',
  6053. * templateNamespace: 'html',
  6054. * scope: false,
  6055. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  6056. * controllerAs: 'stringIdentifier',
  6057. * bindToController: false,
  6058. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  6059. * compile: function compile(tElement, tAttrs, transclude) {
  6060. * return {
  6061. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  6062. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  6063. * }
  6064. * // or
  6065. * // return function postLink( ... ) { ... }
  6066. * },
  6067. * // or
  6068. * // link: {
  6069. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  6070. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  6071. * // }
  6072. * // or
  6073. * // link: function postLink( ... ) { ... }
  6074. * };
  6075. * return directiveDefinitionObject;
  6076. * });
  6077. * ```
  6078. *
  6079. * <div class="alert alert-warning">
  6080. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  6081. * </div>
  6082. *
  6083. * Therefore the above can be simplified as:
  6084. *
  6085. * ```js
  6086. * var myModule = angular.module(...);
  6087. *
  6088. * myModule.directive('directiveName', function factory(injectables) {
  6089. * var directiveDefinitionObject = {
  6090. * link: function postLink(scope, iElement, iAttrs) { ... }
  6091. * };
  6092. * return directiveDefinitionObject;
  6093. * // or
  6094. * // return function postLink(scope, iElement, iAttrs) { ... }
  6095. * });
  6096. * ```
  6097. *
  6098. *
  6099. *
  6100. * ### Directive Definition Object
  6101. *
  6102. * The directive definition object provides instructions to the {@link ng.$compile
  6103. * compiler}. The attributes are:
  6104. *
  6105. * #### `multiElement`
  6106. * When this property is set to true, the HTML compiler will collect DOM nodes between
  6107. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  6108. * together as the directive elements. It is recommended that this feature be used on directives
  6109. * which are not strictly behavioral (such as {@link ngClick}), and which
  6110. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  6111. *
  6112. * #### `priority`
  6113. * When there are multiple directives defined on a single DOM element, sometimes it
  6114. * is necessary to specify the order in which the directives are applied. The `priority` is used
  6115. * to sort the directives before their `compile` functions get called. Priority is defined as a
  6116. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  6117. * are also run in priority order, but post-link functions are run in reverse order. The order
  6118. * of directives with the same priority is undefined. The default priority is `0`.
  6119. *
  6120. * #### `terminal`
  6121. * If set to true then the current `priority` will be the last set of directives
  6122. * which will execute (any directives at the current priority will still execute
  6123. * as the order of execution on same `priority` is undefined). Note that expressions
  6124. * and other directives used in the directive's template will also be excluded from execution.
  6125. *
  6126. * #### `scope`
  6127. * The scope property can be `true`, an object or a falsy value:
  6128. *
  6129. * * **falsy:** No scope will be created for the directive. The directive will use its parent's scope.
  6130. *
  6131. * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
  6132. * the directive's element. If multiple directives on the same element request a new scope,
  6133. * only one new scope is created. The new scope rule does not apply for the root of the template
  6134. * since the root of the template always gets a new scope.
  6135. *
  6136. * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's element. The
  6137. * 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent
  6138. * scope. This is useful when creating reusable components, which should not accidentally read or modify
  6139. * data in the parent scope.
  6140. *
  6141. * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
  6142. * directive's element. These local properties are useful for aliasing values for templates. The keys in
  6143. * the object hash map to the name of the property on the isolate scope; the values define how the property
  6144. * is bound to the parent scope, via matching attributes on the directive's element:
  6145. *
  6146. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  6147. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  6148. * attribute name is assumed to be the same as the local name. Given `<my-component
  6149. * my-attr="hello {{name}}">` and the isolate scope definition `scope: { localName:'@myAttr' }`,
  6150. * the directive's scope property `localName` will reflect the interpolated value of `hello
  6151. * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's
  6152. * scope. The `name` is read from the parent scope (not the directive's scope).
  6153. *
  6154. * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression
  6155. * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.
  6156. * If no `attr` name is specified then the attribute name is assumed to be the same as the local
  6157. * name. Given `<my-component my-attr="parentModel">` and the isolate scope definition `scope: {
  6158. * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the
  6159. * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in
  6160. * `localModel` and vice versa. Optional attributes should be marked as such with a question mark:
  6161. * `=?` or `=?attr`. If the binding expression is non-assignable, or if the attribute isn't
  6162. * optional and doesn't exist, an exception ({@link error/$compile/nonassign `$compile:nonassign`})
  6163. * will be thrown upon discovering changes to the local value, since it will be impossible to sync
  6164. * them back to the parent scope. By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
  6165. * method is used for tracking changes, and the equality check is based on object identity.
  6166. * However, if an object literal or an array literal is passed as the binding expression, the
  6167. * equality check is done by value (using the {@link angular.equals} function). It's also possible
  6168. * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection
  6169. * `$watchCollection`}: use `=*` or `=*attr` (`=*?` or `=*?attr` if the attribute is optional).
  6170. *
  6171. * * `<` or `<attr` - set up a one-way (one-directional) binding between a local scope property and an
  6172. * expression passed via the attribute `attr`. The expression is evaluated in the context of the
  6173. * parent scope. If no `attr` name is specified then the attribute name is assumed to be the same as the
  6174. * local name. You can also make the binding optional by adding `?`: `<?` or `<?attr`.
  6175. *
  6176. * For example, given `<my-component my-attr="parentModel">` and directive definition of
  6177. * `scope: { localModel:'<myAttr' }`, then the isolated scope property `localModel` will reflect the
  6178. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  6179. * in `localModel`, but changes in `localModel` will not reflect in `parentModel`. There are however
  6180. * two caveats:
  6181. * 1. one-way binding does not copy the value from the parent to the isolate scope, it simply
  6182. * sets the same value. That means if your bound value is an object, changes to its properties
  6183. * in the isolated scope will be reflected in the parent scope (because both reference the same object).
  6184. * 2. one-way binding watches changes to the **identity** of the parent value. That means the
  6185. * {@link ng.$rootScope.Scope#$watch `$watch`} on the parent value only fires if the reference
  6186. * to the value has changed. In most cases, this should not be of concern, but can be important
  6187. * to know if you one-way bind to an object, and then replace that object in the isolated scope.
  6188. * If you now change a property of the object in your parent scope, the change will not be
  6189. * propagated to the isolated scope, because the identity of the object on the parent scope
  6190. * has not changed. Instead you must assign a new object.
  6191. *
  6192. * One-way binding is useful if you do not plan to propagate changes to your isolated scope bindings
  6193. * back to the parent. However, it does not make this completely impossible.
  6194. *
  6195. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. If
  6196. * no `attr` name is specified then the attribute name is assumed to be the same as the local name.
  6197. * Given `<my-component my-attr="count = count + value">` and the isolate scope definition `scope: {
  6198. * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for
  6199. * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope
  6200. * via an expression to the parent scope. This can be done by passing a map of local variable names
  6201. * and values into the expression wrapper fn. For example, if the expression is `increment(amount)`
  6202. * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.
  6203. *
  6204. * In general it's possible to apply more than one directive to one element, but there might be limitations
  6205. * depending on the type of scope required by the directives. The following points will help explain these limitations.
  6206. * For simplicity only two directives are taken into account, but it is also applicable for several directives:
  6207. *
  6208. * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
  6209. * * **child scope** + **no scope** => Both directives will share one single child scope
  6210. * * **child scope** + **child scope** => Both directives will share one single child scope
  6211. * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
  6212. * its parent's scope
  6213. * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
  6214. * be applied to the same element.
  6215. * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
  6216. * cannot be applied to the same element.
  6217. *
  6218. *
  6219. * #### `bindToController`
  6220. * This property is used to bind scope properties directly to the controller. It can be either
  6221. * `true` or an object hash with the same format as the `scope` property. Additionally, a controller
  6222. * alias must be set, either by using `controllerAs: 'myAlias'` or by specifying the alias in the controller
  6223. * definition: `controller: 'myCtrl as myAlias'`.
  6224. *
  6225. * When an isolate scope is used for a directive (see above), `bindToController: true` will
  6226. * allow a component to have its properties bound to the controller, rather than to scope.
  6227. *
  6228. * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller
  6229. * properties. You can access these bindings once they have been initialized by providing a controller method called
  6230. * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings
  6231. * initialized.
  6232. *
  6233. * <div class="alert alert-warning">
  6234. * **Deprecation warning:** although bindings for non-ES6 class controllers are currently
  6235. * bound to `this` before the controller constructor is called, this use is now deprecated. Please place initialization
  6236. * code that relies upon bindings inside a `$onInit` method on the controller, instead.
  6237. * </div>
  6238. *
  6239. * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.
  6240. * This will set up the scope bindings to the controller directly. Note that `scope` can still be used
  6241. * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate
  6242. * scope (useful for component directives).
  6243. *
  6244. * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.
  6245. *
  6246. *
  6247. * #### `controller`
  6248. * Controller constructor function. The controller is instantiated before the
  6249. * pre-linking phase and can be accessed by other directives (see
  6250. * `require` attribute). This allows the directives to communicate with each other and augment
  6251. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  6252. *
  6253. * * `$scope` - Current scope associated with the element
  6254. * * `$element` - Current element
  6255. * * `$attrs` - Current attributes object for the element
  6256. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  6257. * `function([scope], cloneLinkingFn, futureParentElement, slotName)`:
  6258. * * `scope`: (optional) override the scope.
  6259. * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.
  6260. * * `futureParentElement` (optional):
  6261. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  6262. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  6263. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  6264. * and when the `cloneLinkinFn` is passed,
  6265. * as those elements need to created and cloned in a special way when they are defined outside their
  6266. * usual containers (e.g. like `<svg>`).
  6267. * * See also the `directive.templateNamespace` property.
  6268. * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`)
  6269. * then the default translusion is provided.
  6270. * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns
  6271. * `true` if the specified slot contains content (i.e. one or more DOM nodes).
  6272. *
  6273. * The controller can provide the following methods that act as life-cycle hooks:
  6274. * * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and
  6275. * had their bindings initialized (and before the pre &amp; post linking functions for the directives on
  6276. * this element). This is a good place to put initialization code for your controller.
  6277. * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The
  6278. * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an
  6279. * object of the form `{ currentValue, previousValue, isFirstChange() }`. Use this hook to trigger updates within a
  6280. * component such as cloning the bound value to prevent accidental mutation of the outer value.
  6281. * * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing
  6282. * external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in
  6283. * the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent
  6284. * components will have their `$onDestroy()` hook called before child components.
  6285. * * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link
  6286. * function this hook can be used to set up DOM event handlers and do direct DOM manipulation.
  6287. * Note that child elements that contain `templateUrl` directives will not have been compiled and linked since
  6288. * they are waiting for their template to load asynchronously and their own compilation and linking has been
  6289. * suspended until that occurs.
  6290. *
  6291. *
  6292. * #### `require`
  6293. * Require another directive and inject its controller as the fourth argument to the linking function. The
  6294. * `require` property can be a string, an array or an object:
  6295. * * a **string** containing the name of the directive to pass to the linking function
  6296. * * an **array** containing the names of directives to pass to the linking function. The argument passed to the
  6297. * linking function will be an array of controllers in the same order as the names in the `require` property
  6298. * * an **object** whose property values are the names of the directives to pass to the linking function. The argument
  6299. * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding
  6300. * controllers.
  6301. *
  6302. * If the `require` property is an object and `bindToController` is truthy, then the required controllers are
  6303. * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers
  6304. * have been constructed but before `$onInit` is called.
  6305. * If the name of the required controller is the same as the local name (the key), the name can be
  6306. * omitted. For example, `{parentDir: '^^'}` is equivalent to `{parentDir: '^^parentDir'}`.
  6307. * See the {@link $compileProvider#component} helper for an example of how this can be used.
  6308. * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is
  6309. * raised (unless no link function is specified and the required controllers are not being bound to the directive
  6310. * controller, in which case error checking is skipped). The name can be prefixed with:
  6311. *
  6312. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  6313. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  6314. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  6315. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  6316. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  6317. * `null` to the `link` fn if not found.
  6318. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  6319. * `null` to the `link` fn if not found.
  6320. *
  6321. *
  6322. * #### `controllerAs`
  6323. * Identifier name for a reference to the controller in the directive's scope.
  6324. * This allows the controller to be referenced from the directive template. This is especially
  6325. * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
  6326. * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
  6327. * `controllerAs` reference might overwrite a property that already exists on the parent scope.
  6328. *
  6329. *
  6330. * #### `restrict`
  6331. * String of subset of `EACM` which restricts the directive to a specific directive
  6332. * declaration style. If omitted, the defaults (elements and attributes) are used.
  6333. *
  6334. * * `E` - Element name (default): `<my-directive></my-directive>`
  6335. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  6336. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  6337. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  6338. *
  6339. *
  6340. * #### `templateNamespace`
  6341. * String representing the document type used by the markup in the template.
  6342. * AngularJS needs this information as those elements need to be created and cloned
  6343. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  6344. *
  6345. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  6346. * top-level elements such as `<svg>` or `<math>`.
  6347. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  6348. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  6349. *
  6350. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  6351. *
  6352. * #### `template`
  6353. * HTML markup that may:
  6354. * * Replace the contents of the directive's element (default).
  6355. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  6356. * * Wrap the contents of the directive's element (if `transclude` is true).
  6357. *
  6358. * Value may be:
  6359. *
  6360. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  6361. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  6362. * function api below) and returns a string value.
  6363. *
  6364. *
  6365. * #### `templateUrl`
  6366. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  6367. *
  6368. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  6369. * for later when the template has been resolved. In the meantime it will continue to compile and link
  6370. * sibling and parent elements as though this element had not contained any directives.
  6371. *
  6372. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  6373. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  6374. * case when only one deeply nested directive has `templateUrl`.
  6375. *
  6376. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  6377. *
  6378. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  6379. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  6380. * a string value representing the url. In either case, the template URL is passed through {@link
  6381. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  6382. *
  6383. *
  6384. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  6385. * specify what the template should replace. Defaults to `false`.
  6386. *
  6387. * * `true` - the template will replace the directive's element.
  6388. * * `false` - the template will replace the contents of the directive's element.
  6389. *
  6390. * The replacement process migrates all of the attributes / classes from the old element to the new
  6391. * one. See the {@link guide/directive#template-expanding-directive
  6392. * Directives Guide} for an example.
  6393. *
  6394. * There are very few scenarios where element replacement is required for the application function,
  6395. * the main one being reusable custom components that are used within SVG contexts
  6396. * (because SVG doesn't work with custom elements in the DOM tree).
  6397. *
  6398. * #### `transclude`
  6399. * Extract the contents of the element where the directive appears and make it available to the directive.
  6400. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  6401. * {@link $compile#transclusion Transclusion} section below.
  6402. *
  6403. *
  6404. * #### `compile`
  6405. *
  6406. * ```js
  6407. * function compile(tElement, tAttrs, transclude) { ... }
  6408. * ```
  6409. *
  6410. * The compile function deals with transforming the template DOM. Since most directives do not do
  6411. * template transformation, it is not used often. The compile function takes the following arguments:
  6412. *
  6413. * * `tElement` - template element - The element where the directive has been declared. It is
  6414. * safe to do template transformation on the element and child elements only.
  6415. *
  6416. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  6417. * between all directive compile functions.
  6418. *
  6419. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  6420. *
  6421. * <div class="alert alert-warning">
  6422. * **Note:** The template instance and the link instance may be different objects if the template has
  6423. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  6424. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  6425. * should be done in a linking function rather than in a compile function.
  6426. * </div>
  6427. * <div class="alert alert-warning">
  6428. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  6429. * own templates or compile functions. Compiling these directives results in an infinite loop and
  6430. * stack overflow errors.
  6431. *
  6432. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  6433. * a directive's template instead of relying on automatic template compilation via `template` or
  6434. * `templateUrl` declaration or manual compilation inside the compile function.
  6435. * </div>
  6436. *
  6437. * <div class="alert alert-danger">
  6438. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  6439. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  6440. * to the link function instead.
  6441. * </div>
  6442. * A compile function can have a return value which can be either a function or an object.
  6443. *
  6444. * * returning a (post-link) function - is equivalent to registering the linking function via the
  6445. * `link` property of the config object when the compile function is empty.
  6446. *
  6447. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  6448. * control when a linking function should be called during the linking phase. See info about
  6449. * pre-linking and post-linking functions below.
  6450. *
  6451. *
  6452. * #### `link`
  6453. * This property is used only if the `compile` property is not defined.
  6454. *
  6455. * ```js
  6456. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  6457. * ```
  6458. *
  6459. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  6460. * executed after the template has been cloned. This is where most of the directive logic will be
  6461. * put.
  6462. *
  6463. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  6464. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  6465. *
  6466. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  6467. * manipulate the children of the element only in `postLink` function since the children have
  6468. * already been linked.
  6469. *
  6470. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  6471. * between all directive linking functions.
  6472. *
  6473. * * `controller` - the directive's required controller instance(s) - Instances are shared
  6474. * among all directives, which allows the directives to use the controllers as a communication
  6475. * channel. The exact value depends on the directive's `require` property:
  6476. * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
  6477. * * `string`: the controller instance
  6478. * * `array`: array of controller instances
  6479. *
  6480. * If a required controller cannot be found, and it is optional, the instance is `null`,
  6481. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  6482. *
  6483. * Note that you can also require the directive's own controller - it will be made available like
  6484. * any other controller.
  6485. *
  6486. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  6487. * This is the same as the `$transclude`
  6488. * parameter of directive controllers, see there for details.
  6489. * `function([scope], cloneLinkingFn, futureParentElement)`.
  6490. *
  6491. * #### Pre-linking function
  6492. *
  6493. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  6494. * compiler linking function will fail to locate the correct elements for linking.
  6495. *
  6496. * #### Post-linking function
  6497. *
  6498. * Executed after the child elements are linked.
  6499. *
  6500. * Note that child elements that contain `templateUrl` directives will not have been compiled
  6501. * and linked since they are waiting for their template to load asynchronously and their own
  6502. * compilation and linking has been suspended until that occurs.
  6503. *
  6504. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  6505. * for their async templates to be resolved.
  6506. *
  6507. *
  6508. * ### Transclusion
  6509. *
  6510. * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
  6511. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  6512. * scope from where they were taken.
  6513. *
  6514. * Transclusion is used (often with {@link ngTransclude}) to insert the
  6515. * original contents of a directive's element into a specified place in the template of the directive.
  6516. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  6517. * content has access to the properties on the scope from which it was taken, even if the directive
  6518. * has isolated scope.
  6519. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  6520. *
  6521. * This makes it possible for the widget to have private state for its template, while the transcluded
  6522. * content has access to its originating scope.
  6523. *
  6524. * <div class="alert alert-warning">
  6525. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  6526. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  6527. * Testing Transclusion Directives}.
  6528. * </div>
  6529. *
  6530. * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the
  6531. * directive's element, the entire element or multiple parts of the element contents:
  6532. *
  6533. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  6534. * * `'element'` - transclude the whole of the directive's element including any directives on this
  6535. * element that defined at a lower priority than this directive. When used, the `template`
  6536. * property is ignored.
  6537. * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template.
  6538. *
  6539. * **Mult-slot transclusion** is declared by providing an object for the `transclude` property.
  6540. *
  6541. * This object is a map where the keys are the name of the slot to fill and the value is an element selector
  6542. * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`)
  6543. * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc).
  6544. *
  6545. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  6546. *
  6547. * If the element selector is prefixed with a `?` then that slot is optional.
  6548. *
  6549. * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `<my-custom-element>` elements to
  6550. * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive.
  6551. *
  6552. * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements
  6553. * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call
  6554. * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and
  6555. * injectable into the directive's controller.
  6556. *
  6557. *
  6558. * #### Transclusion Functions
  6559. *
  6560. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  6561. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  6562. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  6563. *
  6564. * <div class="alert alert-info">
  6565. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  6566. * ngTransclude will deal with it for us.
  6567. * </div>
  6568. *
  6569. * If you want to manually control the insertion and removal of the transcluded content in your directive
  6570. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  6571. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  6572. *
  6573. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  6574. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  6575. * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
  6576. *
  6577. * <div class="alert alert-info">
  6578. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function
  6579. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  6580. * </div>
  6581. *
  6582. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  6583. * attach function**:
  6584. *
  6585. * ```js
  6586. * var transcludedContent, transclusionScope;
  6587. *
  6588. * $transclude(function(clone, scope) {
  6589. * element.append(clone);
  6590. * transcludedContent = clone;
  6591. * transclusionScope = scope;
  6592. * });
  6593. * ```
  6594. *
  6595. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  6596. * associated transclusion scope:
  6597. *
  6598. * ```js
  6599. * transcludedContent.remove();
  6600. * transclusionScope.$destroy();
  6601. * ```
  6602. *
  6603. * <div class="alert alert-info">
  6604. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  6605. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  6606. * then you are also responsible for calling `$destroy` on the transclusion scope.
  6607. * </div>
  6608. *
  6609. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  6610. * automatically destroy their transcluded clones as necessary so you do not need to worry about this if
  6611. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  6612. *
  6613. *
  6614. * #### Transclusion Scopes
  6615. *
  6616. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  6617. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  6618. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  6619. * was taken.
  6620. *
  6621. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  6622. * like this:
  6623. *
  6624. * ```html
  6625. * <div ng-app>
  6626. * <div isolate>
  6627. * <div transclusion>
  6628. * </div>
  6629. * </div>
  6630. * </div>
  6631. * ```
  6632. *
  6633. * The `$parent` scope hierarchy will look like this:
  6634. *
  6635. ```
  6636. - $rootScope
  6637. - isolate
  6638. - transclusion
  6639. ```
  6640. *
  6641. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  6642. *
  6643. ```
  6644. - $rootScope
  6645. - transclusion
  6646. - isolate
  6647. ```
  6648. *
  6649. *
  6650. * ### Attributes
  6651. *
  6652. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  6653. * `link()` or `compile()` functions. It has a variety of uses.
  6654. *
  6655. * * *Accessing normalized attribute names:* Directives like 'ngBind' can be expressed in many ways:
  6656. * 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. The attributes object allows for normalized access
  6657. * to the attributes.
  6658. *
  6659. * * *Directive inter-communication:* All directives share the same instance of the attributes
  6660. * object which allows the directives to use the attributes object as inter directive
  6661. * communication.
  6662. *
  6663. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  6664. * allowing other directives to read the interpolated value.
  6665. *
  6666. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  6667. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  6668. * the only way to easily get the actual value because during the linking phase the interpolation
  6669. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  6670. *
  6671. * ```js
  6672. * function linkingFn(scope, elm, attrs, ctrl) {
  6673. * // get the attribute value
  6674. * console.log(attrs.ngModel);
  6675. *
  6676. * // change the attribute
  6677. * attrs.$set('ngModel', 'new value');
  6678. *
  6679. * // observe changes to interpolated attribute
  6680. * attrs.$observe('ngModel', function(value) {
  6681. * console.log('ngModel has changed value to ' + value);
  6682. * });
  6683. * }
  6684. * ```
  6685. *
  6686. * ## Example
  6687. *
  6688. * <div class="alert alert-warning">
  6689. * **Note**: Typically directives are registered with `module.directive`. The example below is
  6690. * to illustrate how `$compile` works.
  6691. * </div>
  6692. *
  6693. <example module="compileExample">
  6694. <file name="index.html">
  6695. <script>
  6696. angular.module('compileExample', [], function($compileProvider) {
  6697. // configure new 'compile' directive by passing a directive
  6698. // factory function. The factory function injects the '$compile'
  6699. $compileProvider.directive('compile', function($compile) {
  6700. // directive factory creates a link function
  6701. return function(scope, element, attrs) {
  6702. scope.$watch(
  6703. function(scope) {
  6704. // watch the 'compile' expression for changes
  6705. return scope.$eval(attrs.compile);
  6706. },
  6707. function(value) {
  6708. // when the 'compile' expression changes
  6709. // assign it into the current DOM
  6710. element.html(value);
  6711. // compile the new DOM and link it to the current
  6712. // scope.
  6713. // NOTE: we only compile .childNodes so that
  6714. // we don't get into infinite loop compiling ourselves
  6715. $compile(element.contents())(scope);
  6716. }
  6717. );
  6718. };
  6719. });
  6720. })
  6721. .controller('GreeterController', ['$scope', function($scope) {
  6722. $scope.name = 'Angular';
  6723. $scope.html = 'Hello {{name}}';
  6724. }]);
  6725. </script>
  6726. <div ng-controller="GreeterController">
  6727. <input ng-model="name"> <br/>
  6728. <textarea ng-model="html"></textarea> <br/>
  6729. <div compile="html"></div>
  6730. </div>
  6731. </file>
  6732. <file name="protractor.js" type="protractor">
  6733. it('should auto compile', function() {
  6734. var textarea = $('textarea');
  6735. var output = $('div[compile]');
  6736. // The initial state reads 'Hello Angular'.
  6737. expect(output.getText()).toBe('Hello Angular');
  6738. textarea.clear();
  6739. textarea.sendKeys('{{name}}!');
  6740. expect(output.getText()).toBe('Angular!');
  6741. });
  6742. </file>
  6743. </example>
  6744. *
  6745. *
  6746. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  6747. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  6748. *
  6749. * <div class="alert alert-danger">
  6750. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  6751. * e.g. will not use the right outer scope. Please pass the transclude function as a
  6752. * `parentBoundTranscludeFn` to the link function instead.
  6753. * </div>
  6754. *
  6755. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  6756. * root element(s), not their children)
  6757. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  6758. * (a DOM element/tree) to a scope. Where:
  6759. *
  6760. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  6761. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  6762. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  6763. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  6764. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  6765. *
  6766. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  6767. * * `scope` - is the current scope with which the linking function is working with.
  6768. *
  6769. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  6770. * keys may be used to control linking behavior:
  6771. *
  6772. * * `parentBoundTranscludeFn` - the transclude function made available to
  6773. * directives; if given, it will be passed through to the link functions of
  6774. * directives found in `element` during compilation.
  6775. * * `transcludeControllers` - an object hash with keys that map controller names
  6776. * to a hash with the key `instance`, which maps to the controller instance;
  6777. * if given, it will make the controllers available to directives on the compileNode:
  6778. * ```
  6779. * {
  6780. * parent: {
  6781. * instance: parentControllerInstance
  6782. * }
  6783. * }
  6784. * ```
  6785. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  6786. * the cloned elements; only needed for transcludes that are allowed to contain non html
  6787. * elements (e.g. SVG elements). See also the directive.controller property.
  6788. *
  6789. * Calling the linking function returns the element of the template. It is either the original
  6790. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  6791. *
  6792. * After linking the view is not updated until after a call to $digest which typically is done by
  6793. * Angular automatically.
  6794. *
  6795. * If you need access to the bound view, there are two ways to do it:
  6796. *
  6797. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  6798. * before you send them to the compiler and keep this reference around.
  6799. * ```js
  6800. * var element = $compile('<p>{{total}}</p>')(scope);
  6801. * ```
  6802. *
  6803. * - if on the other hand, you need the element to be cloned, the view reference from the original
  6804. * example would not point to the clone, but rather to the original template that was cloned. In
  6805. * this case, you can access the clone via the cloneAttachFn:
  6806. * ```js
  6807. * var templateElement = angular.element('<p>{{total}}</p>'),
  6808. * scope = ....;
  6809. *
  6810. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  6811. * //attach the clone to DOM document at the right place
  6812. * });
  6813. *
  6814. * //now we have reference to the cloned DOM via `clonedElement`
  6815. * ```
  6816. *
  6817. *
  6818. * For information on how the compiler works, see the
  6819. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  6820. */
  6821. var $compileMinErr = minErr('$compile');
  6822. function UNINITIALIZED_VALUE() {}
  6823. var _UNINITIALIZED_VALUE = new UNINITIALIZED_VALUE();
  6824. /**
  6825. * @ngdoc provider
  6826. * @name $compileProvider
  6827. *
  6828. * @description
  6829. */
  6830. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  6831. function $CompileProvider($provide, $$sanitizeUriProvider) {
  6832. var hasDirectives = {},
  6833. Suffix = 'Directive',
  6834. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
  6835. CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
  6836. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  6837. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  6838. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  6839. // The assumption is that future DOM event attribute names will begin with
  6840. // 'on' and be composed of only English letters.
  6841. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  6842. var bindingCache = createMap();
  6843. function parseIsolateBindings(scope, directiveName, isController) {
  6844. var LOCAL_REGEXP = /^\s*([@&<]|=(\*?))(\??)\s*(\w*)\s*$/;
  6845. var bindings = createMap();
  6846. forEach(scope, function(definition, scopeName) {
  6847. if (definition in bindingCache) {
  6848. bindings[scopeName] = bindingCache[definition];
  6849. return;
  6850. }
  6851. var match = definition.match(LOCAL_REGEXP);
  6852. if (!match) {
  6853. throw $compileMinErr('iscp',
  6854. "Invalid {3} for directive '{0}'." +
  6855. " Definition: {... {1}: '{2}' ...}",
  6856. directiveName, scopeName, definition,
  6857. (isController ? "controller bindings definition" :
  6858. "isolate scope definition"));
  6859. }
  6860. bindings[scopeName] = {
  6861. mode: match[1][0],
  6862. collection: match[2] === '*',
  6863. optional: match[3] === '?',
  6864. attrName: match[4] || scopeName
  6865. };
  6866. if (match[4]) {
  6867. bindingCache[definition] = bindings[scopeName];
  6868. }
  6869. });
  6870. return bindings;
  6871. }
  6872. function parseDirectiveBindings(directive, directiveName) {
  6873. var bindings = {
  6874. isolateScope: null,
  6875. bindToController: null
  6876. };
  6877. if (isObject(directive.scope)) {
  6878. if (directive.bindToController === true) {
  6879. bindings.bindToController = parseIsolateBindings(directive.scope,
  6880. directiveName, true);
  6881. bindings.isolateScope = {};
  6882. } else {
  6883. bindings.isolateScope = parseIsolateBindings(directive.scope,
  6884. directiveName, false);
  6885. }
  6886. }
  6887. if (isObject(directive.bindToController)) {
  6888. bindings.bindToController =
  6889. parseIsolateBindings(directive.bindToController, directiveName, true);
  6890. }
  6891. if (isObject(bindings.bindToController)) {
  6892. var controller = directive.controller;
  6893. var controllerAs = directive.controllerAs;
  6894. if (!controller) {
  6895. // There is no controller, there may or may not be a controllerAs property
  6896. throw $compileMinErr('noctrl',
  6897. "Cannot bind to controller without directive '{0}'s controller.",
  6898. directiveName);
  6899. } else if (!identifierForController(controller, controllerAs)) {
  6900. // There is a controller, but no identifier or controllerAs property
  6901. throw $compileMinErr('noident',
  6902. "Cannot bind to controller without identifier for directive '{0}'.",
  6903. directiveName);
  6904. }
  6905. }
  6906. return bindings;
  6907. }
  6908. function assertValidDirectiveName(name) {
  6909. var letter = name.charAt(0);
  6910. if (!letter || letter !== lowercase(letter)) {
  6911. throw $compileMinErr('baddir', "Directive/Component name '{0}' is invalid. The first character must be a lowercase letter", name);
  6912. }
  6913. if (name !== name.trim()) {
  6914. throw $compileMinErr('baddir',
  6915. "Directive/Component name '{0}' is invalid. The name should not contain leading or trailing whitespaces",
  6916. name);
  6917. }
  6918. }
  6919. function getDirectiveRequire(directive) {
  6920. var require = directive.require || (directive.controller && directive.name);
  6921. if (!isArray(require) && isObject(require)) {
  6922. forEach(require, function(value, key) {
  6923. var match = value.match(REQUIRE_PREFIX_REGEXP);
  6924. var name = value.substring(match[0].length);
  6925. if (!name) require[key] = match[0] + key;
  6926. });
  6927. }
  6928. return require;
  6929. }
  6930. /**
  6931. * @ngdoc method
  6932. * @name $compileProvider#directive
  6933. * @kind function
  6934. *
  6935. * @description
  6936. * Register a new directive with the compiler.
  6937. *
  6938. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  6939. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  6940. * names and the values are the factories.
  6941. * @param {Function|Array} directiveFactory An injectable directive factory function. See the
  6942. * {@link guide/directive directive guide} and the {@link $compile compile API} for more info.
  6943. * @returns {ng.$compileProvider} Self for chaining.
  6944. */
  6945. this.directive = function registerDirective(name, directiveFactory) {
  6946. assertNotHasOwnProperty(name, 'directive');
  6947. if (isString(name)) {
  6948. assertValidDirectiveName(name);
  6949. assertArg(directiveFactory, 'directiveFactory');
  6950. if (!hasDirectives.hasOwnProperty(name)) {
  6951. hasDirectives[name] = [];
  6952. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  6953. function($injector, $exceptionHandler) {
  6954. var directives = [];
  6955. forEach(hasDirectives[name], function(directiveFactory, index) {
  6956. try {
  6957. var directive = $injector.invoke(directiveFactory);
  6958. if (isFunction(directive)) {
  6959. directive = { compile: valueFn(directive) };
  6960. } else if (!directive.compile && directive.link) {
  6961. directive.compile = valueFn(directive.link);
  6962. }
  6963. directive.priority = directive.priority || 0;
  6964. directive.index = index;
  6965. directive.name = directive.name || name;
  6966. directive.require = getDirectiveRequire(directive);
  6967. directive.restrict = directive.restrict || 'EA';
  6968. directive.$$moduleName = directiveFactory.$$moduleName;
  6969. directives.push(directive);
  6970. } catch (e) {
  6971. $exceptionHandler(e);
  6972. }
  6973. });
  6974. return directives;
  6975. }]);
  6976. }
  6977. hasDirectives[name].push(directiveFactory);
  6978. } else {
  6979. forEach(name, reverseParams(registerDirective));
  6980. }
  6981. return this;
  6982. };
  6983. /**
  6984. * @ngdoc method
  6985. * @name $compileProvider#component
  6986. * @module ng
  6987. * @param {string} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`)
  6988. * @param {Object} options Component definition object (a simplified
  6989. * {@link ng.$compile#directive-definition-object directive definition object}),
  6990. * with the following properties (all optional):
  6991. *
  6992. * - `controller` – `{(string|function()=}` – controller constructor function that should be
  6993. * associated with newly created scope or the name of a {@link ng.$compile#-controller-
  6994. * registered controller} if passed as a string. An empty `noop` function by default.
  6995. * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope.
  6996. * If present, the controller will be published to scope under the `controllerAs` name.
  6997. * If not present, this will default to be `$ctrl`.
  6998. * - `template` – `{string=|function()=}` – html template as a string or a function that
  6999. * returns an html template as a string which should be used as the contents of this component.
  7000. * Empty string by default.
  7001. *
  7002. * If `template` is a function, then it is {@link auto.$injector#invoke injected} with
  7003. * the following locals:
  7004. *
  7005. * - `$element` - Current element
  7006. * - `$attrs` - Current attributes object for the element
  7007. *
  7008. * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
  7009. * template that should be used as the contents of this component.
  7010. *
  7011. * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
  7012. * the following locals:
  7013. *
  7014. * - `$element` - Current element
  7015. * - `$attrs` - Current attributes object for the element
  7016. *
  7017. * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties.
  7018. * Component properties are always bound to the component controller and not to the scope.
  7019. * See {@link ng.$compile#-bindtocontroller- `bindToController`}.
  7020. * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled.
  7021. * Disabled by default.
  7022. * - `require` - `{Object<string, string>=}` - requires the controllers of other directives and binds them to
  7023. * this component's controller. The object keys specify the property names under which the required
  7024. * controllers (object values) will be bound. See {@link ng.$compile#-require- `require`}.
  7025. * - `$...` – additional properties to attach to the directive factory function and the controller
  7026. * constructor function. (This is used by the component router to annotate)
  7027. *
  7028. * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls.
  7029. * @description
  7030. * Register a **component definition** with the compiler. This is a shorthand for registering a special
  7031. * type of directive, which represents a self-contained UI component in your application. Such components
  7032. * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`).
  7033. *
  7034. * Component definitions are very simple and do not require as much configuration as defining general
  7035. * directives. Component definitions usually consist only of a template and a controller backing it.
  7036. *
  7037. * In order to make the definition easier, components enforce best practices like use of `controllerAs`,
  7038. * `bindToController`. They always have **isolate scope** and are restricted to elements.
  7039. *
  7040. * Here are a few examples of how you would usually define components:
  7041. *
  7042. * ```js
  7043. * var myMod = angular.module(...);
  7044. * myMod.component('myComp', {
  7045. * template: '<div>My name is {{$ctrl.name}}</div>',
  7046. * controller: function() {
  7047. * this.name = 'shahar';
  7048. * }
  7049. * });
  7050. *
  7051. * myMod.component('myComp', {
  7052. * template: '<div>My name is {{$ctrl.name}}</div>',
  7053. * bindings: {name: '@'}
  7054. * });
  7055. *
  7056. * myMod.component('myComp', {
  7057. * templateUrl: 'views/my-comp.html',
  7058. * controller: 'MyCtrl',
  7059. * controllerAs: 'ctrl',
  7060. * bindings: {name: '@'}
  7061. * });
  7062. *
  7063. * ```
  7064. * For more examples, and an in-depth guide, see the {@link guide/component component guide}.
  7065. *
  7066. * <br />
  7067. * See also {@link ng.$compileProvider#directive $compileProvider.directive()}.
  7068. */
  7069. this.component = function registerComponent(name, options) {
  7070. var controller = options.controller || function() {};
  7071. function factory($injector) {
  7072. function makeInjectable(fn) {
  7073. if (isFunction(fn) || isArray(fn)) {
  7074. return function(tElement, tAttrs) {
  7075. return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
  7076. };
  7077. } else {
  7078. return fn;
  7079. }
  7080. }
  7081. var template = (!options.template && !options.templateUrl ? '' : options.template);
  7082. var ddo = {
  7083. controller: controller,
  7084. controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',
  7085. template: makeInjectable(template),
  7086. templateUrl: makeInjectable(options.templateUrl),
  7087. transclude: options.transclude,
  7088. scope: {},
  7089. bindToController: options.bindings || {},
  7090. restrict: 'E',
  7091. require: options.require
  7092. };
  7093. // Copy annotations (starting with $) over to the DDO
  7094. forEach(options, function(val, key) {
  7095. if (key.charAt(0) === '$') ddo[key] = val;
  7096. });
  7097. return ddo;
  7098. }
  7099. // TODO(pete) remove the following `forEach` before we release 1.6.0
  7100. // The component-router@0.2.0 looks for the annotations on the controller constructor
  7101. // Nothing in Angular looks for annotations on the factory function but we can't remove
  7102. // it from 1.5.x yet.
  7103. // Copy any annotation properties (starting with $) over to the factory and controller constructor functions
  7104. // These could be used by libraries such as the new component router
  7105. forEach(options, function(val, key) {
  7106. if (key.charAt(0) === '$') {
  7107. factory[key] = val;
  7108. // Don't try to copy over annotations to named controller
  7109. if (isFunction(controller)) controller[key] = val;
  7110. }
  7111. });
  7112. factory.$inject = ['$injector'];
  7113. return this.directive(name, factory);
  7114. };
  7115. /**
  7116. * @ngdoc method
  7117. * @name $compileProvider#aHrefSanitizationWhitelist
  7118. * @kind function
  7119. *
  7120. * @description
  7121. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  7122. * urls during a[href] sanitization.
  7123. *
  7124. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  7125. *
  7126. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  7127. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  7128. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  7129. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  7130. *
  7131. * @param {RegExp=} regexp New regexp to whitelist urls with.
  7132. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  7133. * chaining otherwise.
  7134. */
  7135. this.aHrefSanitizationWhitelist = function(regexp) {
  7136. if (isDefined(regexp)) {
  7137. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  7138. return this;
  7139. } else {
  7140. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  7141. }
  7142. };
  7143. /**
  7144. * @ngdoc method
  7145. * @name $compileProvider#imgSrcSanitizationWhitelist
  7146. * @kind function
  7147. *
  7148. * @description
  7149. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  7150. * urls during img[src] sanitization.
  7151. *
  7152. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  7153. *
  7154. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  7155. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  7156. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  7157. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  7158. *
  7159. * @param {RegExp=} regexp New regexp to whitelist urls with.
  7160. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  7161. * chaining otherwise.
  7162. */
  7163. this.imgSrcSanitizationWhitelist = function(regexp) {
  7164. if (isDefined(regexp)) {
  7165. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  7166. return this;
  7167. } else {
  7168. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  7169. }
  7170. };
  7171. /**
  7172. * @ngdoc method
  7173. * @name $compileProvider#debugInfoEnabled
  7174. *
  7175. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  7176. * current debugInfoEnabled state
  7177. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  7178. *
  7179. * @kind function
  7180. *
  7181. * @description
  7182. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  7183. * binding information and a reference to the current scope on to DOM elements.
  7184. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  7185. * * `ng-binding` CSS class
  7186. * * `$binding` data property containing an array of the binding expressions
  7187. *
  7188. * You may want to disable this in production for a significant performance boost. See
  7189. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  7190. *
  7191. * The default value is true.
  7192. */
  7193. var debugInfoEnabled = true;
  7194. this.debugInfoEnabled = function(enabled) {
  7195. if (isDefined(enabled)) {
  7196. debugInfoEnabled = enabled;
  7197. return this;
  7198. }
  7199. return debugInfoEnabled;
  7200. };
  7201. var TTL = 10;
  7202. /**
  7203. * @ngdoc method
  7204. * @name $compileProvider#onChangesTtl
  7205. * @description
  7206. *
  7207. * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and
  7208. * assuming that the model is unstable.
  7209. *
  7210. * The current default is 10 iterations.
  7211. *
  7212. * In complex applications it's possible that dependencies between `$onChanges` hooks and bindings will result
  7213. * in several iterations of calls to these hooks. However if an application needs more than the default 10
  7214. * iterations to stabilize then you should investigate what is causing the model to continuously change during
  7215. * the `$onChanges` hook execution.
  7216. *
  7217. * Increasing the TTL could have performance implications, so you should not change it without proper justification.
  7218. *
  7219. * @param {number} limit The number of `$onChanges` hook iterations.
  7220. * @returns {number|object} the current limit (or `this` if called as a setter for chaining)
  7221. */
  7222. this.onChangesTtl = function(value) {
  7223. if (arguments.length) {
  7224. TTL = value;
  7225. return this;
  7226. }
  7227. return TTL;
  7228. };
  7229. this.$get = [
  7230. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  7231. '$controller', '$rootScope', '$sce', '$animate', '$$sanitizeUri',
  7232. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  7233. $controller, $rootScope, $sce, $animate, $$sanitizeUri) {
  7234. var SIMPLE_ATTR_NAME = /^\w/;
  7235. var specialAttrHolder = window.document.createElement('div');
  7236. var onChangesTtl = TTL;
  7237. // The onChanges hooks should all be run together in a single digest
  7238. // When changes occur, the call to trigger their hooks will be added to this queue
  7239. var onChangesQueue;
  7240. // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest
  7241. function flushOnChangesQueue() {
  7242. try {
  7243. if (!(--onChangesTtl)) {
  7244. // We have hit the TTL limit so reset everything
  7245. onChangesQueue = undefined;
  7246. throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\n', TTL);
  7247. }
  7248. // We must run this hook in an apply since the $$postDigest runs outside apply
  7249. $rootScope.$apply(function() {
  7250. var errors = [];
  7251. for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) {
  7252. try {
  7253. onChangesQueue[i]();
  7254. } catch (e) {
  7255. errors.push(e);
  7256. }
  7257. }
  7258. // Reset the queue to trigger a new schedule next time there is a change
  7259. onChangesQueue = undefined;
  7260. if (errors.length) {
  7261. throw errors;
  7262. }
  7263. });
  7264. } finally {
  7265. onChangesTtl++;
  7266. }
  7267. }
  7268. function Attributes(element, attributesToCopy) {
  7269. if (attributesToCopy) {
  7270. var keys = Object.keys(attributesToCopy);
  7271. var i, l, key;
  7272. for (i = 0, l = keys.length; i < l; i++) {
  7273. key = keys[i];
  7274. this[key] = attributesToCopy[key];
  7275. }
  7276. } else {
  7277. this.$attr = {};
  7278. }
  7279. this.$$element = element;
  7280. }
  7281. Attributes.prototype = {
  7282. /**
  7283. * @ngdoc method
  7284. * @name $compile.directive.Attributes#$normalize
  7285. * @kind function
  7286. *
  7287. * @description
  7288. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  7289. * `data-`) to its normalized, camelCase form.
  7290. *
  7291. * Also there is special case for Moz prefix starting with upper case letter.
  7292. *
  7293. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  7294. *
  7295. * @param {string} name Name to normalize
  7296. */
  7297. $normalize: directiveNormalize,
  7298. /**
  7299. * @ngdoc method
  7300. * @name $compile.directive.Attributes#$addClass
  7301. * @kind function
  7302. *
  7303. * @description
  7304. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  7305. * are enabled then an animation will be triggered for the class addition.
  7306. *
  7307. * @param {string} classVal The className value that will be added to the element
  7308. */
  7309. $addClass: function(classVal) {
  7310. if (classVal && classVal.length > 0) {
  7311. $animate.addClass(this.$$element, classVal);
  7312. }
  7313. },
  7314. /**
  7315. * @ngdoc method
  7316. * @name $compile.directive.Attributes#$removeClass
  7317. * @kind function
  7318. *
  7319. * @description
  7320. * Removes the CSS class value specified by the classVal parameter from the element. If
  7321. * animations are enabled then an animation will be triggered for the class removal.
  7322. *
  7323. * @param {string} classVal The className value that will be removed from the element
  7324. */
  7325. $removeClass: function(classVal) {
  7326. if (classVal && classVal.length > 0) {
  7327. $animate.removeClass(this.$$element, classVal);
  7328. }
  7329. },
  7330. /**
  7331. * @ngdoc method
  7332. * @name $compile.directive.Attributes#$updateClass
  7333. * @kind function
  7334. *
  7335. * @description
  7336. * Adds and removes the appropriate CSS class values to the element based on the difference
  7337. * between the new and old CSS class values (specified as newClasses and oldClasses).
  7338. *
  7339. * @param {string} newClasses The current CSS className value
  7340. * @param {string} oldClasses The former CSS className value
  7341. */
  7342. $updateClass: function(newClasses, oldClasses) {
  7343. var toAdd = tokenDifference(newClasses, oldClasses);
  7344. if (toAdd && toAdd.length) {
  7345. $animate.addClass(this.$$element, toAdd);
  7346. }
  7347. var toRemove = tokenDifference(oldClasses, newClasses);
  7348. if (toRemove && toRemove.length) {
  7349. $animate.removeClass(this.$$element, toRemove);
  7350. }
  7351. },
  7352. /**
  7353. * Set a normalized attribute on the element in a way such that all directives
  7354. * can share the attribute. This function properly handles boolean attributes.
  7355. * @param {string} key Normalized key. (ie ngAttribute)
  7356. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  7357. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  7358. * Defaults to true.
  7359. * @param {string=} attrName Optional none normalized name. Defaults to key.
  7360. */
  7361. $set: function(key, value, writeAttr, attrName) {
  7362. // TODO: decide whether or not to throw an error if "class"
  7363. //is set through this function since it may cause $updateClass to
  7364. //become unstable.
  7365. var node = this.$$element[0],
  7366. booleanKey = getBooleanAttrName(node, key),
  7367. aliasedKey = getAliasedAttrName(key),
  7368. observer = key,
  7369. nodeName;
  7370. if (booleanKey) {
  7371. this.$$element.prop(key, value);
  7372. attrName = booleanKey;
  7373. } else if (aliasedKey) {
  7374. this[aliasedKey] = value;
  7375. observer = aliasedKey;
  7376. }
  7377. this[key] = value;
  7378. // translate normalized key to actual key
  7379. if (attrName) {
  7380. this.$attr[key] = attrName;
  7381. } else {
  7382. attrName = this.$attr[key];
  7383. if (!attrName) {
  7384. this.$attr[key] = attrName = snake_case(key, '-');
  7385. }
  7386. }
  7387. nodeName = nodeName_(this.$$element);
  7388. if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) ||
  7389. (nodeName === 'img' && key === 'src')) {
  7390. // sanitize a[href] and img[src] values
  7391. this[key] = value = $$sanitizeUri(value, key === 'src');
  7392. } else if (nodeName === 'img' && key === 'srcset' && isDefined(value)) {
  7393. // sanitize img[srcset] values
  7394. var result = "";
  7395. // first check if there are spaces because it's not the same pattern
  7396. var trimmedSrcset = trim(value);
  7397. // ( 999x ,| 999w ,| ,|, )
  7398. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  7399. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  7400. // split srcset into tuple of uri and descriptor except for the last item
  7401. var rawUris = trimmedSrcset.split(pattern);
  7402. // for each tuples
  7403. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  7404. for (var i = 0; i < nbrUrisWith2parts; i++) {
  7405. var innerIdx = i * 2;
  7406. // sanitize the uri
  7407. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  7408. // add the descriptor
  7409. result += (" " + trim(rawUris[innerIdx + 1]));
  7410. }
  7411. // split the last item into uri and descriptor
  7412. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  7413. // sanitize the last uri
  7414. result += $$sanitizeUri(trim(lastTuple[0]), true);
  7415. // and add the last descriptor if any
  7416. if (lastTuple.length === 2) {
  7417. result += (" " + trim(lastTuple[1]));
  7418. }
  7419. this[key] = value = result;
  7420. }
  7421. if (writeAttr !== false) {
  7422. if (value === null || isUndefined(value)) {
  7423. this.$$element.removeAttr(attrName);
  7424. } else {
  7425. if (SIMPLE_ATTR_NAME.test(attrName)) {
  7426. this.$$element.attr(attrName, value);
  7427. } else {
  7428. setSpecialAttr(this.$$element[0], attrName, value);
  7429. }
  7430. }
  7431. }
  7432. // fire observers
  7433. var $$observers = this.$$observers;
  7434. $$observers && forEach($$observers[observer], function(fn) {
  7435. try {
  7436. fn(value);
  7437. } catch (e) {
  7438. $exceptionHandler(e);
  7439. }
  7440. });
  7441. },
  7442. /**
  7443. * @ngdoc method
  7444. * @name $compile.directive.Attributes#$observe
  7445. * @kind function
  7446. *
  7447. * @description
  7448. * Observes an interpolated attribute.
  7449. *
  7450. * The observer function will be invoked once during the next `$digest` following
  7451. * compilation. The observer is then invoked whenever the interpolated value
  7452. * changes.
  7453. *
  7454. * @param {string} key Normalized key. (ie ngAttribute) .
  7455. * @param {function(interpolatedValue)} fn Function that will be called whenever
  7456. the interpolated value of the attribute changes.
  7457. * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation
  7458. * guide} for more info.
  7459. * @returns {function()} Returns a deregistration function for this observer.
  7460. */
  7461. $observe: function(key, fn) {
  7462. var attrs = this,
  7463. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  7464. listeners = ($$observers[key] || ($$observers[key] = []));
  7465. listeners.push(fn);
  7466. $rootScope.$evalAsync(function() {
  7467. if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
  7468. // no one registered attribute interpolation function, so lets call it manually
  7469. fn(attrs[key]);
  7470. }
  7471. });
  7472. return function() {
  7473. arrayRemove(listeners, fn);
  7474. };
  7475. }
  7476. };
  7477. function setSpecialAttr(element, attrName, value) {
  7478. // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute`
  7479. // so we have to jump through some hoops to get such an attribute
  7480. // https://github.com/angular/angular.js/pull/13318
  7481. specialAttrHolder.innerHTML = "<span " + attrName + ">";
  7482. var attributes = specialAttrHolder.firstChild.attributes;
  7483. var attribute = attributes[0];
  7484. // We have to remove the attribute from its container element before we can add it to the destination element
  7485. attributes.removeNamedItem(attribute.name);
  7486. attribute.value = value;
  7487. element.attributes.setNamedItem(attribute);
  7488. }
  7489. function safeAddClass($element, className) {
  7490. try {
  7491. $element.addClass(className);
  7492. } catch (e) {
  7493. // ignore, since it means that we are trying to set class on
  7494. // SVG element, where class name is read-only.
  7495. }
  7496. }
  7497. var startSymbol = $interpolate.startSymbol(),
  7498. endSymbol = $interpolate.endSymbol(),
  7499. denormalizeTemplate = (startSymbol == '{{' && endSymbol == '}}')
  7500. ? identity
  7501. : function denormalizeTemplate(template) {
  7502. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  7503. },
  7504. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  7505. var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
  7506. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  7507. var bindings = $element.data('$binding') || [];
  7508. if (isArray(binding)) {
  7509. bindings = bindings.concat(binding);
  7510. } else {
  7511. bindings.push(binding);
  7512. }
  7513. $element.data('$binding', bindings);
  7514. } : noop;
  7515. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  7516. safeAddClass($element, 'ng-binding');
  7517. } : noop;
  7518. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  7519. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  7520. $element.data(dataName, scope);
  7521. } : noop;
  7522. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  7523. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  7524. } : noop;
  7525. compile.$$createComment = function(directiveName, comment) {
  7526. var content = '';
  7527. if (debugInfoEnabled) {
  7528. content = ' ' + (directiveName || '') + ': ';
  7529. if (comment) content += comment + ' ';
  7530. }
  7531. return window.document.createComment(content);
  7532. };
  7533. return compile;
  7534. //================================
  7535. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  7536. previousCompileContext) {
  7537. if (!($compileNodes instanceof jqLite)) {
  7538. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  7539. // modify it.
  7540. $compileNodes = jqLite($compileNodes);
  7541. }
  7542. var NOT_EMPTY = /\S+/;
  7543. // We can not compile top level text elements since text nodes can be merged and we will
  7544. // not be able to attach scope data to them, so we will wrap them in <span>
  7545. for (var i = 0, len = $compileNodes.length; i < len; i++) {
  7546. var domNode = $compileNodes[i];
  7547. if (domNode.nodeType === NODE_TYPE_TEXT && domNode.nodeValue.match(NOT_EMPTY) /* non-empty */) {
  7548. jqLiteWrapNode(domNode, $compileNodes[i] = window.document.createElement('span'));
  7549. }
  7550. }
  7551. var compositeLinkFn =
  7552. compileNodes($compileNodes, transcludeFn, $compileNodes,
  7553. maxPriority, ignoreDirective, previousCompileContext);
  7554. compile.$$addScopeClass($compileNodes);
  7555. var namespace = null;
  7556. return function publicLinkFn(scope, cloneConnectFn, options) {
  7557. assertArg(scope, 'scope');
  7558. if (previousCompileContext && previousCompileContext.needsNewScope) {
  7559. // A parent directive did a replace and a directive on this element asked
  7560. // for transclusion, which caused us to lose a layer of element on which
  7561. // we could hold the new transclusion scope, so we will create it manually
  7562. // here.
  7563. scope = scope.$parent.$new();
  7564. }
  7565. options = options || {};
  7566. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  7567. transcludeControllers = options.transcludeControllers,
  7568. futureParentElement = options.futureParentElement;
  7569. // When `parentBoundTranscludeFn` is passed, it is a
  7570. // `controllersBoundTransclude` function (it was previously passed
  7571. // as `transclude` to directive.link) so we must unwrap it to get
  7572. // its `boundTranscludeFn`
  7573. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  7574. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  7575. }
  7576. if (!namespace) {
  7577. namespace = detectNamespaceForChildElements(futureParentElement);
  7578. }
  7579. var $linkNode;
  7580. if (namespace !== 'html') {
  7581. // When using a directive with replace:true and templateUrl the $compileNodes
  7582. // (or a child element inside of them)
  7583. // might change, so we need to recreate the namespace adapted compileNodes
  7584. // for call to the link function.
  7585. // Note: This will already clone the nodes...
  7586. $linkNode = jqLite(
  7587. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  7588. );
  7589. } else if (cloneConnectFn) {
  7590. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  7591. // and sometimes changes the structure of the DOM.
  7592. $linkNode = JQLitePrototype.clone.call($compileNodes);
  7593. } else {
  7594. $linkNode = $compileNodes;
  7595. }
  7596. if (transcludeControllers) {
  7597. for (var controllerName in transcludeControllers) {
  7598. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  7599. }
  7600. }
  7601. compile.$$addScopeInfo($linkNode, scope);
  7602. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  7603. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  7604. return $linkNode;
  7605. };
  7606. }
  7607. function detectNamespaceForChildElements(parentElement) {
  7608. // TODO: Make this detect MathML as well...
  7609. var node = parentElement && parentElement[0];
  7610. if (!node) {
  7611. return 'html';
  7612. } else {
  7613. return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html';
  7614. }
  7615. }
  7616. /**
  7617. * Compile function matches each node in nodeList against the directives. Once all directives
  7618. * for a particular node are collected their compile functions are executed. The compile
  7619. * functions return values - the linking functions - are combined into a composite linking
  7620. * function, which is the a linking function for the node.
  7621. *
  7622. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  7623. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  7624. * scope argument is auto-generated to the new child of the transcluded parent scope.
  7625. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  7626. * the rootElement must be set the jqLite collection of the compile root. This is
  7627. * needed so that the jqLite collection items can be replaced with widgets.
  7628. * @param {number=} maxPriority Max directive priority.
  7629. * @returns {Function} A composite linking function of all of the matched directives or null.
  7630. */
  7631. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  7632. previousCompileContext) {
  7633. var linkFns = [],
  7634. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  7635. for (var i = 0; i < nodeList.length; i++) {
  7636. attrs = new Attributes();
  7637. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  7638. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  7639. ignoreDirective);
  7640. nodeLinkFn = (directives.length)
  7641. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  7642. null, [], [], previousCompileContext)
  7643. : null;
  7644. if (nodeLinkFn && nodeLinkFn.scope) {
  7645. compile.$$addScopeClass(attrs.$$element);
  7646. }
  7647. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  7648. !(childNodes = nodeList[i].childNodes) ||
  7649. !childNodes.length)
  7650. ? null
  7651. : compileNodes(childNodes,
  7652. nodeLinkFn ? (
  7653. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  7654. && nodeLinkFn.transclude) : transcludeFn);
  7655. if (nodeLinkFn || childLinkFn) {
  7656. linkFns.push(i, nodeLinkFn, childLinkFn);
  7657. linkFnFound = true;
  7658. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  7659. }
  7660. //use the previous context only for the first element in the virtual group
  7661. previousCompileContext = null;
  7662. }
  7663. // return a linking function if we have found anything, null otherwise
  7664. return linkFnFound ? compositeLinkFn : null;
  7665. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  7666. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  7667. var stableNodeList;
  7668. if (nodeLinkFnFound) {
  7669. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  7670. // offsets don't get screwed up
  7671. var nodeListLength = nodeList.length;
  7672. stableNodeList = new Array(nodeListLength);
  7673. // create a sparse array by only copying the elements which have a linkFn
  7674. for (i = 0; i < linkFns.length; i+=3) {
  7675. idx = linkFns[i];
  7676. stableNodeList[idx] = nodeList[idx];
  7677. }
  7678. } else {
  7679. stableNodeList = nodeList;
  7680. }
  7681. for (i = 0, ii = linkFns.length; i < ii;) {
  7682. node = stableNodeList[linkFns[i++]];
  7683. nodeLinkFn = linkFns[i++];
  7684. childLinkFn = linkFns[i++];
  7685. if (nodeLinkFn) {
  7686. if (nodeLinkFn.scope) {
  7687. childScope = scope.$new();
  7688. compile.$$addScopeInfo(jqLite(node), childScope);
  7689. } else {
  7690. childScope = scope;
  7691. }
  7692. if (nodeLinkFn.transcludeOnThisElement) {
  7693. childBoundTranscludeFn = createBoundTranscludeFn(
  7694. scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  7695. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  7696. childBoundTranscludeFn = parentBoundTranscludeFn;
  7697. } else if (!parentBoundTranscludeFn && transcludeFn) {
  7698. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  7699. } else {
  7700. childBoundTranscludeFn = null;
  7701. }
  7702. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  7703. } else if (childLinkFn) {
  7704. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  7705. }
  7706. }
  7707. }
  7708. }
  7709. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  7710. function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  7711. if (!transcludedScope) {
  7712. transcludedScope = scope.$new(false, containingScope);
  7713. transcludedScope.$$transcluded = true;
  7714. }
  7715. return transcludeFn(transcludedScope, cloneFn, {
  7716. parentBoundTranscludeFn: previousBoundTranscludeFn,
  7717. transcludeControllers: controllers,
  7718. futureParentElement: futureParentElement
  7719. });
  7720. }
  7721. // We need to attach the transclusion slots onto the `boundTranscludeFn`
  7722. // so that they are available inside the `controllersBoundTransclude` function
  7723. var boundSlots = boundTranscludeFn.$$slots = createMap();
  7724. for (var slotName in transcludeFn.$$slots) {
  7725. if (transcludeFn.$$slots[slotName]) {
  7726. boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);
  7727. } else {
  7728. boundSlots[slotName] = null;
  7729. }
  7730. }
  7731. return boundTranscludeFn;
  7732. }
  7733. /**
  7734. * Looks for directives on the given node and adds them to the directive collection which is
  7735. * sorted.
  7736. *
  7737. * @param node Node to search.
  7738. * @param directives An array to which the directives are added to. This array is sorted before
  7739. * the function returns.
  7740. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  7741. * @param {number=} maxPriority Max directive priority.
  7742. */
  7743. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  7744. var nodeType = node.nodeType,
  7745. attrsMap = attrs.$attr,
  7746. match,
  7747. className;
  7748. switch (nodeType) {
  7749. case NODE_TYPE_ELEMENT: /* Element */
  7750. // use the node name: <directive>
  7751. addDirective(directives,
  7752. directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
  7753. // iterate over the attributes
  7754. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  7755. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  7756. var attrStartName = false;
  7757. var attrEndName = false;
  7758. attr = nAttrs[j];
  7759. name = attr.name;
  7760. value = trim(attr.value);
  7761. // support ngAttr attribute binding
  7762. ngAttrName = directiveNormalize(name);
  7763. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  7764. name = name.replace(PREFIX_REGEXP, '')
  7765. .substr(8).replace(/_(.)/g, function(match, letter) {
  7766. return letter.toUpperCase();
  7767. });
  7768. }
  7769. var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);
  7770. if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {
  7771. attrStartName = name;
  7772. attrEndName = name.substr(0, name.length - 5) + 'end';
  7773. name = name.substr(0, name.length - 6);
  7774. }
  7775. nName = directiveNormalize(name.toLowerCase());
  7776. attrsMap[nName] = name;
  7777. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  7778. attrs[nName] = value;
  7779. if (getBooleanAttrName(node, nName)) {
  7780. attrs[nName] = true; // presence means true
  7781. }
  7782. }
  7783. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  7784. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  7785. attrEndName);
  7786. }
  7787. // use class as directive
  7788. className = node.className;
  7789. if (isObject(className)) {
  7790. // Maybe SVGAnimatedString
  7791. className = className.animVal;
  7792. }
  7793. if (isString(className) && className !== '') {
  7794. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  7795. nName = directiveNormalize(match[2]);
  7796. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  7797. attrs[nName] = trim(match[3]);
  7798. }
  7799. className = className.substr(match.index + match[0].length);
  7800. }
  7801. }
  7802. break;
  7803. case NODE_TYPE_TEXT: /* Text Node */
  7804. if (msie === 11) {
  7805. // Workaround for #11781
  7806. while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {
  7807. node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
  7808. node.parentNode.removeChild(node.nextSibling);
  7809. }
  7810. }
  7811. addTextInterpolateDirective(directives, node.nodeValue);
  7812. break;
  7813. case NODE_TYPE_COMMENT: /* Comment */
  7814. try {
  7815. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  7816. if (match) {
  7817. nName = directiveNormalize(match[1]);
  7818. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  7819. attrs[nName] = trim(match[2]);
  7820. }
  7821. }
  7822. } catch (e) {
  7823. // turns out that under some circumstances IE9 throws errors when one attempts to read
  7824. // comment's node value.
  7825. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  7826. }
  7827. break;
  7828. }
  7829. directives.sort(byPriority);
  7830. return directives;
  7831. }
  7832. /**
  7833. * Given a node with an directive-start it collects all of the siblings until it finds
  7834. * directive-end.
  7835. * @param node
  7836. * @param attrStart
  7837. * @param attrEnd
  7838. * @returns {*}
  7839. */
  7840. function groupScan(node, attrStart, attrEnd) {
  7841. var nodes = [];
  7842. var depth = 0;
  7843. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  7844. do {
  7845. if (!node) {
  7846. throw $compileMinErr('uterdir',
  7847. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  7848. attrStart, attrEnd);
  7849. }
  7850. if (node.nodeType == NODE_TYPE_ELEMENT) {
  7851. if (node.hasAttribute(attrStart)) depth++;
  7852. if (node.hasAttribute(attrEnd)) depth--;
  7853. }
  7854. nodes.push(node);
  7855. node = node.nextSibling;
  7856. } while (depth > 0);
  7857. } else {
  7858. nodes.push(node);
  7859. }
  7860. return jqLite(nodes);
  7861. }
  7862. /**
  7863. * Wrapper for linking function which converts normal linking function into a grouped
  7864. * linking function.
  7865. * @param linkFn
  7866. * @param attrStart
  7867. * @param attrEnd
  7868. * @returns {Function}
  7869. */
  7870. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  7871. return function groupedElementsLink(scope, element, attrs, controllers, transcludeFn) {
  7872. element = groupScan(element[0], attrStart, attrEnd);
  7873. return linkFn(scope, element, attrs, controllers, transcludeFn);
  7874. };
  7875. }
  7876. /**
  7877. * A function generator that is used to support both eager and lazy compilation
  7878. * linking function.
  7879. * @param eager
  7880. * @param $compileNodes
  7881. * @param transcludeFn
  7882. * @param maxPriority
  7883. * @param ignoreDirective
  7884. * @param previousCompileContext
  7885. * @returns {Function}
  7886. */
  7887. function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
  7888. var compiled;
  7889. if (eager) {
  7890. return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  7891. }
  7892. return function lazyCompilation() {
  7893. if (!compiled) {
  7894. compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  7895. // Null out all of these references in order to make them eligible for garbage collection
  7896. // since this is a potentially long lived closure
  7897. $compileNodes = transcludeFn = previousCompileContext = null;
  7898. }
  7899. return compiled.apply(this, arguments);
  7900. };
  7901. }
  7902. /**
  7903. * Once the directives have been collected, their compile functions are executed. This method
  7904. * is responsible for inlining directive templates as well as terminating the application
  7905. * of the directives if the terminal directive has been reached.
  7906. *
  7907. * @param {Array} directives Array of collected directives to execute their compile function.
  7908. * this needs to be pre-sorted by priority order.
  7909. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  7910. * @param {Object} templateAttrs The shared attribute function
  7911. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  7912. * scope argument is auto-generated to the new
  7913. * child of the transcluded parent scope.
  7914. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  7915. * argument has the root jqLite array so that we can replace nodes
  7916. * on it.
  7917. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  7918. * compiling the transclusion.
  7919. * @param {Array.<Function>} preLinkFns
  7920. * @param {Array.<Function>} postLinkFns
  7921. * @param {Object} previousCompileContext Context used for previous compilation of the current
  7922. * node
  7923. * @returns {Function} linkFn
  7924. */
  7925. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  7926. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  7927. previousCompileContext) {
  7928. previousCompileContext = previousCompileContext || {};
  7929. var terminalPriority = -Number.MAX_VALUE,
  7930. newScopeDirective = previousCompileContext.newScopeDirective,
  7931. controllerDirectives = previousCompileContext.controllerDirectives,
  7932. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  7933. templateDirective = previousCompileContext.templateDirective,
  7934. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  7935. hasTranscludeDirective = false,
  7936. hasTemplate = false,
  7937. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  7938. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  7939. directive,
  7940. directiveName,
  7941. $template,
  7942. replaceDirective = originalReplaceDirective,
  7943. childTranscludeFn = transcludeFn,
  7944. linkFn,
  7945. didScanForMultipleTransclusion = false,
  7946. mightHaveMultipleTransclusionError = false,
  7947. directiveValue;
  7948. // executes all directives on the current element
  7949. for (var i = 0, ii = directives.length; i < ii; i++) {
  7950. directive = directives[i];
  7951. var attrStart = directive.$$start;
  7952. var attrEnd = directive.$$end;
  7953. // collect multiblock sections
  7954. if (attrStart) {
  7955. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  7956. }
  7957. $template = undefined;
  7958. if (terminalPriority > directive.priority) {
  7959. break; // prevent further processing of directives
  7960. }
  7961. if (directiveValue = directive.scope) {
  7962. // skip the check for directives with async templates, we'll check the derived sync
  7963. // directive when the template arrives
  7964. if (!directive.templateUrl) {
  7965. if (isObject(directiveValue)) {
  7966. // This directive is trying to add an isolated scope.
  7967. // Check that there is no scope of any kind already
  7968. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  7969. directive, $compileNode);
  7970. newIsolateScopeDirective = directive;
  7971. } else {
  7972. // This directive is trying to add a child scope.
  7973. // Check that there is no isolated scope already
  7974. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  7975. $compileNode);
  7976. }
  7977. }
  7978. newScopeDirective = newScopeDirective || directive;
  7979. }
  7980. directiveName = directive.name;
  7981. // If we encounter a condition that can result in transclusion on the directive,
  7982. // then scan ahead in the remaining directives for others that may cause a multiple
  7983. // transclusion error to be thrown during the compilation process. If a matching directive
  7984. // is found, then we know that when we encounter a transcluded directive, we need to eagerly
  7985. // compile the `transclude` function rather than doing it lazily in order to throw
  7986. // exceptions at the correct time
  7987. if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))
  7988. || (directive.transclude && !directive.$$tlb))) {
  7989. var candidateDirective;
  7990. for (var scanningIndex = i + 1; candidateDirective = directives[scanningIndex++];) {
  7991. if ((candidateDirective.transclude && !candidateDirective.$$tlb)
  7992. || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {
  7993. mightHaveMultipleTransclusionError = true;
  7994. break;
  7995. }
  7996. }
  7997. didScanForMultipleTransclusion = true;
  7998. }
  7999. if (!directive.templateUrl && directive.controller) {
  8000. directiveValue = directive.controller;
  8001. controllerDirectives = controllerDirectives || createMap();
  8002. assertNoDuplicate("'" + directiveName + "' controller",
  8003. controllerDirectives[directiveName], directive, $compileNode);
  8004. controllerDirectives[directiveName] = directive;
  8005. }
  8006. if (directiveValue = directive.transclude) {
  8007. hasTranscludeDirective = true;
  8008. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  8009. // This option should only be used by directives that know how to safely handle element transclusion,
  8010. // where the transcluded nodes are added or replaced after linking.
  8011. if (!directive.$$tlb) {
  8012. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  8013. nonTlbTranscludeDirective = directive;
  8014. }
  8015. if (directiveValue == 'element') {
  8016. hasElementTranscludeDirective = true;
  8017. terminalPriority = directive.priority;
  8018. $template = $compileNode;
  8019. $compileNode = templateAttrs.$$element =
  8020. jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName]));
  8021. compileNode = $compileNode[0];
  8022. replaceWith(jqCollection, sliceArgs($template), compileNode);
  8023. // Support: Chrome < 50
  8024. // https://github.com/angular/angular.js/issues/14041
  8025. // In the versions of V8 prior to Chrome 50, the document fragment that is created
  8026. // in the `replaceWith` function is improperly garbage collected despite still
  8027. // being referenced by the `parentNode` property of all of the child nodes. By adding
  8028. // a reference to the fragment via a different property, we can avoid that incorrect
  8029. // behavior.
  8030. // TODO: remove this line after Chrome 50 has been released
  8031. $template[0].$$parentNode = $template[0].parentNode;
  8032. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
  8033. replaceDirective && replaceDirective.name, {
  8034. // Don't pass in:
  8035. // - controllerDirectives - otherwise we'll create duplicates controllers
  8036. // - newIsolateScopeDirective or templateDirective - combining templates with
  8037. // element transclusion doesn't make sense.
  8038. //
  8039. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  8040. // on the same element more than once.
  8041. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  8042. });
  8043. } else {
  8044. var slots = createMap();
  8045. $template = jqLite(jqLiteClone(compileNode)).contents();
  8046. if (isObject(directiveValue)) {
  8047. // We have transclusion slots,
  8048. // collect them up, compile them and store their transclusion functions
  8049. $template = [];
  8050. var slotMap = createMap();
  8051. var filledSlots = createMap();
  8052. // Parse the element selectors
  8053. forEach(directiveValue, function(elementSelector, slotName) {
  8054. // If an element selector starts with a ? then it is optional
  8055. var optional = (elementSelector.charAt(0) === '?');
  8056. elementSelector = optional ? elementSelector.substring(1) : elementSelector;
  8057. slotMap[elementSelector] = slotName;
  8058. // We explicitly assign `null` since this implies that a slot was defined but not filled.
  8059. // Later when calling boundTransclusion functions with a slot name we only error if the
  8060. // slot is `undefined`
  8061. slots[slotName] = null;
  8062. // filledSlots contains `true` for all slots that are either optional or have been
  8063. // filled. This is used to check that we have not missed any required slots
  8064. filledSlots[slotName] = optional;
  8065. });
  8066. // Add the matching elements into their slot
  8067. forEach($compileNode.contents(), function(node) {
  8068. var slotName = slotMap[directiveNormalize(nodeName_(node))];
  8069. if (slotName) {
  8070. filledSlots[slotName] = true;
  8071. slots[slotName] = slots[slotName] || [];
  8072. slots[slotName].push(node);
  8073. } else {
  8074. $template.push(node);
  8075. }
  8076. });
  8077. // Check for required slots that were not filled
  8078. forEach(filledSlots, function(filled, slotName) {
  8079. if (!filled) {
  8080. throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
  8081. }
  8082. });
  8083. for (var slotName in slots) {
  8084. if (slots[slotName]) {
  8085. // Only define a transclusion function if the slot was filled
  8086. slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn);
  8087. }
  8088. }
  8089. }
  8090. $compileNode.empty(); // clear contents
  8091. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
  8092. undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
  8093. childTranscludeFn.$$slots = slots;
  8094. }
  8095. }
  8096. if (directive.template) {
  8097. hasTemplate = true;
  8098. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  8099. templateDirective = directive;
  8100. directiveValue = (isFunction(directive.template))
  8101. ? directive.template($compileNode, templateAttrs)
  8102. : directive.template;
  8103. directiveValue = denormalizeTemplate(directiveValue);
  8104. if (directive.replace) {
  8105. replaceDirective = directive;
  8106. if (jqLiteIsTextNode(directiveValue)) {
  8107. $template = [];
  8108. } else {
  8109. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  8110. }
  8111. compileNode = $template[0];
  8112. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  8113. throw $compileMinErr('tplrt',
  8114. "Template for directive '{0}' must have exactly one root element. {1}",
  8115. directiveName, '');
  8116. }
  8117. replaceWith(jqCollection, $compileNode, compileNode);
  8118. var newTemplateAttrs = {$attr: {}};
  8119. // combine directives from the original node and from the template:
  8120. // - take the array of directives for this element
  8121. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  8122. // - collect directives from the template and sort them by priority
  8123. // - combine directives as: processed + template + unprocessed
  8124. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  8125. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  8126. if (newIsolateScopeDirective || newScopeDirective) {
  8127. // The original directive caused the current element to be replaced but this element
  8128. // also needs to have a new scope, so we need to tell the template directives
  8129. // that they would need to get their scope from further up, if they require transclusion
  8130. markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
  8131. }
  8132. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  8133. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  8134. ii = directives.length;
  8135. } else {
  8136. $compileNode.html(directiveValue);
  8137. }
  8138. }
  8139. if (directive.templateUrl) {
  8140. hasTemplate = true;
  8141. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  8142. templateDirective = directive;
  8143. if (directive.replace) {
  8144. replaceDirective = directive;
  8145. }
  8146. /* jshint -W021 */
  8147. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  8148. /* jshint +W021 */
  8149. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  8150. controllerDirectives: controllerDirectives,
  8151. newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
  8152. newIsolateScopeDirective: newIsolateScopeDirective,
  8153. templateDirective: templateDirective,
  8154. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  8155. });
  8156. ii = directives.length;
  8157. } else if (directive.compile) {
  8158. try {
  8159. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  8160. var context = directive.$$originalDirective || directive;
  8161. if (isFunction(linkFn)) {
  8162. addLinkFns(null, bind(context, linkFn), attrStart, attrEnd);
  8163. } else if (linkFn) {
  8164. addLinkFns(bind(context, linkFn.pre), bind(context, linkFn.post), attrStart, attrEnd);
  8165. }
  8166. } catch (e) {
  8167. $exceptionHandler(e, startingTag($compileNode));
  8168. }
  8169. }
  8170. if (directive.terminal) {
  8171. nodeLinkFn.terminal = true;
  8172. terminalPriority = Math.max(terminalPriority, directive.priority);
  8173. }
  8174. }
  8175. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  8176. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  8177. nodeLinkFn.templateOnThisElement = hasTemplate;
  8178. nodeLinkFn.transclude = childTranscludeFn;
  8179. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  8180. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  8181. return nodeLinkFn;
  8182. ////////////////////
  8183. function addLinkFns(pre, post, attrStart, attrEnd) {
  8184. if (pre) {
  8185. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  8186. pre.require = directive.require;
  8187. pre.directiveName = directiveName;
  8188. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  8189. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  8190. }
  8191. preLinkFns.push(pre);
  8192. }
  8193. if (post) {
  8194. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  8195. post.require = directive.require;
  8196. post.directiveName = directiveName;
  8197. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  8198. post = cloneAndAnnotateFn(post, {isolateScope: true});
  8199. }
  8200. postLinkFns.push(post);
  8201. }
  8202. }
  8203. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  8204. var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
  8205. attrs, scopeBindingInfo;
  8206. if (compileNode === linkNode) {
  8207. attrs = templateAttrs;
  8208. $element = templateAttrs.$$element;
  8209. } else {
  8210. $element = jqLite(linkNode);
  8211. attrs = new Attributes($element, templateAttrs);
  8212. }
  8213. controllerScope = scope;
  8214. if (newIsolateScopeDirective) {
  8215. isolateScope = scope.$new(true);
  8216. } else if (newScopeDirective) {
  8217. controllerScope = scope.$parent;
  8218. }
  8219. if (boundTranscludeFn) {
  8220. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  8221. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  8222. transcludeFn = controllersBoundTransclude;
  8223. transcludeFn.$$boundTransclude = boundTranscludeFn;
  8224. // expose the slots on the `$transclude` function
  8225. transcludeFn.isSlotFilled = function(slotName) {
  8226. return !!boundTranscludeFn.$$slots[slotName];
  8227. };
  8228. }
  8229. if (controllerDirectives) {
  8230. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective);
  8231. }
  8232. if (newIsolateScopeDirective) {
  8233. // Initialize isolate scope bindings for new isolate scope directive.
  8234. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  8235. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  8236. compile.$$addScopeClass($element, true);
  8237. isolateScope.$$isolateBindings =
  8238. newIsolateScopeDirective.$$isolateBindings;
  8239. scopeBindingInfo = initializeDirectiveBindings(scope, attrs, isolateScope,
  8240. isolateScope.$$isolateBindings,
  8241. newIsolateScopeDirective);
  8242. if (scopeBindingInfo.removeWatches) {
  8243. isolateScope.$on('$destroy', scopeBindingInfo.removeWatches);
  8244. }
  8245. }
  8246. // Initialize bindToController bindings
  8247. for (var name in elementControllers) {
  8248. var controllerDirective = controllerDirectives[name];
  8249. var controller = elementControllers[name];
  8250. var bindings = controllerDirective.$$bindings.bindToController;
  8251. if (controller.identifier && bindings) {
  8252. controller.bindingInfo =
  8253. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8254. } else {
  8255. controller.bindingInfo = {};
  8256. }
  8257. var controllerResult = controller();
  8258. if (controllerResult !== controller.instance) {
  8259. // If the controller constructor has a return value, overwrite the instance
  8260. // from setupControllers
  8261. controller.instance = controllerResult;
  8262. $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
  8263. controller.bindingInfo.removeWatches && controller.bindingInfo.removeWatches();
  8264. controller.bindingInfo =
  8265. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  8266. }
  8267. }
  8268. // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy
  8269. forEach(controllerDirectives, function(controllerDirective, name) {
  8270. var require = controllerDirective.require;
  8271. if (controllerDirective.bindToController && !isArray(require) && isObject(require)) {
  8272. extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers));
  8273. }
  8274. });
  8275. // Handle the init and destroy lifecycle hooks on all controllers that have them
  8276. forEach(elementControllers, function(controller) {
  8277. var controllerInstance = controller.instance;
  8278. if (isFunction(controllerInstance.$onChanges)) {
  8279. try {
  8280. controllerInstance.$onChanges(controller.bindingInfo.initialChanges);
  8281. } catch (e) {
  8282. $exceptionHandler(e);
  8283. }
  8284. }
  8285. if (isFunction(controllerInstance.$onInit)) {
  8286. try {
  8287. controllerInstance.$onInit();
  8288. } catch (e) {
  8289. $exceptionHandler(e);
  8290. }
  8291. }
  8292. if (isFunction(controllerInstance.$onDestroy)) {
  8293. controllerScope.$on('$destroy', function callOnDestroyHook() {
  8294. controllerInstance.$onDestroy();
  8295. });
  8296. }
  8297. });
  8298. // PRELINKING
  8299. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  8300. linkFn = preLinkFns[i];
  8301. invokeLinkFn(linkFn,
  8302. linkFn.isolateScope ? isolateScope : scope,
  8303. $element,
  8304. attrs,
  8305. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  8306. transcludeFn
  8307. );
  8308. }
  8309. // RECURSION
  8310. // We only pass the isolate scope, if the isolate directive has a template,
  8311. // otherwise the child elements do not belong to the isolate directive.
  8312. var scopeToChild = scope;
  8313. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  8314. scopeToChild = isolateScope;
  8315. }
  8316. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  8317. // POSTLINKING
  8318. for (i = postLinkFns.length - 1; i >= 0; i--) {
  8319. linkFn = postLinkFns[i];
  8320. invokeLinkFn(linkFn,
  8321. linkFn.isolateScope ? isolateScope : scope,
  8322. $element,
  8323. attrs,
  8324. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  8325. transcludeFn
  8326. );
  8327. }
  8328. // Trigger $postLink lifecycle hooks
  8329. forEach(elementControllers, function(controller) {
  8330. var controllerInstance = controller.instance;
  8331. if (isFunction(controllerInstance.$postLink)) {
  8332. controllerInstance.$postLink();
  8333. }
  8334. });
  8335. // This is the function that is injected as `$transclude`.
  8336. // Note: all arguments are optional!
  8337. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
  8338. var transcludeControllers;
  8339. // No scope passed in:
  8340. if (!isScope(scope)) {
  8341. slotName = futureParentElement;
  8342. futureParentElement = cloneAttachFn;
  8343. cloneAttachFn = scope;
  8344. scope = undefined;
  8345. }
  8346. if (hasElementTranscludeDirective) {
  8347. transcludeControllers = elementControllers;
  8348. }
  8349. if (!futureParentElement) {
  8350. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  8351. }
  8352. if (slotName) {
  8353. // slotTranscludeFn can be one of three things:
  8354. // * a transclude function - a filled slot
  8355. // * `null` - an optional slot that was not filled
  8356. // * `undefined` - a slot that was not declared (i.e. invalid)
  8357. var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];
  8358. if (slotTranscludeFn) {
  8359. return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  8360. } else if (isUndefined(slotTranscludeFn)) {
  8361. throw $compileMinErr('noslot',
  8362. 'No parent directive that requires a transclusion with slot name "{0}". ' +
  8363. 'Element: {1}',
  8364. slotName, startingTag($element));
  8365. }
  8366. } else {
  8367. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  8368. }
  8369. }
  8370. }
  8371. }
  8372. function getControllers(directiveName, require, $element, elementControllers) {
  8373. var value;
  8374. if (isString(require)) {
  8375. var match = require.match(REQUIRE_PREFIX_REGEXP);
  8376. var name = require.substring(match[0].length);
  8377. var inheritType = match[1] || match[3];
  8378. var optional = match[2] === '?';
  8379. //If only parents then start at the parent element
  8380. if (inheritType === '^^') {
  8381. $element = $element.parent();
  8382. //Otherwise attempt getting the controller from elementControllers in case
  8383. //the element is transcluded (and has no data) and to avoid .data if possible
  8384. } else {
  8385. value = elementControllers && elementControllers[name];
  8386. value = value && value.instance;
  8387. }
  8388. if (!value) {
  8389. var dataName = '$' + name + 'Controller';
  8390. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  8391. }
  8392. if (!value && !optional) {
  8393. throw $compileMinErr('ctreq',
  8394. "Controller '{0}', required by directive '{1}', can't be found!",
  8395. name, directiveName);
  8396. }
  8397. } else if (isArray(require)) {
  8398. value = [];
  8399. for (var i = 0, ii = require.length; i < ii; i++) {
  8400. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  8401. }
  8402. } else if (isObject(require)) {
  8403. value = {};
  8404. forEach(require, function(controller, property) {
  8405. value[property] = getControllers(directiveName, controller, $element, elementControllers);
  8406. });
  8407. }
  8408. return value || null;
  8409. }
  8410. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective) {
  8411. var elementControllers = createMap();
  8412. for (var controllerKey in controllerDirectives) {
  8413. var directive = controllerDirectives[controllerKey];
  8414. var locals = {
  8415. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  8416. $element: $element,
  8417. $attrs: attrs,
  8418. $transclude: transcludeFn
  8419. };
  8420. var controller = directive.controller;
  8421. if (controller == '@') {
  8422. controller = attrs[directive.name];
  8423. }
  8424. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  8425. // For directives with element transclusion the element is a comment.
  8426. // In this case .data will not attach any data.
  8427. // Instead, we save the controllers for the element in a local hash and attach to .data
  8428. // later, once we have the actual element.
  8429. elementControllers[directive.name] = controllerInstance;
  8430. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  8431. }
  8432. return elementControllers;
  8433. }
  8434. // Depending upon the context in which a directive finds itself it might need to have a new isolated
  8435. // or child scope created. For instance:
  8436. // * if the directive has been pulled into a template because another directive with a higher priority
  8437. // asked for element transclusion
  8438. // * if the directive itself asks for transclusion but it is at the root of a template and the original
  8439. // element was replaced. See https://github.com/angular/angular.js/issues/12936
  8440. function markDirectiveScope(directives, isolateScope, newScope) {
  8441. for (var j = 0, jj = directives.length; j < jj; j++) {
  8442. directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
  8443. }
  8444. }
  8445. /**
  8446. * looks up the directive and decorates it with exception handling and proper parameters. We
  8447. * call this the boundDirective.
  8448. *
  8449. * @param {string} name name of the directive to look up.
  8450. * @param {string} location The directive must be found in specific format.
  8451. * String containing any of theses characters:
  8452. *
  8453. * * `E`: element name
  8454. * * `A': attribute
  8455. * * `C`: class
  8456. * * `M`: comment
  8457. * @returns {boolean} true if directive was added.
  8458. */
  8459. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  8460. endAttrName) {
  8461. if (name === ignoreDirective) return null;
  8462. var match = null;
  8463. if (hasDirectives.hasOwnProperty(name)) {
  8464. for (var directive, directives = $injector.get(name + Suffix),
  8465. i = 0, ii = directives.length; i < ii; i++) {
  8466. try {
  8467. directive = directives[i];
  8468. if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
  8469. directive.restrict.indexOf(location) != -1) {
  8470. if (startAttrName) {
  8471. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  8472. }
  8473. if (!directive.$$bindings) {
  8474. var bindings = directive.$$bindings =
  8475. parseDirectiveBindings(directive, directive.name);
  8476. if (isObject(bindings.isolateScope)) {
  8477. directive.$$isolateBindings = bindings.isolateScope;
  8478. }
  8479. }
  8480. tDirectives.push(directive);
  8481. match = directive;
  8482. }
  8483. } catch (e) { $exceptionHandler(e); }
  8484. }
  8485. }
  8486. return match;
  8487. }
  8488. /**
  8489. * looks up the directive and returns true if it is a multi-element directive,
  8490. * and therefore requires DOM nodes between -start and -end markers to be grouped
  8491. * together.
  8492. *
  8493. * @param {string} name name of the directive to look up.
  8494. * @returns true if directive was registered as multi-element.
  8495. */
  8496. function directiveIsMultiElement(name) {
  8497. if (hasDirectives.hasOwnProperty(name)) {
  8498. for (var directive, directives = $injector.get(name + Suffix),
  8499. i = 0, ii = directives.length; i < ii; i++) {
  8500. directive = directives[i];
  8501. if (directive.multiElement) {
  8502. return true;
  8503. }
  8504. }
  8505. }
  8506. return false;
  8507. }
  8508. /**
  8509. * When the element is replaced with HTML template then the new attributes
  8510. * on the template need to be merged with the existing attributes in the DOM.
  8511. * The desired effect is to have both of the attributes present.
  8512. *
  8513. * @param {object} dst destination attributes (original DOM)
  8514. * @param {object} src source attributes (from the directive template)
  8515. */
  8516. function mergeTemplateAttributes(dst, src) {
  8517. var srcAttr = src.$attr,
  8518. dstAttr = dst.$attr,
  8519. $element = dst.$$element;
  8520. // reapply the old attributes to the new element
  8521. forEach(dst, function(value, key) {
  8522. if (key.charAt(0) != '$') {
  8523. if (src[key] && src[key] !== value) {
  8524. value += (key === 'style' ? ';' : ' ') + src[key];
  8525. }
  8526. dst.$set(key, value, true, srcAttr[key]);
  8527. }
  8528. });
  8529. // copy the new attributes on the old attrs object
  8530. forEach(src, function(value, key) {
  8531. // Check if we already set this attribute in the loop above.
  8532. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  8533. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  8534. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  8535. if (!dst.hasOwnProperty(key) && key.charAt(0) !== '$') {
  8536. dst[key] = value;
  8537. if (key !== 'class' && key !== 'style') {
  8538. dstAttr[key] = srcAttr[key];
  8539. }
  8540. }
  8541. });
  8542. }
  8543. function compileTemplateUrl(directives, $compileNode, tAttrs,
  8544. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  8545. var linkQueue = [],
  8546. afterTemplateNodeLinkFn,
  8547. afterTemplateChildLinkFn,
  8548. beforeTemplateCompileNode = $compileNode[0],
  8549. origAsyncDirective = directives.shift(),
  8550. derivedSyncDirective = inherit(origAsyncDirective, {
  8551. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  8552. }),
  8553. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  8554. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  8555. : origAsyncDirective.templateUrl,
  8556. templateNamespace = origAsyncDirective.templateNamespace;
  8557. $compileNode.empty();
  8558. $templateRequest(templateUrl)
  8559. .then(function(content) {
  8560. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  8561. content = denormalizeTemplate(content);
  8562. if (origAsyncDirective.replace) {
  8563. if (jqLiteIsTextNode(content)) {
  8564. $template = [];
  8565. } else {
  8566. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  8567. }
  8568. compileNode = $template[0];
  8569. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  8570. throw $compileMinErr('tplrt',
  8571. "Template for directive '{0}' must have exactly one root element. {1}",
  8572. origAsyncDirective.name, templateUrl);
  8573. }
  8574. tempTemplateAttrs = {$attr: {}};
  8575. replaceWith($rootElement, $compileNode, compileNode);
  8576. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  8577. if (isObject(origAsyncDirective.scope)) {
  8578. // the original directive that caused the template to be loaded async required
  8579. // an isolate scope
  8580. markDirectiveScope(templateDirectives, true);
  8581. }
  8582. directives = templateDirectives.concat(directives);
  8583. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  8584. } else {
  8585. compileNode = beforeTemplateCompileNode;
  8586. $compileNode.html(content);
  8587. }
  8588. directives.unshift(derivedSyncDirective);
  8589. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  8590. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  8591. previousCompileContext);
  8592. forEach($rootElement, function(node, i) {
  8593. if (node == compileNode) {
  8594. $rootElement[i] = $compileNode[0];
  8595. }
  8596. });
  8597. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  8598. while (linkQueue.length) {
  8599. var scope = linkQueue.shift(),
  8600. beforeTemplateLinkNode = linkQueue.shift(),
  8601. linkRootElement = linkQueue.shift(),
  8602. boundTranscludeFn = linkQueue.shift(),
  8603. linkNode = $compileNode[0];
  8604. if (scope.$$destroyed) continue;
  8605. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  8606. var oldClasses = beforeTemplateLinkNode.className;
  8607. if (!(previousCompileContext.hasElementTranscludeDirective &&
  8608. origAsyncDirective.replace)) {
  8609. // it was cloned therefore we have to clone as well.
  8610. linkNode = jqLiteClone(compileNode);
  8611. }
  8612. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  8613. // Copy in CSS classes from original node
  8614. safeAddClass(jqLite(linkNode), oldClasses);
  8615. }
  8616. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  8617. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  8618. } else {
  8619. childBoundTranscludeFn = boundTranscludeFn;
  8620. }
  8621. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  8622. childBoundTranscludeFn);
  8623. }
  8624. linkQueue = null;
  8625. });
  8626. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  8627. var childBoundTranscludeFn = boundTranscludeFn;
  8628. if (scope.$$destroyed) return;
  8629. if (linkQueue) {
  8630. linkQueue.push(scope,
  8631. node,
  8632. rootElement,
  8633. childBoundTranscludeFn);
  8634. } else {
  8635. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  8636. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  8637. }
  8638. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  8639. }
  8640. };
  8641. }
  8642. /**
  8643. * Sorting function for bound directives.
  8644. */
  8645. function byPriority(a, b) {
  8646. var diff = b.priority - a.priority;
  8647. if (diff !== 0) return diff;
  8648. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  8649. return a.index - b.index;
  8650. }
  8651. function assertNoDuplicate(what, previousDirective, directive, element) {
  8652. function wrapModuleNameIfDefined(moduleName) {
  8653. return moduleName ?
  8654. (' (module: ' + moduleName + ')') :
  8655. '';
  8656. }
  8657. if (previousDirective) {
  8658. throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
  8659. previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
  8660. directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
  8661. }
  8662. }
  8663. function addTextInterpolateDirective(directives, text) {
  8664. var interpolateFn = $interpolate(text, true);
  8665. if (interpolateFn) {
  8666. directives.push({
  8667. priority: 0,
  8668. compile: function textInterpolateCompileFn(templateNode) {
  8669. var templateNodeParent = templateNode.parent(),
  8670. hasCompileParent = !!templateNodeParent.length;
  8671. // When transcluding a template that has bindings in the root
  8672. // we don't have a parent and thus need to add the class during linking fn.
  8673. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  8674. return function textInterpolateLinkFn(scope, node) {
  8675. var parent = node.parent();
  8676. if (!hasCompileParent) compile.$$addBindingClass(parent);
  8677. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  8678. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  8679. node[0].nodeValue = value;
  8680. });
  8681. };
  8682. }
  8683. });
  8684. }
  8685. }
  8686. function wrapTemplate(type, template) {
  8687. type = lowercase(type || 'html');
  8688. switch (type) {
  8689. case 'svg':
  8690. case 'math':
  8691. var wrapper = window.document.createElement('div');
  8692. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  8693. return wrapper.childNodes[0].childNodes;
  8694. default:
  8695. return template;
  8696. }
  8697. }
  8698. function getTrustedContext(node, attrNormalizedName) {
  8699. if (attrNormalizedName == "srcdoc") {
  8700. return $sce.HTML;
  8701. }
  8702. var tag = nodeName_(node);
  8703. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  8704. if (attrNormalizedName == "xlinkHref" ||
  8705. (tag == "form" && attrNormalizedName == "action") ||
  8706. (tag != "img" && (attrNormalizedName == "src" ||
  8707. attrNormalizedName == "ngSrc"))) {
  8708. return $sce.RESOURCE_URL;
  8709. }
  8710. }
  8711. function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  8712. var trustedContext = getTrustedContext(node, name);
  8713. allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
  8714. var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
  8715. // no interpolation found -> ignore
  8716. if (!interpolateFn) return;
  8717. if (name === "multiple" && nodeName_(node) === "select") {
  8718. throw $compileMinErr("selmulti",
  8719. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  8720. startingTag(node));
  8721. }
  8722. directives.push({
  8723. priority: 100,
  8724. compile: function() {
  8725. return {
  8726. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  8727. var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
  8728. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  8729. throw $compileMinErr('nodomevents',
  8730. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  8731. "ng- versions (such as ng-click instead of onclick) instead.");
  8732. }
  8733. // If the attribute has changed since last $interpolate()ed
  8734. var newValue = attr[name];
  8735. if (newValue !== value) {
  8736. // we need to interpolate again since the attribute value has been updated
  8737. // (e.g. by another directive's compile function)
  8738. // ensure unset/empty values make interpolateFn falsy
  8739. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  8740. value = newValue;
  8741. }
  8742. // if attribute was updated so that there is no interpolation going on we don't want to
  8743. // register any observers
  8744. if (!interpolateFn) return;
  8745. // initialize attr object so that it's ready in case we need the value for isolate
  8746. // scope initialization, otherwise the value would not be available from isolate
  8747. // directive's linking fn during linking phase
  8748. attr[name] = interpolateFn(scope);
  8749. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  8750. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  8751. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  8752. //special case for class attribute addition + removal
  8753. //so that class changes can tap into the animation
  8754. //hooks provided by the $animate service. Be sure to
  8755. //skip animations when the first digest occurs (when
  8756. //both the new and the old values are the same) since
  8757. //the CSS classes are the non-interpolated values
  8758. if (name === 'class' && newValue != oldValue) {
  8759. attr.$updateClass(newValue, oldValue);
  8760. } else {
  8761. attr.$set(name, newValue);
  8762. }
  8763. });
  8764. }
  8765. };
  8766. }
  8767. });
  8768. }
  8769. /**
  8770. * This is a special jqLite.replaceWith, which can replace items which
  8771. * have no parents, provided that the containing jqLite collection is provided.
  8772. *
  8773. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  8774. * in the root of the tree.
  8775. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  8776. * the shell, but replace its DOM node reference.
  8777. * @param {Node} newNode The new DOM node.
  8778. */
  8779. function replaceWith($rootElement, elementsToRemove, newNode) {
  8780. var firstElementToRemove = elementsToRemove[0],
  8781. removeCount = elementsToRemove.length,
  8782. parent = firstElementToRemove.parentNode,
  8783. i, ii;
  8784. if ($rootElement) {
  8785. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  8786. if ($rootElement[i] == firstElementToRemove) {
  8787. $rootElement[i++] = newNode;
  8788. for (var j = i, j2 = j + removeCount - 1,
  8789. jj = $rootElement.length;
  8790. j < jj; j++, j2++) {
  8791. if (j2 < jj) {
  8792. $rootElement[j] = $rootElement[j2];
  8793. } else {
  8794. delete $rootElement[j];
  8795. }
  8796. }
  8797. $rootElement.length -= removeCount - 1;
  8798. // If the replaced element is also the jQuery .context then replace it
  8799. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  8800. // http://api.jquery.com/context/
  8801. if ($rootElement.context === firstElementToRemove) {
  8802. $rootElement.context = newNode;
  8803. }
  8804. break;
  8805. }
  8806. }
  8807. }
  8808. if (parent) {
  8809. parent.replaceChild(newNode, firstElementToRemove);
  8810. }
  8811. // Append all the `elementsToRemove` to a fragment. This will...
  8812. // - remove them from the DOM
  8813. // - allow them to still be traversed with .nextSibling
  8814. // - allow a single fragment.qSA to fetch all elements being removed
  8815. var fragment = window.document.createDocumentFragment();
  8816. for (i = 0; i < removeCount; i++) {
  8817. fragment.appendChild(elementsToRemove[i]);
  8818. }
  8819. if (jqLite.hasData(firstElementToRemove)) {
  8820. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  8821. // data here because there's no public interface in jQuery to do that and copying over
  8822. // event listeners (which is the main use of private data) wouldn't work anyway.
  8823. jqLite.data(newNode, jqLite.data(firstElementToRemove));
  8824. // Remove $destroy event listeners from `firstElementToRemove`
  8825. jqLite(firstElementToRemove).off('$destroy');
  8826. }
  8827. // Cleanup any data/listeners on the elements and children.
  8828. // This includes invoking the $destroy event on any elements with listeners.
  8829. jqLite.cleanData(fragment.querySelectorAll('*'));
  8830. // Update the jqLite collection to only contain the `newNode`
  8831. for (i = 1; i < removeCount; i++) {
  8832. delete elementsToRemove[i];
  8833. }
  8834. elementsToRemove[0] = newNode;
  8835. elementsToRemove.length = 1;
  8836. }
  8837. function cloneAndAnnotateFn(fn, annotation) {
  8838. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  8839. }
  8840. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  8841. try {
  8842. linkFn(scope, $element, attrs, controllers, transcludeFn);
  8843. } catch (e) {
  8844. $exceptionHandler(e, startingTag($element));
  8845. }
  8846. }
  8847. // Set up $watches for isolate scope and controller bindings. This process
  8848. // only occurs for isolate scopes and new scopes with controllerAs.
  8849. function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
  8850. var removeWatchCollection = [];
  8851. var initialChanges = {};
  8852. var changes;
  8853. forEach(bindings, function initializeBinding(definition, scopeName) {
  8854. var attrName = definition.attrName,
  8855. optional = definition.optional,
  8856. mode = definition.mode, // @, =, or &
  8857. lastValue,
  8858. parentGet, parentSet, compare, removeWatch;
  8859. switch (mode) {
  8860. case '@':
  8861. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  8862. destination[scopeName] = attrs[attrName] = void 0;
  8863. }
  8864. attrs.$observe(attrName, function(value) {
  8865. if (isString(value) || isBoolean(value)) {
  8866. var oldValue = destination[scopeName];
  8867. recordChanges(scopeName, value, oldValue);
  8868. destination[scopeName] = value;
  8869. }
  8870. });
  8871. attrs.$$observers[attrName].$$scope = scope;
  8872. lastValue = attrs[attrName];
  8873. if (isString(lastValue)) {
  8874. // If the attribute has been provided then we trigger an interpolation to ensure
  8875. // the value is there for use in the link fn
  8876. destination[scopeName] = $interpolate(lastValue)(scope);
  8877. } else if (isBoolean(lastValue)) {
  8878. // If the attributes is one of the BOOLEAN_ATTR then Angular will have converted
  8879. // the value to boolean rather than a string, so we special case this situation
  8880. destination[scopeName] = lastValue;
  8881. }
  8882. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  8883. break;
  8884. case '=':
  8885. if (!hasOwnProperty.call(attrs, attrName)) {
  8886. if (optional) break;
  8887. attrs[attrName] = void 0;
  8888. }
  8889. if (optional && !attrs[attrName]) break;
  8890. parentGet = $parse(attrs[attrName]);
  8891. if (parentGet.literal) {
  8892. compare = equals;
  8893. } else {
  8894. compare = function simpleCompare(a, b) { return a === b || (a !== a && b !== b); };
  8895. }
  8896. parentSet = parentGet.assign || function() {
  8897. // reset the change, or we will throw this exception on every $digest
  8898. lastValue = destination[scopeName] = parentGet(scope);
  8899. throw $compileMinErr('nonassign',
  8900. "Expression '{0}' in attribute '{1}' used with directive '{2}' is non-assignable!",
  8901. attrs[attrName], attrName, directive.name);
  8902. };
  8903. lastValue = destination[scopeName] = parentGet(scope);
  8904. var parentValueWatch = function parentValueWatch(parentValue) {
  8905. if (!compare(parentValue, destination[scopeName])) {
  8906. // we are out of sync and need to copy
  8907. if (!compare(parentValue, lastValue)) {
  8908. // parent changed and it has precedence
  8909. destination[scopeName] = parentValue;
  8910. } else {
  8911. // if the parent can be assigned then do so
  8912. parentSet(scope, parentValue = destination[scopeName]);
  8913. }
  8914. }
  8915. return lastValue = parentValue;
  8916. };
  8917. parentValueWatch.$stateful = true;
  8918. if (definition.collection) {
  8919. removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  8920. } else {
  8921. removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  8922. }
  8923. removeWatchCollection.push(removeWatch);
  8924. break;
  8925. case '<':
  8926. if (!hasOwnProperty.call(attrs, attrName)) {
  8927. if (optional) break;
  8928. attrs[attrName] = void 0;
  8929. }
  8930. if (optional && !attrs[attrName]) break;
  8931. parentGet = $parse(attrs[attrName]);
  8932. var initialValue = destination[scopeName] = parentGet(scope);
  8933. initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]);
  8934. removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newValue, oldValue) {
  8935. if (oldValue === newValue) {
  8936. if (oldValue === initialValue) return;
  8937. oldValue = initialValue;
  8938. }
  8939. recordChanges(scopeName, newValue, oldValue);
  8940. destination[scopeName] = newValue;
  8941. }, parentGet.literal);
  8942. removeWatchCollection.push(removeWatch);
  8943. break;
  8944. case '&':
  8945. // Don't assign Object.prototype method to scope
  8946. parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
  8947. // Don't assign noop to destination if expression is not valid
  8948. if (parentGet === noop && optional) break;
  8949. destination[scopeName] = function(locals) {
  8950. return parentGet(scope, locals);
  8951. };
  8952. break;
  8953. }
  8954. });
  8955. function recordChanges(key, currentValue, previousValue) {
  8956. if (isFunction(destination.$onChanges) && currentValue !== previousValue) {
  8957. // If we have not already scheduled the top level onChangesQueue handler then do so now
  8958. if (!onChangesQueue) {
  8959. scope.$$postDigest(flushOnChangesQueue);
  8960. onChangesQueue = [];
  8961. }
  8962. // If we have not already queued a trigger of onChanges for this controller then do so now
  8963. if (!changes) {
  8964. changes = {};
  8965. onChangesQueue.push(triggerOnChangesHook);
  8966. }
  8967. // If the has been a change on this property already then we need to reuse the previous value
  8968. if (changes[key]) {
  8969. previousValue = changes[key].previousValue;
  8970. }
  8971. // Store this change
  8972. changes[key] = new SimpleChange(previousValue, currentValue);
  8973. }
  8974. }
  8975. function triggerOnChangesHook() {
  8976. destination.$onChanges(changes);
  8977. // Now clear the changes so that we schedule onChanges when more changes arrive
  8978. changes = undefined;
  8979. }
  8980. return {
  8981. initialChanges: initialChanges,
  8982. removeWatches: removeWatchCollection.length && function removeWatches() {
  8983. for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
  8984. removeWatchCollection[i]();
  8985. }
  8986. }
  8987. };
  8988. }
  8989. }];
  8990. }
  8991. function SimpleChange(previous, current) {
  8992. this.previousValue = previous;
  8993. this.currentValue = current;
  8994. }
  8995. SimpleChange.prototype.isFirstChange = function() { return this.previousValue === _UNINITIALIZED_VALUE; };
  8996. var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
  8997. /**
  8998. * Converts all accepted directives format into proper directive name.
  8999. * @param name Name to normalize
  9000. */
  9001. function directiveNormalize(name) {
  9002. return camelCase(name.replace(PREFIX_REGEXP, ''));
  9003. }
  9004. /**
  9005. * @ngdoc type
  9006. * @name $compile.directive.Attributes
  9007. *
  9008. * @description
  9009. * A shared object between directive compile / linking functions which contains normalized DOM
  9010. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  9011. * needed since all of these are treated as equivalent in Angular:
  9012. *
  9013. * ```
  9014. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  9015. * ```
  9016. */
  9017. /**
  9018. * @ngdoc property
  9019. * @name $compile.directive.Attributes#$attr
  9020. *
  9021. * @description
  9022. * A map of DOM element attribute names to the normalized name. This is
  9023. * needed to do reverse lookup from normalized name back to actual name.
  9024. */
  9025. /**
  9026. * @ngdoc method
  9027. * @name $compile.directive.Attributes#$set
  9028. * @kind function
  9029. *
  9030. * @description
  9031. * Set DOM element attribute value.
  9032. *
  9033. *
  9034. * @param {string} name Normalized element attribute name of the property to modify. The name is
  9035. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  9036. * property to the original name.
  9037. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  9038. */
  9039. /**
  9040. * Closure compiler type information
  9041. */
  9042. function nodesetLinkingFn(
  9043. /* angular.Scope */ scope,
  9044. /* NodeList */ nodeList,
  9045. /* Element */ rootElement,
  9046. /* function(Function) */ boundTranscludeFn
  9047. ) {}
  9048. function directiveLinkingFn(
  9049. /* nodesetLinkingFn */ nodesetLinkingFn,
  9050. /* angular.Scope */ scope,
  9051. /* Node */ node,
  9052. /* Element */ rootElement,
  9053. /* function(Function) */ boundTranscludeFn
  9054. ) {}
  9055. function tokenDifference(str1, str2) {
  9056. var values = '',
  9057. tokens1 = str1.split(/\s+/),
  9058. tokens2 = str2.split(/\s+/);
  9059. outer:
  9060. for (var i = 0; i < tokens1.length; i++) {
  9061. var token = tokens1[i];
  9062. for (var j = 0; j < tokens2.length; j++) {
  9063. if (token == tokens2[j]) continue outer;
  9064. }
  9065. values += (values.length > 0 ? ' ' : '') + token;
  9066. }
  9067. return values;
  9068. }
  9069. function removeComments(jqNodes) {
  9070. jqNodes = jqLite(jqNodes);
  9071. var i = jqNodes.length;
  9072. if (i <= 1) {
  9073. return jqNodes;
  9074. }
  9075. while (i--) {
  9076. var node = jqNodes[i];
  9077. if (node.nodeType === NODE_TYPE_COMMENT) {
  9078. splice.call(jqNodes, i, 1);
  9079. }
  9080. }
  9081. return jqNodes;
  9082. }
  9083. var $controllerMinErr = minErr('$controller');
  9084. var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/;
  9085. function identifierForController(controller, ident) {
  9086. if (ident && isString(ident)) return ident;
  9087. if (isString(controller)) {
  9088. var match = CNTRL_REG.exec(controller);
  9089. if (match) return match[3];
  9090. }
  9091. }
  9092. /**
  9093. * @ngdoc provider
  9094. * @name $controllerProvider
  9095. * @description
  9096. * The {@link ng.$controller $controller service} is used by Angular to create new
  9097. * controllers.
  9098. *
  9099. * This provider allows controller registration via the
  9100. * {@link ng.$controllerProvider#register register} method.
  9101. */
  9102. function $ControllerProvider() {
  9103. var controllers = {},
  9104. globals = false;
  9105. /**
  9106. * @ngdoc method
  9107. * @name $controllerProvider#has
  9108. * @param {string} name Controller name to check.
  9109. */
  9110. this.has = function(name) {
  9111. return controllers.hasOwnProperty(name);
  9112. };
  9113. /**
  9114. * @ngdoc method
  9115. * @name $controllerProvider#register
  9116. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  9117. * the names and the values are the constructors.
  9118. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  9119. * annotations in the array notation).
  9120. */
  9121. this.register = function(name, constructor) {
  9122. assertNotHasOwnProperty(name, 'controller');
  9123. if (isObject(name)) {
  9124. extend(controllers, name);
  9125. } else {
  9126. controllers[name] = constructor;
  9127. }
  9128. };
  9129. /**
  9130. * @ngdoc method
  9131. * @name $controllerProvider#allowGlobals
  9132. * @description If called, allows `$controller` to find controller constructors on `window`
  9133. */
  9134. this.allowGlobals = function() {
  9135. globals = true;
  9136. };
  9137. this.$get = ['$injector', '$window', function($injector, $window) {
  9138. /**
  9139. * @ngdoc service
  9140. * @name $controller
  9141. * @requires $injector
  9142. *
  9143. * @param {Function|string} constructor If called with a function then it's considered to be the
  9144. * controller constructor function. Otherwise it's considered to be a string which is used
  9145. * to retrieve the controller constructor using the following steps:
  9146. *
  9147. * * check if a controller with given name is registered via `$controllerProvider`
  9148. * * check if evaluating the string on the current scope returns a constructor
  9149. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  9150. * `window` object (not recommended)
  9151. *
  9152. * The string can use the `controller as property` syntax, where the controller instance is published
  9153. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  9154. * to work correctly.
  9155. *
  9156. * @param {Object} locals Injection locals for Controller.
  9157. * @return {Object} Instance of given controller.
  9158. *
  9159. * @description
  9160. * `$controller` service is responsible for instantiating controllers.
  9161. *
  9162. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  9163. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  9164. */
  9165. return function $controller(expression, locals, later, ident) {
  9166. // PRIVATE API:
  9167. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  9168. // If true, $controller will allocate the object with the correct
  9169. // prototype chain, but will not invoke the controller until a returned
  9170. // callback is invoked.
  9171. // param `ident` --- An optional label which overrides the label parsed from the controller
  9172. // expression, if any.
  9173. var instance, match, constructor, identifier;
  9174. later = later === true;
  9175. if (ident && isString(ident)) {
  9176. identifier = ident;
  9177. }
  9178. if (isString(expression)) {
  9179. match = expression.match(CNTRL_REG);
  9180. if (!match) {
  9181. throw $controllerMinErr('ctrlfmt',
  9182. "Badly formed controller string '{0}'. " +
  9183. "Must match `__name__ as __id__` or `__name__`.", expression);
  9184. }
  9185. constructor = match[1],
  9186. identifier = identifier || match[3];
  9187. expression = controllers.hasOwnProperty(constructor)
  9188. ? controllers[constructor]
  9189. : getter(locals.$scope, constructor, true) ||
  9190. (globals ? getter($window, constructor, true) : undefined);
  9191. assertArgFn(expression, constructor, true);
  9192. }
  9193. if (later) {
  9194. // Instantiate controller later:
  9195. // This machinery is used to create an instance of the object before calling the
  9196. // controller's constructor itself.
  9197. //
  9198. // This allows properties to be added to the controller before the constructor is
  9199. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  9200. //
  9201. // This feature is not intended for use by applications, and is thus not documented
  9202. // publicly.
  9203. // Object creation: http://jsperf.com/create-constructor/2
  9204. var controllerPrototype = (isArray(expression) ?
  9205. expression[expression.length - 1] : expression).prototype;
  9206. instance = Object.create(controllerPrototype || null);
  9207. if (identifier) {
  9208. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9209. }
  9210. var instantiate;
  9211. return instantiate = extend(function $controllerInit() {
  9212. var result = $injector.invoke(expression, instance, locals, constructor);
  9213. if (result !== instance && (isObject(result) || isFunction(result))) {
  9214. instance = result;
  9215. if (identifier) {
  9216. // If result changed, re-assign controllerAs value to scope.
  9217. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9218. }
  9219. }
  9220. return instance;
  9221. }, {
  9222. instance: instance,
  9223. identifier: identifier
  9224. });
  9225. }
  9226. instance = $injector.instantiate(expression, locals, constructor);
  9227. if (identifier) {
  9228. addIdentifier(locals, identifier, instance, constructor || expression.name);
  9229. }
  9230. return instance;
  9231. };
  9232. function addIdentifier(locals, identifier, instance, name) {
  9233. if (!(locals && isObject(locals.$scope))) {
  9234. throw minErr('$controller')('noscp',
  9235. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  9236. name, identifier);
  9237. }
  9238. locals.$scope[identifier] = instance;
  9239. }
  9240. }];
  9241. }
  9242. /**
  9243. * @ngdoc service
  9244. * @name $document
  9245. * @requires $window
  9246. *
  9247. * @description
  9248. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  9249. *
  9250. * @example
  9251. <example module="documentExample">
  9252. <file name="index.html">
  9253. <div ng-controller="ExampleController">
  9254. <p>$document title: <b ng-bind="title"></b></p>
  9255. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  9256. </div>
  9257. </file>
  9258. <file name="script.js">
  9259. angular.module('documentExample', [])
  9260. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  9261. $scope.title = $document[0].title;
  9262. $scope.windowTitle = angular.element(window.document)[0].title;
  9263. }]);
  9264. </file>
  9265. </example>
  9266. */
  9267. function $DocumentProvider() {
  9268. this.$get = ['$window', function(window) {
  9269. return jqLite(window.document);
  9270. }];
  9271. }
  9272. /**
  9273. * @ngdoc service
  9274. * @name $exceptionHandler
  9275. * @requires ng.$log
  9276. *
  9277. * @description
  9278. * Any uncaught exception in angular expressions is delegated to this service.
  9279. * The default implementation simply delegates to `$log.error` which logs it into
  9280. * the browser console.
  9281. *
  9282. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  9283. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  9284. *
  9285. * ## Example:
  9286. *
  9287. * The example below will overwrite the default `$exceptionHandler` in order to (a) log uncaught
  9288. * errors to the backend for later inspection by the developers and (b) to use `$log.warn()` instead
  9289. * of `$log.error()`.
  9290. *
  9291. * ```js
  9292. * angular.
  9293. * module('exceptionOverwrite', []).
  9294. * factory('$exceptionHandler', ['$log', 'logErrorsToBackend', function($log, logErrorsToBackend) {
  9295. * return function myExceptionHandler(exception, cause) {
  9296. * logErrorsToBackend(exception, cause);
  9297. * $log.warn(exception, cause);
  9298. * };
  9299. * });
  9300. * ```
  9301. *
  9302. * <hr />
  9303. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  9304. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  9305. * (unless executed during a digest).
  9306. *
  9307. * If you wish, you can manually delegate exceptions, e.g.
  9308. * `try { ... } catch(e) { $exceptionHandler(e); }`
  9309. *
  9310. * @param {Error} exception Exception associated with the error.
  9311. * @param {string=} cause Optional information about the context in which
  9312. * the error was thrown.
  9313. *
  9314. */
  9315. function $ExceptionHandlerProvider() {
  9316. this.$get = ['$log', function($log) {
  9317. return function(exception, cause) {
  9318. $log.error.apply($log, arguments);
  9319. };
  9320. }];
  9321. }
  9322. var $$ForceReflowProvider = function() {
  9323. this.$get = ['$document', function($document) {
  9324. return function(domNode) {
  9325. //the line below will force the browser to perform a repaint so
  9326. //that all the animated elements within the animation frame will
  9327. //be properly updated and drawn on screen. This is required to
  9328. //ensure that the preparation animation is properly flushed so that
  9329. //the active state picks up from there. DO NOT REMOVE THIS LINE.
  9330. //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
  9331. //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
  9332. //WILL TAKE YEARS AWAY FROM YOUR LIFE.
  9333. if (domNode) {
  9334. if (!domNode.nodeType && domNode instanceof jqLite) {
  9335. domNode = domNode[0];
  9336. }
  9337. } else {
  9338. domNode = $document[0].body;
  9339. }
  9340. return domNode.offsetWidth + 1;
  9341. };
  9342. }];
  9343. };
  9344. var APPLICATION_JSON = 'application/json';
  9345. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  9346. var JSON_START = /^\[|^\{(?!\{)/;
  9347. var JSON_ENDS = {
  9348. '[': /]$/,
  9349. '{': /}$/
  9350. };
  9351. var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
  9352. var $httpMinErr = minErr('$http');
  9353. var $httpMinErrLegacyFn = function(method) {
  9354. return function() {
  9355. throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method);
  9356. };
  9357. };
  9358. function serializeValue(v) {
  9359. if (isObject(v)) {
  9360. return isDate(v) ? v.toISOString() : toJson(v);
  9361. }
  9362. return v;
  9363. }
  9364. function $HttpParamSerializerProvider() {
  9365. /**
  9366. * @ngdoc service
  9367. * @name $httpParamSerializer
  9368. * @description
  9369. *
  9370. * Default {@link $http `$http`} params serializer that converts objects to strings
  9371. * according to the following rules:
  9372. *
  9373. * * `{'foo': 'bar'}` results in `foo=bar`
  9374. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  9375. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  9376. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
  9377. *
  9378. * Note that serializer will sort the request parameters alphabetically.
  9379. * */
  9380. this.$get = function() {
  9381. return function ngParamSerializer(params) {
  9382. if (!params) return '';
  9383. var parts = [];
  9384. forEachSorted(params, function(value, key) {
  9385. if (value === null || isUndefined(value)) return;
  9386. if (isArray(value)) {
  9387. forEach(value, function(v) {
  9388. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  9389. });
  9390. } else {
  9391. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  9392. }
  9393. });
  9394. return parts.join('&');
  9395. };
  9396. };
  9397. }
  9398. function $HttpParamSerializerJQLikeProvider() {
  9399. /**
  9400. * @ngdoc service
  9401. * @name $httpParamSerializerJQLike
  9402. * @description
  9403. *
  9404. * Alternative {@link $http `$http`} params serializer that follows
  9405. * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  9406. * The serializer will also sort the params alphabetically.
  9407. *
  9408. * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
  9409. *
  9410. * ```js
  9411. * $http({
  9412. * url: myUrl,
  9413. * method: 'GET',
  9414. * params: myParams,
  9415. * paramSerializer: '$httpParamSerializerJQLike'
  9416. * });
  9417. * ```
  9418. *
  9419. * It is also possible to set it as the default `paramSerializer` in the
  9420. * {@link $httpProvider#defaults `$httpProvider`}.
  9421. *
  9422. * Additionally, you can inject the serializer and use it explicitly, for example to serialize
  9423. * form data for submission:
  9424. *
  9425. * ```js
  9426. * .controller(function($http, $httpParamSerializerJQLike) {
  9427. * //...
  9428. *
  9429. * $http({
  9430. * url: myUrl,
  9431. * method: 'POST',
  9432. * data: $httpParamSerializerJQLike(myData),
  9433. * headers: {
  9434. * 'Content-Type': 'application/x-www-form-urlencoded'
  9435. * }
  9436. * });
  9437. *
  9438. * });
  9439. * ```
  9440. *
  9441. * */
  9442. this.$get = function() {
  9443. return function jQueryLikeParamSerializer(params) {
  9444. if (!params) return '';
  9445. var parts = [];
  9446. serialize(params, '', true);
  9447. return parts.join('&');
  9448. function serialize(toSerialize, prefix, topLevel) {
  9449. if (toSerialize === null || isUndefined(toSerialize)) return;
  9450. if (isArray(toSerialize)) {
  9451. forEach(toSerialize, function(value, index) {
  9452. serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
  9453. });
  9454. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  9455. forEachSorted(toSerialize, function(value, key) {
  9456. serialize(value, prefix +
  9457. (topLevel ? '' : '[') +
  9458. key +
  9459. (topLevel ? '' : ']'));
  9460. });
  9461. } else {
  9462. parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
  9463. }
  9464. }
  9465. };
  9466. };
  9467. }
  9468. function defaultHttpResponseTransform(data, headers) {
  9469. if (isString(data)) {
  9470. // Strip json vulnerability protection prefix and trim whitespace
  9471. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  9472. if (tempData) {
  9473. var contentType = headers('Content-Type');
  9474. if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
  9475. data = fromJson(tempData);
  9476. }
  9477. }
  9478. }
  9479. return data;
  9480. }
  9481. function isJsonLike(str) {
  9482. var jsonStart = str.match(JSON_START);
  9483. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  9484. }
  9485. /**
  9486. * Parse headers into key value object
  9487. *
  9488. * @param {string} headers Raw headers as a string
  9489. * @returns {Object} Parsed headers as key value object
  9490. */
  9491. function parseHeaders(headers) {
  9492. var parsed = createMap(), i;
  9493. function fillInParsed(key, val) {
  9494. if (key) {
  9495. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  9496. }
  9497. }
  9498. if (isString(headers)) {
  9499. forEach(headers.split('\n'), function(line) {
  9500. i = line.indexOf(':');
  9501. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  9502. });
  9503. } else if (isObject(headers)) {
  9504. forEach(headers, function(headerVal, headerKey) {
  9505. fillInParsed(lowercase(headerKey), trim(headerVal));
  9506. });
  9507. }
  9508. return parsed;
  9509. }
  9510. /**
  9511. * Returns a function that provides access to parsed headers.
  9512. *
  9513. * Headers are lazy parsed when first requested.
  9514. * @see parseHeaders
  9515. *
  9516. * @param {(string|Object)} headers Headers to provide access to.
  9517. * @returns {function(string=)} Returns a getter function which if called with:
  9518. *
  9519. * - if called with single an argument returns a single header value or null
  9520. * - if called with no arguments returns an object containing all headers.
  9521. */
  9522. function headersGetter(headers) {
  9523. var headersObj;
  9524. return function(name) {
  9525. if (!headersObj) headersObj = parseHeaders(headers);
  9526. if (name) {
  9527. var value = headersObj[lowercase(name)];
  9528. if (value === void 0) {
  9529. value = null;
  9530. }
  9531. return value;
  9532. }
  9533. return headersObj;
  9534. };
  9535. }
  9536. /**
  9537. * Chain all given functions
  9538. *
  9539. * This function is used for both request and response transforming
  9540. *
  9541. * @param {*} data Data to transform.
  9542. * @param {function(string=)} headers HTTP headers getter fn.
  9543. * @param {number} status HTTP status code of the response.
  9544. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  9545. * @returns {*} Transformed data.
  9546. */
  9547. function transformData(data, headers, status, fns) {
  9548. if (isFunction(fns)) {
  9549. return fns(data, headers, status);
  9550. }
  9551. forEach(fns, function(fn) {
  9552. data = fn(data, headers, status);
  9553. });
  9554. return data;
  9555. }
  9556. function isSuccess(status) {
  9557. return 200 <= status && status < 300;
  9558. }
  9559. /**
  9560. * @ngdoc provider
  9561. * @name $httpProvider
  9562. * @description
  9563. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  9564. * */
  9565. function $HttpProvider() {
  9566. /**
  9567. * @ngdoc property
  9568. * @name $httpProvider#defaults
  9569. * @description
  9570. *
  9571. * Object containing default values for all {@link ng.$http $http} requests.
  9572. *
  9573. * - **`defaults.cache`** - {boolean|Object} - A boolean value or object created with
  9574. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of HTTP responses
  9575. * by default. See {@link $http#caching $http Caching} for more information.
  9576. *
  9577. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  9578. * Defaults value is `'XSRF-TOKEN'`.
  9579. *
  9580. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  9581. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  9582. *
  9583. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  9584. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  9585. * setting default headers.
  9586. * - **`defaults.headers.common`**
  9587. * - **`defaults.headers.post`**
  9588. * - **`defaults.headers.put`**
  9589. * - **`defaults.headers.patch`**
  9590. *
  9591. *
  9592. * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
  9593. * used to the prepare string representation of request parameters (specified as an object).
  9594. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  9595. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  9596. *
  9597. **/
  9598. var defaults = this.defaults = {
  9599. // transform incoming response data
  9600. transformResponse: [defaultHttpResponseTransform],
  9601. // transform outgoing request data
  9602. transformRequest: [function(d) {
  9603. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  9604. }],
  9605. // default headers
  9606. headers: {
  9607. common: {
  9608. 'Accept': 'application/json, text/plain, */*'
  9609. },
  9610. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  9611. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  9612. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  9613. },
  9614. xsrfCookieName: 'XSRF-TOKEN',
  9615. xsrfHeaderName: 'X-XSRF-TOKEN',
  9616. paramSerializer: '$httpParamSerializer'
  9617. };
  9618. var useApplyAsync = false;
  9619. /**
  9620. * @ngdoc method
  9621. * @name $httpProvider#useApplyAsync
  9622. * @description
  9623. *
  9624. * Configure $http service to combine processing of multiple http responses received at around
  9625. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  9626. * significant performance improvement for bigger applications that make many HTTP requests
  9627. * concurrently (common during application bootstrap).
  9628. *
  9629. * Defaults to false. If no value is specified, returns the current configured value.
  9630. *
  9631. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  9632. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  9633. * to load and share the same digest cycle.
  9634. *
  9635. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  9636. * otherwise, returns the current configured value.
  9637. **/
  9638. this.useApplyAsync = function(value) {
  9639. if (isDefined(value)) {
  9640. useApplyAsync = !!value;
  9641. return this;
  9642. }
  9643. return useApplyAsync;
  9644. };
  9645. var useLegacyPromise = true;
  9646. /**
  9647. * @ngdoc method
  9648. * @name $httpProvider#useLegacyPromiseExtensions
  9649. * @description
  9650. *
  9651. * Configure `$http` service to return promises without the shorthand methods `success` and `error`.
  9652. * This should be used to make sure that applications work without these methods.
  9653. *
  9654. * Defaults to true. If no value is specified, returns the current configured value.
  9655. *
  9656. * @param {boolean=} value If true, `$http` will return a promise with the deprecated legacy `success` and `error` methods.
  9657. *
  9658. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  9659. * otherwise, returns the current configured value.
  9660. **/
  9661. this.useLegacyPromiseExtensions = function(value) {
  9662. if (isDefined(value)) {
  9663. useLegacyPromise = !!value;
  9664. return this;
  9665. }
  9666. return useLegacyPromise;
  9667. };
  9668. /**
  9669. * @ngdoc property
  9670. * @name $httpProvider#interceptors
  9671. * @description
  9672. *
  9673. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  9674. * pre-processing of request or postprocessing of responses.
  9675. *
  9676. * These service factories are ordered by request, i.e. they are applied in the same order as the
  9677. * array, on request, but reverse order, on response.
  9678. *
  9679. * {@link ng.$http#interceptors Interceptors detailed info}
  9680. **/
  9681. var interceptorFactories = this.interceptors = [];
  9682. this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
  9683. function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
  9684. var defaultCache = $cacheFactory('$http');
  9685. /**
  9686. * Make sure that default param serializer is exposed as a function
  9687. */
  9688. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  9689. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  9690. /**
  9691. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  9692. * The reversal is needed so that we can build up the interception chain around the
  9693. * server request.
  9694. */
  9695. var reversedInterceptors = [];
  9696. forEach(interceptorFactories, function(interceptorFactory) {
  9697. reversedInterceptors.unshift(isString(interceptorFactory)
  9698. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  9699. });
  9700. /**
  9701. * @ngdoc service
  9702. * @kind function
  9703. * @name $http
  9704. * @requires ng.$httpBackend
  9705. * @requires $cacheFactory
  9706. * @requires $rootScope
  9707. * @requires $q
  9708. * @requires $injector
  9709. *
  9710. * @description
  9711. * The `$http` service is a core Angular service that facilitates communication with the remote
  9712. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  9713. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  9714. *
  9715. * For unit testing applications that use `$http` service, see
  9716. * {@link ngMock.$httpBackend $httpBackend mock}.
  9717. *
  9718. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  9719. * $resource} service.
  9720. *
  9721. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  9722. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  9723. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  9724. *
  9725. *
  9726. * ## General usage
  9727. * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
  9728. * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
  9729. *
  9730. * ```js
  9731. * // Simple GET request example:
  9732. * $http({
  9733. * method: 'GET',
  9734. * url: '/someUrl'
  9735. * }).then(function successCallback(response) {
  9736. * // this callback will be called asynchronously
  9737. * // when the response is available
  9738. * }, function errorCallback(response) {
  9739. * // called asynchronously if an error occurs
  9740. * // or server returns response with an error status.
  9741. * });
  9742. * ```
  9743. *
  9744. * The response object has these properties:
  9745. *
  9746. * - **data** – `{string|Object}` – The response body transformed with the transform
  9747. * functions.
  9748. * - **status** – `{number}` – HTTP status code of the response.
  9749. * - **headers** – `{function([headerName])}` – Header getter function.
  9750. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  9751. * - **statusText** – `{string}` – HTTP status text of the response.
  9752. *
  9753. * A response status code between 200 and 299 is considered a success status and will result in
  9754. * the success callback being called. Any response status code outside of that range is
  9755. * considered an error status and will result in the error callback being called.
  9756. * Also, status codes less than -1 are normalized to zero. -1 usually means the request was
  9757. * aborted, e.g. using a `config.timeout`.
  9758. * Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning
  9759. * that the outcome (success or error) will be determined by the final response status code.
  9760. *
  9761. *
  9762. * ## Shortcut methods
  9763. *
  9764. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  9765. * request data must be passed in for POST/PUT requests. An optional config can be passed as the
  9766. * last argument.
  9767. *
  9768. * ```js
  9769. * $http.get('/someUrl', config).then(successCallback, errorCallback);
  9770. * $http.post('/someUrl', data, config).then(successCallback, errorCallback);
  9771. * ```
  9772. *
  9773. * Complete list of shortcut methods:
  9774. *
  9775. * - {@link ng.$http#get $http.get}
  9776. * - {@link ng.$http#head $http.head}
  9777. * - {@link ng.$http#post $http.post}
  9778. * - {@link ng.$http#put $http.put}
  9779. * - {@link ng.$http#delete $http.delete}
  9780. * - {@link ng.$http#jsonp $http.jsonp}
  9781. * - {@link ng.$http#patch $http.patch}
  9782. *
  9783. *
  9784. * ## Writing Unit Tests that use $http
  9785. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  9786. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  9787. * request using trained responses.
  9788. *
  9789. * ```
  9790. * $httpBackend.expectGET(...);
  9791. * $http.get(...);
  9792. * $httpBackend.flush();
  9793. * ```
  9794. *
  9795. * ## Deprecation Notice
  9796. * <div class="alert alert-danger">
  9797. * The `$http` legacy promise methods `success` and `error` have been deprecated.
  9798. * Use the standard `then` method instead.
  9799. * If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to
  9800. * `false` then these methods will throw {@link $http:legacy `$http/legacy`} error.
  9801. * </div>
  9802. *
  9803. * ## Setting HTTP Headers
  9804. *
  9805. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  9806. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  9807. * object, which currently contains this default configuration:
  9808. *
  9809. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  9810. * - `Accept: application/json, text/plain, * / *`
  9811. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  9812. * - `Content-Type: application/json`
  9813. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  9814. * - `Content-Type: application/json`
  9815. *
  9816. * To add or overwrite these defaults, simply add or remove a property from these configuration
  9817. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  9818. * with the lowercased HTTP method name as the key, e.g.
  9819. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  9820. *
  9821. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  9822. * fashion. For example:
  9823. *
  9824. * ```
  9825. * module.run(function($http) {
  9826. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
  9827. * });
  9828. * ```
  9829. *
  9830. * In addition, you can supply a `headers` property in the config object passed when
  9831. * calling `$http(config)`, which overrides the defaults without changing them globally.
  9832. *
  9833. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  9834. * Use the `headers` property, setting the desired header to `undefined`. For example:
  9835. *
  9836. * ```js
  9837. * var req = {
  9838. * method: 'POST',
  9839. * url: 'http://example.com',
  9840. * headers: {
  9841. * 'Content-Type': undefined
  9842. * },
  9843. * data: { test: 'test' }
  9844. * }
  9845. *
  9846. * $http(req).then(function(){...}, function(){...});
  9847. * ```
  9848. *
  9849. * ## Transforming Requests and Responses
  9850. *
  9851. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  9852. * and `transformResponse`. These properties can be a single function that returns
  9853. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  9854. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  9855. *
  9856. * <div class="alert alert-warning">
  9857. * **Note:** Angular does not make a copy of the `data` parameter before it is passed into the `transformRequest` pipeline.
  9858. * That means changes to the properties of `data` are not local to the transform function (since Javascript passes objects by reference).
  9859. * For example, when calling `$http.get(url, $scope.myObject)`, modifications to the object's properties in a transformRequest
  9860. * function will be reflected on the scope and in any templates where the object is data-bound.
  9861. * To prevent this, transform functions should have no side-effects.
  9862. * If you need to modify properties, it is recommended to make a copy of the data, or create new object to return.
  9863. * </div>
  9864. *
  9865. * ### Default Transformations
  9866. *
  9867. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  9868. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  9869. * then these will be applied.
  9870. *
  9871. * You can augment or replace the default transformations by modifying these properties by adding to or
  9872. * replacing the array.
  9873. *
  9874. * Angular provides the following default transformations:
  9875. *
  9876. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  9877. *
  9878. * - If the `data` property of the request configuration object contains an object, serialize it
  9879. * into JSON format.
  9880. *
  9881. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  9882. *
  9883. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  9884. * - If JSON response is detected, deserialize it using a JSON parser.
  9885. *
  9886. *
  9887. * ### Overriding the Default Transformations Per Request
  9888. *
  9889. * If you wish override the request/response transformations only for a single request then provide
  9890. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  9891. * into `$http`.
  9892. *
  9893. * Note that if you provide these properties on the config object the default transformations will be
  9894. * overwritten. If you wish to augment the default transformations then you must include them in your
  9895. * local transformation array.
  9896. *
  9897. * The following code demonstrates adding a new response transformation to be run after the default response
  9898. * transformations have been run.
  9899. *
  9900. * ```js
  9901. * function appendTransform(defaults, transform) {
  9902. *
  9903. * // We can't guarantee that the default transformation is an array
  9904. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  9905. *
  9906. * // Append the new transformation to the defaults
  9907. * return defaults.concat(transform);
  9908. * }
  9909. *
  9910. * $http({
  9911. * url: '...',
  9912. * method: 'GET',
  9913. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  9914. * return doTransform(value);
  9915. * })
  9916. * });
  9917. * ```
  9918. *
  9919. *
  9920. * ## Caching
  9921. *
  9922. * {@link ng.$http `$http`} responses are not cached by default. To enable caching, you must
  9923. * set the config.cache value or the default cache value to TRUE or to a cache object (created
  9924. * with {@link ng.$cacheFactory `$cacheFactory`}). If defined, the value of config.cache takes
  9925. * precedence over the default cache value.
  9926. *
  9927. * In order to:
  9928. * * cache all responses - set the default cache value to TRUE or to a cache object
  9929. * * cache a specific response - set config.cache value to TRUE or to a cache object
  9930. *
  9931. * If caching is enabled, but neither the default cache nor config.cache are set to a cache object,
  9932. * then the default `$cacheFactory($http)` object is used.
  9933. *
  9934. * The default cache value can be set by updating the
  9935. * {@link ng.$http#defaults `$http.defaults.cache`} property or the
  9936. * {@link $httpProvider#defaults `$httpProvider.defaults.cache`} property.
  9937. *
  9938. * When caching is enabled, {@link ng.$http `$http`} stores the response from the server using
  9939. * the relevant cache object. The next time the same request is made, the response is returned
  9940. * from the cache without sending a request to the server.
  9941. *
  9942. * Take note that:
  9943. *
  9944. * * Only GET and JSONP requests are cached.
  9945. * * The cache key is the request URL including search parameters; headers are not considered.
  9946. * * Cached responses are returned asynchronously, in the same way as responses from the server.
  9947. * * If multiple identical requests are made using the same cache, which is not yet populated,
  9948. * one request will be made to the server and remaining requests will return the same response.
  9949. * * A cache-control header on the response does not affect if or how responses are cached.
  9950. *
  9951. *
  9952. * ## Interceptors
  9953. *
  9954. * Before you start creating interceptors, be sure to understand the
  9955. * {@link ng.$q $q and deferred/promise APIs}.
  9956. *
  9957. * For purposes of global error handling, authentication, or any kind of synchronous or
  9958. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  9959. * able to intercept requests before they are handed to the server and
  9960. * responses before they are handed over to the application code that
  9961. * initiated these requests. The interceptors leverage the {@link ng.$q
  9962. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  9963. *
  9964. * The interceptors are service factories that are registered with the `$httpProvider` by
  9965. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  9966. * injected with dependencies (if specified) and returns the interceptor.
  9967. *
  9968. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  9969. *
  9970. * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
  9971. * modify the `config` object or create a new one. The function needs to return the `config`
  9972. * object directly, or a promise containing the `config` or a new `config` object.
  9973. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  9974. * resolved with a rejection.
  9975. * * `response`: interceptors get called with http `response` object. The function is free to
  9976. * modify the `response` object or create a new one. The function needs to return the `response`
  9977. * object directly, or as a promise containing the `response` or a new `response` object.
  9978. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  9979. * resolved with a rejection.
  9980. *
  9981. *
  9982. * ```js
  9983. * // register the interceptor as a service
  9984. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  9985. * return {
  9986. * // optional method
  9987. * 'request': function(config) {
  9988. * // do something on success
  9989. * return config;
  9990. * },
  9991. *
  9992. * // optional method
  9993. * 'requestError': function(rejection) {
  9994. * // do something on error
  9995. * if (canRecover(rejection)) {
  9996. * return responseOrNewPromise
  9997. * }
  9998. * return $q.reject(rejection);
  9999. * },
  10000. *
  10001. *
  10002. *
  10003. * // optional method
  10004. * 'response': function(response) {
  10005. * // do something on success
  10006. * return response;
  10007. * },
  10008. *
  10009. * // optional method
  10010. * 'responseError': function(rejection) {
  10011. * // do something on error
  10012. * if (canRecover(rejection)) {
  10013. * return responseOrNewPromise
  10014. * }
  10015. * return $q.reject(rejection);
  10016. * }
  10017. * };
  10018. * });
  10019. *
  10020. * $httpProvider.interceptors.push('myHttpInterceptor');
  10021. *
  10022. *
  10023. * // alternatively, register the interceptor via an anonymous factory
  10024. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  10025. * return {
  10026. * 'request': function(config) {
  10027. * // same as above
  10028. * },
  10029. *
  10030. * 'response': function(response) {
  10031. * // same as above
  10032. * }
  10033. * };
  10034. * });
  10035. * ```
  10036. *
  10037. * ## Security Considerations
  10038. *
  10039. * When designing web applications, consider security threats from:
  10040. *
  10041. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  10042. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  10043. *
  10044. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  10045. * pre-configured with strategies that address these issues, but for this to work backend server
  10046. * cooperation is required.
  10047. *
  10048. * ### JSON Vulnerability Protection
  10049. *
  10050. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  10051. * allows third party website to turn your JSON resource URL into
  10052. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  10053. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  10054. * Angular will automatically strip the prefix before processing it as JSON.
  10055. *
  10056. * For example if your server needs to return:
  10057. * ```js
  10058. * ['one','two']
  10059. * ```
  10060. *
  10061. * which is vulnerable to attack, your server can return:
  10062. * ```js
  10063. * )]}',
  10064. * ['one','two']
  10065. * ```
  10066. *
  10067. * Angular will strip the prefix, before processing the JSON.
  10068. *
  10069. *
  10070. * ### Cross Site Request Forgery (XSRF) Protection
  10071. *
  10072. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by
  10073. * which the attacker can trick an authenticated user into unknowingly executing actions on your
  10074. * website. Angular provides a mechanism to counter XSRF. When performing XHR requests, the
  10075. * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP
  10076. * header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the
  10077. * cookie, your server can be assured that the XHR came from JavaScript running on your domain.
  10078. * The header will not be set for cross-domain requests.
  10079. *
  10080. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  10081. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  10082. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  10083. * that only JavaScript running on your domain could have sent the request. The token must be
  10084. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  10085. * making up its own tokens). We recommend that the token is a digest of your site's
  10086. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  10087. * for added security.
  10088. *
  10089. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  10090. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  10091. * or the per-request config object.
  10092. *
  10093. * In order to prevent collisions in environments where multiple Angular apps share the
  10094. * same domain or subdomain, we recommend that each application uses unique cookie name.
  10095. *
  10096. * @param {object} config Object describing the request to be made and how it should be
  10097. * processed. The object has following properties:
  10098. *
  10099. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  10100. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  10101. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
  10102. * with the `paramSerializer` and appended as GET parameters.
  10103. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  10104. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  10105. * HTTP headers to send to the server. If the return value of a function is null, the
  10106. * header will not be sent. Functions accept a config object as an argument.
  10107. * - **eventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest object.
  10108. * To bind events to the XMLHttpRequest upload object, use `uploadEventHandlers`.
  10109. * The handler will be called in the context of a `$apply` block.
  10110. * - **uploadEventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest upload
  10111. * object. To bind events to the XMLHttpRequest object, use `eventHandlers`.
  10112. * The handler will be called in the context of a `$apply` block.
  10113. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  10114. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  10115. * - **transformRequest** –
  10116. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  10117. * transform function or an array of such functions. The transform function takes the http
  10118. * request body and headers and returns its transformed (typically serialized) version.
  10119. * See {@link ng.$http#overriding-the-default-transformations-per-request
  10120. * Overriding the Default Transformations}
  10121. * - **transformResponse** –
  10122. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  10123. * transform function or an array of such functions. The transform function takes the http
  10124. * response body, headers and status and returns its transformed (typically deserialized) version.
  10125. * See {@link ng.$http#overriding-the-default-transformations-per-request
  10126. * Overriding the Default Transformations}
  10127. * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
  10128. * prepare the string representation of request parameters (specified as an object).
  10129. * If specified as string, it is interpreted as function registered with the
  10130. * {@link $injector $injector}, which means you can create your own serializer
  10131. * by registering it as a {@link auto.$provide#service service}.
  10132. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
  10133. * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
  10134. * - **cache** – `{boolean|Object}` – A boolean value or object created with
  10135. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response.
  10136. * See {@link $http#caching $http Caching} for more information.
  10137. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  10138. * that should abort the request when resolved.
  10139. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  10140. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  10141. * for more information.
  10142. * - **responseType** - `{string}` - see
  10143. * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
  10144. *
  10145. * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
  10146. * when the request succeeds or fails.
  10147. *
  10148. *
  10149. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  10150. * requests. This is primarily meant to be used for debugging purposes.
  10151. *
  10152. *
  10153. * @example
  10154. <example module="httpExample">
  10155. <file name="index.html">
  10156. <div ng-controller="FetchController">
  10157. <select ng-model="method" aria-label="Request method">
  10158. <option>GET</option>
  10159. <option>JSONP</option>
  10160. </select>
  10161. <input type="text" ng-model="url" size="80" aria-label="URL" />
  10162. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  10163. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  10164. <button id="samplejsonpbtn"
  10165. ng-click="updateModel('JSONP',
  10166. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  10167. Sample JSONP
  10168. </button>
  10169. <button id="invalidjsonpbtn"
  10170. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  10171. Invalid JSONP
  10172. </button>
  10173. <pre>http status code: {{status}}</pre>
  10174. <pre>http response data: {{data}}</pre>
  10175. </div>
  10176. </file>
  10177. <file name="script.js">
  10178. angular.module('httpExample', [])
  10179. .controller('FetchController', ['$scope', '$http', '$templateCache',
  10180. function($scope, $http, $templateCache) {
  10181. $scope.method = 'GET';
  10182. $scope.url = 'http-hello.html';
  10183. $scope.fetch = function() {
  10184. $scope.code = null;
  10185. $scope.response = null;
  10186. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  10187. then(function(response) {
  10188. $scope.status = response.status;
  10189. $scope.data = response.data;
  10190. }, function(response) {
  10191. $scope.data = response.data || "Request failed";
  10192. $scope.status = response.status;
  10193. });
  10194. };
  10195. $scope.updateModel = function(method, url) {
  10196. $scope.method = method;
  10197. $scope.url = url;
  10198. };
  10199. }]);
  10200. </file>
  10201. <file name="http-hello.html">
  10202. Hello, $http!
  10203. </file>
  10204. <file name="protractor.js" type="protractor">
  10205. var status = element(by.binding('status'));
  10206. var data = element(by.binding('data'));
  10207. var fetchBtn = element(by.id('fetchbtn'));
  10208. var sampleGetBtn = element(by.id('samplegetbtn'));
  10209. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  10210. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  10211. it('should make an xhr GET request', function() {
  10212. sampleGetBtn.click();
  10213. fetchBtn.click();
  10214. expect(status.getText()).toMatch('200');
  10215. expect(data.getText()).toMatch(/Hello, \$http!/);
  10216. });
  10217. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  10218. // it('should make a JSONP request to angularjs.org', function() {
  10219. // sampleJsonpBtn.click();
  10220. // fetchBtn.click();
  10221. // expect(status.getText()).toMatch('200');
  10222. // expect(data.getText()).toMatch(/Super Hero!/);
  10223. // });
  10224. it('should make JSONP request to invalid URL and invoke the error handler',
  10225. function() {
  10226. invalidJsonpBtn.click();
  10227. fetchBtn.click();
  10228. expect(status.getText()).toMatch('0');
  10229. expect(data.getText()).toMatch('Request failed');
  10230. });
  10231. </file>
  10232. </example>
  10233. */
  10234. function $http(requestConfig) {
  10235. if (!isObject(requestConfig)) {
  10236. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  10237. }
  10238. if (!isString(requestConfig.url)) {
  10239. throw minErr('$http')('badreq', 'Http request configuration url must be a string. Received: {0}', requestConfig.url);
  10240. }
  10241. var config = extend({
  10242. method: 'get',
  10243. transformRequest: defaults.transformRequest,
  10244. transformResponse: defaults.transformResponse,
  10245. paramSerializer: defaults.paramSerializer
  10246. }, requestConfig);
  10247. config.headers = mergeHeaders(requestConfig);
  10248. config.method = uppercase(config.method);
  10249. config.paramSerializer = isString(config.paramSerializer) ?
  10250. $injector.get(config.paramSerializer) : config.paramSerializer;
  10251. var serverRequest = function(config) {
  10252. var headers = config.headers;
  10253. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  10254. // strip content-type if data is undefined
  10255. if (isUndefined(reqData)) {
  10256. forEach(headers, function(value, header) {
  10257. if (lowercase(header) === 'content-type') {
  10258. delete headers[header];
  10259. }
  10260. });
  10261. }
  10262. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  10263. config.withCredentials = defaults.withCredentials;
  10264. }
  10265. // send request
  10266. return sendReq(config, reqData).then(transformResponse, transformResponse);
  10267. };
  10268. var chain = [serverRequest, undefined];
  10269. var promise = $q.when(config);
  10270. // apply interceptors
  10271. forEach(reversedInterceptors, function(interceptor) {
  10272. if (interceptor.request || interceptor.requestError) {
  10273. chain.unshift(interceptor.request, interceptor.requestError);
  10274. }
  10275. if (interceptor.response || interceptor.responseError) {
  10276. chain.push(interceptor.response, interceptor.responseError);
  10277. }
  10278. });
  10279. while (chain.length) {
  10280. var thenFn = chain.shift();
  10281. var rejectFn = chain.shift();
  10282. promise = promise.then(thenFn, rejectFn);
  10283. }
  10284. if (useLegacyPromise) {
  10285. promise.success = function(fn) {
  10286. assertArgFn(fn, 'fn');
  10287. promise.then(function(response) {
  10288. fn(response.data, response.status, response.headers, config);
  10289. });
  10290. return promise;
  10291. };
  10292. promise.error = function(fn) {
  10293. assertArgFn(fn, 'fn');
  10294. promise.then(null, function(response) {
  10295. fn(response.data, response.status, response.headers, config);
  10296. });
  10297. return promise;
  10298. };
  10299. } else {
  10300. promise.success = $httpMinErrLegacyFn('success');
  10301. promise.error = $httpMinErrLegacyFn('error');
  10302. }
  10303. return promise;
  10304. function transformResponse(response) {
  10305. // make a copy since the response must be cacheable
  10306. var resp = extend({}, response);
  10307. resp.data = transformData(response.data, response.headers, response.status,
  10308. config.transformResponse);
  10309. return (isSuccess(response.status))
  10310. ? resp
  10311. : $q.reject(resp);
  10312. }
  10313. function executeHeaderFns(headers, config) {
  10314. var headerContent, processedHeaders = {};
  10315. forEach(headers, function(headerFn, header) {
  10316. if (isFunction(headerFn)) {
  10317. headerContent = headerFn(config);
  10318. if (headerContent != null) {
  10319. processedHeaders[header] = headerContent;
  10320. }
  10321. } else {
  10322. processedHeaders[header] = headerFn;
  10323. }
  10324. });
  10325. return processedHeaders;
  10326. }
  10327. function mergeHeaders(config) {
  10328. var defHeaders = defaults.headers,
  10329. reqHeaders = extend({}, config.headers),
  10330. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  10331. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  10332. // using for-in instead of forEach to avoid unnecessary iteration after header has been found
  10333. defaultHeadersIteration:
  10334. for (defHeaderName in defHeaders) {
  10335. lowercaseDefHeaderName = lowercase(defHeaderName);
  10336. for (reqHeaderName in reqHeaders) {
  10337. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  10338. continue defaultHeadersIteration;
  10339. }
  10340. }
  10341. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  10342. }
  10343. // execute if header value is a function for merged headers
  10344. return executeHeaderFns(reqHeaders, shallowCopy(config));
  10345. }
  10346. }
  10347. $http.pendingRequests = [];
  10348. /**
  10349. * @ngdoc method
  10350. * @name $http#get
  10351. *
  10352. * @description
  10353. * Shortcut method to perform `GET` request.
  10354. *
  10355. * @param {string} url Relative or absolute URL specifying the destination of the request
  10356. * @param {Object=} config Optional configuration object
  10357. * @returns {HttpPromise} Future object
  10358. */
  10359. /**
  10360. * @ngdoc method
  10361. * @name $http#delete
  10362. *
  10363. * @description
  10364. * Shortcut method to perform `DELETE` request.
  10365. *
  10366. * @param {string} url Relative or absolute URL specifying the destination of the request
  10367. * @param {Object=} config Optional configuration object
  10368. * @returns {HttpPromise} Future object
  10369. */
  10370. /**
  10371. * @ngdoc method
  10372. * @name $http#head
  10373. *
  10374. * @description
  10375. * Shortcut method to perform `HEAD` request.
  10376. *
  10377. * @param {string} url Relative or absolute URL specifying the destination of the request
  10378. * @param {Object=} config Optional configuration object
  10379. * @returns {HttpPromise} Future object
  10380. */
  10381. /**
  10382. * @ngdoc method
  10383. * @name $http#jsonp
  10384. *
  10385. * @description
  10386. * Shortcut method to perform `JSONP` request.
  10387. *
  10388. * @param {string} url Relative or absolute URL specifying the destination of the request.
  10389. * The name of the callback should be the string `JSON_CALLBACK`.
  10390. * @param {Object=} config Optional configuration object
  10391. * @returns {HttpPromise} Future object
  10392. */
  10393. createShortMethods('get', 'delete', 'head', 'jsonp');
  10394. /**
  10395. * @ngdoc method
  10396. * @name $http#post
  10397. *
  10398. * @description
  10399. * Shortcut method to perform `POST` request.
  10400. *
  10401. * @param {string} url Relative or absolute URL specifying the destination of the request
  10402. * @param {*} data Request content
  10403. * @param {Object=} config Optional configuration object
  10404. * @returns {HttpPromise} Future object
  10405. */
  10406. /**
  10407. * @ngdoc method
  10408. * @name $http#put
  10409. *
  10410. * @description
  10411. * Shortcut method to perform `PUT` request.
  10412. *
  10413. * @param {string} url Relative or absolute URL specifying the destination of the request
  10414. * @param {*} data Request content
  10415. * @param {Object=} config Optional configuration object
  10416. * @returns {HttpPromise} Future object
  10417. */
  10418. /**
  10419. * @ngdoc method
  10420. * @name $http#patch
  10421. *
  10422. * @description
  10423. * Shortcut method to perform `PATCH` request.
  10424. *
  10425. * @param {string} url Relative or absolute URL specifying the destination of the request
  10426. * @param {*} data Request content
  10427. * @param {Object=} config Optional configuration object
  10428. * @returns {HttpPromise} Future object
  10429. */
  10430. createShortMethodsWithData('post', 'put', 'patch');
  10431. /**
  10432. * @ngdoc property
  10433. * @name $http#defaults
  10434. *
  10435. * @description
  10436. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  10437. * default headers, withCredentials as well as request and response transformations.
  10438. *
  10439. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  10440. */
  10441. $http.defaults = defaults;
  10442. return $http;
  10443. function createShortMethods(names) {
  10444. forEach(arguments, function(name) {
  10445. $http[name] = function(url, config) {
  10446. return $http(extend({}, config || {}, {
  10447. method: name,
  10448. url: url
  10449. }));
  10450. };
  10451. });
  10452. }
  10453. function createShortMethodsWithData(name) {
  10454. forEach(arguments, function(name) {
  10455. $http[name] = function(url, data, config) {
  10456. return $http(extend({}, config || {}, {
  10457. method: name,
  10458. url: url,
  10459. data: data
  10460. }));
  10461. };
  10462. });
  10463. }
  10464. /**
  10465. * Makes the request.
  10466. *
  10467. * !!! ACCESSES CLOSURE VARS:
  10468. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  10469. */
  10470. function sendReq(config, reqData) {
  10471. var deferred = $q.defer(),
  10472. promise = deferred.promise,
  10473. cache,
  10474. cachedResp,
  10475. reqHeaders = config.headers,
  10476. url = buildUrl(config.url, config.paramSerializer(config.params));
  10477. $http.pendingRequests.push(config);
  10478. promise.then(removePendingReq, removePendingReq);
  10479. if ((config.cache || defaults.cache) && config.cache !== false &&
  10480. (config.method === 'GET' || config.method === 'JSONP')) {
  10481. cache = isObject(config.cache) ? config.cache
  10482. : isObject(defaults.cache) ? defaults.cache
  10483. : defaultCache;
  10484. }
  10485. if (cache) {
  10486. cachedResp = cache.get(url);
  10487. if (isDefined(cachedResp)) {
  10488. if (isPromiseLike(cachedResp)) {
  10489. // cached request has already been sent, but there is no response yet
  10490. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  10491. } else {
  10492. // serving from cache
  10493. if (isArray(cachedResp)) {
  10494. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  10495. } else {
  10496. resolvePromise(cachedResp, 200, {}, 'OK');
  10497. }
  10498. }
  10499. } else {
  10500. // put the promise for the non-transformed response into cache as a placeholder
  10501. cache.put(url, promise);
  10502. }
  10503. }
  10504. // if we won't have the response in cache, set the xsrf headers and
  10505. // send the request to the backend
  10506. if (isUndefined(cachedResp)) {
  10507. var xsrfValue = urlIsSameOrigin(config.url)
  10508. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  10509. : undefined;
  10510. if (xsrfValue) {
  10511. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  10512. }
  10513. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  10514. config.withCredentials, config.responseType,
  10515. createApplyHandlers(config.eventHandlers),
  10516. createApplyHandlers(config.uploadEventHandlers));
  10517. }
  10518. return promise;
  10519. function createApplyHandlers(eventHandlers) {
  10520. if (eventHandlers) {
  10521. var applyHandlers = {};
  10522. forEach(eventHandlers, function(eventHandler, key) {
  10523. applyHandlers[key] = function(event) {
  10524. if (useApplyAsync) {
  10525. $rootScope.$applyAsync(callEventHandler);
  10526. } else if ($rootScope.$$phase) {
  10527. callEventHandler();
  10528. } else {
  10529. $rootScope.$apply(callEventHandler);
  10530. }
  10531. function callEventHandler() {
  10532. eventHandler(event);
  10533. }
  10534. };
  10535. });
  10536. return applyHandlers;
  10537. }
  10538. }
  10539. /**
  10540. * Callback registered to $httpBackend():
  10541. * - caches the response if desired
  10542. * - resolves the raw $http promise
  10543. * - calls $apply
  10544. */
  10545. function done(status, response, headersString, statusText) {
  10546. if (cache) {
  10547. if (isSuccess(status)) {
  10548. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  10549. } else {
  10550. // remove promise from the cache
  10551. cache.remove(url);
  10552. }
  10553. }
  10554. function resolveHttpPromise() {
  10555. resolvePromise(response, status, headersString, statusText);
  10556. }
  10557. if (useApplyAsync) {
  10558. $rootScope.$applyAsync(resolveHttpPromise);
  10559. } else {
  10560. resolveHttpPromise();
  10561. if (!$rootScope.$$phase) $rootScope.$apply();
  10562. }
  10563. }
  10564. /**
  10565. * Resolves the raw $http promise.
  10566. */
  10567. function resolvePromise(response, status, headers, statusText) {
  10568. //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
  10569. status = status >= -1 ? status : 0;
  10570. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  10571. data: response,
  10572. status: status,
  10573. headers: headersGetter(headers),
  10574. config: config,
  10575. statusText: statusText
  10576. });
  10577. }
  10578. function resolvePromiseWithResult(result) {
  10579. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
  10580. }
  10581. function removePendingReq() {
  10582. var idx = $http.pendingRequests.indexOf(config);
  10583. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  10584. }
  10585. }
  10586. function buildUrl(url, serializedParams) {
  10587. if (serializedParams.length > 0) {
  10588. url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
  10589. }
  10590. return url;
  10591. }
  10592. }];
  10593. }
  10594. /**
  10595. * @ngdoc service
  10596. * @name $xhrFactory
  10597. *
  10598. * @description
  10599. * Factory function used to create XMLHttpRequest objects.
  10600. *
  10601. * Replace or decorate this service to create your own custom XMLHttpRequest objects.
  10602. *
  10603. * ```
  10604. * angular.module('myApp', [])
  10605. * .factory('$xhrFactory', function() {
  10606. * return function createXhr(method, url) {
  10607. * return new window.XMLHttpRequest({mozSystem: true});
  10608. * };
  10609. * });
  10610. * ```
  10611. *
  10612. * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
  10613. * @param {string} url URL of the request.
  10614. */
  10615. function $xhrFactoryProvider() {
  10616. this.$get = function() {
  10617. return function createXhr() {
  10618. return new window.XMLHttpRequest();
  10619. };
  10620. };
  10621. }
  10622. /**
  10623. * @ngdoc service
  10624. * @name $httpBackend
  10625. * @requires $window
  10626. * @requires $document
  10627. * @requires $xhrFactory
  10628. *
  10629. * @description
  10630. * HTTP backend used by the {@link ng.$http service} that delegates to
  10631. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  10632. *
  10633. * You should never need to use this service directly, instead use the higher-level abstractions:
  10634. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  10635. *
  10636. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  10637. * $httpBackend} which can be trained with responses.
  10638. */
  10639. function $HttpBackendProvider() {
  10640. this.$get = ['$browser', '$window', '$document', '$xhrFactory', function($browser, $window, $document, $xhrFactory) {
  10641. return createHttpBackend($browser, $xhrFactory, $browser.defer, $window.angular.callbacks, $document[0]);
  10642. }];
  10643. }
  10644. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  10645. // TODO(vojta): fix the signature
  10646. return function(method, url, post, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) {
  10647. $browser.$$incOutstandingRequestCount();
  10648. url = url || $browser.url();
  10649. if (lowercase(method) == 'jsonp') {
  10650. var callbackId = '_' + (callbacks.counter++).toString(36);
  10651. callbacks[callbackId] = function(data) {
  10652. callbacks[callbackId].data = data;
  10653. callbacks[callbackId].called = true;
  10654. };
  10655. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  10656. callbackId, function(status, text) {
  10657. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  10658. callbacks[callbackId] = noop;
  10659. });
  10660. } else {
  10661. var xhr = createXhr(method, url);
  10662. xhr.open(method, url, true);
  10663. forEach(headers, function(value, key) {
  10664. if (isDefined(value)) {
  10665. xhr.setRequestHeader(key, value);
  10666. }
  10667. });
  10668. xhr.onload = function requestLoaded() {
  10669. var statusText = xhr.statusText || '';
  10670. // responseText is the old-school way of retrieving response (supported by IE9)
  10671. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  10672. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  10673. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  10674. var status = xhr.status === 1223 ? 204 : xhr.status;
  10675. // fix status code when it is 0 (0 status is undocumented).
  10676. // Occurs when accessing file resources or on Android 4.1 stock browser
  10677. // while retrieving files from application cache.
  10678. if (status === 0) {
  10679. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  10680. }
  10681. completeRequest(callback,
  10682. status,
  10683. response,
  10684. xhr.getAllResponseHeaders(),
  10685. statusText);
  10686. };
  10687. var requestError = function() {
  10688. // The response is always empty
  10689. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  10690. completeRequest(callback, -1, null, null, '');
  10691. };
  10692. xhr.onerror = requestError;
  10693. xhr.onabort = requestError;
  10694. forEach(eventHandlers, function(value, key) {
  10695. xhr.addEventListener(key, value);
  10696. });
  10697. forEach(uploadEventHandlers, function(value, key) {
  10698. xhr.upload.addEventListener(key, value);
  10699. });
  10700. if (withCredentials) {
  10701. xhr.withCredentials = true;
  10702. }
  10703. if (responseType) {
  10704. try {
  10705. xhr.responseType = responseType;
  10706. } catch (e) {
  10707. // WebKit added support for the json responseType value on 09/03/2013
  10708. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  10709. // known to throw when setting the value "json" as the response type. Other older
  10710. // browsers implementing the responseType
  10711. //
  10712. // The json response type can be ignored if not supported, because JSON payloads are
  10713. // parsed on the client-side regardless.
  10714. if (responseType !== 'json') {
  10715. throw e;
  10716. }
  10717. }
  10718. }
  10719. xhr.send(isUndefined(post) ? null : post);
  10720. }
  10721. if (timeout > 0) {
  10722. var timeoutId = $browserDefer(timeoutRequest, timeout);
  10723. } else if (isPromiseLike(timeout)) {
  10724. timeout.then(timeoutRequest);
  10725. }
  10726. function timeoutRequest() {
  10727. jsonpDone && jsonpDone();
  10728. xhr && xhr.abort();
  10729. }
  10730. function completeRequest(callback, status, response, headersString, statusText) {
  10731. // cancel timeout and subsequent timeout promise resolution
  10732. if (isDefined(timeoutId)) {
  10733. $browserDefer.cancel(timeoutId);
  10734. }
  10735. jsonpDone = xhr = null;
  10736. callback(status, response, headersString, statusText);
  10737. $browser.$$completeOutstandingRequest(noop);
  10738. }
  10739. };
  10740. function jsonpReq(url, callbackId, done) {
  10741. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  10742. // - fetches local scripts via XHR and evals them
  10743. // - adds and immediately removes script elements from the document
  10744. var script = rawDocument.createElement('script'), callback = null;
  10745. script.type = "text/javascript";
  10746. script.src = url;
  10747. script.async = true;
  10748. callback = function(event) {
  10749. removeEventListenerFn(script, "load", callback);
  10750. removeEventListenerFn(script, "error", callback);
  10751. rawDocument.body.removeChild(script);
  10752. script = null;
  10753. var status = -1;
  10754. var text = "unknown";
  10755. if (event) {
  10756. if (event.type === "load" && !callbacks[callbackId].called) {
  10757. event = { type: "error" };
  10758. }
  10759. text = event.type;
  10760. status = event.type === "error" ? 404 : 200;
  10761. }
  10762. if (done) {
  10763. done(status, text);
  10764. }
  10765. };
  10766. addEventListenerFn(script, "load", callback);
  10767. addEventListenerFn(script, "error", callback);
  10768. rawDocument.body.appendChild(script);
  10769. return callback;
  10770. }
  10771. }
  10772. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  10773. $interpolateMinErr.throwNoconcat = function(text) {
  10774. throw $interpolateMinErr('noconcat',
  10775. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  10776. "interpolations that concatenate multiple expressions when a trusted value is " +
  10777. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  10778. };
  10779. $interpolateMinErr.interr = function(text, err) {
  10780. return $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
  10781. };
  10782. /**
  10783. * @ngdoc provider
  10784. * @name $interpolateProvider
  10785. *
  10786. * @description
  10787. *
  10788. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  10789. *
  10790. * <div class="alert alert-danger">
  10791. * This feature is sometimes used to mix different markup languages, e.g. to wrap an Angular
  10792. * template within a Python Jinja template (or any other template language). Mixing templating
  10793. * languages is **very dangerous**. The embedding template language will not safely escape Angular
  10794. * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)
  10795. * security bugs!
  10796. * </div>
  10797. *
  10798. * @example
  10799. <example name="custom-interpolation-markup" module="customInterpolationApp">
  10800. <file name="index.html">
  10801. <script>
  10802. var customInterpolationApp = angular.module('customInterpolationApp', []);
  10803. customInterpolationApp.config(function($interpolateProvider) {
  10804. $interpolateProvider.startSymbol('//');
  10805. $interpolateProvider.endSymbol('//');
  10806. });
  10807. customInterpolationApp.controller('DemoController', function() {
  10808. this.label = "This binding is brought you by // interpolation symbols.";
  10809. });
  10810. </script>
  10811. <div ng-controller="DemoController as demo">
  10812. //demo.label//
  10813. </div>
  10814. </file>
  10815. <file name="protractor.js" type="protractor">
  10816. it('should interpolate binding with custom symbols', function() {
  10817. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  10818. });
  10819. </file>
  10820. </example>
  10821. */
  10822. function $InterpolateProvider() {
  10823. var startSymbol = '{{';
  10824. var endSymbol = '}}';
  10825. /**
  10826. * @ngdoc method
  10827. * @name $interpolateProvider#startSymbol
  10828. * @description
  10829. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  10830. *
  10831. * @param {string=} value new value to set the starting symbol to.
  10832. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  10833. */
  10834. this.startSymbol = function(value) {
  10835. if (value) {
  10836. startSymbol = value;
  10837. return this;
  10838. } else {
  10839. return startSymbol;
  10840. }
  10841. };
  10842. /**
  10843. * @ngdoc method
  10844. * @name $interpolateProvider#endSymbol
  10845. * @description
  10846. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  10847. *
  10848. * @param {string=} value new value to set the ending symbol to.
  10849. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  10850. */
  10851. this.endSymbol = function(value) {
  10852. if (value) {
  10853. endSymbol = value;
  10854. return this;
  10855. } else {
  10856. return endSymbol;
  10857. }
  10858. };
  10859. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  10860. var startSymbolLength = startSymbol.length,
  10861. endSymbolLength = endSymbol.length,
  10862. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  10863. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  10864. function escape(ch) {
  10865. return '\\\\\\' + ch;
  10866. }
  10867. function unescapeText(text) {
  10868. return text.replace(escapedStartRegexp, startSymbol).
  10869. replace(escapedEndRegexp, endSymbol);
  10870. }
  10871. function stringify(value) {
  10872. if (value == null) { // null || undefined
  10873. return '';
  10874. }
  10875. switch (typeof value) {
  10876. case 'string':
  10877. break;
  10878. case 'number':
  10879. value = '' + value;
  10880. break;
  10881. default:
  10882. value = toJson(value);
  10883. }
  10884. return value;
  10885. }
  10886. //TODO: this is the same as the constantWatchDelegate in parse.js
  10887. function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {
  10888. var unwatch;
  10889. return unwatch = scope.$watch(function constantInterpolateWatch(scope) {
  10890. unwatch();
  10891. return constantInterp(scope);
  10892. }, listener, objectEquality);
  10893. }
  10894. /**
  10895. * @ngdoc service
  10896. * @name $interpolate
  10897. * @kind function
  10898. *
  10899. * @requires $parse
  10900. * @requires $sce
  10901. *
  10902. * @description
  10903. *
  10904. * Compiles a string with markup into an interpolation function. This service is used by the
  10905. * HTML {@link ng.$compile $compile} service for data binding. See
  10906. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  10907. * interpolation markup.
  10908. *
  10909. *
  10910. * ```js
  10911. * var $interpolate = ...; // injected
  10912. * var exp = $interpolate('Hello {{name | uppercase}}!');
  10913. * expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
  10914. * ```
  10915. *
  10916. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  10917. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  10918. * evaluate to a value other than `undefined`.
  10919. *
  10920. * ```js
  10921. * var $interpolate = ...; // injected
  10922. * var context = {greeting: 'Hello', name: undefined };
  10923. *
  10924. * // default "forgiving" mode
  10925. * var exp = $interpolate('{{greeting}} {{name}}!');
  10926. * expect(exp(context)).toEqual('Hello !');
  10927. *
  10928. * // "allOrNothing" mode
  10929. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  10930. * expect(exp(context)).toBeUndefined();
  10931. * context.name = 'Angular';
  10932. * expect(exp(context)).toEqual('Hello Angular!');
  10933. * ```
  10934. *
  10935. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  10936. *
  10937. * ####Escaped Interpolation
  10938. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  10939. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  10940. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  10941. * or binding.
  10942. *
  10943. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  10944. * degree, while also enabling code examples to work without relying on the
  10945. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  10946. *
  10947. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  10948. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  10949. * interpolation start/end markers with their escaped counterparts.**
  10950. *
  10951. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  10952. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  10953. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  10954. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  10955. * this is typically useful only when user-data is used in rendering a template from the server, or
  10956. * when otherwise untrusted data is used by a directive.
  10957. *
  10958. * <example>
  10959. * <file name="index.html">
  10960. * <div ng-init="username='A user'">
  10961. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  10962. * </p>
  10963. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  10964. * application, but fails to accomplish their task, because the server has correctly
  10965. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  10966. * characters.</p>
  10967. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  10968. * from the database by an administrator.</p>
  10969. * </div>
  10970. * </file>
  10971. * </example>
  10972. *
  10973. * @knownIssue
  10974. * It is currently not possible for an interpolated expression to contain the interpolation end
  10975. * symbol. For example, `{{ '}}' }}` will be incorrectly interpreted as `{{ ' }}` + `' }}`, i.e.
  10976. * an interpolated expression consisting of a single-quote (`'`) and the `' }}` string.
  10977. *
  10978. * @knownIssue
  10979. * All directives and components must use the standard `{{` `}}` interpolation symbols
  10980. * in their templates. If you change the application interpolation symbols the {@link $compile}
  10981. * service will attempt to denormalize the standard symbols to the custom symbols.
  10982. * The denormalization process is not clever enough to know not to replace instances of the standard
  10983. * symbols where they would not normally be treated as interpolation symbols. For example in the following
  10984. * code snippet the closing braces of the literal object will get incorrectly denormalized:
  10985. *
  10986. * ```
  10987. * <div data-context='{"context":{"id":3,"type":"page"}}">
  10988. * ```
  10989. *
  10990. * The workaround is to ensure that such instances are separated by whitespace:
  10991. * ```
  10992. * <div data-context='{"context":{"id":3,"type":"page"} }">
  10993. * ```
  10994. *
  10995. * See https://github.com/angular/angular.js/pull/14610#issuecomment-219401099 for more information.
  10996. *
  10997. * @param {string} text The text with markup to interpolate.
  10998. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  10999. * embedded expression in order to return an interpolation function. Strings with no
  11000. * embedded expression will return null for the interpolation function.
  11001. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  11002. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  11003. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  11004. * provides Strict Contextual Escaping for details.
  11005. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  11006. * unless all embedded expressions evaluate to a value other than `undefined`.
  11007. * @returns {function(context)} an interpolation function which is used to compute the
  11008. * interpolated string. The function has these parameters:
  11009. *
  11010. * - `context`: evaluation context for all expressions embedded in the interpolated text
  11011. */
  11012. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  11013. // Provide a quick exit and simplified result function for text with no interpolation
  11014. if (!text.length || text.indexOf(startSymbol) === -1) {
  11015. var constantInterp;
  11016. if (!mustHaveExpression) {
  11017. var unescapedText = unescapeText(text);
  11018. constantInterp = valueFn(unescapedText);
  11019. constantInterp.exp = text;
  11020. constantInterp.expressions = [];
  11021. constantInterp.$$watchDelegate = constantWatchDelegate;
  11022. }
  11023. return constantInterp;
  11024. }
  11025. allOrNothing = !!allOrNothing;
  11026. var startIndex,
  11027. endIndex,
  11028. index = 0,
  11029. expressions = [],
  11030. parseFns = [],
  11031. textLength = text.length,
  11032. exp,
  11033. concat = [],
  11034. expressionPositions = [];
  11035. while (index < textLength) {
  11036. if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  11037. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
  11038. if (index !== startIndex) {
  11039. concat.push(unescapeText(text.substring(index, startIndex)));
  11040. }
  11041. exp = text.substring(startIndex + startSymbolLength, endIndex);
  11042. expressions.push(exp);
  11043. parseFns.push($parse(exp, parseStringifyInterceptor));
  11044. index = endIndex + endSymbolLength;
  11045. expressionPositions.push(concat.length);
  11046. concat.push('');
  11047. } else {
  11048. // we did not find an interpolation, so we have to add the remainder to the separators array
  11049. if (index !== textLength) {
  11050. concat.push(unescapeText(text.substring(index)));
  11051. }
  11052. break;
  11053. }
  11054. }
  11055. // Concatenating expressions makes it hard to reason about whether some combination of
  11056. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  11057. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  11058. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  11059. // make it obvious that you bound the value to some user controlled value. This helps reduce
  11060. // the load when auditing for XSS issues.
  11061. if (trustedContext && concat.length > 1) {
  11062. $interpolateMinErr.throwNoconcat(text);
  11063. }
  11064. if (!mustHaveExpression || expressions.length) {
  11065. var compute = function(values) {
  11066. for (var i = 0, ii = expressions.length; i < ii; i++) {
  11067. if (allOrNothing && isUndefined(values[i])) return;
  11068. concat[expressionPositions[i]] = values[i];
  11069. }
  11070. return concat.join('');
  11071. };
  11072. var getValue = function(value) {
  11073. return trustedContext ?
  11074. $sce.getTrusted(trustedContext, value) :
  11075. $sce.valueOf(value);
  11076. };
  11077. return extend(function interpolationFn(context) {
  11078. var i = 0;
  11079. var ii = expressions.length;
  11080. var values = new Array(ii);
  11081. try {
  11082. for (; i < ii; i++) {
  11083. values[i] = parseFns[i](context);
  11084. }
  11085. return compute(values);
  11086. } catch (err) {
  11087. $exceptionHandler($interpolateMinErr.interr(text, err));
  11088. }
  11089. }, {
  11090. // all of these properties are undocumented for now
  11091. exp: text, //just for compatibility with regular watchers created via $watch
  11092. expressions: expressions,
  11093. $$watchDelegate: function(scope, listener) {
  11094. var lastValue;
  11095. return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
  11096. var currValue = compute(values);
  11097. if (isFunction(listener)) {
  11098. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  11099. }
  11100. lastValue = currValue;
  11101. });
  11102. }
  11103. });
  11104. }
  11105. function parseStringifyInterceptor(value) {
  11106. try {
  11107. value = getValue(value);
  11108. return allOrNothing && !isDefined(value) ? value : stringify(value);
  11109. } catch (err) {
  11110. $exceptionHandler($interpolateMinErr.interr(text, err));
  11111. }
  11112. }
  11113. }
  11114. /**
  11115. * @ngdoc method
  11116. * @name $interpolate#startSymbol
  11117. * @description
  11118. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  11119. *
  11120. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  11121. * the symbol.
  11122. *
  11123. * @returns {string} start symbol.
  11124. */
  11125. $interpolate.startSymbol = function() {
  11126. return startSymbol;
  11127. };
  11128. /**
  11129. * @ngdoc method
  11130. * @name $interpolate#endSymbol
  11131. * @description
  11132. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  11133. *
  11134. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  11135. * the symbol.
  11136. *
  11137. * @returns {string} end symbol.
  11138. */
  11139. $interpolate.endSymbol = function() {
  11140. return endSymbol;
  11141. };
  11142. return $interpolate;
  11143. }];
  11144. }
  11145. function $IntervalProvider() {
  11146. this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',
  11147. function($rootScope, $window, $q, $$q, $browser) {
  11148. var intervals = {};
  11149. /**
  11150. * @ngdoc service
  11151. * @name $interval
  11152. *
  11153. * @description
  11154. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  11155. * milliseconds.
  11156. *
  11157. * The return value of registering an interval function is a promise. This promise will be
  11158. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  11159. * run indefinitely if `count` is not defined. The value of the notification will be the
  11160. * number of iterations that have run.
  11161. * To cancel an interval, call `$interval.cancel(promise)`.
  11162. *
  11163. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  11164. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  11165. * time.
  11166. *
  11167. * <div class="alert alert-warning">
  11168. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  11169. * with them. In particular they are not automatically destroyed when a controller's scope or a
  11170. * directive's element are destroyed.
  11171. * You should take this into consideration and make sure to always cancel the interval at the
  11172. * appropriate moment. See the example below for more details on how and when to do this.
  11173. * </div>
  11174. *
  11175. * @param {function()} fn A function that should be called repeatedly.
  11176. * @param {number} delay Number of milliseconds between each function call.
  11177. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  11178. * indefinitely.
  11179. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  11180. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  11181. * @param {...*=} Pass additional parameters to the executed function.
  11182. * @returns {promise} A promise which will be notified on each iteration.
  11183. *
  11184. * @example
  11185. * <example module="intervalExample">
  11186. * <file name="index.html">
  11187. * <script>
  11188. * angular.module('intervalExample', [])
  11189. * .controller('ExampleController', ['$scope', '$interval',
  11190. * function($scope, $interval) {
  11191. * $scope.format = 'M/d/yy h:mm:ss a';
  11192. * $scope.blood_1 = 100;
  11193. * $scope.blood_2 = 120;
  11194. *
  11195. * var stop;
  11196. * $scope.fight = function() {
  11197. * // Don't start a new fight if we are already fighting
  11198. * if ( angular.isDefined(stop) ) return;
  11199. *
  11200. * stop = $interval(function() {
  11201. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  11202. * $scope.blood_1 = $scope.blood_1 - 3;
  11203. * $scope.blood_2 = $scope.blood_2 - 4;
  11204. * } else {
  11205. * $scope.stopFight();
  11206. * }
  11207. * }, 100);
  11208. * };
  11209. *
  11210. * $scope.stopFight = function() {
  11211. * if (angular.isDefined(stop)) {
  11212. * $interval.cancel(stop);
  11213. * stop = undefined;
  11214. * }
  11215. * };
  11216. *
  11217. * $scope.resetFight = function() {
  11218. * $scope.blood_1 = 100;
  11219. * $scope.blood_2 = 120;
  11220. * };
  11221. *
  11222. * $scope.$on('$destroy', function() {
  11223. * // Make sure that the interval is destroyed too
  11224. * $scope.stopFight();
  11225. * });
  11226. * }])
  11227. * // Register the 'myCurrentTime' directive factory method.
  11228. * // We inject $interval and dateFilter service since the factory method is DI.
  11229. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  11230. * function($interval, dateFilter) {
  11231. * // return the directive link function. (compile function not needed)
  11232. * return function(scope, element, attrs) {
  11233. * var format, // date format
  11234. * stopTime; // so that we can cancel the time updates
  11235. *
  11236. * // used to update the UI
  11237. * function updateTime() {
  11238. * element.text(dateFilter(new Date(), format));
  11239. * }
  11240. *
  11241. * // watch the expression, and update the UI on change.
  11242. * scope.$watch(attrs.myCurrentTime, function(value) {
  11243. * format = value;
  11244. * updateTime();
  11245. * });
  11246. *
  11247. * stopTime = $interval(updateTime, 1000);
  11248. *
  11249. * // listen on DOM destroy (removal) event, and cancel the next UI update
  11250. * // to prevent updating time after the DOM element was removed.
  11251. * element.on('$destroy', function() {
  11252. * $interval.cancel(stopTime);
  11253. * });
  11254. * }
  11255. * }]);
  11256. * </script>
  11257. *
  11258. * <div>
  11259. * <div ng-controller="ExampleController">
  11260. * <label>Date format: <input ng-model="format"></label> <hr/>
  11261. * Current time is: <span my-current-time="format"></span>
  11262. * <hr/>
  11263. * Blood 1 : <font color='red'>{{blood_1}}</font>
  11264. * Blood 2 : <font color='red'>{{blood_2}}</font>
  11265. * <button type="button" data-ng-click="fight()">Fight</button>
  11266. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  11267. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  11268. * </div>
  11269. * </div>
  11270. *
  11271. * </file>
  11272. * </example>
  11273. */
  11274. function interval(fn, delay, count, invokeApply) {
  11275. var hasParams = arguments.length > 4,
  11276. args = hasParams ? sliceArgs(arguments, 4) : [],
  11277. setInterval = $window.setInterval,
  11278. clearInterval = $window.clearInterval,
  11279. iteration = 0,
  11280. skipApply = (isDefined(invokeApply) && !invokeApply),
  11281. deferred = (skipApply ? $$q : $q).defer(),
  11282. promise = deferred.promise;
  11283. count = isDefined(count) ? count : 0;
  11284. promise.$$intervalId = setInterval(function tick() {
  11285. if (skipApply) {
  11286. $browser.defer(callback);
  11287. } else {
  11288. $rootScope.$evalAsync(callback);
  11289. }
  11290. deferred.notify(iteration++);
  11291. if (count > 0 && iteration >= count) {
  11292. deferred.resolve(iteration);
  11293. clearInterval(promise.$$intervalId);
  11294. delete intervals[promise.$$intervalId];
  11295. }
  11296. if (!skipApply) $rootScope.$apply();
  11297. }, delay);
  11298. intervals[promise.$$intervalId] = deferred;
  11299. return promise;
  11300. function callback() {
  11301. if (!hasParams) {
  11302. fn(iteration);
  11303. } else {
  11304. fn.apply(null, args);
  11305. }
  11306. }
  11307. }
  11308. /**
  11309. * @ngdoc method
  11310. * @name $interval#cancel
  11311. *
  11312. * @description
  11313. * Cancels a task associated with the `promise`.
  11314. *
  11315. * @param {Promise=} promise returned by the `$interval` function.
  11316. * @returns {boolean} Returns `true` if the task was successfully canceled.
  11317. */
  11318. interval.cancel = function(promise) {
  11319. if (promise && promise.$$intervalId in intervals) {
  11320. intervals[promise.$$intervalId].reject('canceled');
  11321. $window.clearInterval(promise.$$intervalId);
  11322. delete intervals[promise.$$intervalId];
  11323. return true;
  11324. }
  11325. return false;
  11326. };
  11327. return interval;
  11328. }];
  11329. }
  11330. /**
  11331. * @ngdoc service
  11332. * @name $locale
  11333. *
  11334. * @description
  11335. * $locale service provides localization rules for various Angular components. As of right now the
  11336. * only public api is:
  11337. *
  11338. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  11339. */
  11340. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  11341. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  11342. var $locationMinErr = minErr('$location');
  11343. /**
  11344. * Encode path using encodeUriSegment, ignoring forward slashes
  11345. *
  11346. * @param {string} path Path to encode
  11347. * @returns {string}
  11348. */
  11349. function encodePath(path) {
  11350. var segments = path.split('/'),
  11351. i = segments.length;
  11352. while (i--) {
  11353. segments[i] = encodeUriSegment(segments[i]);
  11354. }
  11355. return segments.join('/');
  11356. }
  11357. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  11358. var parsedUrl = urlResolve(absoluteUrl);
  11359. locationObj.$$protocol = parsedUrl.protocol;
  11360. locationObj.$$host = parsedUrl.hostname;
  11361. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  11362. }
  11363. function parseAppUrl(relativeUrl, locationObj) {
  11364. var prefixed = (relativeUrl.charAt(0) !== '/');
  11365. if (prefixed) {
  11366. relativeUrl = '/' + relativeUrl;
  11367. }
  11368. var match = urlResolve(relativeUrl);
  11369. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  11370. match.pathname.substring(1) : match.pathname);
  11371. locationObj.$$search = parseKeyValue(match.search);
  11372. locationObj.$$hash = decodeURIComponent(match.hash);
  11373. // make sure path starts with '/';
  11374. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  11375. locationObj.$$path = '/' + locationObj.$$path;
  11376. }
  11377. }
  11378. function startsWith(haystack, needle) {
  11379. return haystack.lastIndexOf(needle, 0) === 0;
  11380. }
  11381. /**
  11382. *
  11383. * @param {string} base
  11384. * @param {string} url
  11385. * @returns {string} returns text from `url` after `base` or `undefined` if it does not begin with
  11386. * the expected string.
  11387. */
  11388. function stripBaseUrl(base, url) {
  11389. if (startsWith(url, base)) {
  11390. return url.substr(base.length);
  11391. }
  11392. }
  11393. function stripHash(url) {
  11394. var index = url.indexOf('#');
  11395. return index == -1 ? url : url.substr(0, index);
  11396. }
  11397. function trimEmptyHash(url) {
  11398. return url.replace(/(#.+)|#$/, '$1');
  11399. }
  11400. function stripFile(url) {
  11401. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  11402. }
  11403. /* return the server only (scheme://host:port) */
  11404. function serverBase(url) {
  11405. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  11406. }
  11407. /**
  11408. * LocationHtml5Url represents an url
  11409. * This object is exposed as $location service when HTML5 mode is enabled and supported
  11410. *
  11411. * @constructor
  11412. * @param {string} appBase application base URL
  11413. * @param {string} appBaseNoFile application base URL stripped of any filename
  11414. * @param {string} basePrefix url path prefix
  11415. */
  11416. function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
  11417. this.$$html5 = true;
  11418. basePrefix = basePrefix || '';
  11419. parseAbsoluteUrl(appBase, this);
  11420. /**
  11421. * Parse given html5 (regular) url string into properties
  11422. * @param {string} url HTML5 url
  11423. * @private
  11424. */
  11425. this.$$parse = function(url) {
  11426. var pathUrl = stripBaseUrl(appBaseNoFile, url);
  11427. if (!isString(pathUrl)) {
  11428. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  11429. appBaseNoFile);
  11430. }
  11431. parseAppUrl(pathUrl, this);
  11432. if (!this.$$path) {
  11433. this.$$path = '/';
  11434. }
  11435. this.$$compose();
  11436. };
  11437. /**
  11438. * Compose url and update `absUrl` property
  11439. * @private
  11440. */
  11441. this.$$compose = function() {
  11442. var search = toKeyValue(this.$$search),
  11443. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  11444. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  11445. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  11446. };
  11447. this.$$parseLinkUrl = function(url, relHref) {
  11448. if (relHref && relHref[0] === '#') {
  11449. // special case for links to hash fragments:
  11450. // keep the old url and only replace the hash fragment
  11451. this.hash(relHref.slice(1));
  11452. return true;
  11453. }
  11454. var appUrl, prevAppUrl;
  11455. var rewrittenUrl;
  11456. if (isDefined(appUrl = stripBaseUrl(appBase, url))) {
  11457. prevAppUrl = appUrl;
  11458. if (isDefined(appUrl = stripBaseUrl(basePrefix, appUrl))) {
  11459. rewrittenUrl = appBaseNoFile + (stripBaseUrl('/', appUrl) || appUrl);
  11460. } else {
  11461. rewrittenUrl = appBase + prevAppUrl;
  11462. }
  11463. } else if (isDefined(appUrl = stripBaseUrl(appBaseNoFile, url))) {
  11464. rewrittenUrl = appBaseNoFile + appUrl;
  11465. } else if (appBaseNoFile == url + '/') {
  11466. rewrittenUrl = appBaseNoFile;
  11467. }
  11468. if (rewrittenUrl) {
  11469. this.$$parse(rewrittenUrl);
  11470. }
  11471. return !!rewrittenUrl;
  11472. };
  11473. }
  11474. /**
  11475. * LocationHashbangUrl represents url
  11476. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  11477. * It also serves as the base class for html5 mode fallback on legacy browsers.
  11478. *
  11479. * @constructor
  11480. * @param {string} appBase application base URL
  11481. * @param {string} appBaseNoFile application base URL stripped of any filename
  11482. * @param {string} hashPrefix hashbang prefix
  11483. */
  11484. function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
  11485. parseAbsoluteUrl(appBase, this);
  11486. /**
  11487. * Parse given hashbang url into properties
  11488. * @param {string} url Hashbang url
  11489. * @private
  11490. */
  11491. this.$$parse = function(url) {
  11492. var withoutBaseUrl = stripBaseUrl(appBase, url) || stripBaseUrl(appBaseNoFile, url);
  11493. var withoutHashUrl;
  11494. if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
  11495. // The rest of the url starts with a hash so we have
  11496. // got either a hashbang path or a plain hash fragment
  11497. withoutHashUrl = stripBaseUrl(hashPrefix, withoutBaseUrl);
  11498. if (isUndefined(withoutHashUrl)) {
  11499. // There was no hashbang prefix so we just have a hash fragment
  11500. withoutHashUrl = withoutBaseUrl;
  11501. }
  11502. } else {
  11503. // There was no hashbang path nor hash fragment:
  11504. // If we are in HTML5 mode we use what is left as the path;
  11505. // Otherwise we ignore what is left
  11506. if (this.$$html5) {
  11507. withoutHashUrl = withoutBaseUrl;
  11508. } else {
  11509. withoutHashUrl = '';
  11510. if (isUndefined(withoutBaseUrl)) {
  11511. appBase = url;
  11512. this.replace();
  11513. }
  11514. }
  11515. }
  11516. parseAppUrl(withoutHashUrl, this);
  11517. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  11518. this.$$compose();
  11519. /*
  11520. * In Windows, on an anchor node on documents loaded from
  11521. * the filesystem, the browser will return a pathname
  11522. * prefixed with the drive name ('/C:/path') when a
  11523. * pathname without a drive is set:
  11524. * * a.setAttribute('href', '/foo')
  11525. * * a.pathname === '/C:/foo' //true
  11526. *
  11527. * Inside of Angular, we're always using pathnames that
  11528. * do not include drive names for routing.
  11529. */
  11530. function removeWindowsDriveName(path, url, base) {
  11531. /*
  11532. Matches paths for file protocol on windows,
  11533. such as /C:/foo/bar, and captures only /foo/bar.
  11534. */
  11535. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  11536. var firstPathSegmentMatch;
  11537. //Get the relative path from the input URL.
  11538. if (startsWith(url, base)) {
  11539. url = url.replace(base, '');
  11540. }
  11541. // The input URL intentionally contains a first path segment that ends with a colon.
  11542. if (windowsFilePathExp.exec(url)) {
  11543. return path;
  11544. }
  11545. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  11546. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  11547. }
  11548. };
  11549. /**
  11550. * Compose hashbang url and update `absUrl` property
  11551. * @private
  11552. */
  11553. this.$$compose = function() {
  11554. var search = toKeyValue(this.$$search),
  11555. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  11556. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  11557. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  11558. };
  11559. this.$$parseLinkUrl = function(url, relHref) {
  11560. if (stripHash(appBase) == stripHash(url)) {
  11561. this.$$parse(url);
  11562. return true;
  11563. }
  11564. return false;
  11565. };
  11566. }
  11567. /**
  11568. * LocationHashbangUrl represents url
  11569. * This object is exposed as $location service when html5 history api is enabled but the browser
  11570. * does not support it.
  11571. *
  11572. * @constructor
  11573. * @param {string} appBase application base URL
  11574. * @param {string} appBaseNoFile application base URL stripped of any filename
  11575. * @param {string} hashPrefix hashbang prefix
  11576. */
  11577. function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
  11578. this.$$html5 = true;
  11579. LocationHashbangUrl.apply(this, arguments);
  11580. this.$$parseLinkUrl = function(url, relHref) {
  11581. if (relHref && relHref[0] === '#') {
  11582. // special case for links to hash fragments:
  11583. // keep the old url and only replace the hash fragment
  11584. this.hash(relHref.slice(1));
  11585. return true;
  11586. }
  11587. var rewrittenUrl;
  11588. var appUrl;
  11589. if (appBase == stripHash(url)) {
  11590. rewrittenUrl = url;
  11591. } else if ((appUrl = stripBaseUrl(appBaseNoFile, url))) {
  11592. rewrittenUrl = appBase + hashPrefix + appUrl;
  11593. } else if (appBaseNoFile === url + '/') {
  11594. rewrittenUrl = appBaseNoFile;
  11595. }
  11596. if (rewrittenUrl) {
  11597. this.$$parse(rewrittenUrl);
  11598. }
  11599. return !!rewrittenUrl;
  11600. };
  11601. this.$$compose = function() {
  11602. var search = toKeyValue(this.$$search),
  11603. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  11604. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  11605. // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
  11606. this.$$absUrl = appBase + hashPrefix + this.$$url;
  11607. };
  11608. }
  11609. var locationPrototype = {
  11610. /**
  11611. * Ensure absolute url is initialized.
  11612. * @private
  11613. */
  11614. $$absUrl:'',
  11615. /**
  11616. * Are we in html5 mode?
  11617. * @private
  11618. */
  11619. $$html5: false,
  11620. /**
  11621. * Has any change been replacing?
  11622. * @private
  11623. */
  11624. $$replace: false,
  11625. /**
  11626. * @ngdoc method
  11627. * @name $location#absUrl
  11628. *
  11629. * @description
  11630. * This method is getter only.
  11631. *
  11632. * Return full url representation with all segments encoded according to rules specified in
  11633. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  11634. *
  11635. *
  11636. * ```js
  11637. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11638. * var absUrl = $location.absUrl();
  11639. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  11640. * ```
  11641. *
  11642. * @return {string} full url
  11643. */
  11644. absUrl: locationGetter('$$absUrl'),
  11645. /**
  11646. * @ngdoc method
  11647. * @name $location#url
  11648. *
  11649. * @description
  11650. * This method is getter / setter.
  11651. *
  11652. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  11653. *
  11654. * Change path, search and hash, when called with parameter and return `$location`.
  11655. *
  11656. *
  11657. * ```js
  11658. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11659. * var url = $location.url();
  11660. * // => "/some/path?foo=bar&baz=xoxo"
  11661. * ```
  11662. *
  11663. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  11664. * @return {string} url
  11665. */
  11666. url: function(url) {
  11667. if (isUndefined(url)) {
  11668. return this.$$url;
  11669. }
  11670. var match = PATH_MATCH.exec(url);
  11671. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  11672. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  11673. this.hash(match[5] || '');
  11674. return this;
  11675. },
  11676. /**
  11677. * @ngdoc method
  11678. * @name $location#protocol
  11679. *
  11680. * @description
  11681. * This method is getter only.
  11682. *
  11683. * Return protocol of current url.
  11684. *
  11685. *
  11686. * ```js
  11687. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11688. * var protocol = $location.protocol();
  11689. * // => "http"
  11690. * ```
  11691. *
  11692. * @return {string} protocol of current url
  11693. */
  11694. protocol: locationGetter('$$protocol'),
  11695. /**
  11696. * @ngdoc method
  11697. * @name $location#host
  11698. *
  11699. * @description
  11700. * This method is getter only.
  11701. *
  11702. * Return host of current url.
  11703. *
  11704. * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  11705. *
  11706. *
  11707. * ```js
  11708. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11709. * var host = $location.host();
  11710. * // => "example.com"
  11711. *
  11712. * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  11713. * host = $location.host();
  11714. * // => "example.com"
  11715. * host = location.host;
  11716. * // => "example.com:8080"
  11717. * ```
  11718. *
  11719. * @return {string} host of current url.
  11720. */
  11721. host: locationGetter('$$host'),
  11722. /**
  11723. * @ngdoc method
  11724. * @name $location#port
  11725. *
  11726. * @description
  11727. * This method is getter only.
  11728. *
  11729. * Return port of current url.
  11730. *
  11731. *
  11732. * ```js
  11733. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11734. * var port = $location.port();
  11735. * // => 80
  11736. * ```
  11737. *
  11738. * @return {Number} port
  11739. */
  11740. port: locationGetter('$$port'),
  11741. /**
  11742. * @ngdoc method
  11743. * @name $location#path
  11744. *
  11745. * @description
  11746. * This method is getter / setter.
  11747. *
  11748. * Return path of current url when called without any parameter.
  11749. *
  11750. * Change path when called with parameter and return `$location`.
  11751. *
  11752. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  11753. * if it is missing.
  11754. *
  11755. *
  11756. * ```js
  11757. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11758. * var path = $location.path();
  11759. * // => "/some/path"
  11760. * ```
  11761. *
  11762. * @param {(string|number)=} path New path
  11763. * @return {(string|object)} path if called with no parameters, or `$location` if called with a parameter
  11764. */
  11765. path: locationGetterSetter('$$path', function(path) {
  11766. path = path !== null ? path.toString() : '';
  11767. return path.charAt(0) == '/' ? path : '/' + path;
  11768. }),
  11769. /**
  11770. * @ngdoc method
  11771. * @name $location#search
  11772. *
  11773. * @description
  11774. * This method is getter / setter.
  11775. *
  11776. * Return search part (as object) of current url when called without any parameter.
  11777. *
  11778. * Change search part when called with parameter and return `$location`.
  11779. *
  11780. *
  11781. * ```js
  11782. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  11783. * var searchObject = $location.search();
  11784. * // => {foo: 'bar', baz: 'xoxo'}
  11785. *
  11786. * // set foo to 'yipee'
  11787. * $location.search('foo', 'yipee');
  11788. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  11789. * ```
  11790. *
  11791. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  11792. * hash object.
  11793. *
  11794. * When called with a single argument the method acts as a setter, setting the `search` component
  11795. * of `$location` to the specified value.
  11796. *
  11797. * If the argument is a hash object containing an array of values, these values will be encoded
  11798. * as duplicate search parameters in the url.
  11799. *
  11800. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  11801. * will override only a single search property.
  11802. *
  11803. * If `paramValue` is an array, it will override the property of the `search` component of
  11804. * `$location` specified via the first argument.
  11805. *
  11806. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  11807. *
  11808. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  11809. * value nor trailing equal sign.
  11810. *
  11811. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  11812. * one or more arguments returns `$location` object itself.
  11813. */
  11814. search: function(search, paramValue) {
  11815. switch (arguments.length) {
  11816. case 0:
  11817. return this.$$search;
  11818. case 1:
  11819. if (isString(search) || isNumber(search)) {
  11820. search = search.toString();
  11821. this.$$search = parseKeyValue(search);
  11822. } else if (isObject(search)) {
  11823. search = copy(search, {});
  11824. // remove object undefined or null properties
  11825. forEach(search, function(value, key) {
  11826. if (value == null) delete search[key];
  11827. });
  11828. this.$$search = search;
  11829. } else {
  11830. throw $locationMinErr('isrcharg',
  11831. 'The first argument of the `$location#search()` call must be a string or an object.');
  11832. }
  11833. break;
  11834. default:
  11835. if (isUndefined(paramValue) || paramValue === null) {
  11836. delete this.$$search[search];
  11837. } else {
  11838. this.$$search[search] = paramValue;
  11839. }
  11840. }
  11841. this.$$compose();
  11842. return this;
  11843. },
  11844. /**
  11845. * @ngdoc method
  11846. * @name $location#hash
  11847. *
  11848. * @description
  11849. * This method is getter / setter.
  11850. *
  11851. * Returns the hash fragment when called without any parameters.
  11852. *
  11853. * Changes the hash fragment when called with a parameter and returns `$location`.
  11854. *
  11855. *
  11856. * ```js
  11857. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  11858. * var hash = $location.hash();
  11859. * // => "hashValue"
  11860. * ```
  11861. *
  11862. * @param {(string|number)=} hash New hash fragment
  11863. * @return {string} hash
  11864. */
  11865. hash: locationGetterSetter('$$hash', function(hash) {
  11866. return hash !== null ? hash.toString() : '';
  11867. }),
  11868. /**
  11869. * @ngdoc method
  11870. * @name $location#replace
  11871. *
  11872. * @description
  11873. * If called, all changes to $location during the current `$digest` will replace the current history
  11874. * record, instead of adding a new one.
  11875. */
  11876. replace: function() {
  11877. this.$$replace = true;
  11878. return this;
  11879. }
  11880. };
  11881. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  11882. Location.prototype = Object.create(locationPrototype);
  11883. /**
  11884. * @ngdoc method
  11885. * @name $location#state
  11886. *
  11887. * @description
  11888. * This method is getter / setter.
  11889. *
  11890. * Return the history state object when called without any parameter.
  11891. *
  11892. * Change the history state object when called with one parameter and return `$location`.
  11893. * The state object is later passed to `pushState` or `replaceState`.
  11894. *
  11895. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  11896. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  11897. * older browsers (like IE9 or Android < 4.0), don't use this method.
  11898. *
  11899. * @param {object=} state State object for pushState or replaceState
  11900. * @return {object} state
  11901. */
  11902. Location.prototype.state = function(state) {
  11903. if (!arguments.length) {
  11904. return this.$$state;
  11905. }
  11906. if (Location !== LocationHtml5Url || !this.$$html5) {
  11907. throw $locationMinErr('nostate', 'History API state support is available only ' +
  11908. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  11909. }
  11910. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  11911. // but we're changing the $$state reference to $browser.state() during the $digest
  11912. // so the modification window is narrow.
  11913. this.$$state = isUndefined(state) ? null : state;
  11914. return this;
  11915. };
  11916. });
  11917. function locationGetter(property) {
  11918. return function() {
  11919. return this[property];
  11920. };
  11921. }
  11922. function locationGetterSetter(property, preprocess) {
  11923. return function(value) {
  11924. if (isUndefined(value)) {
  11925. return this[property];
  11926. }
  11927. this[property] = preprocess(value);
  11928. this.$$compose();
  11929. return this;
  11930. };
  11931. }
  11932. /**
  11933. * @ngdoc service
  11934. * @name $location
  11935. *
  11936. * @requires $rootElement
  11937. *
  11938. * @description
  11939. * The $location service parses the URL in the browser address bar (based on the
  11940. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  11941. * available to your application. Changes to the URL in the address bar are reflected into
  11942. * $location service and changes to $location are reflected into the browser address bar.
  11943. *
  11944. * **The $location service:**
  11945. *
  11946. * - Exposes the current URL in the browser address bar, so you can
  11947. * - Watch and observe the URL.
  11948. * - Change the URL.
  11949. * - Synchronizes the URL with the browser when the user
  11950. * - Changes the address bar.
  11951. * - Clicks the back or forward button (or clicks a History link).
  11952. * - Clicks on a link.
  11953. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  11954. *
  11955. * For more information see {@link guide/$location Developer Guide: Using $location}
  11956. */
  11957. /**
  11958. * @ngdoc provider
  11959. * @name $locationProvider
  11960. * @description
  11961. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  11962. */
  11963. function $LocationProvider() {
  11964. var hashPrefix = '',
  11965. html5Mode = {
  11966. enabled: false,
  11967. requireBase: true,
  11968. rewriteLinks: true
  11969. };
  11970. /**
  11971. * @ngdoc method
  11972. * @name $locationProvider#hashPrefix
  11973. * @description
  11974. * @param {string=} prefix Prefix for hash part (containing path and search)
  11975. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  11976. */
  11977. this.hashPrefix = function(prefix) {
  11978. if (isDefined(prefix)) {
  11979. hashPrefix = prefix;
  11980. return this;
  11981. } else {
  11982. return hashPrefix;
  11983. }
  11984. };
  11985. /**
  11986. * @ngdoc method
  11987. * @name $locationProvider#html5Mode
  11988. * @description
  11989. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  11990. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  11991. * properties:
  11992. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  11993. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  11994. * support `pushState`.
  11995. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  11996. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  11997. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  11998. * See the {@link guide/$location $location guide for more information}
  11999. * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
  12000. * enables/disables url rewriting for relative links.
  12001. *
  12002. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  12003. */
  12004. this.html5Mode = function(mode) {
  12005. if (isBoolean(mode)) {
  12006. html5Mode.enabled = mode;
  12007. return this;
  12008. } else if (isObject(mode)) {
  12009. if (isBoolean(mode.enabled)) {
  12010. html5Mode.enabled = mode.enabled;
  12011. }
  12012. if (isBoolean(mode.requireBase)) {
  12013. html5Mode.requireBase = mode.requireBase;
  12014. }
  12015. if (isBoolean(mode.rewriteLinks)) {
  12016. html5Mode.rewriteLinks = mode.rewriteLinks;
  12017. }
  12018. return this;
  12019. } else {
  12020. return html5Mode;
  12021. }
  12022. };
  12023. /**
  12024. * @ngdoc event
  12025. * @name $location#$locationChangeStart
  12026. * @eventType broadcast on root scope
  12027. * @description
  12028. * Broadcasted before a URL will change.
  12029. *
  12030. * This change can be prevented by calling
  12031. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  12032. * details about event object. Upon successful change
  12033. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  12034. *
  12035. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  12036. * the browser supports the HTML5 History API.
  12037. *
  12038. * @param {Object} angularEvent Synthetic event object.
  12039. * @param {string} newUrl New URL
  12040. * @param {string=} oldUrl URL that was before it was changed.
  12041. * @param {string=} newState New history state object
  12042. * @param {string=} oldState History state object that was before it was changed.
  12043. */
  12044. /**
  12045. * @ngdoc event
  12046. * @name $location#$locationChangeSuccess
  12047. * @eventType broadcast on root scope
  12048. * @description
  12049. * Broadcasted after a URL was changed.
  12050. *
  12051. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  12052. * the browser supports the HTML5 History API.
  12053. *
  12054. * @param {Object} angularEvent Synthetic event object.
  12055. * @param {string} newUrl New URL
  12056. * @param {string=} oldUrl URL that was before it was changed.
  12057. * @param {string=} newState New history state object
  12058. * @param {string=} oldState History state object that was before it was changed.
  12059. */
  12060. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  12061. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  12062. var $location,
  12063. LocationMode,
  12064. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  12065. initialUrl = $browser.url(),
  12066. appBase;
  12067. if (html5Mode.enabled) {
  12068. if (!baseHref && html5Mode.requireBase) {
  12069. throw $locationMinErr('nobase',
  12070. "$location in HTML5 mode requires a <base> tag to be present!");
  12071. }
  12072. appBase = serverBase(initialUrl) + (baseHref || '/');
  12073. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  12074. } else {
  12075. appBase = stripHash(initialUrl);
  12076. LocationMode = LocationHashbangUrl;
  12077. }
  12078. var appBaseNoFile = stripFile(appBase);
  12079. $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
  12080. $location.$$parseLinkUrl(initialUrl, initialUrl);
  12081. $location.$$state = $browser.state();
  12082. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  12083. function setBrowserUrlWithFallback(url, replace, state) {
  12084. var oldUrl = $location.url();
  12085. var oldState = $location.$$state;
  12086. try {
  12087. $browser.url(url, replace, state);
  12088. // Make sure $location.state() returns referentially identical (not just deeply equal)
  12089. // state object; this makes possible quick checking if the state changed in the digest
  12090. // loop. Checking deep equality would be too expensive.
  12091. $location.$$state = $browser.state();
  12092. } catch (e) {
  12093. // Restore old values if pushState fails
  12094. $location.url(oldUrl);
  12095. $location.$$state = oldState;
  12096. throw e;
  12097. }
  12098. }
  12099. $rootElement.on('click', function(event) {
  12100. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  12101. // currently we open nice url link and redirect then
  12102. if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
  12103. var elm = jqLite(event.target);
  12104. // traverse the DOM up to find first A tag
  12105. while (nodeName_(elm[0]) !== 'a') {
  12106. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  12107. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  12108. }
  12109. var absHref = elm.prop('href');
  12110. // get the actual href attribute - see
  12111. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  12112. var relHref = elm.attr('href') || elm.attr('xlink:href');
  12113. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  12114. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  12115. // an animation.
  12116. absHref = urlResolve(absHref.animVal).href;
  12117. }
  12118. // Ignore when url is started with javascript: or mailto:
  12119. if (IGNORE_URI_REGEXP.test(absHref)) return;
  12120. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  12121. if ($location.$$parseLinkUrl(absHref, relHref)) {
  12122. // We do a preventDefault for all urls that are part of the angular application,
  12123. // in html5mode and also without, so that we are able to abort navigation without
  12124. // getting double entries in the location history.
  12125. event.preventDefault();
  12126. // update location manually
  12127. if ($location.absUrl() != $browser.url()) {
  12128. $rootScope.$apply();
  12129. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  12130. $window.angular['ff-684208-preventDefault'] = true;
  12131. }
  12132. }
  12133. }
  12134. });
  12135. // rewrite hashbang url <> html5 url
  12136. if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
  12137. $browser.url($location.absUrl(), true);
  12138. }
  12139. var initializing = true;
  12140. // update $location when $browser url changes
  12141. $browser.onUrlChange(function(newUrl, newState) {
  12142. if (isUndefined(stripBaseUrl(appBaseNoFile, newUrl))) {
  12143. // If we are navigating outside of the app then force a reload
  12144. $window.location.href = newUrl;
  12145. return;
  12146. }
  12147. $rootScope.$evalAsync(function() {
  12148. var oldUrl = $location.absUrl();
  12149. var oldState = $location.$$state;
  12150. var defaultPrevented;
  12151. newUrl = trimEmptyHash(newUrl);
  12152. $location.$$parse(newUrl);
  12153. $location.$$state = newState;
  12154. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  12155. newState, oldState).defaultPrevented;
  12156. // if the location was changed by a `$locationChangeStart` handler then stop
  12157. // processing this location change
  12158. if ($location.absUrl() !== newUrl) return;
  12159. if (defaultPrevented) {
  12160. $location.$$parse(oldUrl);
  12161. $location.$$state = oldState;
  12162. setBrowserUrlWithFallback(oldUrl, false, oldState);
  12163. } else {
  12164. initializing = false;
  12165. afterLocationChange(oldUrl, oldState);
  12166. }
  12167. });
  12168. if (!$rootScope.$$phase) $rootScope.$digest();
  12169. });
  12170. // update browser
  12171. $rootScope.$watch(function $locationWatch() {
  12172. var oldUrl = trimEmptyHash($browser.url());
  12173. var newUrl = trimEmptyHash($location.absUrl());
  12174. var oldState = $browser.state();
  12175. var currentReplace = $location.$$replace;
  12176. var urlOrStateChanged = oldUrl !== newUrl ||
  12177. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  12178. if (initializing || urlOrStateChanged) {
  12179. initializing = false;
  12180. $rootScope.$evalAsync(function() {
  12181. var newUrl = $location.absUrl();
  12182. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  12183. $location.$$state, oldState).defaultPrevented;
  12184. // if the location was changed by a `$locationChangeStart` handler then stop
  12185. // processing this location change
  12186. if ($location.absUrl() !== newUrl) return;
  12187. if (defaultPrevented) {
  12188. $location.$$parse(oldUrl);
  12189. $location.$$state = oldState;
  12190. } else {
  12191. if (urlOrStateChanged) {
  12192. setBrowserUrlWithFallback(newUrl, currentReplace,
  12193. oldState === $location.$$state ? null : $location.$$state);
  12194. }
  12195. afterLocationChange(oldUrl, oldState);
  12196. }
  12197. });
  12198. }
  12199. $location.$$replace = false;
  12200. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  12201. // there is a change
  12202. });
  12203. return $location;
  12204. function afterLocationChange(oldUrl, oldState) {
  12205. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  12206. $location.$$state, oldState);
  12207. }
  12208. }];
  12209. }
  12210. /**
  12211. * @ngdoc service
  12212. * @name $log
  12213. * @requires $window
  12214. *
  12215. * @description
  12216. * Simple service for logging. Default implementation safely writes the message
  12217. * into the browser's console (if present).
  12218. *
  12219. * The main purpose of this service is to simplify debugging and troubleshooting.
  12220. *
  12221. * The default is to log `debug` messages. You can use
  12222. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  12223. *
  12224. * @example
  12225. <example module="logExample">
  12226. <file name="script.js">
  12227. angular.module('logExample', [])
  12228. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  12229. $scope.$log = $log;
  12230. $scope.message = 'Hello World!';
  12231. }]);
  12232. </file>
  12233. <file name="index.html">
  12234. <div ng-controller="LogController">
  12235. <p>Reload this page with open console, enter text and hit the log button...</p>
  12236. <label>Message:
  12237. <input type="text" ng-model="message" /></label>
  12238. <button ng-click="$log.log(message)">log</button>
  12239. <button ng-click="$log.warn(message)">warn</button>
  12240. <button ng-click="$log.info(message)">info</button>
  12241. <button ng-click="$log.error(message)">error</button>
  12242. <button ng-click="$log.debug(message)">debug</button>
  12243. </div>
  12244. </file>
  12245. </example>
  12246. */
  12247. /**
  12248. * @ngdoc provider
  12249. * @name $logProvider
  12250. * @description
  12251. * Use the `$logProvider` to configure how the application logs messages
  12252. */
  12253. function $LogProvider() {
  12254. var debug = true,
  12255. self = this;
  12256. /**
  12257. * @ngdoc method
  12258. * @name $logProvider#debugEnabled
  12259. * @description
  12260. * @param {boolean=} flag enable or disable debug level messages
  12261. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  12262. */
  12263. this.debugEnabled = function(flag) {
  12264. if (isDefined(flag)) {
  12265. debug = flag;
  12266. return this;
  12267. } else {
  12268. return debug;
  12269. }
  12270. };
  12271. this.$get = ['$window', function($window) {
  12272. return {
  12273. /**
  12274. * @ngdoc method
  12275. * @name $log#log
  12276. *
  12277. * @description
  12278. * Write a log message
  12279. */
  12280. log: consoleLog('log'),
  12281. /**
  12282. * @ngdoc method
  12283. * @name $log#info
  12284. *
  12285. * @description
  12286. * Write an information message
  12287. */
  12288. info: consoleLog('info'),
  12289. /**
  12290. * @ngdoc method
  12291. * @name $log#warn
  12292. *
  12293. * @description
  12294. * Write a warning message
  12295. */
  12296. warn: consoleLog('warn'),
  12297. /**
  12298. * @ngdoc method
  12299. * @name $log#error
  12300. *
  12301. * @description
  12302. * Write an error message
  12303. */
  12304. error: consoleLog('error'),
  12305. /**
  12306. * @ngdoc method
  12307. * @name $log#debug
  12308. *
  12309. * @description
  12310. * Write a debug message
  12311. */
  12312. debug: (function() {
  12313. var fn = consoleLog('debug');
  12314. return function() {
  12315. if (debug) {
  12316. fn.apply(self, arguments);
  12317. }
  12318. };
  12319. }())
  12320. };
  12321. function formatError(arg) {
  12322. if (arg instanceof Error) {
  12323. if (arg.stack) {
  12324. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  12325. ? 'Error: ' + arg.message + '\n' + arg.stack
  12326. : arg.stack;
  12327. } else if (arg.sourceURL) {
  12328. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  12329. }
  12330. }
  12331. return arg;
  12332. }
  12333. function consoleLog(type) {
  12334. var console = $window.console || {},
  12335. logFn = console[type] || console.log || noop,
  12336. hasApply = false;
  12337. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  12338. // The reason behind this is that console.log has type "object" in IE8...
  12339. try {
  12340. hasApply = !!logFn.apply;
  12341. } catch (e) {}
  12342. if (hasApply) {
  12343. return function() {
  12344. var args = [];
  12345. forEach(arguments, function(arg) {
  12346. args.push(formatError(arg));
  12347. });
  12348. return logFn.apply(console, args);
  12349. };
  12350. }
  12351. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  12352. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  12353. return function(arg1, arg2) {
  12354. logFn(arg1, arg2 == null ? '' : arg2);
  12355. };
  12356. }
  12357. }];
  12358. }
  12359. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  12360. * Any commits to this file should be reviewed with security in mind. *
  12361. * Changes to this file can potentially create security vulnerabilities. *
  12362. * An approval from 2 Core members with history of modifying *
  12363. * this file is required. *
  12364. * *
  12365. * Does the change somehow allow for arbitrary javascript to be executed? *
  12366. * Or allows for someone to change the prototype of built-in objects? *
  12367. * Or gives undesired access to variables likes document or window? *
  12368. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  12369. var $parseMinErr = minErr('$parse');
  12370. // Sandboxing Angular Expressions
  12371. // ------------------------------
  12372. // Angular expressions are generally considered safe because these expressions only have direct
  12373. // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
  12374. // obtaining a reference to native JS functions such as the Function constructor.
  12375. //
  12376. // As an example, consider the following Angular expression:
  12377. //
  12378. // {}.toString.constructor('alert("evil JS code")')
  12379. //
  12380. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  12381. // against the expression language, but not to prevent exploits that were enabled by exposing
  12382. // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
  12383. // practice and therefore we are not even trying to protect against interaction with an object
  12384. // explicitly exposed in this way.
  12385. //
  12386. // In general, it is not possible to access a Window object from an angular expression unless a
  12387. // window or some DOM object that has a reference to window is published onto a Scope.
  12388. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  12389. // native objects.
  12390. //
  12391. // See https://docs.angularjs.org/guide/security
  12392. function ensureSafeMemberName(name, fullExpression) {
  12393. if (name === "__defineGetter__" || name === "__defineSetter__"
  12394. || name === "__lookupGetter__" || name === "__lookupSetter__"
  12395. || name === "__proto__") {
  12396. throw $parseMinErr('isecfld',
  12397. 'Attempting to access a disallowed field in Angular expressions! '
  12398. + 'Expression: {0}', fullExpression);
  12399. }
  12400. return name;
  12401. }
  12402. function getStringValue(name) {
  12403. // Property names must be strings. This means that non-string objects cannot be used
  12404. // as keys in an object. Any non-string object, including a number, is typecasted
  12405. // into a string via the toString method.
  12406. // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names
  12407. //
  12408. // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it
  12409. // to a string. It's not always possible. If `name` is an object and its `toString` method is
  12410. // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:
  12411. //
  12412. // TypeError: Cannot convert object to primitive value
  12413. //
  12414. // For performance reasons, we don't catch this error here and allow it to propagate up the call
  12415. // stack. Note that you'll get the same error in JavaScript if you try to access a property using
  12416. // such a 'broken' object as a key.
  12417. return name + '';
  12418. }
  12419. function ensureSafeObject(obj, fullExpression) {
  12420. // nifty check if obj is Function that is fast and works across iframes and other contexts
  12421. if (obj) {
  12422. if (obj.constructor === obj) {
  12423. throw $parseMinErr('isecfn',
  12424. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  12425. fullExpression);
  12426. } else if (// isWindow(obj)
  12427. obj.window === obj) {
  12428. throw $parseMinErr('isecwindow',
  12429. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  12430. fullExpression);
  12431. } else if (// isElement(obj)
  12432. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  12433. throw $parseMinErr('isecdom',
  12434. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  12435. fullExpression);
  12436. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  12437. obj === Object) {
  12438. throw $parseMinErr('isecobj',
  12439. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  12440. fullExpression);
  12441. }
  12442. }
  12443. return obj;
  12444. }
  12445. var CALL = Function.prototype.call;
  12446. var APPLY = Function.prototype.apply;
  12447. var BIND = Function.prototype.bind;
  12448. function ensureSafeFunction(obj, fullExpression) {
  12449. if (obj) {
  12450. if (obj.constructor === obj) {
  12451. throw $parseMinErr('isecfn',
  12452. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  12453. fullExpression);
  12454. } else if (obj === CALL || obj === APPLY || obj === BIND) {
  12455. throw $parseMinErr('isecff',
  12456. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  12457. fullExpression);
  12458. }
  12459. }
  12460. }
  12461. function ensureSafeAssignContext(obj, fullExpression) {
  12462. if (obj) {
  12463. if (obj === (0).constructor || obj === (false).constructor || obj === ''.constructor ||
  12464. obj === {}.constructor || obj === [].constructor || obj === Function.constructor) {
  12465. throw $parseMinErr('isecaf',
  12466. 'Assigning to a constructor is disallowed! Expression: {0}', fullExpression);
  12467. }
  12468. }
  12469. }
  12470. var OPERATORS = createMap();
  12471. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  12472. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  12473. /////////////////////////////////////////
  12474. /**
  12475. * @constructor
  12476. */
  12477. var Lexer = function(options) {
  12478. this.options = options;
  12479. };
  12480. Lexer.prototype = {
  12481. constructor: Lexer,
  12482. lex: function(text) {
  12483. this.text = text;
  12484. this.index = 0;
  12485. this.tokens = [];
  12486. while (this.index < this.text.length) {
  12487. var ch = this.text.charAt(this.index);
  12488. if (ch === '"' || ch === "'") {
  12489. this.readString(ch);
  12490. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  12491. this.readNumber();
  12492. } else if (this.isIdentifierStart(this.peekMultichar())) {
  12493. this.readIdent();
  12494. } else if (this.is(ch, '(){}[].,;:?')) {
  12495. this.tokens.push({index: this.index, text: ch});
  12496. this.index++;
  12497. } else if (this.isWhitespace(ch)) {
  12498. this.index++;
  12499. } else {
  12500. var ch2 = ch + this.peek();
  12501. var ch3 = ch2 + this.peek(2);
  12502. var op1 = OPERATORS[ch];
  12503. var op2 = OPERATORS[ch2];
  12504. var op3 = OPERATORS[ch3];
  12505. if (op1 || op2 || op3) {
  12506. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  12507. this.tokens.push({index: this.index, text: token, operator: true});
  12508. this.index += token.length;
  12509. } else {
  12510. this.throwError('Unexpected next character ', this.index, this.index + 1);
  12511. }
  12512. }
  12513. }
  12514. return this.tokens;
  12515. },
  12516. is: function(ch, chars) {
  12517. return chars.indexOf(ch) !== -1;
  12518. },
  12519. peek: function(i) {
  12520. var num = i || 1;
  12521. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  12522. },
  12523. isNumber: function(ch) {
  12524. return ('0' <= ch && ch <= '9') && typeof ch === "string";
  12525. },
  12526. isWhitespace: function(ch) {
  12527. // IE treats non-breaking space as \u00A0
  12528. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  12529. ch === '\n' || ch === '\v' || ch === '\u00A0');
  12530. },
  12531. isIdentifierStart: function(ch) {
  12532. return this.options.isIdentifierStart ?
  12533. this.options.isIdentifierStart(ch, this.codePointAt(ch)) :
  12534. this.isValidIdentifierStart(ch);
  12535. },
  12536. isValidIdentifierStart: function(ch) {
  12537. return ('a' <= ch && ch <= 'z' ||
  12538. 'A' <= ch && ch <= 'Z' ||
  12539. '_' === ch || ch === '$');
  12540. },
  12541. isIdentifierContinue: function(ch) {
  12542. return this.options.isIdentifierContinue ?
  12543. this.options.isIdentifierContinue(ch, this.codePointAt(ch)) :
  12544. this.isValidIdentifierContinue(ch);
  12545. },
  12546. isValidIdentifierContinue: function(ch, cp) {
  12547. return this.isValidIdentifierStart(ch, cp) || this.isNumber(ch);
  12548. },
  12549. codePointAt: function(ch) {
  12550. if (ch.length === 1) return ch.charCodeAt(0);
  12551. /*jshint bitwise: false*/
  12552. return (ch.charCodeAt(0) << 10) + ch.charCodeAt(1) - 0x35FDC00;
  12553. /*jshint bitwise: true*/
  12554. },
  12555. peekMultichar: function() {
  12556. var ch = this.text.charAt(this.index);
  12557. var peek = this.peek();
  12558. if (!peek) {
  12559. return ch;
  12560. }
  12561. var cp1 = ch.charCodeAt(0);
  12562. var cp2 = peek.charCodeAt(0);
  12563. if (cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF) {
  12564. return ch + peek;
  12565. }
  12566. return ch;
  12567. },
  12568. isExpOperator: function(ch) {
  12569. return (ch === '-' || ch === '+' || this.isNumber(ch));
  12570. },
  12571. throwError: function(error, start, end) {
  12572. end = end || this.index;
  12573. var colStr = (isDefined(start)
  12574. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  12575. : ' ' + end);
  12576. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  12577. error, colStr, this.text);
  12578. },
  12579. readNumber: function() {
  12580. var number = '';
  12581. var start = this.index;
  12582. while (this.index < this.text.length) {
  12583. var ch = lowercase(this.text.charAt(this.index));
  12584. if (ch == '.' || this.isNumber(ch)) {
  12585. number += ch;
  12586. } else {
  12587. var peekCh = this.peek();
  12588. if (ch == 'e' && this.isExpOperator(peekCh)) {
  12589. number += ch;
  12590. } else if (this.isExpOperator(ch) &&
  12591. peekCh && this.isNumber(peekCh) &&
  12592. number.charAt(number.length - 1) == 'e') {
  12593. number += ch;
  12594. } else if (this.isExpOperator(ch) &&
  12595. (!peekCh || !this.isNumber(peekCh)) &&
  12596. number.charAt(number.length - 1) == 'e') {
  12597. this.throwError('Invalid exponent');
  12598. } else {
  12599. break;
  12600. }
  12601. }
  12602. this.index++;
  12603. }
  12604. this.tokens.push({
  12605. index: start,
  12606. text: number,
  12607. constant: true,
  12608. value: Number(number)
  12609. });
  12610. },
  12611. readIdent: function() {
  12612. var start = this.index;
  12613. this.index += this.peekMultichar().length;
  12614. while (this.index < this.text.length) {
  12615. var ch = this.peekMultichar();
  12616. if (!this.isIdentifierContinue(ch)) {
  12617. break;
  12618. }
  12619. this.index += ch.length;
  12620. }
  12621. this.tokens.push({
  12622. index: start,
  12623. text: this.text.slice(start, this.index),
  12624. identifier: true
  12625. });
  12626. },
  12627. readString: function(quote) {
  12628. var start = this.index;
  12629. this.index++;
  12630. var string = '';
  12631. var rawString = quote;
  12632. var escape = false;
  12633. while (this.index < this.text.length) {
  12634. var ch = this.text.charAt(this.index);
  12635. rawString += ch;
  12636. if (escape) {
  12637. if (ch === 'u') {
  12638. var hex = this.text.substring(this.index + 1, this.index + 5);
  12639. if (!hex.match(/[\da-f]{4}/i)) {
  12640. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  12641. }
  12642. this.index += 4;
  12643. string += String.fromCharCode(parseInt(hex, 16));
  12644. } else {
  12645. var rep = ESCAPE[ch];
  12646. string = string + (rep || ch);
  12647. }
  12648. escape = false;
  12649. } else if (ch === '\\') {
  12650. escape = true;
  12651. } else if (ch === quote) {
  12652. this.index++;
  12653. this.tokens.push({
  12654. index: start,
  12655. text: rawString,
  12656. constant: true,
  12657. value: string
  12658. });
  12659. return;
  12660. } else {
  12661. string += ch;
  12662. }
  12663. this.index++;
  12664. }
  12665. this.throwError('Unterminated quote', start);
  12666. }
  12667. };
  12668. var AST = function(lexer, options) {
  12669. this.lexer = lexer;
  12670. this.options = options;
  12671. };
  12672. AST.Program = 'Program';
  12673. AST.ExpressionStatement = 'ExpressionStatement';
  12674. AST.AssignmentExpression = 'AssignmentExpression';
  12675. AST.ConditionalExpression = 'ConditionalExpression';
  12676. AST.LogicalExpression = 'LogicalExpression';
  12677. AST.BinaryExpression = 'BinaryExpression';
  12678. AST.UnaryExpression = 'UnaryExpression';
  12679. AST.CallExpression = 'CallExpression';
  12680. AST.MemberExpression = 'MemberExpression';
  12681. AST.Identifier = 'Identifier';
  12682. AST.Literal = 'Literal';
  12683. AST.ArrayExpression = 'ArrayExpression';
  12684. AST.Property = 'Property';
  12685. AST.ObjectExpression = 'ObjectExpression';
  12686. AST.ThisExpression = 'ThisExpression';
  12687. AST.LocalsExpression = 'LocalsExpression';
  12688. // Internal use only
  12689. AST.NGValueParameter = 'NGValueParameter';
  12690. AST.prototype = {
  12691. ast: function(text) {
  12692. this.text = text;
  12693. this.tokens = this.lexer.lex(text);
  12694. var value = this.program();
  12695. if (this.tokens.length !== 0) {
  12696. this.throwError('is an unexpected token', this.tokens[0]);
  12697. }
  12698. return value;
  12699. },
  12700. program: function() {
  12701. var body = [];
  12702. while (true) {
  12703. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  12704. body.push(this.expressionStatement());
  12705. if (!this.expect(';')) {
  12706. return { type: AST.Program, body: body};
  12707. }
  12708. }
  12709. },
  12710. expressionStatement: function() {
  12711. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  12712. },
  12713. filterChain: function() {
  12714. var left = this.expression();
  12715. var token;
  12716. while ((token = this.expect('|'))) {
  12717. left = this.filter(left);
  12718. }
  12719. return left;
  12720. },
  12721. expression: function() {
  12722. return this.assignment();
  12723. },
  12724. assignment: function() {
  12725. var result = this.ternary();
  12726. if (this.expect('=')) {
  12727. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  12728. }
  12729. return result;
  12730. },
  12731. ternary: function() {
  12732. var test = this.logicalOR();
  12733. var alternate;
  12734. var consequent;
  12735. if (this.expect('?')) {
  12736. alternate = this.expression();
  12737. if (this.consume(':')) {
  12738. consequent = this.expression();
  12739. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  12740. }
  12741. }
  12742. return test;
  12743. },
  12744. logicalOR: function() {
  12745. var left = this.logicalAND();
  12746. while (this.expect('||')) {
  12747. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  12748. }
  12749. return left;
  12750. },
  12751. logicalAND: function() {
  12752. var left = this.equality();
  12753. while (this.expect('&&')) {
  12754. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  12755. }
  12756. return left;
  12757. },
  12758. equality: function() {
  12759. var left = this.relational();
  12760. var token;
  12761. while ((token = this.expect('==','!=','===','!=='))) {
  12762. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  12763. }
  12764. return left;
  12765. },
  12766. relational: function() {
  12767. var left = this.additive();
  12768. var token;
  12769. while ((token = this.expect('<', '>', '<=', '>='))) {
  12770. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  12771. }
  12772. return left;
  12773. },
  12774. additive: function() {
  12775. var left = this.multiplicative();
  12776. var token;
  12777. while ((token = this.expect('+','-'))) {
  12778. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  12779. }
  12780. return left;
  12781. },
  12782. multiplicative: function() {
  12783. var left = this.unary();
  12784. var token;
  12785. while ((token = this.expect('*','/','%'))) {
  12786. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  12787. }
  12788. return left;
  12789. },
  12790. unary: function() {
  12791. var token;
  12792. if ((token = this.expect('+', '-', '!'))) {
  12793. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  12794. } else {
  12795. return this.primary();
  12796. }
  12797. },
  12798. primary: function() {
  12799. var primary;
  12800. if (this.expect('(')) {
  12801. primary = this.filterChain();
  12802. this.consume(')');
  12803. } else if (this.expect('[')) {
  12804. primary = this.arrayDeclaration();
  12805. } else if (this.expect('{')) {
  12806. primary = this.object();
  12807. } else if (this.selfReferential.hasOwnProperty(this.peek().text)) {
  12808. primary = copy(this.selfReferential[this.consume().text]);
  12809. } else if (this.options.literals.hasOwnProperty(this.peek().text)) {
  12810. primary = { type: AST.Literal, value: this.options.literals[this.consume().text]};
  12811. } else if (this.peek().identifier) {
  12812. primary = this.identifier();
  12813. } else if (this.peek().constant) {
  12814. primary = this.constant();
  12815. } else {
  12816. this.throwError('not a primary expression', this.peek());
  12817. }
  12818. var next;
  12819. while ((next = this.expect('(', '[', '.'))) {
  12820. if (next.text === '(') {
  12821. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  12822. this.consume(')');
  12823. } else if (next.text === '[') {
  12824. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  12825. this.consume(']');
  12826. } else if (next.text === '.') {
  12827. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  12828. } else {
  12829. this.throwError('IMPOSSIBLE');
  12830. }
  12831. }
  12832. return primary;
  12833. },
  12834. filter: function(baseExpression) {
  12835. var args = [baseExpression];
  12836. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  12837. while (this.expect(':')) {
  12838. args.push(this.expression());
  12839. }
  12840. return result;
  12841. },
  12842. parseArguments: function() {
  12843. var args = [];
  12844. if (this.peekToken().text !== ')') {
  12845. do {
  12846. args.push(this.filterChain());
  12847. } while (this.expect(','));
  12848. }
  12849. return args;
  12850. },
  12851. identifier: function() {
  12852. var token = this.consume();
  12853. if (!token.identifier) {
  12854. this.throwError('is not a valid identifier', token);
  12855. }
  12856. return { type: AST.Identifier, name: token.text };
  12857. },
  12858. constant: function() {
  12859. // TODO check that it is a constant
  12860. return { type: AST.Literal, value: this.consume().value };
  12861. },
  12862. arrayDeclaration: function() {
  12863. var elements = [];
  12864. if (this.peekToken().text !== ']') {
  12865. do {
  12866. if (this.peek(']')) {
  12867. // Support trailing commas per ES5.1.
  12868. break;
  12869. }
  12870. elements.push(this.expression());
  12871. } while (this.expect(','));
  12872. }
  12873. this.consume(']');
  12874. return { type: AST.ArrayExpression, elements: elements };
  12875. },
  12876. object: function() {
  12877. var properties = [], property;
  12878. if (this.peekToken().text !== '}') {
  12879. do {
  12880. if (this.peek('}')) {
  12881. // Support trailing commas per ES5.1.
  12882. break;
  12883. }
  12884. property = {type: AST.Property, kind: 'init'};
  12885. if (this.peek().constant) {
  12886. property.key = this.constant();
  12887. property.computed = false;
  12888. this.consume(':');
  12889. property.value = this.expression();
  12890. } else if (this.peek().identifier) {
  12891. property.key = this.identifier();
  12892. property.computed = false;
  12893. if (this.peek(':')) {
  12894. this.consume(':');
  12895. property.value = this.expression();
  12896. } else {
  12897. property.value = property.key;
  12898. }
  12899. } else if (this.peek('[')) {
  12900. this.consume('[');
  12901. property.key = this.expression();
  12902. this.consume(']');
  12903. property.computed = true;
  12904. this.consume(':');
  12905. property.value = this.expression();
  12906. } else {
  12907. this.throwError("invalid key", this.peek());
  12908. }
  12909. properties.push(property);
  12910. } while (this.expect(','));
  12911. }
  12912. this.consume('}');
  12913. return {type: AST.ObjectExpression, properties: properties };
  12914. },
  12915. throwError: function(msg, token) {
  12916. throw $parseMinErr('syntax',
  12917. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  12918. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  12919. },
  12920. consume: function(e1) {
  12921. if (this.tokens.length === 0) {
  12922. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  12923. }
  12924. var token = this.expect(e1);
  12925. if (!token) {
  12926. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  12927. }
  12928. return token;
  12929. },
  12930. peekToken: function() {
  12931. if (this.tokens.length === 0) {
  12932. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  12933. }
  12934. return this.tokens[0];
  12935. },
  12936. peek: function(e1, e2, e3, e4) {
  12937. return this.peekAhead(0, e1, e2, e3, e4);
  12938. },
  12939. peekAhead: function(i, e1, e2, e3, e4) {
  12940. if (this.tokens.length > i) {
  12941. var token = this.tokens[i];
  12942. var t = token.text;
  12943. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  12944. (!e1 && !e2 && !e3 && !e4)) {
  12945. return token;
  12946. }
  12947. }
  12948. return false;
  12949. },
  12950. expect: function(e1, e2, e3, e4) {
  12951. var token = this.peek(e1, e2, e3, e4);
  12952. if (token) {
  12953. this.tokens.shift();
  12954. return token;
  12955. }
  12956. return false;
  12957. },
  12958. selfReferential: {
  12959. 'this': {type: AST.ThisExpression },
  12960. '$locals': {type: AST.LocalsExpression }
  12961. }
  12962. };
  12963. function ifDefined(v, d) {
  12964. return typeof v !== 'undefined' ? v : d;
  12965. }
  12966. function plusFn(l, r) {
  12967. if (typeof l === 'undefined') return r;
  12968. if (typeof r === 'undefined') return l;
  12969. return l + r;
  12970. }
  12971. function isStateless($filter, filterName) {
  12972. var fn = $filter(filterName);
  12973. return !fn.$stateful;
  12974. }
  12975. function findConstantAndWatchExpressions(ast, $filter) {
  12976. var allConstants;
  12977. var argsToWatch;
  12978. switch (ast.type) {
  12979. case AST.Program:
  12980. allConstants = true;
  12981. forEach(ast.body, function(expr) {
  12982. findConstantAndWatchExpressions(expr.expression, $filter);
  12983. allConstants = allConstants && expr.expression.constant;
  12984. });
  12985. ast.constant = allConstants;
  12986. break;
  12987. case AST.Literal:
  12988. ast.constant = true;
  12989. ast.toWatch = [];
  12990. break;
  12991. case AST.UnaryExpression:
  12992. findConstantAndWatchExpressions(ast.argument, $filter);
  12993. ast.constant = ast.argument.constant;
  12994. ast.toWatch = ast.argument.toWatch;
  12995. break;
  12996. case AST.BinaryExpression:
  12997. findConstantAndWatchExpressions(ast.left, $filter);
  12998. findConstantAndWatchExpressions(ast.right, $filter);
  12999. ast.constant = ast.left.constant && ast.right.constant;
  13000. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  13001. break;
  13002. case AST.LogicalExpression:
  13003. findConstantAndWatchExpressions(ast.left, $filter);
  13004. findConstantAndWatchExpressions(ast.right, $filter);
  13005. ast.constant = ast.left.constant && ast.right.constant;
  13006. ast.toWatch = ast.constant ? [] : [ast];
  13007. break;
  13008. case AST.ConditionalExpression:
  13009. findConstantAndWatchExpressions(ast.test, $filter);
  13010. findConstantAndWatchExpressions(ast.alternate, $filter);
  13011. findConstantAndWatchExpressions(ast.consequent, $filter);
  13012. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  13013. ast.toWatch = ast.constant ? [] : [ast];
  13014. break;
  13015. case AST.Identifier:
  13016. ast.constant = false;
  13017. ast.toWatch = [ast];
  13018. break;
  13019. case AST.MemberExpression:
  13020. findConstantAndWatchExpressions(ast.object, $filter);
  13021. if (ast.computed) {
  13022. findConstantAndWatchExpressions(ast.property, $filter);
  13023. }
  13024. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  13025. ast.toWatch = [ast];
  13026. break;
  13027. case AST.CallExpression:
  13028. allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
  13029. argsToWatch = [];
  13030. forEach(ast.arguments, function(expr) {
  13031. findConstantAndWatchExpressions(expr, $filter);
  13032. allConstants = allConstants && expr.constant;
  13033. if (!expr.constant) {
  13034. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  13035. }
  13036. });
  13037. ast.constant = allConstants;
  13038. ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
  13039. break;
  13040. case AST.AssignmentExpression:
  13041. findConstantAndWatchExpressions(ast.left, $filter);
  13042. findConstantAndWatchExpressions(ast.right, $filter);
  13043. ast.constant = ast.left.constant && ast.right.constant;
  13044. ast.toWatch = [ast];
  13045. break;
  13046. case AST.ArrayExpression:
  13047. allConstants = true;
  13048. argsToWatch = [];
  13049. forEach(ast.elements, function(expr) {
  13050. findConstantAndWatchExpressions(expr, $filter);
  13051. allConstants = allConstants && expr.constant;
  13052. if (!expr.constant) {
  13053. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  13054. }
  13055. });
  13056. ast.constant = allConstants;
  13057. ast.toWatch = argsToWatch;
  13058. break;
  13059. case AST.ObjectExpression:
  13060. allConstants = true;
  13061. argsToWatch = [];
  13062. forEach(ast.properties, function(property) {
  13063. findConstantAndWatchExpressions(property.value, $filter);
  13064. allConstants = allConstants && property.value.constant && !property.computed;
  13065. if (!property.value.constant) {
  13066. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  13067. }
  13068. });
  13069. ast.constant = allConstants;
  13070. ast.toWatch = argsToWatch;
  13071. break;
  13072. case AST.ThisExpression:
  13073. ast.constant = false;
  13074. ast.toWatch = [];
  13075. break;
  13076. case AST.LocalsExpression:
  13077. ast.constant = false;
  13078. ast.toWatch = [];
  13079. break;
  13080. }
  13081. }
  13082. function getInputs(body) {
  13083. if (body.length != 1) return;
  13084. var lastExpression = body[0].expression;
  13085. var candidate = lastExpression.toWatch;
  13086. if (candidate.length !== 1) return candidate;
  13087. return candidate[0] !== lastExpression ? candidate : undefined;
  13088. }
  13089. function isAssignable(ast) {
  13090. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  13091. }
  13092. function assignableAST(ast) {
  13093. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  13094. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  13095. }
  13096. }
  13097. function isLiteral(ast) {
  13098. return ast.body.length === 0 ||
  13099. ast.body.length === 1 && (
  13100. ast.body[0].expression.type === AST.Literal ||
  13101. ast.body[0].expression.type === AST.ArrayExpression ||
  13102. ast.body[0].expression.type === AST.ObjectExpression);
  13103. }
  13104. function isConstant(ast) {
  13105. return ast.constant;
  13106. }
  13107. function ASTCompiler(astBuilder, $filter) {
  13108. this.astBuilder = astBuilder;
  13109. this.$filter = $filter;
  13110. }
  13111. ASTCompiler.prototype = {
  13112. compile: function(expression, expensiveChecks) {
  13113. var self = this;
  13114. var ast = this.astBuilder.ast(expression);
  13115. this.state = {
  13116. nextId: 0,
  13117. filters: {},
  13118. expensiveChecks: expensiveChecks,
  13119. fn: {vars: [], body: [], own: {}},
  13120. assign: {vars: [], body: [], own: {}},
  13121. inputs: []
  13122. };
  13123. findConstantAndWatchExpressions(ast, self.$filter);
  13124. var extra = '';
  13125. var assignable;
  13126. this.stage = 'assign';
  13127. if ((assignable = assignableAST(ast))) {
  13128. this.state.computing = 'assign';
  13129. var result = this.nextId();
  13130. this.recurse(assignable, result);
  13131. this.return_(result);
  13132. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  13133. }
  13134. var toWatch = getInputs(ast.body);
  13135. self.stage = 'inputs';
  13136. forEach(toWatch, function(watch, key) {
  13137. var fnKey = 'fn' + key;
  13138. self.state[fnKey] = {vars: [], body: [], own: {}};
  13139. self.state.computing = fnKey;
  13140. var intoId = self.nextId();
  13141. self.recurse(watch, intoId);
  13142. self.return_(intoId);
  13143. self.state.inputs.push(fnKey);
  13144. watch.watchId = key;
  13145. });
  13146. this.state.computing = 'fn';
  13147. this.stage = 'main';
  13148. this.recurse(ast);
  13149. var fnString =
  13150. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  13151. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  13152. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  13153. this.filterPrefix() +
  13154. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  13155. extra +
  13156. this.watchFns() +
  13157. 'return fn;';
  13158. /* jshint -W054 */
  13159. var fn = (new Function('$filter',
  13160. 'ensureSafeMemberName',
  13161. 'ensureSafeObject',
  13162. 'ensureSafeFunction',
  13163. 'getStringValue',
  13164. 'ensureSafeAssignContext',
  13165. 'ifDefined',
  13166. 'plus',
  13167. 'text',
  13168. fnString))(
  13169. this.$filter,
  13170. ensureSafeMemberName,
  13171. ensureSafeObject,
  13172. ensureSafeFunction,
  13173. getStringValue,
  13174. ensureSafeAssignContext,
  13175. ifDefined,
  13176. plusFn,
  13177. expression);
  13178. /* jshint +W054 */
  13179. this.state = this.stage = undefined;
  13180. fn.literal = isLiteral(ast);
  13181. fn.constant = isConstant(ast);
  13182. return fn;
  13183. },
  13184. USE: 'use',
  13185. STRICT: 'strict',
  13186. watchFns: function() {
  13187. var result = [];
  13188. var fns = this.state.inputs;
  13189. var self = this;
  13190. forEach(fns, function(name) {
  13191. result.push('var ' + name + '=' + self.generateFunction(name, 's'));
  13192. });
  13193. if (fns.length) {
  13194. result.push('fn.inputs=[' + fns.join(',') + '];');
  13195. }
  13196. return result.join('');
  13197. },
  13198. generateFunction: function(name, params) {
  13199. return 'function(' + params + '){' +
  13200. this.varsPrefix(name) +
  13201. this.body(name) +
  13202. '};';
  13203. },
  13204. filterPrefix: function() {
  13205. var parts = [];
  13206. var self = this;
  13207. forEach(this.state.filters, function(id, filter) {
  13208. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  13209. });
  13210. if (parts.length) return 'var ' + parts.join(',') + ';';
  13211. return '';
  13212. },
  13213. varsPrefix: function(section) {
  13214. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  13215. },
  13216. body: function(section) {
  13217. return this.state[section].body.join('');
  13218. },
  13219. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  13220. var left, right, self = this, args, expression, computed;
  13221. recursionFn = recursionFn || noop;
  13222. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  13223. intoId = intoId || this.nextId();
  13224. this.if_('i',
  13225. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  13226. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  13227. );
  13228. return;
  13229. }
  13230. switch (ast.type) {
  13231. case AST.Program:
  13232. forEach(ast.body, function(expression, pos) {
  13233. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  13234. if (pos !== ast.body.length - 1) {
  13235. self.current().body.push(right, ';');
  13236. } else {
  13237. self.return_(right);
  13238. }
  13239. });
  13240. break;
  13241. case AST.Literal:
  13242. expression = this.escape(ast.value);
  13243. this.assign(intoId, expression);
  13244. recursionFn(expression);
  13245. break;
  13246. case AST.UnaryExpression:
  13247. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  13248. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  13249. this.assign(intoId, expression);
  13250. recursionFn(expression);
  13251. break;
  13252. case AST.BinaryExpression:
  13253. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  13254. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  13255. if (ast.operator === '+') {
  13256. expression = this.plus(left, right);
  13257. } else if (ast.operator === '-') {
  13258. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  13259. } else {
  13260. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  13261. }
  13262. this.assign(intoId, expression);
  13263. recursionFn(expression);
  13264. break;
  13265. case AST.LogicalExpression:
  13266. intoId = intoId || this.nextId();
  13267. self.recurse(ast.left, intoId);
  13268. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  13269. recursionFn(intoId);
  13270. break;
  13271. case AST.ConditionalExpression:
  13272. intoId = intoId || this.nextId();
  13273. self.recurse(ast.test, intoId);
  13274. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  13275. recursionFn(intoId);
  13276. break;
  13277. case AST.Identifier:
  13278. intoId = intoId || this.nextId();
  13279. if (nameId) {
  13280. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  13281. nameId.computed = false;
  13282. nameId.name = ast.name;
  13283. }
  13284. ensureSafeMemberName(ast.name);
  13285. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  13286. function() {
  13287. self.if_(self.stage === 'inputs' || 's', function() {
  13288. if (create && create !== 1) {
  13289. self.if_(
  13290. self.not(self.nonComputedMember('s', ast.name)),
  13291. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  13292. }
  13293. self.assign(intoId, self.nonComputedMember('s', ast.name));
  13294. });
  13295. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  13296. );
  13297. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
  13298. self.addEnsureSafeObject(intoId);
  13299. }
  13300. recursionFn(intoId);
  13301. break;
  13302. case AST.MemberExpression:
  13303. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  13304. intoId = intoId || this.nextId();
  13305. self.recurse(ast.object, left, undefined, function() {
  13306. self.if_(self.notNull(left), function() {
  13307. if (create && create !== 1) {
  13308. self.addEnsureSafeAssignContext(left);
  13309. }
  13310. if (ast.computed) {
  13311. right = self.nextId();
  13312. self.recurse(ast.property, right);
  13313. self.getStringValue(right);
  13314. self.addEnsureSafeMemberName(right);
  13315. if (create && create !== 1) {
  13316. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  13317. }
  13318. expression = self.ensureSafeObject(self.computedMember(left, right));
  13319. self.assign(intoId, expression);
  13320. if (nameId) {
  13321. nameId.computed = true;
  13322. nameId.name = right;
  13323. }
  13324. } else {
  13325. ensureSafeMemberName(ast.property.name);
  13326. if (create && create !== 1) {
  13327. self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  13328. }
  13329. expression = self.nonComputedMember(left, ast.property.name);
  13330. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
  13331. expression = self.ensureSafeObject(expression);
  13332. }
  13333. self.assign(intoId, expression);
  13334. if (nameId) {
  13335. nameId.computed = false;
  13336. nameId.name = ast.property.name;
  13337. }
  13338. }
  13339. }, function() {
  13340. self.assign(intoId, 'undefined');
  13341. });
  13342. recursionFn(intoId);
  13343. }, !!create);
  13344. break;
  13345. case AST.CallExpression:
  13346. intoId = intoId || this.nextId();
  13347. if (ast.filter) {
  13348. right = self.filter(ast.callee.name);
  13349. args = [];
  13350. forEach(ast.arguments, function(expr) {
  13351. var argument = self.nextId();
  13352. self.recurse(expr, argument);
  13353. args.push(argument);
  13354. });
  13355. expression = right + '(' + args.join(',') + ')';
  13356. self.assign(intoId, expression);
  13357. recursionFn(intoId);
  13358. } else {
  13359. right = self.nextId();
  13360. left = {};
  13361. args = [];
  13362. self.recurse(ast.callee, right, left, function() {
  13363. self.if_(self.notNull(right), function() {
  13364. self.addEnsureSafeFunction(right);
  13365. forEach(ast.arguments, function(expr) {
  13366. self.recurse(expr, self.nextId(), undefined, function(argument) {
  13367. args.push(self.ensureSafeObject(argument));
  13368. });
  13369. });
  13370. if (left.name) {
  13371. if (!self.state.expensiveChecks) {
  13372. self.addEnsureSafeObject(left.context);
  13373. }
  13374. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  13375. } else {
  13376. expression = right + '(' + args.join(',') + ')';
  13377. }
  13378. expression = self.ensureSafeObject(expression);
  13379. self.assign(intoId, expression);
  13380. }, function() {
  13381. self.assign(intoId, 'undefined');
  13382. });
  13383. recursionFn(intoId);
  13384. });
  13385. }
  13386. break;
  13387. case AST.AssignmentExpression:
  13388. right = this.nextId();
  13389. left = {};
  13390. if (!isAssignable(ast.left)) {
  13391. throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
  13392. }
  13393. this.recurse(ast.left, undefined, left, function() {
  13394. self.if_(self.notNull(left.context), function() {
  13395. self.recurse(ast.right, right);
  13396. self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
  13397. self.addEnsureSafeAssignContext(left.context);
  13398. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  13399. self.assign(intoId, expression);
  13400. recursionFn(intoId || expression);
  13401. });
  13402. }, 1);
  13403. break;
  13404. case AST.ArrayExpression:
  13405. args = [];
  13406. forEach(ast.elements, function(expr) {
  13407. self.recurse(expr, self.nextId(), undefined, function(argument) {
  13408. args.push(argument);
  13409. });
  13410. });
  13411. expression = '[' + args.join(',') + ']';
  13412. this.assign(intoId, expression);
  13413. recursionFn(expression);
  13414. break;
  13415. case AST.ObjectExpression:
  13416. args = [];
  13417. computed = false;
  13418. forEach(ast.properties, function(property) {
  13419. if (property.computed) {
  13420. computed = true;
  13421. }
  13422. });
  13423. if (computed) {
  13424. intoId = intoId || this.nextId();
  13425. this.assign(intoId, '{}');
  13426. forEach(ast.properties, function(property) {
  13427. if (property.computed) {
  13428. left = self.nextId();
  13429. self.recurse(property.key, left);
  13430. } else {
  13431. left = property.key.type === AST.Identifier ?
  13432. property.key.name :
  13433. ('' + property.key.value);
  13434. }
  13435. right = self.nextId();
  13436. self.recurse(property.value, right);
  13437. self.assign(self.member(intoId, left, property.computed), right);
  13438. });
  13439. } else {
  13440. forEach(ast.properties, function(property) {
  13441. self.recurse(property.value, ast.constant ? undefined : self.nextId(), undefined, function(expr) {
  13442. args.push(self.escape(
  13443. property.key.type === AST.Identifier ? property.key.name :
  13444. ('' + property.key.value)) +
  13445. ':' + expr);
  13446. });
  13447. });
  13448. expression = '{' + args.join(',') + '}';
  13449. this.assign(intoId, expression);
  13450. }
  13451. recursionFn(intoId || expression);
  13452. break;
  13453. case AST.ThisExpression:
  13454. this.assign(intoId, 's');
  13455. recursionFn('s');
  13456. break;
  13457. case AST.LocalsExpression:
  13458. this.assign(intoId, 'l');
  13459. recursionFn('l');
  13460. break;
  13461. case AST.NGValueParameter:
  13462. this.assign(intoId, 'v');
  13463. recursionFn('v');
  13464. break;
  13465. }
  13466. },
  13467. getHasOwnProperty: function(element, property) {
  13468. var key = element + '.' + property;
  13469. var own = this.current().own;
  13470. if (!own.hasOwnProperty(key)) {
  13471. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  13472. }
  13473. return own[key];
  13474. },
  13475. assign: function(id, value) {
  13476. if (!id) return;
  13477. this.current().body.push(id, '=', value, ';');
  13478. return id;
  13479. },
  13480. filter: function(filterName) {
  13481. if (!this.state.filters.hasOwnProperty(filterName)) {
  13482. this.state.filters[filterName] = this.nextId(true);
  13483. }
  13484. return this.state.filters[filterName];
  13485. },
  13486. ifDefined: function(id, defaultValue) {
  13487. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  13488. },
  13489. plus: function(left, right) {
  13490. return 'plus(' + left + ',' + right + ')';
  13491. },
  13492. return_: function(id) {
  13493. this.current().body.push('return ', id, ';');
  13494. },
  13495. if_: function(test, alternate, consequent) {
  13496. if (test === true) {
  13497. alternate();
  13498. } else {
  13499. var body = this.current().body;
  13500. body.push('if(', test, '){');
  13501. alternate();
  13502. body.push('}');
  13503. if (consequent) {
  13504. body.push('else{');
  13505. consequent();
  13506. body.push('}');
  13507. }
  13508. }
  13509. },
  13510. not: function(expression) {
  13511. return '!(' + expression + ')';
  13512. },
  13513. notNull: function(expression) {
  13514. return expression + '!=null';
  13515. },
  13516. nonComputedMember: function(left, right) {
  13517. var SAFE_IDENTIFIER = /[$_a-zA-Z][$_a-zA-Z0-9]*/;
  13518. var UNSAFE_CHARACTERS = /[^$_a-zA-Z0-9]/g;
  13519. if (SAFE_IDENTIFIER.test(right)) {
  13520. return left + '.' + right;
  13521. } else {
  13522. return left + '["' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '"]';
  13523. }
  13524. },
  13525. computedMember: function(left, right) {
  13526. return left + '[' + right + ']';
  13527. },
  13528. member: function(left, right, computed) {
  13529. if (computed) return this.computedMember(left, right);
  13530. return this.nonComputedMember(left, right);
  13531. },
  13532. addEnsureSafeObject: function(item) {
  13533. this.current().body.push(this.ensureSafeObject(item), ';');
  13534. },
  13535. addEnsureSafeMemberName: function(item) {
  13536. this.current().body.push(this.ensureSafeMemberName(item), ';');
  13537. },
  13538. addEnsureSafeFunction: function(item) {
  13539. this.current().body.push(this.ensureSafeFunction(item), ';');
  13540. },
  13541. addEnsureSafeAssignContext: function(item) {
  13542. this.current().body.push(this.ensureSafeAssignContext(item), ';');
  13543. },
  13544. ensureSafeObject: function(item) {
  13545. return 'ensureSafeObject(' + item + ',text)';
  13546. },
  13547. ensureSafeMemberName: function(item) {
  13548. return 'ensureSafeMemberName(' + item + ',text)';
  13549. },
  13550. ensureSafeFunction: function(item) {
  13551. return 'ensureSafeFunction(' + item + ',text)';
  13552. },
  13553. getStringValue: function(item) {
  13554. this.assign(item, 'getStringValue(' + item + ')');
  13555. },
  13556. ensureSafeAssignContext: function(item) {
  13557. return 'ensureSafeAssignContext(' + item + ',text)';
  13558. },
  13559. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  13560. var self = this;
  13561. return function() {
  13562. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  13563. };
  13564. },
  13565. lazyAssign: function(id, value) {
  13566. var self = this;
  13567. return function() {
  13568. self.assign(id, value);
  13569. };
  13570. },
  13571. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  13572. stringEscapeFn: function(c) {
  13573. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  13574. },
  13575. escape: function(value) {
  13576. if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
  13577. if (isNumber(value)) return value.toString();
  13578. if (value === true) return 'true';
  13579. if (value === false) return 'false';
  13580. if (value === null) return 'null';
  13581. if (typeof value === 'undefined') return 'undefined';
  13582. throw $parseMinErr('esc', 'IMPOSSIBLE');
  13583. },
  13584. nextId: function(skip, init) {
  13585. var id = 'v' + (this.state.nextId++);
  13586. if (!skip) {
  13587. this.current().vars.push(id + (init ? '=' + init : ''));
  13588. }
  13589. return id;
  13590. },
  13591. current: function() {
  13592. return this.state[this.state.computing];
  13593. }
  13594. };
  13595. function ASTInterpreter(astBuilder, $filter) {
  13596. this.astBuilder = astBuilder;
  13597. this.$filter = $filter;
  13598. }
  13599. ASTInterpreter.prototype = {
  13600. compile: function(expression, expensiveChecks) {
  13601. var self = this;
  13602. var ast = this.astBuilder.ast(expression);
  13603. this.expression = expression;
  13604. this.expensiveChecks = expensiveChecks;
  13605. findConstantAndWatchExpressions(ast, self.$filter);
  13606. var assignable;
  13607. var assign;
  13608. if ((assignable = assignableAST(ast))) {
  13609. assign = this.recurse(assignable);
  13610. }
  13611. var toWatch = getInputs(ast.body);
  13612. var inputs;
  13613. if (toWatch) {
  13614. inputs = [];
  13615. forEach(toWatch, function(watch, key) {
  13616. var input = self.recurse(watch);
  13617. watch.input = input;
  13618. inputs.push(input);
  13619. watch.watchId = key;
  13620. });
  13621. }
  13622. var expressions = [];
  13623. forEach(ast.body, function(expression) {
  13624. expressions.push(self.recurse(expression.expression));
  13625. });
  13626. var fn = ast.body.length === 0 ? noop :
  13627. ast.body.length === 1 ? expressions[0] :
  13628. function(scope, locals) {
  13629. var lastValue;
  13630. forEach(expressions, function(exp) {
  13631. lastValue = exp(scope, locals);
  13632. });
  13633. return lastValue;
  13634. };
  13635. if (assign) {
  13636. fn.assign = function(scope, value, locals) {
  13637. return assign(scope, locals, value);
  13638. };
  13639. }
  13640. if (inputs) {
  13641. fn.inputs = inputs;
  13642. }
  13643. fn.literal = isLiteral(ast);
  13644. fn.constant = isConstant(ast);
  13645. return fn;
  13646. },
  13647. recurse: function(ast, context, create) {
  13648. var left, right, self = this, args, expression;
  13649. if (ast.input) {
  13650. return this.inputs(ast.input, ast.watchId);
  13651. }
  13652. switch (ast.type) {
  13653. case AST.Literal:
  13654. return this.value(ast.value, context);
  13655. case AST.UnaryExpression:
  13656. right = this.recurse(ast.argument);
  13657. return this['unary' + ast.operator](right, context);
  13658. case AST.BinaryExpression:
  13659. left = this.recurse(ast.left);
  13660. right = this.recurse(ast.right);
  13661. return this['binary' + ast.operator](left, right, context);
  13662. case AST.LogicalExpression:
  13663. left = this.recurse(ast.left);
  13664. right = this.recurse(ast.right);
  13665. return this['binary' + ast.operator](left, right, context);
  13666. case AST.ConditionalExpression:
  13667. return this['ternary?:'](
  13668. this.recurse(ast.test),
  13669. this.recurse(ast.alternate),
  13670. this.recurse(ast.consequent),
  13671. context
  13672. );
  13673. case AST.Identifier:
  13674. ensureSafeMemberName(ast.name, self.expression);
  13675. return self.identifier(ast.name,
  13676. self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
  13677. context, create, self.expression);
  13678. case AST.MemberExpression:
  13679. left = this.recurse(ast.object, false, !!create);
  13680. if (!ast.computed) {
  13681. ensureSafeMemberName(ast.property.name, self.expression);
  13682. right = ast.property.name;
  13683. }
  13684. if (ast.computed) right = this.recurse(ast.property);
  13685. return ast.computed ?
  13686. this.computedMember(left, right, context, create, self.expression) :
  13687. this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
  13688. case AST.CallExpression:
  13689. args = [];
  13690. forEach(ast.arguments, function(expr) {
  13691. args.push(self.recurse(expr));
  13692. });
  13693. if (ast.filter) right = this.$filter(ast.callee.name);
  13694. if (!ast.filter) right = this.recurse(ast.callee, true);
  13695. return ast.filter ?
  13696. function(scope, locals, assign, inputs) {
  13697. var values = [];
  13698. for (var i = 0; i < args.length; ++i) {
  13699. values.push(args[i](scope, locals, assign, inputs));
  13700. }
  13701. var value = right.apply(undefined, values, inputs);
  13702. return context ? {context: undefined, name: undefined, value: value} : value;
  13703. } :
  13704. function(scope, locals, assign, inputs) {
  13705. var rhs = right(scope, locals, assign, inputs);
  13706. var value;
  13707. if (rhs.value != null) {
  13708. ensureSafeObject(rhs.context, self.expression);
  13709. ensureSafeFunction(rhs.value, self.expression);
  13710. var values = [];
  13711. for (var i = 0; i < args.length; ++i) {
  13712. values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
  13713. }
  13714. value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
  13715. }
  13716. return context ? {value: value} : value;
  13717. };
  13718. case AST.AssignmentExpression:
  13719. left = this.recurse(ast.left, true, 1);
  13720. right = this.recurse(ast.right);
  13721. return function(scope, locals, assign, inputs) {
  13722. var lhs = left(scope, locals, assign, inputs);
  13723. var rhs = right(scope, locals, assign, inputs);
  13724. ensureSafeObject(lhs.value, self.expression);
  13725. ensureSafeAssignContext(lhs.context);
  13726. lhs.context[lhs.name] = rhs;
  13727. return context ? {value: rhs} : rhs;
  13728. };
  13729. case AST.ArrayExpression:
  13730. args = [];
  13731. forEach(ast.elements, function(expr) {
  13732. args.push(self.recurse(expr));
  13733. });
  13734. return function(scope, locals, assign, inputs) {
  13735. var value = [];
  13736. for (var i = 0; i < args.length; ++i) {
  13737. value.push(args[i](scope, locals, assign, inputs));
  13738. }
  13739. return context ? {value: value} : value;
  13740. };
  13741. case AST.ObjectExpression:
  13742. args = [];
  13743. forEach(ast.properties, function(property) {
  13744. if (property.computed) {
  13745. args.push({key: self.recurse(property.key),
  13746. computed: true,
  13747. value: self.recurse(property.value)
  13748. });
  13749. } else {
  13750. args.push({key: property.key.type === AST.Identifier ?
  13751. property.key.name :
  13752. ('' + property.key.value),
  13753. computed: false,
  13754. value: self.recurse(property.value)
  13755. });
  13756. }
  13757. });
  13758. return function(scope, locals, assign, inputs) {
  13759. var value = {};
  13760. for (var i = 0; i < args.length; ++i) {
  13761. if (args[i].computed) {
  13762. value[args[i].key(scope, locals, assign, inputs)] = args[i].value(scope, locals, assign, inputs);
  13763. } else {
  13764. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  13765. }
  13766. }
  13767. return context ? {value: value} : value;
  13768. };
  13769. case AST.ThisExpression:
  13770. return function(scope) {
  13771. return context ? {value: scope} : scope;
  13772. };
  13773. case AST.LocalsExpression:
  13774. return function(scope, locals) {
  13775. return context ? {value: locals} : locals;
  13776. };
  13777. case AST.NGValueParameter:
  13778. return function(scope, locals, assign) {
  13779. return context ? {value: assign} : assign;
  13780. };
  13781. }
  13782. },
  13783. 'unary+': function(argument, context) {
  13784. return function(scope, locals, assign, inputs) {
  13785. var arg = argument(scope, locals, assign, inputs);
  13786. if (isDefined(arg)) {
  13787. arg = +arg;
  13788. } else {
  13789. arg = 0;
  13790. }
  13791. return context ? {value: arg} : arg;
  13792. };
  13793. },
  13794. 'unary-': function(argument, context) {
  13795. return function(scope, locals, assign, inputs) {
  13796. var arg = argument(scope, locals, assign, inputs);
  13797. if (isDefined(arg)) {
  13798. arg = -arg;
  13799. } else {
  13800. arg = 0;
  13801. }
  13802. return context ? {value: arg} : arg;
  13803. };
  13804. },
  13805. 'unary!': function(argument, context) {
  13806. return function(scope, locals, assign, inputs) {
  13807. var arg = !argument(scope, locals, assign, inputs);
  13808. return context ? {value: arg} : arg;
  13809. };
  13810. },
  13811. 'binary+': function(left, right, context) {
  13812. return function(scope, locals, assign, inputs) {
  13813. var lhs = left(scope, locals, assign, inputs);
  13814. var rhs = right(scope, locals, assign, inputs);
  13815. var arg = plusFn(lhs, rhs);
  13816. return context ? {value: arg} : arg;
  13817. };
  13818. },
  13819. 'binary-': function(left, right, context) {
  13820. return function(scope, locals, assign, inputs) {
  13821. var lhs = left(scope, locals, assign, inputs);
  13822. var rhs = right(scope, locals, assign, inputs);
  13823. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  13824. return context ? {value: arg} : arg;
  13825. };
  13826. },
  13827. 'binary*': function(left, right, context) {
  13828. return function(scope, locals, assign, inputs) {
  13829. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  13830. return context ? {value: arg} : arg;
  13831. };
  13832. },
  13833. 'binary/': function(left, right, context) {
  13834. return function(scope, locals, assign, inputs) {
  13835. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  13836. return context ? {value: arg} : arg;
  13837. };
  13838. },
  13839. 'binary%': function(left, right, context) {
  13840. return function(scope, locals, assign, inputs) {
  13841. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  13842. return context ? {value: arg} : arg;
  13843. };
  13844. },
  13845. 'binary===': function(left, right, context) {
  13846. return function(scope, locals, assign, inputs) {
  13847. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  13848. return context ? {value: arg} : arg;
  13849. };
  13850. },
  13851. 'binary!==': function(left, right, context) {
  13852. return function(scope, locals, assign, inputs) {
  13853. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  13854. return context ? {value: arg} : arg;
  13855. };
  13856. },
  13857. 'binary==': function(left, right, context) {
  13858. return function(scope, locals, assign, inputs) {
  13859. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  13860. return context ? {value: arg} : arg;
  13861. };
  13862. },
  13863. 'binary!=': function(left, right, context) {
  13864. return function(scope, locals, assign, inputs) {
  13865. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  13866. return context ? {value: arg} : arg;
  13867. };
  13868. },
  13869. 'binary<': function(left, right, context) {
  13870. return function(scope, locals, assign, inputs) {
  13871. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  13872. return context ? {value: arg} : arg;
  13873. };
  13874. },
  13875. 'binary>': function(left, right, context) {
  13876. return function(scope, locals, assign, inputs) {
  13877. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  13878. return context ? {value: arg} : arg;
  13879. };
  13880. },
  13881. 'binary<=': function(left, right, context) {
  13882. return function(scope, locals, assign, inputs) {
  13883. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  13884. return context ? {value: arg} : arg;
  13885. };
  13886. },
  13887. 'binary>=': function(left, right, context) {
  13888. return function(scope, locals, assign, inputs) {
  13889. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  13890. return context ? {value: arg} : arg;
  13891. };
  13892. },
  13893. 'binary&&': function(left, right, context) {
  13894. return function(scope, locals, assign, inputs) {
  13895. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  13896. return context ? {value: arg} : arg;
  13897. };
  13898. },
  13899. 'binary||': function(left, right, context) {
  13900. return function(scope, locals, assign, inputs) {
  13901. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  13902. return context ? {value: arg} : arg;
  13903. };
  13904. },
  13905. 'ternary?:': function(test, alternate, consequent, context) {
  13906. return function(scope, locals, assign, inputs) {
  13907. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  13908. return context ? {value: arg} : arg;
  13909. };
  13910. },
  13911. value: function(value, context) {
  13912. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  13913. },
  13914. identifier: function(name, expensiveChecks, context, create, expression) {
  13915. return function(scope, locals, assign, inputs) {
  13916. var base = locals && (name in locals) ? locals : scope;
  13917. if (create && create !== 1 && base && !(base[name])) {
  13918. base[name] = {};
  13919. }
  13920. var value = base ? base[name] : undefined;
  13921. if (expensiveChecks) {
  13922. ensureSafeObject(value, expression);
  13923. }
  13924. if (context) {
  13925. return {context: base, name: name, value: value};
  13926. } else {
  13927. return value;
  13928. }
  13929. };
  13930. },
  13931. computedMember: function(left, right, context, create, expression) {
  13932. return function(scope, locals, assign, inputs) {
  13933. var lhs = left(scope, locals, assign, inputs);
  13934. var rhs;
  13935. var value;
  13936. if (lhs != null) {
  13937. rhs = right(scope, locals, assign, inputs);
  13938. rhs = getStringValue(rhs);
  13939. ensureSafeMemberName(rhs, expression);
  13940. if (create && create !== 1) {
  13941. ensureSafeAssignContext(lhs);
  13942. if (lhs && !(lhs[rhs])) {
  13943. lhs[rhs] = {};
  13944. }
  13945. }
  13946. value = lhs[rhs];
  13947. ensureSafeObject(value, expression);
  13948. }
  13949. if (context) {
  13950. return {context: lhs, name: rhs, value: value};
  13951. } else {
  13952. return value;
  13953. }
  13954. };
  13955. },
  13956. nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
  13957. return function(scope, locals, assign, inputs) {
  13958. var lhs = left(scope, locals, assign, inputs);
  13959. if (create && create !== 1) {
  13960. ensureSafeAssignContext(lhs);
  13961. if (lhs && !(lhs[right])) {
  13962. lhs[right] = {};
  13963. }
  13964. }
  13965. var value = lhs != null ? lhs[right] : undefined;
  13966. if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
  13967. ensureSafeObject(value, expression);
  13968. }
  13969. if (context) {
  13970. return {context: lhs, name: right, value: value};
  13971. } else {
  13972. return value;
  13973. }
  13974. };
  13975. },
  13976. inputs: function(input, watchId) {
  13977. return function(scope, value, locals, inputs) {
  13978. if (inputs) return inputs[watchId];
  13979. return input(scope, value, locals);
  13980. };
  13981. }
  13982. };
  13983. /**
  13984. * @constructor
  13985. */
  13986. var Parser = function(lexer, $filter, options) {
  13987. this.lexer = lexer;
  13988. this.$filter = $filter;
  13989. this.options = options;
  13990. this.ast = new AST(lexer, options);
  13991. this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
  13992. new ASTCompiler(this.ast, $filter);
  13993. };
  13994. Parser.prototype = {
  13995. constructor: Parser,
  13996. parse: function(text) {
  13997. return this.astCompiler.compile(text, this.options.expensiveChecks);
  13998. }
  13999. };
  14000. function isPossiblyDangerousMemberName(name) {
  14001. return name == 'constructor';
  14002. }
  14003. var objectValueOf = Object.prototype.valueOf;
  14004. function getValueOf(value) {
  14005. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  14006. }
  14007. ///////////////////////////////////
  14008. /**
  14009. * @ngdoc service
  14010. * @name $parse
  14011. * @kind function
  14012. *
  14013. * @description
  14014. *
  14015. * Converts Angular {@link guide/expression expression} into a function.
  14016. *
  14017. * ```js
  14018. * var getter = $parse('user.name');
  14019. * var setter = getter.assign;
  14020. * var context = {user:{name:'angular'}};
  14021. * var locals = {user:{name:'local'}};
  14022. *
  14023. * expect(getter(context)).toEqual('angular');
  14024. * setter(context, 'newValue');
  14025. * expect(context.user.name).toEqual('newValue');
  14026. * expect(getter(context, locals)).toEqual('local');
  14027. * ```
  14028. *
  14029. *
  14030. * @param {string} expression String expression to compile.
  14031. * @returns {function(context, locals)} a function which represents the compiled expression:
  14032. *
  14033. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14034. * are evaluated against (typically a scope object).
  14035. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14036. * `context`.
  14037. *
  14038. * The returned function also has the following properties:
  14039. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  14040. * literal.
  14041. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  14042. * constant literals.
  14043. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  14044. * set to a function to change its value on the given context.
  14045. *
  14046. */
  14047. /**
  14048. * @ngdoc provider
  14049. * @name $parseProvider
  14050. *
  14051. * @description
  14052. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  14053. * service.
  14054. */
  14055. function $ParseProvider() {
  14056. var cacheDefault = createMap();
  14057. var cacheExpensive = createMap();
  14058. var literals = {
  14059. 'true': true,
  14060. 'false': false,
  14061. 'null': null,
  14062. 'undefined': undefined
  14063. };
  14064. var identStart, identContinue;
  14065. /**
  14066. * @ngdoc method
  14067. * @name $parseProvider#addLiteral
  14068. * @description
  14069. *
  14070. * Configure $parse service to add literal values that will be present as literal at expressions.
  14071. *
  14072. * @param {string} literalName Token for the literal value. The literal name value must be a valid literal name.
  14073. * @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`.
  14074. *
  14075. **/
  14076. this.addLiteral = function(literalName, literalValue) {
  14077. literals[literalName] = literalValue;
  14078. };
  14079. /**
  14080. * @ngdoc method
  14081. * @name $parseProvider#setIdentifierFns
  14082. * @description
  14083. *
  14084. * Allows defining the set of characters that are allowed in Angular expressions. The function
  14085. * `identifierStart` will get called to know if a given character is a valid character to be the
  14086. * first character for an identifier. The function `identifierContinue` will get called to know if
  14087. * a given character is a valid character to be a follow-up identifier character. The functions
  14088. * `identifierStart` and `identifierContinue` will receive as arguments the single character to be
  14089. * identifier and the character code point. These arguments will be `string` and `numeric`. Keep in
  14090. * mind that the `string` parameter can be two characters long depending on the character
  14091. * representation. It is expected for the function to return `true` or `false`, whether that
  14092. * character is allowed or not.
  14093. *
  14094. * Since this function will be called extensivelly, keep the implementation of these functions fast,
  14095. * as the performance of these functions have a direct impact on the expressions parsing speed.
  14096. *
  14097. * @param {function=} identifierStart The function that will decide whether the given character is
  14098. * a valid identifier start character.
  14099. * @param {function=} identifierContinue The function that will decide whether the given character is
  14100. * a valid identifier continue character.
  14101. */
  14102. this.setIdentifierFns = function(identifierStart, identifierContinue) {
  14103. identStart = identifierStart;
  14104. identContinue = identifierContinue;
  14105. return this;
  14106. };
  14107. this.$get = ['$filter', function($filter) {
  14108. var noUnsafeEval = csp().noUnsafeEval;
  14109. var $parseOptions = {
  14110. csp: noUnsafeEval,
  14111. expensiveChecks: false,
  14112. literals: copy(literals),
  14113. isIdentifierStart: isFunction(identStart) && identStart,
  14114. isIdentifierContinue: isFunction(identContinue) && identContinue
  14115. },
  14116. $parseOptionsExpensive = {
  14117. csp: noUnsafeEval,
  14118. expensiveChecks: true,
  14119. literals: copy(literals),
  14120. isIdentifierStart: isFunction(identStart) && identStart,
  14121. isIdentifierContinue: isFunction(identContinue) && identContinue
  14122. };
  14123. var runningChecksEnabled = false;
  14124. $parse.$$runningExpensiveChecks = function() {
  14125. return runningChecksEnabled;
  14126. };
  14127. return $parse;
  14128. function $parse(exp, interceptorFn, expensiveChecks) {
  14129. var parsedExpression, oneTime, cacheKey;
  14130. expensiveChecks = expensiveChecks || runningChecksEnabled;
  14131. switch (typeof exp) {
  14132. case 'string':
  14133. exp = exp.trim();
  14134. cacheKey = exp;
  14135. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  14136. parsedExpression = cache[cacheKey];
  14137. if (!parsedExpression) {
  14138. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  14139. oneTime = true;
  14140. exp = exp.substring(2);
  14141. }
  14142. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  14143. var lexer = new Lexer(parseOptions);
  14144. var parser = new Parser(lexer, $filter, parseOptions);
  14145. parsedExpression = parser.parse(exp);
  14146. if (parsedExpression.constant) {
  14147. parsedExpression.$$watchDelegate = constantWatchDelegate;
  14148. } else if (oneTime) {
  14149. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  14150. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  14151. } else if (parsedExpression.inputs) {
  14152. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  14153. }
  14154. if (expensiveChecks) {
  14155. parsedExpression = expensiveChecksInterceptor(parsedExpression);
  14156. }
  14157. cache[cacheKey] = parsedExpression;
  14158. }
  14159. return addInterceptor(parsedExpression, interceptorFn);
  14160. case 'function':
  14161. return addInterceptor(exp, interceptorFn);
  14162. default:
  14163. return addInterceptor(noop, interceptorFn);
  14164. }
  14165. }
  14166. function expensiveChecksInterceptor(fn) {
  14167. if (!fn) return fn;
  14168. expensiveCheckFn.$$watchDelegate = fn.$$watchDelegate;
  14169. expensiveCheckFn.assign = expensiveChecksInterceptor(fn.assign);
  14170. expensiveCheckFn.constant = fn.constant;
  14171. expensiveCheckFn.literal = fn.literal;
  14172. for (var i = 0; fn.inputs && i < fn.inputs.length; ++i) {
  14173. fn.inputs[i] = expensiveChecksInterceptor(fn.inputs[i]);
  14174. }
  14175. expensiveCheckFn.inputs = fn.inputs;
  14176. return expensiveCheckFn;
  14177. function expensiveCheckFn(scope, locals, assign, inputs) {
  14178. var expensiveCheckOldValue = runningChecksEnabled;
  14179. runningChecksEnabled = true;
  14180. try {
  14181. return fn(scope, locals, assign, inputs);
  14182. } finally {
  14183. runningChecksEnabled = expensiveCheckOldValue;
  14184. }
  14185. }
  14186. }
  14187. function expressionInputDirtyCheck(newValue, oldValueOfValue) {
  14188. if (newValue == null || oldValueOfValue == null) { // null/undefined
  14189. return newValue === oldValueOfValue;
  14190. }
  14191. if (typeof newValue === 'object') {
  14192. // attempt to convert the value to a primitive type
  14193. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  14194. // be cheaply dirty-checked
  14195. newValue = getValueOf(newValue);
  14196. if (typeof newValue === 'object') {
  14197. // objects/arrays are not supported - deep-watching them would be too expensive
  14198. return false;
  14199. }
  14200. // fall-through to the primitive equality check
  14201. }
  14202. //Primitive or NaN
  14203. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  14204. }
  14205. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  14206. var inputExpressions = parsedExpression.inputs;
  14207. var lastResult;
  14208. if (inputExpressions.length === 1) {
  14209. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  14210. inputExpressions = inputExpressions[0];
  14211. return scope.$watch(function expressionInputWatch(scope) {
  14212. var newInputValue = inputExpressions(scope);
  14213. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
  14214. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  14215. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  14216. }
  14217. return lastResult;
  14218. }, listener, objectEquality, prettyPrintExpression);
  14219. }
  14220. var oldInputValueOfValues = [];
  14221. var oldInputValues = [];
  14222. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  14223. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  14224. oldInputValues[i] = null;
  14225. }
  14226. return scope.$watch(function expressionInputsWatch(scope) {
  14227. var changed = false;
  14228. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  14229. var newInputValue = inputExpressions[i](scope);
  14230. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
  14231. oldInputValues[i] = newInputValue;
  14232. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  14233. }
  14234. }
  14235. if (changed) {
  14236. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  14237. }
  14238. return lastResult;
  14239. }, listener, objectEquality, prettyPrintExpression);
  14240. }
  14241. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  14242. var unwatch, lastValue;
  14243. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  14244. return parsedExpression(scope);
  14245. }, function oneTimeListener(value, old, scope) {
  14246. lastValue = value;
  14247. if (isFunction(listener)) {
  14248. listener.apply(this, arguments);
  14249. }
  14250. if (isDefined(value)) {
  14251. scope.$$postDigest(function() {
  14252. if (isDefined(lastValue)) {
  14253. unwatch();
  14254. }
  14255. });
  14256. }
  14257. }, objectEquality);
  14258. }
  14259. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  14260. var unwatch, lastValue;
  14261. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  14262. return parsedExpression(scope);
  14263. }, function oneTimeListener(value, old, scope) {
  14264. lastValue = value;
  14265. if (isFunction(listener)) {
  14266. listener.call(this, value, old, scope);
  14267. }
  14268. if (isAllDefined(value)) {
  14269. scope.$$postDigest(function() {
  14270. if (isAllDefined(lastValue)) unwatch();
  14271. });
  14272. }
  14273. }, objectEquality);
  14274. function isAllDefined(value) {
  14275. var allDefined = true;
  14276. forEach(value, function(val) {
  14277. if (!isDefined(val)) allDefined = false;
  14278. });
  14279. return allDefined;
  14280. }
  14281. }
  14282. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  14283. var unwatch;
  14284. return unwatch = scope.$watch(function constantWatch(scope) {
  14285. unwatch();
  14286. return parsedExpression(scope);
  14287. }, listener, objectEquality);
  14288. }
  14289. function addInterceptor(parsedExpression, interceptorFn) {
  14290. if (!interceptorFn) return parsedExpression;
  14291. var watchDelegate = parsedExpression.$$watchDelegate;
  14292. var useInputs = false;
  14293. var regularWatch =
  14294. watchDelegate !== oneTimeLiteralWatchDelegate &&
  14295. watchDelegate !== oneTimeWatchDelegate;
  14296. var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
  14297. var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
  14298. return interceptorFn(value, scope, locals);
  14299. } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
  14300. var value = parsedExpression(scope, locals, assign, inputs);
  14301. var result = interceptorFn(value, scope, locals);
  14302. // we only return the interceptor's result if the
  14303. // initial value is defined (for bind-once)
  14304. return isDefined(value) ? result : value;
  14305. };
  14306. // Propagate $$watchDelegates other then inputsWatchDelegate
  14307. if (parsedExpression.$$watchDelegate &&
  14308. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  14309. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  14310. } else if (!interceptorFn.$stateful) {
  14311. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  14312. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  14313. fn.$$watchDelegate = inputsWatchDelegate;
  14314. useInputs = !parsedExpression.inputs;
  14315. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  14316. }
  14317. return fn;
  14318. }
  14319. }];
  14320. }
  14321. /**
  14322. * @ngdoc service
  14323. * @name $q
  14324. * @requires $rootScope
  14325. *
  14326. * @description
  14327. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  14328. * when they are done processing.
  14329. *
  14330. * This is an implementation of promises/deferred objects inspired by
  14331. * [Kris Kowal's Q](https://github.com/kriskowal/q).
  14332. *
  14333. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  14334. * implementations, and the other which resembles ES6 (ES2015) promises to some degree.
  14335. *
  14336. * # $q constructor
  14337. *
  14338. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  14339. * function as the first argument. This is similar to the native Promise implementation from ES6,
  14340. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  14341. *
  14342. * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are
  14343. * available yet.
  14344. *
  14345. * It can be used like so:
  14346. *
  14347. * ```js
  14348. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  14349. * // are available in the current lexical scope (they could have been injected or passed in).
  14350. *
  14351. * function asyncGreet(name) {
  14352. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  14353. * return $q(function(resolve, reject) {
  14354. * setTimeout(function() {
  14355. * if (okToGreet(name)) {
  14356. * resolve('Hello, ' + name + '!');
  14357. * } else {
  14358. * reject('Greeting ' + name + ' is not allowed.');
  14359. * }
  14360. * }, 1000);
  14361. * });
  14362. * }
  14363. *
  14364. * var promise = asyncGreet('Robin Hood');
  14365. * promise.then(function(greeting) {
  14366. * alert('Success: ' + greeting);
  14367. * }, function(reason) {
  14368. * alert('Failed: ' + reason);
  14369. * });
  14370. * ```
  14371. *
  14372. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  14373. *
  14374. * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.
  14375. *
  14376. * However, the more traditional CommonJS-style usage is still available, and documented below.
  14377. *
  14378. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  14379. * interface for interacting with an object that represents the result of an action that is
  14380. * performed asynchronously, and may or may not be finished at any given point in time.
  14381. *
  14382. * From the perspective of dealing with error handling, deferred and promise APIs are to
  14383. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  14384. *
  14385. * ```js
  14386. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  14387. * // are available in the current lexical scope (they could have been injected or passed in).
  14388. *
  14389. * function asyncGreet(name) {
  14390. * var deferred = $q.defer();
  14391. *
  14392. * setTimeout(function() {
  14393. * deferred.notify('About to greet ' + name + '.');
  14394. *
  14395. * if (okToGreet(name)) {
  14396. * deferred.resolve('Hello, ' + name + '!');
  14397. * } else {
  14398. * deferred.reject('Greeting ' + name + ' is not allowed.');
  14399. * }
  14400. * }, 1000);
  14401. *
  14402. * return deferred.promise;
  14403. * }
  14404. *
  14405. * var promise = asyncGreet('Robin Hood');
  14406. * promise.then(function(greeting) {
  14407. * alert('Success: ' + greeting);
  14408. * }, function(reason) {
  14409. * alert('Failed: ' + reason);
  14410. * }, function(update) {
  14411. * alert('Got notification: ' + update);
  14412. * });
  14413. * ```
  14414. *
  14415. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  14416. * comes in the way of guarantees that promise and deferred APIs make, see
  14417. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  14418. *
  14419. * Additionally the promise api allows for composition that is very hard to do with the
  14420. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  14421. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  14422. * section on serial or parallel joining of promises.
  14423. *
  14424. * # The Deferred API
  14425. *
  14426. * A new instance of deferred is constructed by calling `$q.defer()`.
  14427. *
  14428. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  14429. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  14430. * of the task.
  14431. *
  14432. * **Methods**
  14433. *
  14434. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  14435. * constructed via `$q.reject`, the promise will be rejected instead.
  14436. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  14437. * resolving it with a rejection constructed via `$q.reject`.
  14438. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  14439. * multiple times before the promise is either resolved or rejected.
  14440. *
  14441. * **Properties**
  14442. *
  14443. * - promise – `{Promise}` – promise object associated with this deferred.
  14444. *
  14445. *
  14446. * # The Promise API
  14447. *
  14448. * A new promise instance is created when a deferred instance is created and can be retrieved by
  14449. * calling `deferred.promise`.
  14450. *
  14451. * The purpose of the promise object is to allow for interested parties to get access to the result
  14452. * of the deferred task when it completes.
  14453. *
  14454. * **Methods**
  14455. *
  14456. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  14457. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  14458. * as soon as the result is available. The callbacks are called with a single argument: the result
  14459. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  14460. * provide a progress indication, before the promise is resolved or rejected.
  14461. *
  14462. * This method *returns a new promise* which is resolved or rejected via the return value of the
  14463. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  14464. * with the value which is resolved in that promise using
  14465. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  14466. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  14467. * resolved or rejected from the notifyCallback method.
  14468. *
  14469. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  14470. *
  14471. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  14472. * but to do so without modifying the final value. This is useful to release resources or do some
  14473. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  14474. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  14475. * more information.
  14476. *
  14477. * # Chaining promises
  14478. *
  14479. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  14480. * possible to create a chain of promises:
  14481. *
  14482. * ```js
  14483. * promiseB = promiseA.then(function(result) {
  14484. * return result + 1;
  14485. * });
  14486. *
  14487. * // promiseB will be resolved immediately after promiseA is resolved and its value
  14488. * // will be the result of promiseA incremented by 1
  14489. * ```
  14490. *
  14491. * It is possible to create chains of any length and since a promise can be resolved with another
  14492. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  14493. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  14494. * $http's response interceptors.
  14495. *
  14496. *
  14497. * # Differences between Kris Kowal's Q and $q
  14498. *
  14499. * There are two main differences:
  14500. *
  14501. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  14502. * mechanism in angular, which means faster propagation of resolution or rejection into your
  14503. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  14504. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  14505. * all the important functionality needed for common async tasks.
  14506. *
  14507. * # Testing
  14508. *
  14509. * ```js
  14510. * it('should simulate promise', inject(function($q, $rootScope) {
  14511. * var deferred = $q.defer();
  14512. * var promise = deferred.promise;
  14513. * var resolvedValue;
  14514. *
  14515. * promise.then(function(value) { resolvedValue = value; });
  14516. * expect(resolvedValue).toBeUndefined();
  14517. *
  14518. * // Simulate resolving of promise
  14519. * deferred.resolve(123);
  14520. * // Note that the 'then' function does not get called synchronously.
  14521. * // This is because we want the promise API to always be async, whether or not
  14522. * // it got called synchronously or asynchronously.
  14523. * expect(resolvedValue).toBeUndefined();
  14524. *
  14525. * // Propagate promise resolution to 'then' functions using $apply().
  14526. * $rootScope.$apply();
  14527. * expect(resolvedValue).toEqual(123);
  14528. * }));
  14529. * ```
  14530. *
  14531. * @param {function(function, function)} resolver Function which is responsible for resolving or
  14532. * rejecting the newly created promise. The first parameter is a function which resolves the
  14533. * promise, the second parameter is a function which rejects the promise.
  14534. *
  14535. * @returns {Promise} The newly created promise.
  14536. */
  14537. function $QProvider() {
  14538. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  14539. return qFactory(function(callback) {
  14540. $rootScope.$evalAsync(callback);
  14541. }, $exceptionHandler);
  14542. }];
  14543. }
  14544. function $$QProvider() {
  14545. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  14546. return qFactory(function(callback) {
  14547. $browser.defer(callback);
  14548. }, $exceptionHandler);
  14549. }];
  14550. }
  14551. /**
  14552. * Constructs a promise manager.
  14553. *
  14554. * @param {function(function)} nextTick Function for executing functions in the next turn.
  14555. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  14556. * debugging purposes.
  14557. * @returns {object} Promise manager.
  14558. */
  14559. function qFactory(nextTick, exceptionHandler) {
  14560. var $qMinErr = minErr('$q', TypeError);
  14561. /**
  14562. * @ngdoc method
  14563. * @name ng.$q#defer
  14564. * @kind function
  14565. *
  14566. * @description
  14567. * Creates a `Deferred` object which represents a task which will finish in the future.
  14568. *
  14569. * @returns {Deferred} Returns a new instance of deferred.
  14570. */
  14571. var defer = function() {
  14572. var d = new Deferred();
  14573. //Necessary to support unbound execution :/
  14574. d.resolve = simpleBind(d, d.resolve);
  14575. d.reject = simpleBind(d, d.reject);
  14576. d.notify = simpleBind(d, d.notify);
  14577. return d;
  14578. };
  14579. function Promise() {
  14580. this.$$state = { status: 0 };
  14581. }
  14582. extend(Promise.prototype, {
  14583. then: function(onFulfilled, onRejected, progressBack) {
  14584. if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
  14585. return this;
  14586. }
  14587. var result = new Deferred();
  14588. this.$$state.pending = this.$$state.pending || [];
  14589. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  14590. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  14591. return result.promise;
  14592. },
  14593. "catch": function(callback) {
  14594. return this.then(null, callback);
  14595. },
  14596. "finally": function(callback, progressBack) {
  14597. return this.then(function(value) {
  14598. return handleCallback(value, true, callback);
  14599. }, function(error) {
  14600. return handleCallback(error, false, callback);
  14601. }, progressBack);
  14602. }
  14603. });
  14604. //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
  14605. function simpleBind(context, fn) {
  14606. return function(value) {
  14607. fn.call(context, value);
  14608. };
  14609. }
  14610. function processQueue(state) {
  14611. var fn, deferred, pending;
  14612. pending = state.pending;
  14613. state.processScheduled = false;
  14614. state.pending = undefined;
  14615. for (var i = 0, ii = pending.length; i < ii; ++i) {
  14616. deferred = pending[i][0];
  14617. fn = pending[i][state.status];
  14618. try {
  14619. if (isFunction(fn)) {
  14620. deferred.resolve(fn(state.value));
  14621. } else if (state.status === 1) {
  14622. deferred.resolve(state.value);
  14623. } else {
  14624. deferred.reject(state.value);
  14625. }
  14626. } catch (e) {
  14627. deferred.reject(e);
  14628. exceptionHandler(e);
  14629. }
  14630. }
  14631. }
  14632. function scheduleProcessQueue(state) {
  14633. if (state.processScheduled || !state.pending) return;
  14634. state.processScheduled = true;
  14635. nextTick(function() { processQueue(state); });
  14636. }
  14637. function Deferred() {
  14638. this.promise = new Promise();
  14639. }
  14640. extend(Deferred.prototype, {
  14641. resolve: function(val) {
  14642. if (this.promise.$$state.status) return;
  14643. if (val === this.promise) {
  14644. this.$$reject($qMinErr(
  14645. 'qcycle',
  14646. "Expected promise to be resolved with value other than itself '{0}'",
  14647. val));
  14648. } else {
  14649. this.$$resolve(val);
  14650. }
  14651. },
  14652. $$resolve: function(val) {
  14653. var then;
  14654. var that = this;
  14655. var done = false;
  14656. try {
  14657. if ((isObject(val) || isFunction(val))) then = val && val.then;
  14658. if (isFunction(then)) {
  14659. this.promise.$$state.status = -1;
  14660. then.call(val, resolvePromise, rejectPromise, simpleBind(this, this.notify));
  14661. } else {
  14662. this.promise.$$state.value = val;
  14663. this.promise.$$state.status = 1;
  14664. scheduleProcessQueue(this.promise.$$state);
  14665. }
  14666. } catch (e) {
  14667. rejectPromise(e);
  14668. exceptionHandler(e);
  14669. }
  14670. function resolvePromise(val) {
  14671. if (done) return;
  14672. done = true;
  14673. that.$$resolve(val);
  14674. }
  14675. function rejectPromise(val) {
  14676. if (done) return;
  14677. done = true;
  14678. that.$$reject(val);
  14679. }
  14680. },
  14681. reject: function(reason) {
  14682. if (this.promise.$$state.status) return;
  14683. this.$$reject(reason);
  14684. },
  14685. $$reject: function(reason) {
  14686. this.promise.$$state.value = reason;
  14687. this.promise.$$state.status = 2;
  14688. scheduleProcessQueue(this.promise.$$state);
  14689. },
  14690. notify: function(progress) {
  14691. var callbacks = this.promise.$$state.pending;
  14692. if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
  14693. nextTick(function() {
  14694. var callback, result;
  14695. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  14696. result = callbacks[i][0];
  14697. callback = callbacks[i][3];
  14698. try {
  14699. result.notify(isFunction(callback) ? callback(progress) : progress);
  14700. } catch (e) {
  14701. exceptionHandler(e);
  14702. }
  14703. }
  14704. });
  14705. }
  14706. }
  14707. });
  14708. /**
  14709. * @ngdoc method
  14710. * @name $q#reject
  14711. * @kind function
  14712. *
  14713. * @description
  14714. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  14715. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  14716. * a promise chain, you don't need to worry about it.
  14717. *
  14718. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  14719. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  14720. * a promise error callback and you want to forward the error to the promise derived from the
  14721. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  14722. * `reject`.
  14723. *
  14724. * ```js
  14725. * promiseB = promiseA.then(function(result) {
  14726. * // success: do something and resolve promiseB
  14727. * // with the old or a new result
  14728. * return result;
  14729. * }, function(reason) {
  14730. * // error: handle the error if possible and
  14731. * // resolve promiseB with newPromiseOrValue,
  14732. * // otherwise forward the rejection to promiseB
  14733. * if (canHandle(reason)) {
  14734. * // handle the error and recover
  14735. * return newPromiseOrValue;
  14736. * }
  14737. * return $q.reject(reason);
  14738. * });
  14739. * ```
  14740. *
  14741. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  14742. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  14743. */
  14744. var reject = function(reason) {
  14745. var result = new Deferred();
  14746. result.reject(reason);
  14747. return result.promise;
  14748. };
  14749. var makePromise = function makePromise(value, resolved) {
  14750. var result = new Deferred();
  14751. if (resolved) {
  14752. result.resolve(value);
  14753. } else {
  14754. result.reject(value);
  14755. }
  14756. return result.promise;
  14757. };
  14758. var handleCallback = function handleCallback(value, isResolved, callback) {
  14759. var callbackOutput = null;
  14760. try {
  14761. if (isFunction(callback)) callbackOutput = callback();
  14762. } catch (e) {
  14763. return makePromise(e, false);
  14764. }
  14765. if (isPromiseLike(callbackOutput)) {
  14766. return callbackOutput.then(function() {
  14767. return makePromise(value, isResolved);
  14768. }, function(error) {
  14769. return makePromise(error, false);
  14770. });
  14771. } else {
  14772. return makePromise(value, isResolved);
  14773. }
  14774. };
  14775. /**
  14776. * @ngdoc method
  14777. * @name $q#when
  14778. * @kind function
  14779. *
  14780. * @description
  14781. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  14782. * This is useful when you are dealing with an object that might or might not be a promise, or if
  14783. * the promise comes from a source that can't be trusted.
  14784. *
  14785. * @param {*} value Value or a promise
  14786. * @param {Function=} successCallback
  14787. * @param {Function=} errorCallback
  14788. * @param {Function=} progressCallback
  14789. * @returns {Promise} Returns a promise of the passed value or promise
  14790. */
  14791. var when = function(value, callback, errback, progressBack) {
  14792. var result = new Deferred();
  14793. result.resolve(value);
  14794. return result.promise.then(callback, errback, progressBack);
  14795. };
  14796. /**
  14797. * @ngdoc method
  14798. * @name $q#resolve
  14799. * @kind function
  14800. *
  14801. * @description
  14802. * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
  14803. *
  14804. * @param {*} value Value or a promise
  14805. * @param {Function=} successCallback
  14806. * @param {Function=} errorCallback
  14807. * @param {Function=} progressCallback
  14808. * @returns {Promise} Returns a promise of the passed value or promise
  14809. */
  14810. var resolve = when;
  14811. /**
  14812. * @ngdoc method
  14813. * @name $q#all
  14814. * @kind function
  14815. *
  14816. * @description
  14817. * Combines multiple promises into a single promise that is resolved when all of the input
  14818. * promises are resolved.
  14819. *
  14820. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  14821. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  14822. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  14823. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  14824. * with the same rejection value.
  14825. */
  14826. function all(promises) {
  14827. var deferred = new Deferred(),
  14828. counter = 0,
  14829. results = isArray(promises) ? [] : {};
  14830. forEach(promises, function(promise, key) {
  14831. counter++;
  14832. when(promise).then(function(value) {
  14833. if (results.hasOwnProperty(key)) return;
  14834. results[key] = value;
  14835. if (!(--counter)) deferred.resolve(results);
  14836. }, function(reason) {
  14837. if (results.hasOwnProperty(key)) return;
  14838. deferred.reject(reason);
  14839. });
  14840. });
  14841. if (counter === 0) {
  14842. deferred.resolve(results);
  14843. }
  14844. return deferred.promise;
  14845. }
  14846. var $Q = function Q(resolver) {
  14847. if (!isFunction(resolver)) {
  14848. throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
  14849. }
  14850. var deferred = new Deferred();
  14851. function resolveFn(value) {
  14852. deferred.resolve(value);
  14853. }
  14854. function rejectFn(reason) {
  14855. deferred.reject(reason);
  14856. }
  14857. resolver(resolveFn, rejectFn);
  14858. return deferred.promise;
  14859. };
  14860. // Let's make the instanceof operator work for promises, so that
  14861. // `new $q(fn) instanceof $q` would evaluate to true.
  14862. $Q.prototype = Promise.prototype;
  14863. $Q.defer = defer;
  14864. $Q.reject = reject;
  14865. $Q.when = when;
  14866. $Q.resolve = resolve;
  14867. $Q.all = all;
  14868. return $Q;
  14869. }
  14870. function $$RAFProvider() { //rAF
  14871. this.$get = ['$window', '$timeout', function($window, $timeout) {
  14872. var requestAnimationFrame = $window.requestAnimationFrame ||
  14873. $window.webkitRequestAnimationFrame;
  14874. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  14875. $window.webkitCancelAnimationFrame ||
  14876. $window.webkitCancelRequestAnimationFrame;
  14877. var rafSupported = !!requestAnimationFrame;
  14878. var raf = rafSupported
  14879. ? function(fn) {
  14880. var id = requestAnimationFrame(fn);
  14881. return function() {
  14882. cancelAnimationFrame(id);
  14883. };
  14884. }
  14885. : function(fn) {
  14886. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  14887. return function() {
  14888. $timeout.cancel(timer);
  14889. };
  14890. };
  14891. raf.supported = rafSupported;
  14892. return raf;
  14893. }];
  14894. }
  14895. /**
  14896. * DESIGN NOTES
  14897. *
  14898. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  14899. *
  14900. * The typical use of scope is to watch the expressions, which most of the time return the same
  14901. * value as last time so we optimize the operation.
  14902. *
  14903. * Closures construction is expensive in terms of speed as well as memory:
  14904. * - No closures, instead use prototypical inheritance for API
  14905. * - Internal state needs to be stored on scope directly, which means that private state is
  14906. * exposed as $$____ properties
  14907. *
  14908. * Loop operations are optimized by using while(count--) { ... }
  14909. * - This means that in order to keep the same order of execution as addition we have to add
  14910. * items to the array at the beginning (unshift) instead of at the end (push)
  14911. *
  14912. * Child scopes are created and removed often
  14913. * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
  14914. *
  14915. * There are fewer watches than observers. This is why you don't want the observer to be implemented
  14916. * in the same way as watch. Watch requires return of the initialization function which is expensive
  14917. * to construct.
  14918. */
  14919. /**
  14920. * @ngdoc provider
  14921. * @name $rootScopeProvider
  14922. * @description
  14923. *
  14924. * Provider for the $rootScope service.
  14925. */
  14926. /**
  14927. * @ngdoc method
  14928. * @name $rootScopeProvider#digestTtl
  14929. * @description
  14930. *
  14931. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  14932. * assuming that the model is unstable.
  14933. *
  14934. * The current default is 10 iterations.
  14935. *
  14936. * In complex applications it's possible that the dependencies between `$watch`s will result in
  14937. * several digest iterations. However if an application needs more than the default 10 digest
  14938. * iterations for its model to stabilize then you should investigate what is causing the model to
  14939. * continuously change during the digest.
  14940. *
  14941. * Increasing the TTL could have performance implications, so you should not change it without
  14942. * proper justification.
  14943. *
  14944. * @param {number} limit The number of digest iterations.
  14945. */
  14946. /**
  14947. * @ngdoc service
  14948. * @name $rootScope
  14949. * @description
  14950. *
  14951. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  14952. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  14953. * between the model and the view, via a mechanism for watching the model for changes.
  14954. * They also provide event emission/broadcast and subscription facility. See the
  14955. * {@link guide/scope developer guide on scopes}.
  14956. */
  14957. function $RootScopeProvider() {
  14958. var TTL = 10;
  14959. var $rootScopeMinErr = minErr('$rootScope');
  14960. var lastDirtyWatch = null;
  14961. var applyAsyncId = null;
  14962. this.digestTtl = function(value) {
  14963. if (arguments.length) {
  14964. TTL = value;
  14965. }
  14966. return TTL;
  14967. };
  14968. function createChildScopeClass(parent) {
  14969. function ChildScope() {
  14970. this.$$watchers = this.$$nextSibling =
  14971. this.$$childHead = this.$$childTail = null;
  14972. this.$$listeners = {};
  14973. this.$$listenerCount = {};
  14974. this.$$watchersCount = 0;
  14975. this.$id = nextUid();
  14976. this.$$ChildScope = null;
  14977. }
  14978. ChildScope.prototype = parent;
  14979. return ChildScope;
  14980. }
  14981. this.$get = ['$exceptionHandler', '$parse', '$browser',
  14982. function($exceptionHandler, $parse, $browser) {
  14983. function destroyChildScope($event) {
  14984. $event.currentScope.$$destroyed = true;
  14985. }
  14986. function cleanUpScope($scope) {
  14987. if (msie === 9) {
  14988. // There is a memory leak in IE9 if all child scopes are not disconnected
  14989. // completely when a scope is destroyed. So this code will recurse up through
  14990. // all this scopes children
  14991. //
  14992. // See issue https://github.com/angular/angular.js/issues/10706
  14993. $scope.$$childHead && cleanUpScope($scope.$$childHead);
  14994. $scope.$$nextSibling && cleanUpScope($scope.$$nextSibling);
  14995. }
  14996. // The code below works around IE9 and V8's memory leaks
  14997. //
  14998. // See:
  14999. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  15000. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  15001. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  15002. $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
  15003. $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
  15004. }
  15005. /**
  15006. * @ngdoc type
  15007. * @name $rootScope.Scope
  15008. *
  15009. * @description
  15010. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  15011. * {@link auto.$injector $injector}. Child scopes are created using the
  15012. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  15013. * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
  15014. * an in-depth introduction and usage examples.
  15015. *
  15016. *
  15017. * # Inheritance
  15018. * A scope can inherit from a parent scope, as in this example:
  15019. * ```js
  15020. var parent = $rootScope;
  15021. var child = parent.$new();
  15022. parent.salutation = "Hello";
  15023. expect(child.salutation).toEqual('Hello');
  15024. child.salutation = "Welcome";
  15025. expect(child.salutation).toEqual('Welcome');
  15026. expect(parent.salutation).toEqual('Hello');
  15027. * ```
  15028. *
  15029. * When interacting with `Scope` in tests, additional helper methods are available on the
  15030. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  15031. * details.
  15032. *
  15033. *
  15034. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  15035. * provided for the current scope. Defaults to {@link ng}.
  15036. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  15037. * append/override services provided by `providers`. This is handy
  15038. * when unit-testing and having the need to override a default
  15039. * service.
  15040. * @returns {Object} Newly created scope.
  15041. *
  15042. */
  15043. function Scope() {
  15044. this.$id = nextUid();
  15045. this.$$phase = this.$parent = this.$$watchers =
  15046. this.$$nextSibling = this.$$prevSibling =
  15047. this.$$childHead = this.$$childTail = null;
  15048. this.$root = this;
  15049. this.$$destroyed = false;
  15050. this.$$listeners = {};
  15051. this.$$listenerCount = {};
  15052. this.$$watchersCount = 0;
  15053. this.$$isolateBindings = null;
  15054. }
  15055. /**
  15056. * @ngdoc property
  15057. * @name $rootScope.Scope#$id
  15058. *
  15059. * @description
  15060. * Unique scope ID (monotonically increasing) useful for debugging.
  15061. */
  15062. /**
  15063. * @ngdoc property
  15064. * @name $rootScope.Scope#$parent
  15065. *
  15066. * @description
  15067. * Reference to the parent scope.
  15068. */
  15069. /**
  15070. * @ngdoc property
  15071. * @name $rootScope.Scope#$root
  15072. *
  15073. * @description
  15074. * Reference to the root scope.
  15075. */
  15076. Scope.prototype = {
  15077. constructor: Scope,
  15078. /**
  15079. * @ngdoc method
  15080. * @name $rootScope.Scope#$new
  15081. * @kind function
  15082. *
  15083. * @description
  15084. * Creates a new child {@link ng.$rootScope.Scope scope}.
  15085. *
  15086. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  15087. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  15088. *
  15089. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  15090. * desired for the scope and its child scopes to be permanently detached from the parent and
  15091. * thus stop participating in model change detection and listener notification by invoking.
  15092. *
  15093. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  15094. * parent scope. The scope is isolated, as it can not see parent scope properties.
  15095. * When creating widgets, it is useful for the widget to not accidentally read parent
  15096. * state.
  15097. *
  15098. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  15099. * of the newly created scope. Defaults to `this` scope if not provided.
  15100. * This is used when creating a transclude scope to correctly place it
  15101. * in the scope hierarchy while maintaining the correct prototypical
  15102. * inheritance.
  15103. *
  15104. * @returns {Object} The newly created child scope.
  15105. *
  15106. */
  15107. $new: function(isolate, parent) {
  15108. var child;
  15109. parent = parent || this;
  15110. if (isolate) {
  15111. child = new Scope();
  15112. child.$root = this.$root;
  15113. } else {
  15114. // Only create a child scope class if somebody asks for one,
  15115. // but cache it to allow the VM to optimize lookups.
  15116. if (!this.$$ChildScope) {
  15117. this.$$ChildScope = createChildScopeClass(this);
  15118. }
  15119. child = new this.$$ChildScope();
  15120. }
  15121. child.$parent = parent;
  15122. child.$$prevSibling = parent.$$childTail;
  15123. if (parent.$$childHead) {
  15124. parent.$$childTail.$$nextSibling = child;
  15125. parent.$$childTail = child;
  15126. } else {
  15127. parent.$$childHead = parent.$$childTail = child;
  15128. }
  15129. // When the new scope is not isolated or we inherit from `this`, and
  15130. // the parent scope is destroyed, the property `$$destroyed` is inherited
  15131. // prototypically. In all other cases, this property needs to be set
  15132. // when the parent scope is destroyed.
  15133. // The listener needs to be added after the parent is set
  15134. if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
  15135. return child;
  15136. },
  15137. /**
  15138. * @ngdoc method
  15139. * @name $rootScope.Scope#$watch
  15140. * @kind function
  15141. *
  15142. * @description
  15143. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  15144. *
  15145. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  15146. * $digest()} and should return the value that will be watched. (`watchExpression` should not change
  15147. * its value when executed multiple times with the same input because it may be executed multiple
  15148. * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
  15149. * [idempotent](http://en.wikipedia.org/wiki/Idempotence).
  15150. * - The `listener` is called only when the value from the current `watchExpression` and the
  15151. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  15152. * see below). Inequality is determined according to reference inequality,
  15153. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  15154. * via the `!==` Javascript operator, unless `objectEquality == true`
  15155. * (see next point)
  15156. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  15157. * according to the {@link angular.equals} function. To save the value of the object for
  15158. * later comparison, the {@link angular.copy} function is used. This therefore means that
  15159. * watching complex objects will have adverse memory and performance implications.
  15160. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  15161. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  15162. * iteration limit is 10 to prevent an infinite loop deadlock.
  15163. *
  15164. *
  15165. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  15166. * you can register a `watchExpression` function with no `listener`. (Be prepared for
  15167. * multiple calls to your `watchExpression` because it will execute multiple times in a
  15168. * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
  15169. *
  15170. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  15171. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  15172. * watcher. In rare cases, this is undesirable because the listener is called when the result
  15173. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  15174. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  15175. * listener was called due to initialization.
  15176. *
  15177. *
  15178. *
  15179. * # Example
  15180. * ```js
  15181. // let's assume that scope was dependency injected as the $rootScope
  15182. var scope = $rootScope;
  15183. scope.name = 'misko';
  15184. scope.counter = 0;
  15185. expect(scope.counter).toEqual(0);
  15186. scope.$watch('name', function(newValue, oldValue) {
  15187. scope.counter = scope.counter + 1;
  15188. });
  15189. expect(scope.counter).toEqual(0);
  15190. scope.$digest();
  15191. // the listener is always called during the first $digest loop after it was registered
  15192. expect(scope.counter).toEqual(1);
  15193. scope.$digest();
  15194. // but now it will not be called unless the value changes
  15195. expect(scope.counter).toEqual(1);
  15196. scope.name = 'adam';
  15197. scope.$digest();
  15198. expect(scope.counter).toEqual(2);
  15199. // Using a function as a watchExpression
  15200. var food;
  15201. scope.foodCounter = 0;
  15202. expect(scope.foodCounter).toEqual(0);
  15203. scope.$watch(
  15204. // This function returns the value being watched. It is called for each turn of the $digest loop
  15205. function() { return food; },
  15206. // This is the change listener, called when the value returned from the above function changes
  15207. function(newValue, oldValue) {
  15208. if ( newValue !== oldValue ) {
  15209. // Only increment the counter if the value changed
  15210. scope.foodCounter = scope.foodCounter + 1;
  15211. }
  15212. }
  15213. );
  15214. // No digest has been run so the counter will be zero
  15215. expect(scope.foodCounter).toEqual(0);
  15216. // Run the digest but since food has not changed count will still be zero
  15217. scope.$digest();
  15218. expect(scope.foodCounter).toEqual(0);
  15219. // Update food and run digest. Now the counter will increment
  15220. food = 'cheeseburger';
  15221. scope.$digest();
  15222. expect(scope.foodCounter).toEqual(1);
  15223. * ```
  15224. *
  15225. *
  15226. *
  15227. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  15228. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  15229. * a call to the `listener`.
  15230. *
  15231. * - `string`: Evaluated as {@link guide/expression expression}
  15232. * - `function(scope)`: called with current `scope` as a parameter.
  15233. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  15234. * of `watchExpression` changes.
  15235. *
  15236. * - `newVal` contains the current value of the `watchExpression`
  15237. * - `oldVal` contains the previous value of the `watchExpression`
  15238. * - `scope` refers to the current scope
  15239. * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of
  15240. * comparing for reference equality.
  15241. * @returns {function()} Returns a deregistration function for this listener.
  15242. */
  15243. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  15244. var get = $parse(watchExp);
  15245. if (get.$$watchDelegate) {
  15246. return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
  15247. }
  15248. var scope = this,
  15249. array = scope.$$watchers,
  15250. watcher = {
  15251. fn: listener,
  15252. last: initWatchVal,
  15253. get: get,
  15254. exp: prettyPrintExpression || watchExp,
  15255. eq: !!objectEquality
  15256. };
  15257. lastDirtyWatch = null;
  15258. if (!isFunction(listener)) {
  15259. watcher.fn = noop;
  15260. }
  15261. if (!array) {
  15262. array = scope.$$watchers = [];
  15263. }
  15264. // we use unshift since we use a while loop in $digest for speed.
  15265. // the while loop reads in reverse order.
  15266. array.unshift(watcher);
  15267. incrementWatchersCount(this, 1);
  15268. return function deregisterWatch() {
  15269. if (arrayRemove(array, watcher) >= 0) {
  15270. incrementWatchersCount(scope, -1);
  15271. }
  15272. lastDirtyWatch = null;
  15273. };
  15274. },
  15275. /**
  15276. * @ngdoc method
  15277. * @name $rootScope.Scope#$watchGroup
  15278. * @kind function
  15279. *
  15280. * @description
  15281. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  15282. * If any one expression in the collection changes the `listener` is executed.
  15283. *
  15284. * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
  15285. * call to $digest() to see if any items changes.
  15286. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  15287. *
  15288. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  15289. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  15290. *
  15291. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  15292. * expression in `watchExpressions` changes
  15293. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  15294. * those of `watchExpression`
  15295. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  15296. * those of `watchExpression`
  15297. * The `scope` refers to the current scope.
  15298. * @returns {function()} Returns a de-registration function for all listeners.
  15299. */
  15300. $watchGroup: function(watchExpressions, listener) {
  15301. var oldValues = new Array(watchExpressions.length);
  15302. var newValues = new Array(watchExpressions.length);
  15303. var deregisterFns = [];
  15304. var self = this;
  15305. var changeReactionScheduled = false;
  15306. var firstRun = true;
  15307. if (!watchExpressions.length) {
  15308. // No expressions means we call the listener ASAP
  15309. var shouldCall = true;
  15310. self.$evalAsync(function() {
  15311. if (shouldCall) listener(newValues, newValues, self);
  15312. });
  15313. return function deregisterWatchGroup() {
  15314. shouldCall = false;
  15315. };
  15316. }
  15317. if (watchExpressions.length === 1) {
  15318. // Special case size of one
  15319. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  15320. newValues[0] = value;
  15321. oldValues[0] = oldValue;
  15322. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  15323. });
  15324. }
  15325. forEach(watchExpressions, function(expr, i) {
  15326. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  15327. newValues[i] = value;
  15328. oldValues[i] = oldValue;
  15329. if (!changeReactionScheduled) {
  15330. changeReactionScheduled = true;
  15331. self.$evalAsync(watchGroupAction);
  15332. }
  15333. });
  15334. deregisterFns.push(unwatchFn);
  15335. });
  15336. function watchGroupAction() {
  15337. changeReactionScheduled = false;
  15338. if (firstRun) {
  15339. firstRun = false;
  15340. listener(newValues, newValues, self);
  15341. } else {
  15342. listener(newValues, oldValues, self);
  15343. }
  15344. }
  15345. return function deregisterWatchGroup() {
  15346. while (deregisterFns.length) {
  15347. deregisterFns.shift()();
  15348. }
  15349. };
  15350. },
  15351. /**
  15352. * @ngdoc method
  15353. * @name $rootScope.Scope#$watchCollection
  15354. * @kind function
  15355. *
  15356. * @description
  15357. * Shallow watches the properties of an object and fires whenever any of the properties change
  15358. * (for arrays, this implies watching the array items; for object maps, this implies watching
  15359. * the properties). If a change is detected, the `listener` callback is fired.
  15360. *
  15361. * - The `obj` collection is observed via standard $watch operation and is examined on every
  15362. * call to $digest() to see if any items have been added, removed, or moved.
  15363. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  15364. * adding, removing, and moving items belonging to an object or array.
  15365. *
  15366. *
  15367. * # Example
  15368. * ```js
  15369. $scope.names = ['igor', 'matias', 'misko', 'james'];
  15370. $scope.dataCount = 4;
  15371. $scope.$watchCollection('names', function(newNames, oldNames) {
  15372. $scope.dataCount = newNames.length;
  15373. });
  15374. expect($scope.dataCount).toEqual(4);
  15375. $scope.$digest();
  15376. //still at 4 ... no changes
  15377. expect($scope.dataCount).toEqual(4);
  15378. $scope.names.pop();
  15379. $scope.$digest();
  15380. //now there's been a change
  15381. expect($scope.dataCount).toEqual(3);
  15382. * ```
  15383. *
  15384. *
  15385. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  15386. * expression value should evaluate to an object or an array which is observed on each
  15387. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  15388. * collection will trigger a call to the `listener`.
  15389. *
  15390. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  15391. * when a change is detected.
  15392. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  15393. * - The `oldCollection` object is a copy of the former collection data.
  15394. * Due to performance considerations, the`oldCollection` value is computed only if the
  15395. * `listener` function declares two or more arguments.
  15396. * - The `scope` argument refers to the current scope.
  15397. *
  15398. * @returns {function()} Returns a de-registration function for this listener. When the
  15399. * de-registration function is executed, the internal watch operation is terminated.
  15400. */
  15401. $watchCollection: function(obj, listener) {
  15402. $watchCollectionInterceptor.$stateful = true;
  15403. var self = this;
  15404. // the current value, updated on each dirty-check run
  15405. var newValue;
  15406. // a shallow copy of the newValue from the last dirty-check run,
  15407. // updated to match newValue during dirty-check run
  15408. var oldValue;
  15409. // a shallow copy of the newValue from when the last change happened
  15410. var veryOldValue;
  15411. // only track veryOldValue if the listener is asking for it
  15412. var trackVeryOldValue = (listener.length > 1);
  15413. var changeDetected = 0;
  15414. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  15415. var internalArray = [];
  15416. var internalObject = {};
  15417. var initRun = true;
  15418. var oldLength = 0;
  15419. function $watchCollectionInterceptor(_value) {
  15420. newValue = _value;
  15421. var newLength, key, bothNaN, newItem, oldItem;
  15422. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  15423. if (isUndefined(newValue)) return;
  15424. if (!isObject(newValue)) { // if primitive
  15425. if (oldValue !== newValue) {
  15426. oldValue = newValue;
  15427. changeDetected++;
  15428. }
  15429. } else if (isArrayLike(newValue)) {
  15430. if (oldValue !== internalArray) {
  15431. // we are transitioning from something which was not an array into array.
  15432. oldValue = internalArray;
  15433. oldLength = oldValue.length = 0;
  15434. changeDetected++;
  15435. }
  15436. newLength = newValue.length;
  15437. if (oldLength !== newLength) {
  15438. // if lengths do not match we need to trigger change notification
  15439. changeDetected++;
  15440. oldValue.length = oldLength = newLength;
  15441. }
  15442. // copy the items to oldValue and look for changes.
  15443. for (var i = 0; i < newLength; i++) {
  15444. oldItem = oldValue[i];
  15445. newItem = newValue[i];
  15446. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  15447. if (!bothNaN && (oldItem !== newItem)) {
  15448. changeDetected++;
  15449. oldValue[i] = newItem;
  15450. }
  15451. }
  15452. } else {
  15453. if (oldValue !== internalObject) {
  15454. // we are transitioning from something which was not an object into object.
  15455. oldValue = internalObject = {};
  15456. oldLength = 0;
  15457. changeDetected++;
  15458. }
  15459. // copy the items to oldValue and look for changes.
  15460. newLength = 0;
  15461. for (key in newValue) {
  15462. if (hasOwnProperty.call(newValue, key)) {
  15463. newLength++;
  15464. newItem = newValue[key];
  15465. oldItem = oldValue[key];
  15466. if (key in oldValue) {
  15467. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  15468. if (!bothNaN && (oldItem !== newItem)) {
  15469. changeDetected++;
  15470. oldValue[key] = newItem;
  15471. }
  15472. } else {
  15473. oldLength++;
  15474. oldValue[key] = newItem;
  15475. changeDetected++;
  15476. }
  15477. }
  15478. }
  15479. if (oldLength > newLength) {
  15480. // we used to have more keys, need to find them and destroy them.
  15481. changeDetected++;
  15482. for (key in oldValue) {
  15483. if (!hasOwnProperty.call(newValue, key)) {
  15484. oldLength--;
  15485. delete oldValue[key];
  15486. }
  15487. }
  15488. }
  15489. }
  15490. return changeDetected;
  15491. }
  15492. function $watchCollectionAction() {
  15493. if (initRun) {
  15494. initRun = false;
  15495. listener(newValue, newValue, self);
  15496. } else {
  15497. listener(newValue, veryOldValue, self);
  15498. }
  15499. // make a copy for the next time a collection is changed
  15500. if (trackVeryOldValue) {
  15501. if (!isObject(newValue)) {
  15502. //primitive
  15503. veryOldValue = newValue;
  15504. } else if (isArrayLike(newValue)) {
  15505. veryOldValue = new Array(newValue.length);
  15506. for (var i = 0; i < newValue.length; i++) {
  15507. veryOldValue[i] = newValue[i];
  15508. }
  15509. } else { // if object
  15510. veryOldValue = {};
  15511. for (var key in newValue) {
  15512. if (hasOwnProperty.call(newValue, key)) {
  15513. veryOldValue[key] = newValue[key];
  15514. }
  15515. }
  15516. }
  15517. }
  15518. }
  15519. return this.$watch(changeDetector, $watchCollectionAction);
  15520. },
  15521. /**
  15522. * @ngdoc method
  15523. * @name $rootScope.Scope#$digest
  15524. * @kind function
  15525. *
  15526. * @description
  15527. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  15528. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  15529. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  15530. * until no more listeners are firing. This means that it is possible to get into an infinite
  15531. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  15532. * iterations exceeds 10.
  15533. *
  15534. * Usually, you don't call `$digest()` directly in
  15535. * {@link ng.directive:ngController controllers} or in
  15536. * {@link ng.$compileProvider#directive directives}.
  15537. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  15538. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  15539. *
  15540. * If you want to be notified whenever `$digest()` is called,
  15541. * you can register a `watchExpression` function with
  15542. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  15543. *
  15544. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  15545. *
  15546. * # Example
  15547. * ```js
  15548. var scope = ...;
  15549. scope.name = 'misko';
  15550. scope.counter = 0;
  15551. expect(scope.counter).toEqual(0);
  15552. scope.$watch('name', function(newValue, oldValue) {
  15553. scope.counter = scope.counter + 1;
  15554. });
  15555. expect(scope.counter).toEqual(0);
  15556. scope.$digest();
  15557. // the listener is always called during the first $digest loop after it was registered
  15558. expect(scope.counter).toEqual(1);
  15559. scope.$digest();
  15560. // but now it will not be called unless the value changes
  15561. expect(scope.counter).toEqual(1);
  15562. scope.name = 'adam';
  15563. scope.$digest();
  15564. expect(scope.counter).toEqual(2);
  15565. * ```
  15566. *
  15567. */
  15568. $digest: function() {
  15569. var watch, value, last, fn, get,
  15570. watchers,
  15571. length,
  15572. dirty, ttl = TTL,
  15573. next, current, target = this,
  15574. watchLog = [],
  15575. logIdx, asyncTask;
  15576. beginPhase('$digest');
  15577. // Check for changes to browser url that happened in sync before the call to $digest
  15578. $browser.$$checkUrlChange();
  15579. if (this === $rootScope && applyAsyncId !== null) {
  15580. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  15581. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  15582. $browser.defer.cancel(applyAsyncId);
  15583. flushApplyAsync();
  15584. }
  15585. lastDirtyWatch = null;
  15586. do { // "while dirty" loop
  15587. dirty = false;
  15588. current = target;
  15589. // It's safe for asyncQueuePosition to be a local variable here because this loop can't
  15590. // be reentered recursively. Calling $digest from a function passed to $applyAsync would
  15591. // lead to a '$digest already in progress' error.
  15592. for (var asyncQueuePosition = 0; asyncQueuePosition < asyncQueue.length; asyncQueuePosition++) {
  15593. try {
  15594. asyncTask = asyncQueue[asyncQueuePosition];
  15595. asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
  15596. } catch (e) {
  15597. $exceptionHandler(e);
  15598. }
  15599. lastDirtyWatch = null;
  15600. }
  15601. asyncQueue.length = 0;
  15602. traverseScopesLoop:
  15603. do { // "traverse the scopes" loop
  15604. if ((watchers = current.$$watchers)) {
  15605. // process our watches
  15606. length = watchers.length;
  15607. while (length--) {
  15608. try {
  15609. watch = watchers[length];
  15610. // Most common watches are on primitives, in which case we can short
  15611. // circuit it with === operator, only when === fails do we use .equals
  15612. if (watch) {
  15613. get = watch.get;
  15614. if ((value = get(current)) !== (last = watch.last) &&
  15615. !(watch.eq
  15616. ? equals(value, last)
  15617. : (typeof value === 'number' && typeof last === 'number'
  15618. && isNaN(value) && isNaN(last)))) {
  15619. dirty = true;
  15620. lastDirtyWatch = watch;
  15621. watch.last = watch.eq ? copy(value, null) : value;
  15622. fn = watch.fn;
  15623. fn(value, ((last === initWatchVal) ? value : last), current);
  15624. if (ttl < 5) {
  15625. logIdx = 4 - ttl;
  15626. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  15627. watchLog[logIdx].push({
  15628. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  15629. newVal: value,
  15630. oldVal: last
  15631. });
  15632. }
  15633. } else if (watch === lastDirtyWatch) {
  15634. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  15635. // have already been tested.
  15636. dirty = false;
  15637. break traverseScopesLoop;
  15638. }
  15639. }
  15640. } catch (e) {
  15641. $exceptionHandler(e);
  15642. }
  15643. }
  15644. }
  15645. // Insanity Warning: scope depth-first traversal
  15646. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  15647. // this piece should be kept in sync with the traversal in $broadcast
  15648. if (!(next = ((current.$$watchersCount && current.$$childHead) ||
  15649. (current !== target && current.$$nextSibling)))) {
  15650. while (current !== target && !(next = current.$$nextSibling)) {
  15651. current = current.$parent;
  15652. }
  15653. }
  15654. } while ((current = next));
  15655. // `break traverseScopesLoop;` takes us to here
  15656. if ((dirty || asyncQueue.length) && !(ttl--)) {
  15657. clearPhase();
  15658. throw $rootScopeMinErr('infdig',
  15659. '{0} $digest() iterations reached. Aborting!\n' +
  15660. 'Watchers fired in the last 5 iterations: {1}',
  15661. TTL, watchLog);
  15662. }
  15663. } while (dirty || asyncQueue.length);
  15664. clearPhase();
  15665. // postDigestQueuePosition isn't local here because this loop can be reentered recursively.
  15666. while (postDigestQueuePosition < postDigestQueue.length) {
  15667. try {
  15668. postDigestQueue[postDigestQueuePosition++]();
  15669. } catch (e) {
  15670. $exceptionHandler(e);
  15671. }
  15672. }
  15673. postDigestQueue.length = postDigestQueuePosition = 0;
  15674. },
  15675. /**
  15676. * @ngdoc event
  15677. * @name $rootScope.Scope#$destroy
  15678. * @eventType broadcast on scope being destroyed
  15679. *
  15680. * @description
  15681. * Broadcasted when a scope and its children are being destroyed.
  15682. *
  15683. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  15684. * clean up DOM bindings before an element is removed from the DOM.
  15685. */
  15686. /**
  15687. * @ngdoc method
  15688. * @name $rootScope.Scope#$destroy
  15689. * @kind function
  15690. *
  15691. * @description
  15692. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  15693. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  15694. * propagate to the current scope and its children. Removal also implies that the current
  15695. * scope is eligible for garbage collection.
  15696. *
  15697. * The `$destroy()` is usually used by directives such as
  15698. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  15699. * unrolling of the loop.
  15700. *
  15701. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  15702. * Application code can register a `$destroy` event handler that will give it a chance to
  15703. * perform any necessary cleanup.
  15704. *
  15705. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  15706. * clean up DOM bindings before an element is removed from the DOM.
  15707. */
  15708. $destroy: function() {
  15709. // We can't destroy a scope that has been already destroyed.
  15710. if (this.$$destroyed) return;
  15711. var parent = this.$parent;
  15712. this.$broadcast('$destroy');
  15713. this.$$destroyed = true;
  15714. if (this === $rootScope) {
  15715. //Remove handlers attached to window when $rootScope is removed
  15716. $browser.$$applicationDestroyed();
  15717. }
  15718. incrementWatchersCount(this, -this.$$watchersCount);
  15719. for (var eventName in this.$$listenerCount) {
  15720. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  15721. }
  15722. // sever all the references to parent scopes (after this cleanup, the current scope should
  15723. // not be retained by any of our references and should be eligible for garbage collection)
  15724. if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  15725. if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  15726. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  15727. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  15728. // Disable listeners, watchers and apply/digest methods
  15729. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  15730. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  15731. this.$$listeners = {};
  15732. // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
  15733. this.$$nextSibling = null;
  15734. cleanUpScope(this);
  15735. },
  15736. /**
  15737. * @ngdoc method
  15738. * @name $rootScope.Scope#$eval
  15739. * @kind function
  15740. *
  15741. * @description
  15742. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  15743. * the expression are propagated (uncaught). This is useful when evaluating Angular
  15744. * expressions.
  15745. *
  15746. * # Example
  15747. * ```js
  15748. var scope = ng.$rootScope.Scope();
  15749. scope.a = 1;
  15750. scope.b = 2;
  15751. expect(scope.$eval('a+b')).toEqual(3);
  15752. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  15753. * ```
  15754. *
  15755. * @param {(string|function())=} expression An angular expression to be executed.
  15756. *
  15757. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  15758. * - `function(scope)`: execute the function with the current `scope` parameter.
  15759. *
  15760. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  15761. * @returns {*} The result of evaluating the expression.
  15762. */
  15763. $eval: function(expr, locals) {
  15764. return $parse(expr)(this, locals);
  15765. },
  15766. /**
  15767. * @ngdoc method
  15768. * @name $rootScope.Scope#$evalAsync
  15769. * @kind function
  15770. *
  15771. * @description
  15772. * Executes the expression on the current scope at a later point in time.
  15773. *
  15774. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  15775. * that:
  15776. *
  15777. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  15778. * rendering).
  15779. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  15780. * `expression` execution.
  15781. *
  15782. * Any exceptions from the execution of the expression are forwarded to the
  15783. * {@link ng.$exceptionHandler $exceptionHandler} service.
  15784. *
  15785. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  15786. * will be scheduled. However, it is encouraged to always call code that changes the model
  15787. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  15788. *
  15789. * @param {(string|function())=} expression An angular expression to be executed.
  15790. *
  15791. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  15792. * - `function(scope)`: execute the function with the current `scope` parameter.
  15793. *
  15794. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  15795. */
  15796. $evalAsync: function(expr, locals) {
  15797. // if we are outside of an $digest loop and this is the first time we are scheduling async
  15798. // task also schedule async auto-flush
  15799. if (!$rootScope.$$phase && !asyncQueue.length) {
  15800. $browser.defer(function() {
  15801. if (asyncQueue.length) {
  15802. $rootScope.$digest();
  15803. }
  15804. });
  15805. }
  15806. asyncQueue.push({scope: this, expression: $parse(expr), locals: locals});
  15807. },
  15808. $$postDigest: function(fn) {
  15809. postDigestQueue.push(fn);
  15810. },
  15811. /**
  15812. * @ngdoc method
  15813. * @name $rootScope.Scope#$apply
  15814. * @kind function
  15815. *
  15816. * @description
  15817. * `$apply()` is used to execute an expression in angular from outside of the angular
  15818. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  15819. * Because we are calling into the angular framework we need to perform proper scope life
  15820. * cycle of {@link ng.$exceptionHandler exception handling},
  15821. * {@link ng.$rootScope.Scope#$digest executing watches}.
  15822. *
  15823. * ## Life cycle
  15824. *
  15825. * # Pseudo-Code of `$apply()`
  15826. * ```js
  15827. function $apply(expr) {
  15828. try {
  15829. return $eval(expr);
  15830. } catch (e) {
  15831. $exceptionHandler(e);
  15832. } finally {
  15833. $root.$digest();
  15834. }
  15835. }
  15836. * ```
  15837. *
  15838. *
  15839. * Scope's `$apply()` method transitions through the following stages:
  15840. *
  15841. * 1. The {@link guide/expression expression} is executed using the
  15842. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  15843. * 2. Any exceptions from the execution of the expression are forwarded to the
  15844. * {@link ng.$exceptionHandler $exceptionHandler} service.
  15845. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  15846. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  15847. *
  15848. *
  15849. * @param {(string|function())=} exp An angular expression to be executed.
  15850. *
  15851. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  15852. * - `function(scope)`: execute the function with current `scope` parameter.
  15853. *
  15854. * @returns {*} The result of evaluating the expression.
  15855. */
  15856. $apply: function(expr) {
  15857. try {
  15858. beginPhase('$apply');
  15859. try {
  15860. return this.$eval(expr);
  15861. } finally {
  15862. clearPhase();
  15863. }
  15864. } catch (e) {
  15865. $exceptionHandler(e);
  15866. } finally {
  15867. try {
  15868. $rootScope.$digest();
  15869. } catch (e) {
  15870. $exceptionHandler(e);
  15871. throw e;
  15872. }
  15873. }
  15874. },
  15875. /**
  15876. * @ngdoc method
  15877. * @name $rootScope.Scope#$applyAsync
  15878. * @kind function
  15879. *
  15880. * @description
  15881. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  15882. * varies across browsers, but is typically around ~10 milliseconds.
  15883. *
  15884. * This can be used to queue up multiple expressions which need to be evaluated in the same
  15885. * digest.
  15886. *
  15887. * @param {(string|function())=} exp An angular expression to be executed.
  15888. *
  15889. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  15890. * - `function(scope)`: execute the function with current `scope` parameter.
  15891. */
  15892. $applyAsync: function(expr) {
  15893. var scope = this;
  15894. expr && applyAsyncQueue.push($applyAsyncExpression);
  15895. expr = $parse(expr);
  15896. scheduleApplyAsync();
  15897. function $applyAsyncExpression() {
  15898. scope.$eval(expr);
  15899. }
  15900. },
  15901. /**
  15902. * @ngdoc method
  15903. * @name $rootScope.Scope#$on
  15904. * @kind function
  15905. *
  15906. * @description
  15907. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  15908. * discussion of event life cycle.
  15909. *
  15910. * The event listener function format is: `function(event, args...)`. The `event` object
  15911. * passed into the listener has the following attributes:
  15912. *
  15913. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  15914. * `$broadcast`-ed.
  15915. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  15916. * event propagates through the scope hierarchy, this property is set to null.
  15917. * - `name` - `{string}`: name of the event.
  15918. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  15919. * further event propagation (available only for events that were `$emit`-ed).
  15920. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  15921. * to true.
  15922. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  15923. *
  15924. * @param {string} name Event name to listen on.
  15925. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  15926. * @returns {function()} Returns a deregistration function for this listener.
  15927. */
  15928. $on: function(name, listener) {
  15929. var namedListeners = this.$$listeners[name];
  15930. if (!namedListeners) {
  15931. this.$$listeners[name] = namedListeners = [];
  15932. }
  15933. namedListeners.push(listener);
  15934. var current = this;
  15935. do {
  15936. if (!current.$$listenerCount[name]) {
  15937. current.$$listenerCount[name] = 0;
  15938. }
  15939. current.$$listenerCount[name]++;
  15940. } while ((current = current.$parent));
  15941. var self = this;
  15942. return function() {
  15943. var indexOfListener = namedListeners.indexOf(listener);
  15944. if (indexOfListener !== -1) {
  15945. namedListeners[indexOfListener] = null;
  15946. decrementListenerCount(self, 1, name);
  15947. }
  15948. };
  15949. },
  15950. /**
  15951. * @ngdoc method
  15952. * @name $rootScope.Scope#$emit
  15953. * @kind function
  15954. *
  15955. * @description
  15956. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  15957. * registered {@link ng.$rootScope.Scope#$on} listeners.
  15958. *
  15959. * The event life cycle starts at the scope on which `$emit` was called. All
  15960. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  15961. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  15962. * registered listeners along the way. The event will stop propagating if one of the listeners
  15963. * cancels it.
  15964. *
  15965. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  15966. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  15967. *
  15968. * @param {string} name Event name to emit.
  15969. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  15970. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  15971. */
  15972. $emit: function(name, args) {
  15973. var empty = [],
  15974. namedListeners,
  15975. scope = this,
  15976. stopPropagation = false,
  15977. event = {
  15978. name: name,
  15979. targetScope: scope,
  15980. stopPropagation: function() {stopPropagation = true;},
  15981. preventDefault: function() {
  15982. event.defaultPrevented = true;
  15983. },
  15984. defaultPrevented: false
  15985. },
  15986. listenerArgs = concat([event], arguments, 1),
  15987. i, length;
  15988. do {
  15989. namedListeners = scope.$$listeners[name] || empty;
  15990. event.currentScope = scope;
  15991. for (i = 0, length = namedListeners.length; i < length; i++) {
  15992. // if listeners were deregistered, defragment the array
  15993. if (!namedListeners[i]) {
  15994. namedListeners.splice(i, 1);
  15995. i--;
  15996. length--;
  15997. continue;
  15998. }
  15999. try {
  16000. //allow all listeners attached to the current scope to run
  16001. namedListeners[i].apply(null, listenerArgs);
  16002. } catch (e) {
  16003. $exceptionHandler(e);
  16004. }
  16005. }
  16006. //if any listener on the current scope stops propagation, prevent bubbling
  16007. if (stopPropagation) {
  16008. event.currentScope = null;
  16009. return event;
  16010. }
  16011. //traverse upwards
  16012. scope = scope.$parent;
  16013. } while (scope);
  16014. event.currentScope = null;
  16015. return event;
  16016. },
  16017. /**
  16018. * @ngdoc method
  16019. * @name $rootScope.Scope#$broadcast
  16020. * @kind function
  16021. *
  16022. * @description
  16023. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  16024. * registered {@link ng.$rootScope.Scope#$on} listeners.
  16025. *
  16026. * The event life cycle starts at the scope on which `$broadcast` was called. All
  16027. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  16028. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  16029. * scope and calls all registered listeners along the way. The event cannot be canceled.
  16030. *
  16031. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  16032. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  16033. *
  16034. * @param {string} name Event name to broadcast.
  16035. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  16036. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  16037. */
  16038. $broadcast: function(name, args) {
  16039. var target = this,
  16040. current = target,
  16041. next = target,
  16042. event = {
  16043. name: name,
  16044. targetScope: target,
  16045. preventDefault: function() {
  16046. event.defaultPrevented = true;
  16047. },
  16048. defaultPrevented: false
  16049. };
  16050. if (!target.$$listenerCount[name]) return event;
  16051. var listenerArgs = concat([event], arguments, 1),
  16052. listeners, i, length;
  16053. //down while you can, then up and next sibling or up and next sibling until back at root
  16054. while ((current = next)) {
  16055. event.currentScope = current;
  16056. listeners = current.$$listeners[name] || [];
  16057. for (i = 0, length = listeners.length; i < length; i++) {
  16058. // if listeners were deregistered, defragment the array
  16059. if (!listeners[i]) {
  16060. listeners.splice(i, 1);
  16061. i--;
  16062. length--;
  16063. continue;
  16064. }
  16065. try {
  16066. listeners[i].apply(null, listenerArgs);
  16067. } catch (e) {
  16068. $exceptionHandler(e);
  16069. }
  16070. }
  16071. // Insanity Warning: scope depth-first traversal
  16072. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  16073. // this piece should be kept in sync with the traversal in $digest
  16074. // (though it differs due to having the extra check for $$listenerCount)
  16075. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  16076. (current !== target && current.$$nextSibling)))) {
  16077. while (current !== target && !(next = current.$$nextSibling)) {
  16078. current = current.$parent;
  16079. }
  16080. }
  16081. }
  16082. event.currentScope = null;
  16083. return event;
  16084. }
  16085. };
  16086. var $rootScope = new Scope();
  16087. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  16088. var asyncQueue = $rootScope.$$asyncQueue = [];
  16089. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  16090. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  16091. var postDigestQueuePosition = 0;
  16092. return $rootScope;
  16093. function beginPhase(phase) {
  16094. if ($rootScope.$$phase) {
  16095. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  16096. }
  16097. $rootScope.$$phase = phase;
  16098. }
  16099. function clearPhase() {
  16100. $rootScope.$$phase = null;
  16101. }
  16102. function incrementWatchersCount(current, count) {
  16103. do {
  16104. current.$$watchersCount += count;
  16105. } while ((current = current.$parent));
  16106. }
  16107. function decrementListenerCount(current, count, name) {
  16108. do {
  16109. current.$$listenerCount[name] -= count;
  16110. if (current.$$listenerCount[name] === 0) {
  16111. delete current.$$listenerCount[name];
  16112. }
  16113. } while ((current = current.$parent));
  16114. }
  16115. /**
  16116. * function used as an initial value for watchers.
  16117. * because it's unique we can easily tell it apart from other values
  16118. */
  16119. function initWatchVal() {}
  16120. function flushApplyAsync() {
  16121. while (applyAsyncQueue.length) {
  16122. try {
  16123. applyAsyncQueue.shift()();
  16124. } catch (e) {
  16125. $exceptionHandler(e);
  16126. }
  16127. }
  16128. applyAsyncId = null;
  16129. }
  16130. function scheduleApplyAsync() {
  16131. if (applyAsyncId === null) {
  16132. applyAsyncId = $browser.defer(function() {
  16133. $rootScope.$apply(flushApplyAsync);
  16134. });
  16135. }
  16136. }
  16137. }];
  16138. }
  16139. /**
  16140. * @ngdoc service
  16141. * @name $rootElement
  16142. *
  16143. * @description
  16144. * The root element of Angular application. This is either the element where {@link
  16145. * ng.directive:ngApp ngApp} was declared or the element passed into
  16146. * {@link angular.bootstrap}. The element represents the root element of application. It is also the
  16147. * location where the application's {@link auto.$injector $injector} service gets
  16148. * published, and can be retrieved using `$rootElement.injector()`.
  16149. */
  16150. // the implementation is in angular.bootstrap
  16151. /**
  16152. * @description
  16153. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  16154. */
  16155. function $$SanitizeUriProvider() {
  16156. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  16157. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  16158. /**
  16159. * @description
  16160. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  16161. * urls during a[href] sanitization.
  16162. *
  16163. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  16164. *
  16165. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  16166. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  16167. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  16168. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  16169. *
  16170. * @param {RegExp=} regexp New regexp to whitelist urls with.
  16171. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  16172. * chaining otherwise.
  16173. */
  16174. this.aHrefSanitizationWhitelist = function(regexp) {
  16175. if (isDefined(regexp)) {
  16176. aHrefSanitizationWhitelist = regexp;
  16177. return this;
  16178. }
  16179. return aHrefSanitizationWhitelist;
  16180. };
  16181. /**
  16182. * @description
  16183. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  16184. * urls during img[src] sanitization.
  16185. *
  16186. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  16187. *
  16188. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  16189. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  16190. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  16191. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  16192. *
  16193. * @param {RegExp=} regexp New regexp to whitelist urls with.
  16194. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  16195. * chaining otherwise.
  16196. */
  16197. this.imgSrcSanitizationWhitelist = function(regexp) {
  16198. if (isDefined(regexp)) {
  16199. imgSrcSanitizationWhitelist = regexp;
  16200. return this;
  16201. }
  16202. return imgSrcSanitizationWhitelist;
  16203. };
  16204. this.$get = function() {
  16205. return function sanitizeUri(uri, isImage) {
  16206. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  16207. var normalizedVal;
  16208. normalizedVal = urlResolve(uri).href;
  16209. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  16210. return 'unsafe:' + normalizedVal;
  16211. }
  16212. return uri;
  16213. };
  16214. };
  16215. }
  16216. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  16217. * Any commits to this file should be reviewed with security in mind. *
  16218. * Changes to this file can potentially create security vulnerabilities. *
  16219. * An approval from 2 Core members with history of modifying *
  16220. * this file is required. *
  16221. * *
  16222. * Does the change somehow allow for arbitrary javascript to be executed? *
  16223. * Or allows for someone to change the prototype of built-in objects? *
  16224. * Or gives undesired access to variables likes document or window? *
  16225. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  16226. var $sceMinErr = minErr('$sce');
  16227. var SCE_CONTEXTS = {
  16228. HTML: 'html',
  16229. CSS: 'css',
  16230. URL: 'url',
  16231. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  16232. // url. (e.g. ng-include, script src, templateUrl)
  16233. RESOURCE_URL: 'resourceUrl',
  16234. JS: 'js'
  16235. };
  16236. // Helper functions follow.
  16237. function adjustMatcher(matcher) {
  16238. if (matcher === 'self') {
  16239. return matcher;
  16240. } else if (isString(matcher)) {
  16241. // Strings match exactly except for 2 wildcards - '*' and '**'.
  16242. // '*' matches any character except those from the set ':/.?&'.
  16243. // '**' matches any character (like .* in a RegExp).
  16244. // More than 2 *'s raises an error as it's ill defined.
  16245. if (matcher.indexOf('***') > -1) {
  16246. throw $sceMinErr('iwcard',
  16247. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  16248. }
  16249. matcher = escapeForRegexp(matcher).
  16250. replace('\\*\\*', '.*').
  16251. replace('\\*', '[^:/.?&;]*');
  16252. return new RegExp('^' + matcher + '$');
  16253. } else if (isRegExp(matcher)) {
  16254. // The only other type of matcher allowed is a Regexp.
  16255. // Match entire URL / disallow partial matches.
  16256. // Flags are reset (i.e. no global, ignoreCase or multiline)
  16257. return new RegExp('^' + matcher.source + '$');
  16258. } else {
  16259. throw $sceMinErr('imatcher',
  16260. 'Matchers may only be "self", string patterns or RegExp objects');
  16261. }
  16262. }
  16263. function adjustMatchers(matchers) {
  16264. var adjustedMatchers = [];
  16265. if (isDefined(matchers)) {
  16266. forEach(matchers, function(matcher) {
  16267. adjustedMatchers.push(adjustMatcher(matcher));
  16268. });
  16269. }
  16270. return adjustedMatchers;
  16271. }
  16272. /**
  16273. * @ngdoc service
  16274. * @name $sceDelegate
  16275. * @kind function
  16276. *
  16277. * @description
  16278. *
  16279. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  16280. * Contextual Escaping (SCE)} services to AngularJS.
  16281. *
  16282. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  16283. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  16284. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  16285. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  16286. * work because `$sce` delegates to `$sceDelegate` for these operations.
  16287. *
  16288. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  16289. *
  16290. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  16291. * can override it completely to change the behavior of `$sce`, the common case would
  16292. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  16293. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  16294. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  16295. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  16296. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  16297. */
  16298. /**
  16299. * @ngdoc provider
  16300. * @name $sceDelegateProvider
  16301. * @description
  16302. *
  16303. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  16304. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  16305. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  16306. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  16307. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  16308. *
  16309. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  16310. * Strict Contextual Escaping (SCE)}.
  16311. *
  16312. * **Example**: Consider the following case. <a name="example"></a>
  16313. *
  16314. * - your app is hosted at url `http://myapp.example.com/`
  16315. * - but some of your templates are hosted on other domains you control such as
  16316. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  16317. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  16318. *
  16319. * Here is what a secure configuration for this scenario might look like:
  16320. *
  16321. * ```
  16322. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  16323. * $sceDelegateProvider.resourceUrlWhitelist([
  16324. * // Allow same origin resource loads.
  16325. * 'self',
  16326. * // Allow loading from our assets domain. Notice the difference between * and **.
  16327. * 'http://srv*.assets.example.com/**'
  16328. * ]);
  16329. *
  16330. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  16331. * $sceDelegateProvider.resourceUrlBlacklist([
  16332. * 'http://myapp.example.com/clickThru**'
  16333. * ]);
  16334. * });
  16335. * ```
  16336. */
  16337. function $SceDelegateProvider() {
  16338. this.SCE_CONTEXTS = SCE_CONTEXTS;
  16339. // Resource URLs can also be trusted by policy.
  16340. var resourceUrlWhitelist = ['self'],
  16341. resourceUrlBlacklist = [];
  16342. /**
  16343. * @ngdoc method
  16344. * @name $sceDelegateProvider#resourceUrlWhitelist
  16345. * @kind function
  16346. *
  16347. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  16348. * provided. This must be an array or null. A snapshot of this array is used so further
  16349. * changes to the array are ignored.
  16350. *
  16351. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  16352. * allowed in this array.
  16353. *
  16354. * <div class="alert alert-warning">
  16355. * **Note:** an empty whitelist array will block all URLs!
  16356. * </div>
  16357. *
  16358. * @return {Array} the currently set whitelist array.
  16359. *
  16360. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  16361. * same origin resource requests.
  16362. *
  16363. * @description
  16364. * Sets/Gets the whitelist of trusted resource URLs.
  16365. */
  16366. this.resourceUrlWhitelist = function(value) {
  16367. if (arguments.length) {
  16368. resourceUrlWhitelist = adjustMatchers(value);
  16369. }
  16370. return resourceUrlWhitelist;
  16371. };
  16372. /**
  16373. * @ngdoc method
  16374. * @name $sceDelegateProvider#resourceUrlBlacklist
  16375. * @kind function
  16376. *
  16377. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  16378. * provided. This must be an array or null. A snapshot of this array is used so further
  16379. * changes to the array are ignored.
  16380. *
  16381. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  16382. * allowed in this array.
  16383. *
  16384. * The typical usage for the blacklist is to **block
  16385. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  16386. * these would otherwise be trusted but actually return content from the redirected domain.
  16387. *
  16388. * Finally, **the blacklist overrides the whitelist** and has the final say.
  16389. *
  16390. * @return {Array} the currently set blacklist array.
  16391. *
  16392. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  16393. * is no blacklist.)
  16394. *
  16395. * @description
  16396. * Sets/Gets the blacklist of trusted resource URLs.
  16397. */
  16398. this.resourceUrlBlacklist = function(value) {
  16399. if (arguments.length) {
  16400. resourceUrlBlacklist = adjustMatchers(value);
  16401. }
  16402. return resourceUrlBlacklist;
  16403. };
  16404. this.$get = ['$injector', function($injector) {
  16405. var htmlSanitizer = function htmlSanitizer(html) {
  16406. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  16407. };
  16408. if ($injector.has('$sanitize')) {
  16409. htmlSanitizer = $injector.get('$sanitize');
  16410. }
  16411. function matchUrl(matcher, parsedUrl) {
  16412. if (matcher === 'self') {
  16413. return urlIsSameOrigin(parsedUrl);
  16414. } else {
  16415. // definitely a regex. See adjustMatchers()
  16416. return !!matcher.exec(parsedUrl.href);
  16417. }
  16418. }
  16419. function isResourceUrlAllowedByPolicy(url) {
  16420. var parsedUrl = urlResolve(url.toString());
  16421. var i, n, allowed = false;
  16422. // Ensure that at least one item from the whitelist allows this url.
  16423. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  16424. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  16425. allowed = true;
  16426. break;
  16427. }
  16428. }
  16429. if (allowed) {
  16430. // Ensure that no item from the blacklist blocked this url.
  16431. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  16432. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  16433. allowed = false;
  16434. break;
  16435. }
  16436. }
  16437. }
  16438. return allowed;
  16439. }
  16440. function generateHolderType(Base) {
  16441. var holderType = function TrustedValueHolderType(trustedValue) {
  16442. this.$$unwrapTrustedValue = function() {
  16443. return trustedValue;
  16444. };
  16445. };
  16446. if (Base) {
  16447. holderType.prototype = new Base();
  16448. }
  16449. holderType.prototype.valueOf = function sceValueOf() {
  16450. return this.$$unwrapTrustedValue();
  16451. };
  16452. holderType.prototype.toString = function sceToString() {
  16453. return this.$$unwrapTrustedValue().toString();
  16454. };
  16455. return holderType;
  16456. }
  16457. var trustedValueHolderBase = generateHolderType(),
  16458. byType = {};
  16459. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  16460. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  16461. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  16462. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  16463. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  16464. /**
  16465. * @ngdoc method
  16466. * @name $sceDelegate#trustAs
  16467. *
  16468. * @description
  16469. * Returns an object that is trusted by angular for use in specified strict
  16470. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  16471. * attribute interpolation, any dom event binding attribute interpolation
  16472. * such as for onclick, etc.) that uses the provided value.
  16473. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  16474. *
  16475. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  16476. * resourceUrl, html, js and css.
  16477. * @param {*} value The value that that should be considered trusted/safe.
  16478. * @returns {*} A value that can be used to stand in for the provided `value` in places
  16479. * where Angular expects a $sce.trustAs() return value.
  16480. */
  16481. function trustAs(type, trustedValue) {
  16482. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  16483. if (!Constructor) {
  16484. throw $sceMinErr('icontext',
  16485. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  16486. type, trustedValue);
  16487. }
  16488. if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
  16489. return trustedValue;
  16490. }
  16491. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  16492. // mutable objects, we ensure here that the value passed in is actually a string.
  16493. if (typeof trustedValue !== 'string') {
  16494. throw $sceMinErr('itype',
  16495. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  16496. type);
  16497. }
  16498. return new Constructor(trustedValue);
  16499. }
  16500. /**
  16501. * @ngdoc method
  16502. * @name $sceDelegate#valueOf
  16503. *
  16504. * @description
  16505. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  16506. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  16507. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  16508. *
  16509. * If the passed parameter is not a value that had been returned by {@link
  16510. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  16511. *
  16512. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  16513. * call or anything else.
  16514. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  16515. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  16516. * `value` unchanged.
  16517. */
  16518. function valueOf(maybeTrusted) {
  16519. if (maybeTrusted instanceof trustedValueHolderBase) {
  16520. return maybeTrusted.$$unwrapTrustedValue();
  16521. } else {
  16522. return maybeTrusted;
  16523. }
  16524. }
  16525. /**
  16526. * @ngdoc method
  16527. * @name $sceDelegate#getTrusted
  16528. *
  16529. * @description
  16530. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  16531. * returns the originally supplied value if the queried context type is a supertype of the
  16532. * created type. If this condition isn't satisfied, throws an exception.
  16533. *
  16534. * <div class="alert alert-danger">
  16535. * Disabling auto-escaping is extremely dangerous, it usually creates a Cross Site Scripting
  16536. * (XSS) vulnerability in your application.
  16537. * </div>
  16538. *
  16539. * @param {string} type The kind of context in which this value is to be used.
  16540. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  16541. * `$sceDelegate.trustAs`} call.
  16542. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  16543. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  16544. */
  16545. function getTrusted(type, maybeTrusted) {
  16546. if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
  16547. return maybeTrusted;
  16548. }
  16549. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  16550. if (constructor && maybeTrusted instanceof constructor) {
  16551. return maybeTrusted.$$unwrapTrustedValue();
  16552. }
  16553. // If we get here, then we may only take one of two actions.
  16554. // 1. sanitize the value for the requested type, or
  16555. // 2. throw an exception.
  16556. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  16557. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  16558. return maybeTrusted;
  16559. } else {
  16560. throw $sceMinErr('insecurl',
  16561. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  16562. maybeTrusted.toString());
  16563. }
  16564. } else if (type === SCE_CONTEXTS.HTML) {
  16565. return htmlSanitizer(maybeTrusted);
  16566. }
  16567. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  16568. }
  16569. return { trustAs: trustAs,
  16570. getTrusted: getTrusted,
  16571. valueOf: valueOf };
  16572. }];
  16573. }
  16574. /**
  16575. * @ngdoc provider
  16576. * @name $sceProvider
  16577. * @description
  16578. *
  16579. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  16580. * - enable/disable Strict Contextual Escaping (SCE) in a module
  16581. * - override the default implementation with a custom delegate
  16582. *
  16583. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  16584. */
  16585. /* jshint maxlen: false*/
  16586. /**
  16587. * @ngdoc service
  16588. * @name $sce
  16589. * @kind function
  16590. *
  16591. * @description
  16592. *
  16593. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  16594. *
  16595. * # Strict Contextual Escaping
  16596. *
  16597. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  16598. * contexts to result in a value that is marked as safe to use for that context. One example of
  16599. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  16600. * to these contexts as privileged or SCE contexts.
  16601. *
  16602. * As of version 1.2, Angular ships with SCE enabled by default.
  16603. *
  16604. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  16605. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  16606. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  16607. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  16608. * to the top of your HTML document.
  16609. *
  16610. * SCE assists in writing code in a way that (a) is secure by default and (b) makes auditing for
  16611. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  16612. *
  16613. * Here's an example of a binding in a privileged context:
  16614. *
  16615. * ```
  16616. * <input ng-model="userHtml" aria-label="User input">
  16617. * <div ng-bind-html="userHtml"></div>
  16618. * ```
  16619. *
  16620. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  16621. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  16622. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  16623. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  16624. * security vulnerabilities.)
  16625. *
  16626. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  16627. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  16628. *
  16629. * How would you ensure that every place that used these types of bindings was bound to a value that
  16630. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  16631. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  16632. * properties/fields and forgot to update the binding to the sanitized value?
  16633. *
  16634. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  16635. * determine that something explicitly says it's safe to use a value for binding in that
  16636. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  16637. * for those values that you can easily tell are safe - because they were received from your server,
  16638. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  16639. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  16640. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  16641. *
  16642. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  16643. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  16644. * obtain values that will be accepted by SCE / privileged contexts.
  16645. *
  16646. *
  16647. * ## How does it work?
  16648. *
  16649. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  16650. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  16651. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  16652. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  16653. *
  16654. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  16655. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  16656. * simplified):
  16657. *
  16658. * ```
  16659. * var ngBindHtmlDirective = ['$sce', function($sce) {
  16660. * return function(scope, element, attr) {
  16661. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  16662. * element.html(value || '');
  16663. * });
  16664. * };
  16665. * }];
  16666. * ```
  16667. *
  16668. * ## Impact on loading templates
  16669. *
  16670. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  16671. * `templateUrl`'s specified by {@link guide/directive directives}.
  16672. *
  16673. * By default, Angular only loads templates from the same domain and protocol as the application
  16674. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  16675. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  16676. * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  16677. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  16678. *
  16679. * *Please note*:
  16680. * The browser's
  16681. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  16682. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  16683. * policy apply in addition to this and may further restrict whether the template is successfully
  16684. * loaded. This means that without the right CORS policy, loading templates from a different domain
  16685. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  16686. * browsers.
  16687. *
  16688. * ## This feels like too much overhead
  16689. *
  16690. * It's important to remember that SCE only applies to interpolation expressions.
  16691. *
  16692. * If your expressions are constant literals, they're automatically trusted and you don't need to
  16693. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  16694. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  16695. *
  16696. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  16697. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  16698. *
  16699. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  16700. * templates in `ng-include` from your application's domain without having to even know about SCE.
  16701. * It blocks loading templates from other domains or loading templates over http from an https
  16702. * served document. You can change these by setting your own custom {@link
  16703. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  16704. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  16705. *
  16706. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  16707. * application that's secure and can be audited to verify that with much more ease than bolting
  16708. * security onto an application later.
  16709. *
  16710. * <a name="contexts"></a>
  16711. * ## What trusted context types are supported?
  16712. *
  16713. * | Context | Notes |
  16714. * |---------------------|----------------|
  16715. * | `$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. |
  16716. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  16717. * | `$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. |
  16718. * | `$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. |
  16719. * | `$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. |
  16720. *
  16721. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  16722. *
  16723. * Each element in these arrays must be one of the following:
  16724. *
  16725. * - **'self'**
  16726. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  16727. * domain** as the application document using the **same protocol**.
  16728. * - **String** (except the special value `'self'`)
  16729. * - The string is matched against the full *normalized / absolute URL* of the resource
  16730. * being tested (substring matches are not good enough.)
  16731. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  16732. * match themselves.
  16733. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  16734. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
  16735. * in a whitelist.
  16736. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  16737. * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
  16738. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  16739. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  16740. * http://foo.example.com/templates/**).
  16741. * - **RegExp** (*see caveat below*)
  16742. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  16743. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  16744. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  16745. * have good test coverage). For instance, the use of `.` in the regex is correct only in a
  16746. * small number of cases. A `.` character in the regex used when matching the scheme or a
  16747. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  16748. * is highly recommended to use the string patterns and only fall back to regular expressions
  16749. * as a last resort.
  16750. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  16751. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  16752. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  16753. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  16754. * - If you are generating your JavaScript from some other templating engine (not
  16755. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  16756. * remember to escape your regular expression (and be aware that you might need more than
  16757. * one level of escaping depending on your templating engine and the way you interpolated
  16758. * the value.) Do make use of your platform's escaping mechanism as it might be good
  16759. * enough before coding your own. E.g. Ruby has
  16760. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  16761. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  16762. * Javascript lacks a similar built in function for escaping. Take a look at Google
  16763. * Closure library's [goog.string.regExpEscape(s)](
  16764. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  16765. *
  16766. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  16767. *
  16768. * ## Show me an example using SCE.
  16769. *
  16770. * <example module="mySceApp" deps="angular-sanitize.js">
  16771. * <file name="index.html">
  16772. * <div ng-controller="AppController as myCtrl">
  16773. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  16774. * <b>User comments</b><br>
  16775. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  16776. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  16777. * exploit.
  16778. * <div class="well">
  16779. * <div ng-repeat="userComment in myCtrl.userComments">
  16780. * <b>{{userComment.name}}</b>:
  16781. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  16782. * <br>
  16783. * </div>
  16784. * </div>
  16785. * </div>
  16786. * </file>
  16787. *
  16788. * <file name="script.js">
  16789. * angular.module('mySceApp', ['ngSanitize'])
  16790. * .controller('AppController', ['$http', '$templateCache', '$sce',
  16791. * function($http, $templateCache, $sce) {
  16792. * var self = this;
  16793. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  16794. * self.userComments = userComments;
  16795. * });
  16796. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  16797. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  16798. * 'sanitization.&quot;">Hover over this text.</span>');
  16799. * }]);
  16800. * </file>
  16801. *
  16802. * <file name="test_data.json">
  16803. * [
  16804. * { "name": "Alice",
  16805. * "htmlComment":
  16806. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  16807. * },
  16808. * { "name": "Bob",
  16809. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  16810. * }
  16811. * ]
  16812. * </file>
  16813. *
  16814. * <file name="protractor.js" type="protractor">
  16815. * describe('SCE doc demo', function() {
  16816. * it('should sanitize untrusted values', function() {
  16817. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  16818. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  16819. * });
  16820. *
  16821. * it('should NOT sanitize explicitly trusted values', function() {
  16822. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  16823. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  16824. * 'sanitization.&quot;">Hover over this text.</span>');
  16825. * });
  16826. * });
  16827. * </file>
  16828. * </example>
  16829. *
  16830. *
  16831. *
  16832. * ## Can I disable SCE completely?
  16833. *
  16834. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  16835. * for little coding overhead. It will be much harder to take an SCE disabled application and
  16836. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  16837. * for cases where you have a lot of existing code that was written before SCE was introduced and
  16838. * you're migrating them a module at a time.
  16839. *
  16840. * That said, here's how you can completely disable SCE:
  16841. *
  16842. * ```
  16843. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  16844. * // Completely disable SCE. For demonstration purposes only!
  16845. * // Do not use in new projects.
  16846. * $sceProvider.enabled(false);
  16847. * });
  16848. * ```
  16849. *
  16850. */
  16851. /* jshint maxlen: 100 */
  16852. function $SceProvider() {
  16853. var enabled = true;
  16854. /**
  16855. * @ngdoc method
  16856. * @name $sceProvider#enabled
  16857. * @kind function
  16858. *
  16859. * @param {boolean=} value If provided, then enables/disables SCE.
  16860. * @return {boolean} true if SCE is enabled, false otherwise.
  16861. *
  16862. * @description
  16863. * Enables/disables SCE and returns the current value.
  16864. */
  16865. this.enabled = function(value) {
  16866. if (arguments.length) {
  16867. enabled = !!value;
  16868. }
  16869. return enabled;
  16870. };
  16871. /* Design notes on the default implementation for SCE.
  16872. *
  16873. * The API contract for the SCE delegate
  16874. * -------------------------------------
  16875. * The SCE delegate object must provide the following 3 methods:
  16876. *
  16877. * - trustAs(contextEnum, value)
  16878. * This method is used to tell the SCE service that the provided value is OK to use in the
  16879. * contexts specified by contextEnum. It must return an object that will be accepted by
  16880. * getTrusted() for a compatible contextEnum and return this value.
  16881. *
  16882. * - valueOf(value)
  16883. * For values that were not produced by trustAs(), return them as is. For values that were
  16884. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  16885. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  16886. * such a value.
  16887. *
  16888. * - getTrusted(contextEnum, value)
  16889. * This function should return the a value that is safe to use in the context specified by
  16890. * contextEnum or throw and exception otherwise.
  16891. *
  16892. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  16893. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  16894. * instance, an implementation could maintain a registry of all trusted objects by context. In
  16895. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  16896. * return the same object passed in if it was found in the registry under a compatible context or
  16897. * throw an exception otherwise. An implementation might only wrap values some of the time based
  16898. * on some criteria. getTrusted() might return a value and not throw an exception for special
  16899. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  16900. *
  16901. *
  16902. * A note on the inheritance model for SCE contexts
  16903. * ------------------------------------------------
  16904. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  16905. * is purely an implementation details.
  16906. *
  16907. * The contract is simply this:
  16908. *
  16909. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  16910. * will also succeed.
  16911. *
  16912. * Inheritance happens to capture this in a natural way. In some future, we
  16913. * may not use inheritance anymore. That is OK because no code outside of
  16914. * sce.js and sceSpecs.js would need to be aware of this detail.
  16915. */
  16916. this.$get = ['$parse', '$sceDelegate', function(
  16917. $parse, $sceDelegate) {
  16918. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  16919. // the "expression(javascript expression)" syntax which is insecure.
  16920. if (enabled && msie < 8) {
  16921. throw $sceMinErr('iequirks',
  16922. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  16923. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  16924. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  16925. }
  16926. var sce = shallowCopy(SCE_CONTEXTS);
  16927. /**
  16928. * @ngdoc method
  16929. * @name $sce#isEnabled
  16930. * @kind function
  16931. *
  16932. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  16933. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  16934. *
  16935. * @description
  16936. * Returns a boolean indicating if SCE is enabled.
  16937. */
  16938. sce.isEnabled = function() {
  16939. return enabled;
  16940. };
  16941. sce.trustAs = $sceDelegate.trustAs;
  16942. sce.getTrusted = $sceDelegate.getTrusted;
  16943. sce.valueOf = $sceDelegate.valueOf;
  16944. if (!enabled) {
  16945. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  16946. sce.valueOf = identity;
  16947. }
  16948. /**
  16949. * @ngdoc method
  16950. * @name $sce#parseAs
  16951. *
  16952. * @description
  16953. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  16954. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  16955. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  16956. * *result*)}
  16957. *
  16958. * @param {string} type The kind of SCE context in which this result will be used.
  16959. * @param {string} expression String expression to compile.
  16960. * @returns {function(context, locals)} a function which represents the compiled expression:
  16961. *
  16962. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  16963. * are evaluated against (typically a scope object).
  16964. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  16965. * `context`.
  16966. */
  16967. sce.parseAs = function sceParseAs(type, expr) {
  16968. var parsed = $parse(expr);
  16969. if (parsed.literal && parsed.constant) {
  16970. return parsed;
  16971. } else {
  16972. return $parse(expr, function(value) {
  16973. return sce.getTrusted(type, value);
  16974. });
  16975. }
  16976. };
  16977. /**
  16978. * @ngdoc method
  16979. * @name $sce#trustAs
  16980. *
  16981. * @description
  16982. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  16983. * returns an object that is trusted by angular for use in specified strict contextual
  16984. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  16985. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  16986. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  16987. * escaping.
  16988. *
  16989. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  16990. * resourceUrl, html, js and css.
  16991. * @param {*} value The value that that should be considered trusted/safe.
  16992. * @returns {*} A value that can be used to stand in for the provided `value` in places
  16993. * where Angular expects a $sce.trustAs() return value.
  16994. */
  16995. /**
  16996. * @ngdoc method
  16997. * @name $sce#trustAsHtml
  16998. *
  16999. * @description
  17000. * Shorthand method. `$sce.trustAsHtml(value)` →
  17001. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  17002. *
  17003. * @param {*} value The value to trustAs.
  17004. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  17005. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  17006. * only accept expressions that are either literal constants or are the
  17007. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17008. */
  17009. /**
  17010. * @ngdoc method
  17011. * @name $sce#trustAsUrl
  17012. *
  17013. * @description
  17014. * Shorthand method. `$sce.trustAsUrl(value)` →
  17015. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  17016. *
  17017. * @param {*} value The value to trustAs.
  17018. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  17019. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  17020. * only accept expressions that are either literal constants or are the
  17021. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17022. */
  17023. /**
  17024. * @ngdoc method
  17025. * @name $sce#trustAsResourceUrl
  17026. *
  17027. * @description
  17028. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  17029. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  17030. *
  17031. * @param {*} value The value to trustAs.
  17032. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  17033. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  17034. * only accept expressions that are either literal constants or are the return
  17035. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17036. */
  17037. /**
  17038. * @ngdoc method
  17039. * @name $sce#trustAsJs
  17040. *
  17041. * @description
  17042. * Shorthand method. `$sce.trustAsJs(value)` →
  17043. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  17044. *
  17045. * @param {*} value The value to trustAs.
  17046. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  17047. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  17048. * only accept expressions that are either literal constants or are the
  17049. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  17050. */
  17051. /**
  17052. * @ngdoc method
  17053. * @name $sce#getTrusted
  17054. *
  17055. * @description
  17056. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  17057. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  17058. * originally supplied value if the queried context type is a supertype of the created type.
  17059. * If this condition isn't satisfied, throws an exception.
  17060. *
  17061. * @param {string} type The kind of context in which this value is to be used.
  17062. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  17063. * call.
  17064. * @returns {*} The value the was originally provided to
  17065. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  17066. * Otherwise, throws an exception.
  17067. */
  17068. /**
  17069. * @ngdoc method
  17070. * @name $sce#getTrustedHtml
  17071. *
  17072. * @description
  17073. * Shorthand method. `$sce.getTrustedHtml(value)` →
  17074. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  17075. *
  17076. * @param {*} value The value to pass to `$sce.getTrusted`.
  17077. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  17078. */
  17079. /**
  17080. * @ngdoc method
  17081. * @name $sce#getTrustedCss
  17082. *
  17083. * @description
  17084. * Shorthand method. `$sce.getTrustedCss(value)` →
  17085. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  17086. *
  17087. * @param {*} value The value to pass to `$sce.getTrusted`.
  17088. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  17089. */
  17090. /**
  17091. * @ngdoc method
  17092. * @name $sce#getTrustedUrl
  17093. *
  17094. * @description
  17095. * Shorthand method. `$sce.getTrustedUrl(value)` →
  17096. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  17097. *
  17098. * @param {*} value The value to pass to `$sce.getTrusted`.
  17099. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  17100. */
  17101. /**
  17102. * @ngdoc method
  17103. * @name $sce#getTrustedResourceUrl
  17104. *
  17105. * @description
  17106. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  17107. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  17108. *
  17109. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  17110. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  17111. */
  17112. /**
  17113. * @ngdoc method
  17114. * @name $sce#getTrustedJs
  17115. *
  17116. * @description
  17117. * Shorthand method. `$sce.getTrustedJs(value)` →
  17118. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  17119. *
  17120. * @param {*} value The value to pass to `$sce.getTrusted`.
  17121. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  17122. */
  17123. /**
  17124. * @ngdoc method
  17125. * @name $sce#parseAsHtml
  17126. *
  17127. * @description
  17128. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  17129. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  17130. *
  17131. * @param {string} expression String expression to compile.
  17132. * @returns {function(context, locals)} a function which represents the compiled expression:
  17133. *
  17134. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17135. * are evaluated against (typically a scope object).
  17136. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17137. * `context`.
  17138. */
  17139. /**
  17140. * @ngdoc method
  17141. * @name $sce#parseAsCss
  17142. *
  17143. * @description
  17144. * Shorthand method. `$sce.parseAsCss(value)` →
  17145. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  17146. *
  17147. * @param {string} expression String expression to compile.
  17148. * @returns {function(context, locals)} a function which represents the compiled expression:
  17149. *
  17150. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17151. * are evaluated against (typically a scope object).
  17152. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17153. * `context`.
  17154. */
  17155. /**
  17156. * @ngdoc method
  17157. * @name $sce#parseAsUrl
  17158. *
  17159. * @description
  17160. * Shorthand method. `$sce.parseAsUrl(value)` →
  17161. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  17162. *
  17163. * @param {string} expression String expression to compile.
  17164. * @returns {function(context, locals)} a function which represents the compiled expression:
  17165. *
  17166. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17167. * are evaluated against (typically a scope object).
  17168. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17169. * `context`.
  17170. */
  17171. /**
  17172. * @ngdoc method
  17173. * @name $sce#parseAsResourceUrl
  17174. *
  17175. * @description
  17176. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  17177. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  17178. *
  17179. * @param {string} expression String expression to compile.
  17180. * @returns {function(context, locals)} a function which represents the compiled expression:
  17181. *
  17182. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17183. * are evaluated against (typically a scope object).
  17184. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17185. * `context`.
  17186. */
  17187. /**
  17188. * @ngdoc method
  17189. * @name $sce#parseAsJs
  17190. *
  17191. * @description
  17192. * Shorthand method. `$sce.parseAsJs(value)` →
  17193. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  17194. *
  17195. * @param {string} expression String expression to compile.
  17196. * @returns {function(context, locals)} a function which represents the compiled expression:
  17197. *
  17198. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  17199. * are evaluated against (typically a scope object).
  17200. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  17201. * `context`.
  17202. */
  17203. // Shorthand delegations.
  17204. var parse = sce.parseAs,
  17205. getTrusted = sce.getTrusted,
  17206. trustAs = sce.trustAs;
  17207. forEach(SCE_CONTEXTS, function(enumValue, name) {
  17208. var lName = lowercase(name);
  17209. sce[camelCase("parse_as_" + lName)] = function(expr) {
  17210. return parse(enumValue, expr);
  17211. };
  17212. sce[camelCase("get_trusted_" + lName)] = function(value) {
  17213. return getTrusted(enumValue, value);
  17214. };
  17215. sce[camelCase("trust_as_" + lName)] = function(value) {
  17216. return trustAs(enumValue, value);
  17217. };
  17218. });
  17219. return sce;
  17220. }];
  17221. }
  17222. /**
  17223. * !!! This is an undocumented "private" service !!!
  17224. *
  17225. * @name $sniffer
  17226. * @requires $window
  17227. * @requires $document
  17228. *
  17229. * @property {boolean} history Does the browser support html5 history api ?
  17230. * @property {boolean} transitions Does the browser support CSS transition events ?
  17231. * @property {boolean} animations Does the browser support CSS animation events ?
  17232. *
  17233. * @description
  17234. * This is very simple implementation of testing browser's features.
  17235. */
  17236. function $SnifferProvider() {
  17237. this.$get = ['$window', '$document', function($window, $document) {
  17238. var eventSupport = {},
  17239. // Chrome Packaged Apps are not allowed to access `history.pushState`. They can be detected by
  17240. // the presence of `chrome.app.runtime` (see https://developer.chrome.com/apps/api_index)
  17241. isChromePackagedApp = $window.chrome && $window.chrome.app && $window.chrome.app.runtime,
  17242. hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState,
  17243. android =
  17244. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  17245. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  17246. document = $document[0] || {},
  17247. vendorPrefix,
  17248. vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
  17249. bodyStyle = document.body && document.body.style,
  17250. transitions = false,
  17251. animations = false,
  17252. match;
  17253. if (bodyStyle) {
  17254. for (var prop in bodyStyle) {
  17255. if (match = vendorRegex.exec(prop)) {
  17256. vendorPrefix = match[0];
  17257. vendorPrefix = vendorPrefix[0].toUpperCase() + vendorPrefix.substr(1);
  17258. break;
  17259. }
  17260. }
  17261. if (!vendorPrefix) {
  17262. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  17263. }
  17264. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  17265. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  17266. if (android && (!transitions || !animations)) {
  17267. transitions = isString(bodyStyle.webkitTransition);
  17268. animations = isString(bodyStyle.webkitAnimation);
  17269. }
  17270. }
  17271. return {
  17272. // Android has history.pushState, but it does not update location correctly
  17273. // so let's not use the history API at all.
  17274. // http://code.google.com/p/android/issues/detail?id=17471
  17275. // https://github.com/angular/angular.js/issues/904
  17276. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  17277. // so let's not use the history API also
  17278. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  17279. // jshint -W018
  17280. history: !!(hasHistoryPushState && !(android < 4) && !boxee),
  17281. // jshint +W018
  17282. hasEvent: function(event) {
  17283. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  17284. // it. In particular the event is not fired when backspace or delete key are pressed or
  17285. // when cut operation is performed.
  17286. // IE10+ implements 'input' event but it erroneously fires under various situations,
  17287. // e.g. when placeholder changes, or a form is focused.
  17288. if (event === 'input' && msie <= 11) return false;
  17289. if (isUndefined(eventSupport[event])) {
  17290. var divElm = document.createElement('div');
  17291. eventSupport[event] = 'on' + event in divElm;
  17292. }
  17293. return eventSupport[event];
  17294. },
  17295. csp: csp(),
  17296. vendorPrefix: vendorPrefix,
  17297. transitions: transitions,
  17298. animations: animations,
  17299. android: android
  17300. };
  17301. }];
  17302. }
  17303. var $templateRequestMinErr = minErr('$compile');
  17304. /**
  17305. * @ngdoc provider
  17306. * @name $templateRequestProvider
  17307. * @description
  17308. * Used to configure the options passed to the {@link $http} service when making a template request.
  17309. *
  17310. * For example, it can be used for specifying the "Accept" header that is sent to the server, when
  17311. * requesting a template.
  17312. */
  17313. function $TemplateRequestProvider() {
  17314. var httpOptions;
  17315. /**
  17316. * @ngdoc method
  17317. * @name $templateRequestProvider#httpOptions
  17318. * @description
  17319. * The options to be passed to the {@link $http} service when making the request.
  17320. * You can use this to override options such as the "Accept" header for template requests.
  17321. *
  17322. * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
  17323. * options if not overridden here.
  17324. *
  17325. * @param {string=} value new value for the {@link $http} options.
  17326. * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.
  17327. */
  17328. this.httpOptions = function(val) {
  17329. if (val) {
  17330. httpOptions = val;
  17331. return this;
  17332. }
  17333. return httpOptions;
  17334. };
  17335. /**
  17336. * @ngdoc service
  17337. * @name $templateRequest
  17338. *
  17339. * @description
  17340. * The `$templateRequest` service runs security checks then downloads the provided template using
  17341. * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
  17342. * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
  17343. * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
  17344. * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
  17345. * when `tpl` is of type string and `$templateCache` has the matching entry.
  17346. *
  17347. * If you want to pass custom options to the `$http` service, such as setting the Accept header you
  17348. * can configure this via {@link $templateRequestProvider#httpOptions}.
  17349. *
  17350. * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
  17351. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  17352. *
  17353. * @return {Promise} a promise for the HTTP response data of the given URL.
  17354. *
  17355. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  17356. */
  17357. this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
  17358. function handleRequestFn(tpl, ignoreRequestError) {
  17359. handleRequestFn.totalPendingRequests++;
  17360. // We consider the template cache holds only trusted templates, so
  17361. // there's no need to go through whitelisting again for keys that already
  17362. // are included in there. This also makes Angular accept any script
  17363. // directive, no matter its name. However, we still need to unwrap trusted
  17364. // types.
  17365. if (!isString(tpl) || isUndefined($templateCache.get(tpl))) {
  17366. tpl = $sce.getTrustedResourceUrl(tpl);
  17367. }
  17368. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  17369. if (isArray(transformResponse)) {
  17370. transformResponse = transformResponse.filter(function(transformer) {
  17371. return transformer !== defaultHttpResponseTransform;
  17372. });
  17373. } else if (transformResponse === defaultHttpResponseTransform) {
  17374. transformResponse = null;
  17375. }
  17376. return $http.get(tpl, extend({
  17377. cache: $templateCache,
  17378. transformResponse: transformResponse
  17379. }, httpOptions))
  17380. ['finally'](function() {
  17381. handleRequestFn.totalPendingRequests--;
  17382. })
  17383. .then(function(response) {
  17384. $templateCache.put(tpl, response.data);
  17385. return response.data;
  17386. }, handleError);
  17387. function handleError(resp) {
  17388. if (!ignoreRequestError) {
  17389. throw $templateRequestMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
  17390. tpl, resp.status, resp.statusText);
  17391. }
  17392. return $q.reject(resp);
  17393. }
  17394. }
  17395. handleRequestFn.totalPendingRequests = 0;
  17396. return handleRequestFn;
  17397. }];
  17398. }
  17399. function $$TestabilityProvider() {
  17400. this.$get = ['$rootScope', '$browser', '$location',
  17401. function($rootScope, $browser, $location) {
  17402. /**
  17403. * @name $testability
  17404. *
  17405. * @description
  17406. * The private $$testability service provides a collection of methods for use when debugging
  17407. * or by automated test and debugging tools.
  17408. */
  17409. var testability = {};
  17410. /**
  17411. * @name $$testability#findBindings
  17412. *
  17413. * @description
  17414. * Returns an array of elements that are bound (via ng-bind or {{}})
  17415. * to expressions matching the input.
  17416. *
  17417. * @param {Element} element The element root to search from.
  17418. * @param {string} expression The binding expression to match.
  17419. * @param {boolean} opt_exactMatch If true, only returns exact matches
  17420. * for the expression. Filters and whitespace are ignored.
  17421. */
  17422. testability.findBindings = function(element, expression, opt_exactMatch) {
  17423. var bindings = element.getElementsByClassName('ng-binding');
  17424. var matches = [];
  17425. forEach(bindings, function(binding) {
  17426. var dataBinding = angular.element(binding).data('$binding');
  17427. if (dataBinding) {
  17428. forEach(dataBinding, function(bindingName) {
  17429. if (opt_exactMatch) {
  17430. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  17431. if (matcher.test(bindingName)) {
  17432. matches.push(binding);
  17433. }
  17434. } else {
  17435. if (bindingName.indexOf(expression) != -1) {
  17436. matches.push(binding);
  17437. }
  17438. }
  17439. });
  17440. }
  17441. });
  17442. return matches;
  17443. };
  17444. /**
  17445. * @name $$testability#findModels
  17446. *
  17447. * @description
  17448. * Returns an array of elements that are two-way found via ng-model to
  17449. * expressions matching the input.
  17450. *
  17451. * @param {Element} element The element root to search from.
  17452. * @param {string} expression The model expression to match.
  17453. * @param {boolean} opt_exactMatch If true, only returns exact matches
  17454. * for the expression.
  17455. */
  17456. testability.findModels = function(element, expression, opt_exactMatch) {
  17457. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  17458. for (var p = 0; p < prefixes.length; ++p) {
  17459. var attributeEquals = opt_exactMatch ? '=' : '*=';
  17460. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  17461. var elements = element.querySelectorAll(selector);
  17462. if (elements.length) {
  17463. return elements;
  17464. }
  17465. }
  17466. };
  17467. /**
  17468. * @name $$testability#getLocation
  17469. *
  17470. * @description
  17471. * Shortcut for getting the location in a browser agnostic way. Returns
  17472. * the path, search, and hash. (e.g. /path?a=b#hash)
  17473. */
  17474. testability.getLocation = function() {
  17475. return $location.url();
  17476. };
  17477. /**
  17478. * @name $$testability#setLocation
  17479. *
  17480. * @description
  17481. * Shortcut for navigating to a location without doing a full page reload.
  17482. *
  17483. * @param {string} url The location url (path, search and hash,
  17484. * e.g. /path?a=b#hash) to go to.
  17485. */
  17486. testability.setLocation = function(url) {
  17487. if (url !== $location.url()) {
  17488. $location.url(url);
  17489. $rootScope.$digest();
  17490. }
  17491. };
  17492. /**
  17493. * @name $$testability#whenStable
  17494. *
  17495. * @description
  17496. * Calls the callback when $timeout and $http requests are completed.
  17497. *
  17498. * @param {function} callback
  17499. */
  17500. testability.whenStable = function(callback) {
  17501. $browser.notifyWhenNoOutstandingRequests(callback);
  17502. };
  17503. return testability;
  17504. }];
  17505. }
  17506. function $TimeoutProvider() {
  17507. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  17508. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  17509. var deferreds = {};
  17510. /**
  17511. * @ngdoc service
  17512. * @name $timeout
  17513. *
  17514. * @description
  17515. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  17516. * block and delegates any exceptions to
  17517. * {@link ng.$exceptionHandler $exceptionHandler} service.
  17518. *
  17519. * The return value of calling `$timeout` is a promise, which will be resolved when
  17520. * the delay has passed and the timeout function, if provided, is executed.
  17521. *
  17522. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  17523. *
  17524. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  17525. * synchronously flush the queue of deferred functions.
  17526. *
  17527. * If you only want a promise that will be resolved after some specified delay
  17528. * then you can call `$timeout` without the `fn` function.
  17529. *
  17530. * @param {function()=} fn A function, whose execution should be delayed.
  17531. * @param {number=} [delay=0] Delay in milliseconds.
  17532. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  17533. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  17534. * @param {...*=} Pass additional parameters to the executed function.
  17535. * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise
  17536. * will be resolved with the return value of the `fn` function.
  17537. *
  17538. */
  17539. function timeout(fn, delay, invokeApply) {
  17540. if (!isFunction(fn)) {
  17541. invokeApply = delay;
  17542. delay = fn;
  17543. fn = noop;
  17544. }
  17545. var args = sliceArgs(arguments, 3),
  17546. skipApply = (isDefined(invokeApply) && !invokeApply),
  17547. deferred = (skipApply ? $$q : $q).defer(),
  17548. promise = deferred.promise,
  17549. timeoutId;
  17550. timeoutId = $browser.defer(function() {
  17551. try {
  17552. deferred.resolve(fn.apply(null, args));
  17553. } catch (e) {
  17554. deferred.reject(e);
  17555. $exceptionHandler(e);
  17556. }
  17557. finally {
  17558. delete deferreds[promise.$$timeoutId];
  17559. }
  17560. if (!skipApply) $rootScope.$apply();
  17561. }, delay);
  17562. promise.$$timeoutId = timeoutId;
  17563. deferreds[timeoutId] = deferred;
  17564. return promise;
  17565. }
  17566. /**
  17567. * @ngdoc method
  17568. * @name $timeout#cancel
  17569. *
  17570. * @description
  17571. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  17572. * resolved with a rejection.
  17573. *
  17574. * @param {Promise=} promise Promise returned by the `$timeout` function.
  17575. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  17576. * canceled.
  17577. */
  17578. timeout.cancel = function(promise) {
  17579. if (promise && promise.$$timeoutId in deferreds) {
  17580. deferreds[promise.$$timeoutId].reject('canceled');
  17581. delete deferreds[promise.$$timeoutId];
  17582. return $browser.defer.cancel(promise.$$timeoutId);
  17583. }
  17584. return false;
  17585. };
  17586. return timeout;
  17587. }];
  17588. }
  17589. // NOTE: The usage of window and document instead of $window and $document here is
  17590. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  17591. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  17592. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  17593. // doesn't know about mocked locations and resolves URLs to the real document - which is
  17594. // exactly the behavior needed here. There is little value is mocking these out for this
  17595. // service.
  17596. var urlParsingNode = window.document.createElement("a");
  17597. var originUrl = urlResolve(window.location.href);
  17598. /**
  17599. *
  17600. * Implementation Notes for non-IE browsers
  17601. * ----------------------------------------
  17602. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  17603. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  17604. * URL will be resolved into an absolute URL in the context of the application document.
  17605. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  17606. * properties are all populated to reflect the normalized URL. This approach has wide
  17607. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  17608. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  17609. *
  17610. * Implementation Notes for IE
  17611. * ---------------------------
  17612. * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
  17613. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  17614. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  17615. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  17616. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  17617. * properties such as protocol, hostname, port, etc.
  17618. *
  17619. * References:
  17620. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  17621. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  17622. * http://url.spec.whatwg.org/#urlutils
  17623. * https://github.com/angular/angular.js/pull/2902
  17624. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  17625. *
  17626. * @kind function
  17627. * @param {string} url The URL to be parsed.
  17628. * @description Normalizes and parses a URL.
  17629. * @returns {object} Returns the normalized URL as a dictionary.
  17630. *
  17631. * | member name | Description |
  17632. * |---------------|----------------|
  17633. * | href | A normalized version of the provided URL if it was not an absolute URL |
  17634. * | protocol | The protocol including the trailing colon |
  17635. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  17636. * | search | The search params, minus the question mark |
  17637. * | hash | The hash string, minus the hash symbol
  17638. * | hostname | The hostname
  17639. * | port | The port, without ":"
  17640. * | pathname | The pathname, beginning with "/"
  17641. *
  17642. */
  17643. function urlResolve(url) {
  17644. var href = url;
  17645. if (msie) {
  17646. // Normalize before parse. Refer Implementation Notes on why this is
  17647. // done in two steps on IE.
  17648. urlParsingNode.setAttribute("href", href);
  17649. href = urlParsingNode.href;
  17650. }
  17651. urlParsingNode.setAttribute('href', href);
  17652. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  17653. return {
  17654. href: urlParsingNode.href,
  17655. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  17656. host: urlParsingNode.host,
  17657. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  17658. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  17659. hostname: urlParsingNode.hostname,
  17660. port: urlParsingNode.port,
  17661. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  17662. ? urlParsingNode.pathname
  17663. : '/' + urlParsingNode.pathname
  17664. };
  17665. }
  17666. /**
  17667. * Parse a request URL and determine whether this is a same-origin request as the application document.
  17668. *
  17669. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  17670. * or a parsed URL object.
  17671. * @returns {boolean} Whether the request is for the same origin as the application document.
  17672. */
  17673. function urlIsSameOrigin(requestUrl) {
  17674. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  17675. return (parsed.protocol === originUrl.protocol &&
  17676. parsed.host === originUrl.host);
  17677. }
  17678. /**
  17679. * @ngdoc service
  17680. * @name $window
  17681. *
  17682. * @description
  17683. * A reference to the browser's `window` object. While `window`
  17684. * is globally available in JavaScript, it causes testability problems, because
  17685. * it is a global variable. In angular we always refer to it through the
  17686. * `$window` service, so it may be overridden, removed or mocked for testing.
  17687. *
  17688. * Expressions, like the one defined for the `ngClick` directive in the example
  17689. * below, are evaluated with respect to the current scope. Therefore, there is
  17690. * no risk of inadvertently coding in a dependency on a global value in such an
  17691. * expression.
  17692. *
  17693. * @example
  17694. <example module="windowExample">
  17695. <file name="index.html">
  17696. <script>
  17697. angular.module('windowExample', [])
  17698. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  17699. $scope.greeting = 'Hello, World!';
  17700. $scope.doGreeting = function(greeting) {
  17701. $window.alert(greeting);
  17702. };
  17703. }]);
  17704. </script>
  17705. <div ng-controller="ExampleController">
  17706. <input type="text" ng-model="greeting" aria-label="greeting" />
  17707. <button ng-click="doGreeting(greeting)">ALERT</button>
  17708. </div>
  17709. </file>
  17710. <file name="protractor.js" type="protractor">
  17711. it('should display the greeting in the input box', function() {
  17712. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  17713. // If we click the button it will block the test runner
  17714. // element(':button').click();
  17715. });
  17716. </file>
  17717. </example>
  17718. */
  17719. function $WindowProvider() {
  17720. this.$get = valueFn(window);
  17721. }
  17722. /**
  17723. * @name $$cookieReader
  17724. * @requires $document
  17725. *
  17726. * @description
  17727. * This is a private service for reading cookies used by $http and ngCookies
  17728. *
  17729. * @return {Object} a key/value map of the current cookies
  17730. */
  17731. function $$CookieReader($document) {
  17732. var rawDocument = $document[0] || {};
  17733. var lastCookies = {};
  17734. var lastCookieString = '';
  17735. function safeDecodeURIComponent(str) {
  17736. try {
  17737. return decodeURIComponent(str);
  17738. } catch (e) {
  17739. return str;
  17740. }
  17741. }
  17742. return function() {
  17743. var cookieArray, cookie, i, index, name;
  17744. var currentCookieString = rawDocument.cookie || '';
  17745. if (currentCookieString !== lastCookieString) {
  17746. lastCookieString = currentCookieString;
  17747. cookieArray = lastCookieString.split('; ');
  17748. lastCookies = {};
  17749. for (i = 0; i < cookieArray.length; i++) {
  17750. cookie = cookieArray[i];
  17751. index = cookie.indexOf('=');
  17752. if (index > 0) { //ignore nameless cookies
  17753. name = safeDecodeURIComponent(cookie.substring(0, index));
  17754. // the first value that is seen for a cookie is the most
  17755. // specific one. values for the same cookie name that
  17756. // follow are for less specific paths.
  17757. if (isUndefined(lastCookies[name])) {
  17758. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  17759. }
  17760. }
  17761. }
  17762. }
  17763. return lastCookies;
  17764. };
  17765. }
  17766. $$CookieReader.$inject = ['$document'];
  17767. function $$CookieReaderProvider() {
  17768. this.$get = $$CookieReader;
  17769. }
  17770. /* global currencyFilter: true,
  17771. dateFilter: true,
  17772. filterFilter: true,
  17773. jsonFilter: true,
  17774. limitToFilter: true,
  17775. lowercaseFilter: true,
  17776. numberFilter: true,
  17777. orderByFilter: true,
  17778. uppercaseFilter: true,
  17779. */
  17780. /**
  17781. * @ngdoc provider
  17782. * @name $filterProvider
  17783. * @description
  17784. *
  17785. * Filters are just functions which transform input to an output. However filters need to be
  17786. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  17787. * annotated with dependencies and is responsible for creating a filter function.
  17788. *
  17789. * <div class="alert alert-warning">
  17790. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  17791. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  17792. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  17793. * (`myapp_subsection_filterx`).
  17794. * </div>
  17795. *
  17796. * ```js
  17797. * // Filter registration
  17798. * function MyModule($provide, $filterProvider) {
  17799. * // create a service to demonstrate injection (not always needed)
  17800. * $provide.value('greet', function(name){
  17801. * return 'Hello ' + name + '!';
  17802. * });
  17803. *
  17804. * // register a filter factory which uses the
  17805. * // greet service to demonstrate DI.
  17806. * $filterProvider.register('greet', function(greet){
  17807. * // return the filter function which uses the greet service
  17808. * // to generate salutation
  17809. * return function(text) {
  17810. * // filters need to be forgiving so check input validity
  17811. * return text && greet(text) || text;
  17812. * };
  17813. * });
  17814. * }
  17815. * ```
  17816. *
  17817. * The filter function is registered with the `$injector` under the filter name suffix with
  17818. * `Filter`.
  17819. *
  17820. * ```js
  17821. * it('should be the same instance', inject(
  17822. * function($filterProvider) {
  17823. * $filterProvider.register('reverse', function(){
  17824. * return ...;
  17825. * });
  17826. * },
  17827. * function($filter, reverseFilter) {
  17828. * expect($filter('reverse')).toBe(reverseFilter);
  17829. * });
  17830. * ```
  17831. *
  17832. *
  17833. * For more information about how angular filters work, and how to create your own filters, see
  17834. * {@link guide/filter Filters} in the Angular Developer Guide.
  17835. */
  17836. /**
  17837. * @ngdoc service
  17838. * @name $filter
  17839. * @kind function
  17840. * @description
  17841. * Filters are used for formatting data displayed to the user.
  17842. *
  17843. * The general syntax in templates is as follows:
  17844. *
  17845. * {{ expression [| filter_name[:parameter_value] ... ] }}
  17846. *
  17847. * @param {String} name Name of the filter function to retrieve
  17848. * @return {Function} the filter function
  17849. * @example
  17850. <example name="$filter" module="filterExample">
  17851. <file name="index.html">
  17852. <div ng-controller="MainCtrl">
  17853. <h3>{{ originalText }}</h3>
  17854. <h3>{{ filteredText }}</h3>
  17855. </div>
  17856. </file>
  17857. <file name="script.js">
  17858. angular.module('filterExample', [])
  17859. .controller('MainCtrl', function($scope, $filter) {
  17860. $scope.originalText = 'hello';
  17861. $scope.filteredText = $filter('uppercase')($scope.originalText);
  17862. });
  17863. </file>
  17864. </example>
  17865. */
  17866. $FilterProvider.$inject = ['$provide'];
  17867. function $FilterProvider($provide) {
  17868. var suffix = 'Filter';
  17869. /**
  17870. * @ngdoc method
  17871. * @name $filterProvider#register
  17872. * @param {string|Object} name Name of the filter function, or an object map of filters where
  17873. * the keys are the filter names and the values are the filter factories.
  17874. *
  17875. * <div class="alert alert-warning">
  17876. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  17877. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  17878. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  17879. * (`myapp_subsection_filterx`).
  17880. * </div>
  17881. * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
  17882. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  17883. * of the registered filter instances.
  17884. */
  17885. function register(name, factory) {
  17886. if (isObject(name)) {
  17887. var filters = {};
  17888. forEach(name, function(filter, key) {
  17889. filters[key] = register(key, filter);
  17890. });
  17891. return filters;
  17892. } else {
  17893. return $provide.factory(name + suffix, factory);
  17894. }
  17895. }
  17896. this.register = register;
  17897. this.$get = ['$injector', function($injector) {
  17898. return function(name) {
  17899. return $injector.get(name + suffix);
  17900. };
  17901. }];
  17902. ////////////////////////////////////////
  17903. /* global
  17904. currencyFilter: false,
  17905. dateFilter: false,
  17906. filterFilter: false,
  17907. jsonFilter: false,
  17908. limitToFilter: false,
  17909. lowercaseFilter: false,
  17910. numberFilter: false,
  17911. orderByFilter: false,
  17912. uppercaseFilter: false,
  17913. */
  17914. register('currency', currencyFilter);
  17915. register('date', dateFilter);
  17916. register('filter', filterFilter);
  17917. register('json', jsonFilter);
  17918. register('limitTo', limitToFilter);
  17919. register('lowercase', lowercaseFilter);
  17920. register('number', numberFilter);
  17921. register('orderBy', orderByFilter);
  17922. register('uppercase', uppercaseFilter);
  17923. }
  17924. /**
  17925. * @ngdoc filter
  17926. * @name filter
  17927. * @kind function
  17928. *
  17929. * @description
  17930. * Selects a subset of items from `array` and returns it as a new array.
  17931. *
  17932. * @param {Array} array The source array.
  17933. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  17934. * `array`.
  17935. *
  17936. * Can be one of:
  17937. *
  17938. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  17939. * objects with string properties in `array` that match this string will be returned. This also
  17940. * applies to nested object properties.
  17941. * The predicate can be negated by prefixing the string with `!`.
  17942. *
  17943. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  17944. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  17945. * which have property `name` containing "M" and property `phone` containing "1". A special
  17946. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  17947. * property of the object or its nested object properties. That's equivalent to the simple
  17948. * substring match with a `string` as described above. The predicate can be negated by prefixing
  17949. * the string with `!`.
  17950. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  17951. * not containing "M".
  17952. *
  17953. * Note that a named property will match properties on the same level only, while the special
  17954. * `$` property will match properties on the same level or deeper. E.g. an array item like
  17955. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  17956. * **will** be matched by `{$: 'John'}`.
  17957. *
  17958. * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
  17959. * The function is called for each element of the array, with the element, its index, and
  17960. * the entire array itself as arguments.
  17961. *
  17962. * The final result is an array of those elements that the predicate returned true for.
  17963. *
  17964. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  17965. * determining if the expected value (from the filter expression) and actual value (from
  17966. * the object in the array) should be considered a match.
  17967. *
  17968. * Can be one of:
  17969. *
  17970. * - `function(actual, expected)`:
  17971. * The function will be given the object value and the predicate value to compare and
  17972. * should return true if both values should be considered equal.
  17973. *
  17974. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  17975. * This is essentially strict comparison of expected and actual.
  17976. *
  17977. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  17978. * insensitive way.
  17979. *
  17980. * Primitive values are converted to strings. Objects are not compared against primitives,
  17981. * unless they have a custom `toString` method (e.g. `Date` objects).
  17982. *
  17983. * @example
  17984. <example>
  17985. <file name="index.html">
  17986. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  17987. {name:'Mary', phone:'800-BIG-MARY'},
  17988. {name:'Mike', phone:'555-4321'},
  17989. {name:'Adam', phone:'555-5678'},
  17990. {name:'Julie', phone:'555-8765'},
  17991. {name:'Juliette', phone:'555-5678'}]"></div>
  17992. <label>Search: <input ng-model="searchText"></label>
  17993. <table id="searchTextResults">
  17994. <tr><th>Name</th><th>Phone</th></tr>
  17995. <tr ng-repeat="friend in friends | filter:searchText">
  17996. <td>{{friend.name}}</td>
  17997. <td>{{friend.phone}}</td>
  17998. </tr>
  17999. </table>
  18000. <hr>
  18001. <label>Any: <input ng-model="search.$"></label> <br>
  18002. <label>Name only <input ng-model="search.name"></label><br>
  18003. <label>Phone only <input ng-model="search.phone"></label><br>
  18004. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  18005. <table id="searchObjResults">
  18006. <tr><th>Name</th><th>Phone</th></tr>
  18007. <tr ng-repeat="friendObj in friends | filter:search:strict">
  18008. <td>{{friendObj.name}}</td>
  18009. <td>{{friendObj.phone}}</td>
  18010. </tr>
  18011. </table>
  18012. </file>
  18013. <file name="protractor.js" type="protractor">
  18014. var expectFriendNames = function(expectedNames, key) {
  18015. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  18016. arr.forEach(function(wd, i) {
  18017. expect(wd.getText()).toMatch(expectedNames[i]);
  18018. });
  18019. });
  18020. };
  18021. it('should search across all fields when filtering with a string', function() {
  18022. var searchText = element(by.model('searchText'));
  18023. searchText.clear();
  18024. searchText.sendKeys('m');
  18025. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  18026. searchText.clear();
  18027. searchText.sendKeys('76');
  18028. expectFriendNames(['John', 'Julie'], 'friend');
  18029. });
  18030. it('should search in specific fields when filtering with a predicate object', function() {
  18031. var searchAny = element(by.model('search.$'));
  18032. searchAny.clear();
  18033. searchAny.sendKeys('i');
  18034. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  18035. });
  18036. it('should use a equal comparison when comparator is true', function() {
  18037. var searchName = element(by.model('search.name'));
  18038. var strict = element(by.model('strict'));
  18039. searchName.clear();
  18040. searchName.sendKeys('Julie');
  18041. strict.click();
  18042. expectFriendNames(['Julie'], 'friendObj');
  18043. });
  18044. </file>
  18045. </example>
  18046. */
  18047. function filterFilter() {
  18048. return function(array, expression, comparator) {
  18049. if (!isArrayLike(array)) {
  18050. if (array == null) {
  18051. return array;
  18052. } else {
  18053. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  18054. }
  18055. }
  18056. var expressionType = getTypeForFilter(expression);
  18057. var predicateFn;
  18058. var matchAgainstAnyProp;
  18059. switch (expressionType) {
  18060. case 'function':
  18061. predicateFn = expression;
  18062. break;
  18063. case 'boolean':
  18064. case 'null':
  18065. case 'number':
  18066. case 'string':
  18067. matchAgainstAnyProp = true;
  18068. //jshint -W086
  18069. case 'object':
  18070. //jshint +W086
  18071. predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
  18072. break;
  18073. default:
  18074. return array;
  18075. }
  18076. return Array.prototype.filter.call(array, predicateFn);
  18077. };
  18078. }
  18079. // Helper functions for `filterFilter`
  18080. function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
  18081. var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
  18082. var predicateFn;
  18083. if (comparator === true) {
  18084. comparator = equals;
  18085. } else if (!isFunction(comparator)) {
  18086. comparator = function(actual, expected) {
  18087. if (isUndefined(actual)) {
  18088. // No substring matching against `undefined`
  18089. return false;
  18090. }
  18091. if ((actual === null) || (expected === null)) {
  18092. // No substring matching against `null`; only match against `null`
  18093. return actual === expected;
  18094. }
  18095. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  18096. // Should not compare primitives against objects, unless they have custom `toString` method
  18097. return false;
  18098. }
  18099. actual = lowercase('' + actual);
  18100. expected = lowercase('' + expected);
  18101. return actual.indexOf(expected) !== -1;
  18102. };
  18103. }
  18104. predicateFn = function(item) {
  18105. if (shouldMatchPrimitives && !isObject(item)) {
  18106. return deepCompare(item, expression.$, comparator, false);
  18107. }
  18108. return deepCompare(item, expression, comparator, matchAgainstAnyProp);
  18109. };
  18110. return predicateFn;
  18111. }
  18112. function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
  18113. var actualType = getTypeForFilter(actual);
  18114. var expectedType = getTypeForFilter(expected);
  18115. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  18116. return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
  18117. } else if (isArray(actual)) {
  18118. // In case `actual` is an array, consider it a match
  18119. // if ANY of it's items matches `expected`
  18120. return actual.some(function(item) {
  18121. return deepCompare(item, expected, comparator, matchAgainstAnyProp);
  18122. });
  18123. }
  18124. switch (actualType) {
  18125. case 'object':
  18126. var key;
  18127. if (matchAgainstAnyProp) {
  18128. for (key in actual) {
  18129. if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
  18130. return true;
  18131. }
  18132. }
  18133. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
  18134. } else if (expectedType === 'object') {
  18135. for (key in expected) {
  18136. var expectedVal = expected[key];
  18137. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  18138. continue;
  18139. }
  18140. var matchAnyProperty = key === '$';
  18141. var actualVal = matchAnyProperty ? actual : actual[key];
  18142. if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
  18143. return false;
  18144. }
  18145. }
  18146. return true;
  18147. } else {
  18148. return comparator(actual, expected);
  18149. }
  18150. break;
  18151. case 'function':
  18152. return false;
  18153. default:
  18154. return comparator(actual, expected);
  18155. }
  18156. }
  18157. // Used for easily differentiating between `null` and actual `object`
  18158. function getTypeForFilter(val) {
  18159. return (val === null) ? 'null' : typeof val;
  18160. }
  18161. var MAX_DIGITS = 22;
  18162. var DECIMAL_SEP = '.';
  18163. var ZERO_CHAR = '0';
  18164. /**
  18165. * @ngdoc filter
  18166. * @name currency
  18167. * @kind function
  18168. *
  18169. * @description
  18170. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  18171. * symbol for current locale is used.
  18172. *
  18173. * @param {number} amount Input to filter.
  18174. * @param {string=} symbol Currency symbol or identifier to be displayed.
  18175. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  18176. * @returns {string} Formatted number.
  18177. *
  18178. *
  18179. * @example
  18180. <example module="currencyExample">
  18181. <file name="index.html">
  18182. <script>
  18183. angular.module('currencyExample', [])
  18184. .controller('ExampleController', ['$scope', function($scope) {
  18185. $scope.amount = 1234.56;
  18186. }]);
  18187. </script>
  18188. <div ng-controller="ExampleController">
  18189. <input type="number" ng-model="amount" aria-label="amount"> <br>
  18190. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  18191. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
  18192. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  18193. </div>
  18194. </file>
  18195. <file name="protractor.js" type="protractor">
  18196. it('should init with 1234.56', function() {
  18197. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  18198. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  18199. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  18200. });
  18201. it('should update', function() {
  18202. if (browser.params.browser == 'safari') {
  18203. // Safari does not understand the minus key. See
  18204. // https://github.com/angular/protractor/issues/481
  18205. return;
  18206. }
  18207. element(by.model('amount')).clear();
  18208. element(by.model('amount')).sendKeys('-1234');
  18209. expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
  18210. expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
  18211. expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
  18212. });
  18213. </file>
  18214. </example>
  18215. */
  18216. currencyFilter.$inject = ['$locale'];
  18217. function currencyFilter($locale) {
  18218. var formats = $locale.NUMBER_FORMATS;
  18219. return function(amount, currencySymbol, fractionSize) {
  18220. if (isUndefined(currencySymbol)) {
  18221. currencySymbol = formats.CURRENCY_SYM;
  18222. }
  18223. if (isUndefined(fractionSize)) {
  18224. fractionSize = formats.PATTERNS[1].maxFrac;
  18225. }
  18226. // if null or undefined pass it through
  18227. return (amount == null)
  18228. ? amount
  18229. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  18230. replace(/\u00A4/g, currencySymbol);
  18231. };
  18232. }
  18233. /**
  18234. * @ngdoc filter
  18235. * @name number
  18236. * @kind function
  18237. *
  18238. * @description
  18239. * Formats a number as text.
  18240. *
  18241. * If the input is null or undefined, it will just be returned.
  18242. * If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively.
  18243. * If the input is not a number an empty string is returned.
  18244. *
  18245. *
  18246. * @param {number|string} number Number to format.
  18247. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  18248. * If this is not provided then the fraction size is computed from the current locale's number
  18249. * formatting pattern. In the case of the default locale, it will be 3.
  18250. * @returns {string} Number rounded to `fractionSize` appropriately formatted based on the current
  18251. * locale (e.g., in the en_US locale it will have "." as the decimal separator and
  18252. * include "," group separators after each third digit).
  18253. *
  18254. * @example
  18255. <example module="numberFilterExample">
  18256. <file name="index.html">
  18257. <script>
  18258. angular.module('numberFilterExample', [])
  18259. .controller('ExampleController', ['$scope', function($scope) {
  18260. $scope.val = 1234.56789;
  18261. }]);
  18262. </script>
  18263. <div ng-controller="ExampleController">
  18264. <label>Enter number: <input ng-model='val'></label><br>
  18265. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  18266. No fractions: <span>{{val | number:0}}</span><br>
  18267. Negative number: <span>{{-val | number:4}}</span>
  18268. </div>
  18269. </file>
  18270. <file name="protractor.js" type="protractor">
  18271. it('should format numbers', function() {
  18272. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  18273. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  18274. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  18275. });
  18276. it('should update', function() {
  18277. element(by.model('val')).clear();
  18278. element(by.model('val')).sendKeys('3374.333');
  18279. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  18280. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  18281. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  18282. });
  18283. </file>
  18284. </example>
  18285. */
  18286. numberFilter.$inject = ['$locale'];
  18287. function numberFilter($locale) {
  18288. var formats = $locale.NUMBER_FORMATS;
  18289. return function(number, fractionSize) {
  18290. // if null or undefined pass it through
  18291. return (number == null)
  18292. ? number
  18293. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  18294. fractionSize);
  18295. };
  18296. }
  18297. /**
  18298. * Parse a number (as a string) into three components that can be used
  18299. * for formatting the number.
  18300. *
  18301. * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)
  18302. *
  18303. * @param {string} numStr The number to parse
  18304. * @return {object} An object describing this number, containing the following keys:
  18305. * - d : an array of digits containing leading zeros as necessary
  18306. * - i : the number of the digits in `d` that are to the left of the decimal point
  18307. * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`
  18308. *
  18309. */
  18310. function parse(numStr) {
  18311. var exponent = 0, digits, numberOfIntegerDigits;
  18312. var i, j, zeros;
  18313. // Decimal point?
  18314. if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {
  18315. numStr = numStr.replace(DECIMAL_SEP, '');
  18316. }
  18317. // Exponential form?
  18318. if ((i = numStr.search(/e/i)) > 0) {
  18319. // Work out the exponent.
  18320. if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i;
  18321. numberOfIntegerDigits += +numStr.slice(i + 1);
  18322. numStr = numStr.substring(0, i);
  18323. } else if (numberOfIntegerDigits < 0) {
  18324. // There was no decimal point or exponent so it is an integer.
  18325. numberOfIntegerDigits = numStr.length;
  18326. }
  18327. // Count the number of leading zeros.
  18328. for (i = 0; numStr.charAt(i) == ZERO_CHAR; i++) {/* jshint noempty: false */}
  18329. if (i == (zeros = numStr.length)) {
  18330. // The digits are all zero.
  18331. digits = [0];
  18332. numberOfIntegerDigits = 1;
  18333. } else {
  18334. // Count the number of trailing zeros
  18335. zeros--;
  18336. while (numStr.charAt(zeros) == ZERO_CHAR) zeros--;
  18337. // Trailing zeros are insignificant so ignore them
  18338. numberOfIntegerDigits -= i;
  18339. digits = [];
  18340. // Convert string to array of digits without leading/trailing zeros.
  18341. for (j = 0; i <= zeros; i++, j++) {
  18342. digits[j] = +numStr.charAt(i);
  18343. }
  18344. }
  18345. // If the number overflows the maximum allowed digits then use an exponent.
  18346. if (numberOfIntegerDigits > MAX_DIGITS) {
  18347. digits = digits.splice(0, MAX_DIGITS - 1);
  18348. exponent = numberOfIntegerDigits - 1;
  18349. numberOfIntegerDigits = 1;
  18350. }
  18351. return { d: digits, e: exponent, i: numberOfIntegerDigits };
  18352. }
  18353. /**
  18354. * Round the parsed number to the specified number of decimal places
  18355. * This function changed the parsedNumber in-place
  18356. */
  18357. function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
  18358. var digits = parsedNumber.d;
  18359. var fractionLen = digits.length - parsedNumber.i;
  18360. // determine fractionSize if it is not specified; `+fractionSize` converts it to a number
  18361. fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
  18362. // The index of the digit to where rounding is to occur
  18363. var roundAt = fractionSize + parsedNumber.i;
  18364. var digit = digits[roundAt];
  18365. if (roundAt > 0) {
  18366. // Drop fractional digits beyond `roundAt`
  18367. digits.splice(Math.max(parsedNumber.i, roundAt));
  18368. // Set non-fractional digits beyond `roundAt` to 0
  18369. for (var j = roundAt; j < digits.length; j++) {
  18370. digits[j] = 0;
  18371. }
  18372. } else {
  18373. // We rounded to zero so reset the parsedNumber
  18374. fractionLen = Math.max(0, fractionLen);
  18375. parsedNumber.i = 1;
  18376. digits.length = Math.max(1, roundAt = fractionSize + 1);
  18377. digits[0] = 0;
  18378. for (var i = 1; i < roundAt; i++) digits[i] = 0;
  18379. }
  18380. if (digit >= 5) {
  18381. if (roundAt - 1 < 0) {
  18382. for (var k = 0; k > roundAt; k--) {
  18383. digits.unshift(0);
  18384. parsedNumber.i++;
  18385. }
  18386. digits.unshift(1);
  18387. parsedNumber.i++;
  18388. } else {
  18389. digits[roundAt - 1]++;
  18390. }
  18391. }
  18392. // Pad out with zeros to get the required fraction length
  18393. for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);
  18394. // Do any carrying, e.g. a digit was rounded up to 10
  18395. var carry = digits.reduceRight(function(carry, d, i, digits) {
  18396. d = d + carry;
  18397. digits[i] = d % 10;
  18398. return Math.floor(d / 10);
  18399. }, 0);
  18400. if (carry) {
  18401. digits.unshift(carry);
  18402. parsedNumber.i++;
  18403. }
  18404. }
  18405. /**
  18406. * Format a number into a string
  18407. * @param {number} number The number to format
  18408. * @param {{
  18409. * minFrac, // the minimum number of digits required in the fraction part of the number
  18410. * maxFrac, // the maximum number of digits required in the fraction part of the number
  18411. * gSize, // number of digits in each group of separated digits
  18412. * lgSize, // number of digits in the last group of digits before the decimal separator
  18413. * negPre, // the string to go in front of a negative number (e.g. `-` or `(`))
  18414. * posPre, // the string to go in front of a positive number
  18415. * negSuf, // the string to go after a negative number (e.g. `)`)
  18416. * posSuf // the string to go after a positive number
  18417. * }} pattern
  18418. * @param {string} groupSep The string to separate groups of number (e.g. `,`)
  18419. * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`)
  18420. * @param {[type]} fractionSize The size of the fractional part of the number
  18421. * @return {string} The number formatted as a string
  18422. */
  18423. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  18424. if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';
  18425. var isInfinity = !isFinite(number);
  18426. var isZero = false;
  18427. var numStr = Math.abs(number) + '',
  18428. formattedText = '',
  18429. parsedNumber;
  18430. if (isInfinity) {
  18431. formattedText = '\u221e';
  18432. } else {
  18433. parsedNumber = parse(numStr);
  18434. roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);
  18435. var digits = parsedNumber.d;
  18436. var integerLen = parsedNumber.i;
  18437. var exponent = parsedNumber.e;
  18438. var decimals = [];
  18439. isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);
  18440. // pad zeros for small numbers
  18441. while (integerLen < 0) {
  18442. digits.unshift(0);
  18443. integerLen++;
  18444. }
  18445. // extract decimals digits
  18446. if (integerLen > 0) {
  18447. decimals = digits.splice(integerLen, digits.length);
  18448. } else {
  18449. decimals = digits;
  18450. digits = [0];
  18451. }
  18452. // format the integer digits with grouping separators
  18453. var groups = [];
  18454. if (digits.length >= pattern.lgSize) {
  18455. groups.unshift(digits.splice(-pattern.lgSize, digits.length).join(''));
  18456. }
  18457. while (digits.length > pattern.gSize) {
  18458. groups.unshift(digits.splice(-pattern.gSize, digits.length).join(''));
  18459. }
  18460. if (digits.length) {
  18461. groups.unshift(digits.join(''));
  18462. }
  18463. formattedText = groups.join(groupSep);
  18464. // append the decimal digits
  18465. if (decimals.length) {
  18466. formattedText += decimalSep + decimals.join('');
  18467. }
  18468. if (exponent) {
  18469. formattedText += 'e+' + exponent;
  18470. }
  18471. }
  18472. if (number < 0 && !isZero) {
  18473. return pattern.negPre + formattedText + pattern.negSuf;
  18474. } else {
  18475. return pattern.posPre + formattedText + pattern.posSuf;
  18476. }
  18477. }
  18478. function padNumber(num, digits, trim, negWrap) {
  18479. var neg = '';
  18480. if (num < 0 || (negWrap && num <= 0)) {
  18481. if (negWrap) {
  18482. num = -num + 1;
  18483. } else {
  18484. num = -num;
  18485. neg = '-';
  18486. }
  18487. }
  18488. num = '' + num;
  18489. while (num.length < digits) num = ZERO_CHAR + num;
  18490. if (trim) {
  18491. num = num.substr(num.length - digits);
  18492. }
  18493. return neg + num;
  18494. }
  18495. function dateGetter(name, size, offset, trim, negWrap) {
  18496. offset = offset || 0;
  18497. return function(date) {
  18498. var value = date['get' + name]();
  18499. if (offset > 0 || value > -offset) {
  18500. value += offset;
  18501. }
  18502. if (value === 0 && offset == -12) value = 12;
  18503. return padNumber(value, size, trim, negWrap);
  18504. };
  18505. }
  18506. function dateStrGetter(name, shortForm, standAlone) {
  18507. return function(date, formats) {
  18508. var value = date['get' + name]();
  18509. var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : '');
  18510. var get = uppercase(propPrefix + name);
  18511. return formats[get][value];
  18512. };
  18513. }
  18514. function timeZoneGetter(date, formats, offset) {
  18515. var zone = -1 * offset;
  18516. var paddedZone = (zone >= 0) ? "+" : "";
  18517. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  18518. padNumber(Math.abs(zone % 60), 2);
  18519. return paddedZone;
  18520. }
  18521. function getFirstThursdayOfYear(year) {
  18522. // 0 = index of January
  18523. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  18524. // 4 = index of Thursday (+1 to account for 1st = 5)
  18525. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  18526. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  18527. }
  18528. function getThursdayThisWeek(datetime) {
  18529. return new Date(datetime.getFullYear(), datetime.getMonth(),
  18530. // 4 = index of Thursday
  18531. datetime.getDate() + (4 - datetime.getDay()));
  18532. }
  18533. function weekGetter(size) {
  18534. return function(date) {
  18535. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  18536. thisThurs = getThursdayThisWeek(date);
  18537. var diff = +thisThurs - +firstThurs,
  18538. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  18539. return padNumber(result, size);
  18540. };
  18541. }
  18542. function ampmGetter(date, formats) {
  18543. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  18544. }
  18545. function eraGetter(date, formats) {
  18546. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  18547. }
  18548. function longEraGetter(date, formats) {
  18549. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  18550. }
  18551. var DATE_FORMATS = {
  18552. yyyy: dateGetter('FullYear', 4, 0, false, true),
  18553. yy: dateGetter('FullYear', 2, 0, true, true),
  18554. y: dateGetter('FullYear', 1, 0, false, true),
  18555. MMMM: dateStrGetter('Month'),
  18556. MMM: dateStrGetter('Month', true),
  18557. MM: dateGetter('Month', 2, 1),
  18558. M: dateGetter('Month', 1, 1),
  18559. LLLL: dateStrGetter('Month', false, true),
  18560. dd: dateGetter('Date', 2),
  18561. d: dateGetter('Date', 1),
  18562. HH: dateGetter('Hours', 2),
  18563. H: dateGetter('Hours', 1),
  18564. hh: dateGetter('Hours', 2, -12),
  18565. h: dateGetter('Hours', 1, -12),
  18566. mm: dateGetter('Minutes', 2),
  18567. m: dateGetter('Minutes', 1),
  18568. ss: dateGetter('Seconds', 2),
  18569. s: dateGetter('Seconds', 1),
  18570. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  18571. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  18572. sss: dateGetter('Milliseconds', 3),
  18573. EEEE: dateStrGetter('Day'),
  18574. EEE: dateStrGetter('Day', true),
  18575. a: ampmGetter,
  18576. Z: timeZoneGetter,
  18577. ww: weekGetter(2),
  18578. w: weekGetter(1),
  18579. G: eraGetter,
  18580. GG: eraGetter,
  18581. GGG: eraGetter,
  18582. GGGG: longEraGetter
  18583. };
  18584. var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
  18585. NUMBER_STRING = /^\-?\d+$/;
  18586. /**
  18587. * @ngdoc filter
  18588. * @name date
  18589. * @kind function
  18590. *
  18591. * @description
  18592. * Formats `date` to a string based on the requested `format`.
  18593. *
  18594. * `format` string can be composed of the following elements:
  18595. *
  18596. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  18597. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  18598. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  18599. * * `'MMMM'`: Month in year (January-December)
  18600. * * `'MMM'`: Month in year (Jan-Dec)
  18601. * * `'MM'`: Month in year, padded (01-12)
  18602. * * `'M'`: Month in year (1-12)
  18603. * * `'LLLL'`: Stand-alone month in year (January-December)
  18604. * * `'dd'`: Day in month, padded (01-31)
  18605. * * `'d'`: Day in month (1-31)
  18606. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  18607. * * `'EEE'`: Day in Week, (Sun-Sat)
  18608. * * `'HH'`: Hour in day, padded (00-23)
  18609. * * `'H'`: Hour in day (0-23)
  18610. * * `'hh'`: Hour in AM/PM, padded (01-12)
  18611. * * `'h'`: Hour in AM/PM, (1-12)
  18612. * * `'mm'`: Minute in hour, padded (00-59)
  18613. * * `'m'`: Minute in hour (0-59)
  18614. * * `'ss'`: Second in minute, padded (00-59)
  18615. * * `'s'`: Second in minute (0-59)
  18616. * * `'sss'`: Millisecond in second, padded (000-999)
  18617. * * `'a'`: AM/PM marker
  18618. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  18619. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  18620. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  18621. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  18622. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  18623. *
  18624. * `format` string can also be one of the following predefined
  18625. * {@link guide/i18n localizable formats}:
  18626. *
  18627. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  18628. * (e.g. Sep 3, 2010 12:05:08 PM)
  18629. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  18630. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  18631. * (e.g. Friday, September 3, 2010)
  18632. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  18633. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  18634. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  18635. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  18636. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  18637. *
  18638. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  18639. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  18640. * (e.g. `"h 'o''clock'"`).
  18641. *
  18642. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  18643. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  18644. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  18645. * specified in the string input, the time is considered to be in the local timezone.
  18646. * @param {string=} format Formatting rules (see Description). If not specified,
  18647. * `mediumDate` is used.
  18648. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  18649. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  18650. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  18651. * If not specified, the timezone of the browser will be used.
  18652. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  18653. *
  18654. * @example
  18655. <example>
  18656. <file name="index.html">
  18657. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  18658. <span>{{1288323623006 | date:'medium'}}</span><br>
  18659. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  18660. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  18661. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  18662. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  18663. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  18664. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  18665. </file>
  18666. <file name="protractor.js" type="protractor">
  18667. it('should format date', function() {
  18668. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  18669. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  18670. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  18671. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  18672. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  18673. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  18674. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  18675. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  18676. });
  18677. </file>
  18678. </example>
  18679. */
  18680. dateFilter.$inject = ['$locale'];
  18681. function dateFilter($locale) {
  18682. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  18683. // 1 2 3 4 5 6 7 8 9 10 11
  18684. function jsonStringToDate(string) {
  18685. var match;
  18686. if (match = string.match(R_ISO8601_STR)) {
  18687. var date = new Date(0),
  18688. tzHour = 0,
  18689. tzMin = 0,
  18690. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  18691. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  18692. if (match[9]) {
  18693. tzHour = toInt(match[9] + match[10]);
  18694. tzMin = toInt(match[9] + match[11]);
  18695. }
  18696. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  18697. var h = toInt(match[4] || 0) - tzHour;
  18698. var m = toInt(match[5] || 0) - tzMin;
  18699. var s = toInt(match[6] || 0);
  18700. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  18701. timeSetter.call(date, h, m, s, ms);
  18702. return date;
  18703. }
  18704. return string;
  18705. }
  18706. return function(date, format, timezone) {
  18707. var text = '',
  18708. parts = [],
  18709. fn, match;
  18710. format = format || 'mediumDate';
  18711. format = $locale.DATETIME_FORMATS[format] || format;
  18712. if (isString(date)) {
  18713. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  18714. }
  18715. if (isNumber(date)) {
  18716. date = new Date(date);
  18717. }
  18718. if (!isDate(date) || !isFinite(date.getTime())) {
  18719. return date;
  18720. }
  18721. while (format) {
  18722. match = DATE_FORMATS_SPLIT.exec(format);
  18723. if (match) {
  18724. parts = concat(parts, match, 1);
  18725. format = parts.pop();
  18726. } else {
  18727. parts.push(format);
  18728. format = null;
  18729. }
  18730. }
  18731. var dateTimezoneOffset = date.getTimezoneOffset();
  18732. if (timezone) {
  18733. dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  18734. date = convertTimezoneToLocal(date, timezone, true);
  18735. }
  18736. forEach(parts, function(value) {
  18737. fn = DATE_FORMATS[value];
  18738. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  18739. : value === "''" ? "'" : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  18740. });
  18741. return text;
  18742. };
  18743. }
  18744. /**
  18745. * @ngdoc filter
  18746. * @name json
  18747. * @kind function
  18748. *
  18749. * @description
  18750. * Allows you to convert a JavaScript object into JSON string.
  18751. *
  18752. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  18753. * the binding is automatically converted to JSON.
  18754. *
  18755. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  18756. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  18757. * @returns {string} JSON string.
  18758. *
  18759. *
  18760. * @example
  18761. <example>
  18762. <file name="index.html">
  18763. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  18764. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  18765. </file>
  18766. <file name="protractor.js" type="protractor">
  18767. it('should jsonify filtered objects', function() {
  18768. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  18769. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  18770. });
  18771. </file>
  18772. </example>
  18773. *
  18774. */
  18775. function jsonFilter() {
  18776. return function(object, spacing) {
  18777. if (isUndefined(spacing)) {
  18778. spacing = 2;
  18779. }
  18780. return toJson(object, spacing);
  18781. };
  18782. }
  18783. /**
  18784. * @ngdoc filter
  18785. * @name lowercase
  18786. * @kind function
  18787. * @description
  18788. * Converts string to lowercase.
  18789. * @see angular.lowercase
  18790. */
  18791. var lowercaseFilter = valueFn(lowercase);
  18792. /**
  18793. * @ngdoc filter
  18794. * @name uppercase
  18795. * @kind function
  18796. * @description
  18797. * Converts string to uppercase.
  18798. * @see angular.uppercase
  18799. */
  18800. var uppercaseFilter = valueFn(uppercase);
  18801. /**
  18802. * @ngdoc filter
  18803. * @name limitTo
  18804. * @kind function
  18805. *
  18806. * @description
  18807. * Creates a new array or string containing only a specified number of elements. The elements are
  18808. * taken from either the beginning or the end of the source array, string or number, as specified by
  18809. * the value and sign (positive or negative) of `limit`. Other array-like objects are also supported
  18810. * (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input,
  18811. * it is converted to a string.
  18812. *
  18813. * @param {Array|ArrayLike|string|number} input - Array/array-like, string or number to be limited.
  18814. * @param {string|number} limit - The length of the returned array or string. If the `limit` number
  18815. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  18816. * If the number is negative, `limit` number of items from the end of the source array/string
  18817. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  18818. * the input will be returned unchanged.
  18819. * @param {(string|number)=} begin - Index at which to begin limitation. As a negative index,
  18820. * `begin` indicates an offset from the end of `input`. Defaults to `0`.
  18821. * @returns {Array|string} A new sub-array or substring of length `limit` or less if the input had
  18822. * less than `limit` elements.
  18823. *
  18824. * @example
  18825. <example module="limitToExample">
  18826. <file name="index.html">
  18827. <script>
  18828. angular.module('limitToExample', [])
  18829. .controller('ExampleController', ['$scope', function($scope) {
  18830. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  18831. $scope.letters = "abcdefghi";
  18832. $scope.longNumber = 2345432342;
  18833. $scope.numLimit = 3;
  18834. $scope.letterLimit = 3;
  18835. $scope.longNumberLimit = 3;
  18836. }]);
  18837. </script>
  18838. <div ng-controller="ExampleController">
  18839. <label>
  18840. Limit {{numbers}} to:
  18841. <input type="number" step="1" ng-model="numLimit">
  18842. </label>
  18843. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  18844. <label>
  18845. Limit {{letters}} to:
  18846. <input type="number" step="1" ng-model="letterLimit">
  18847. </label>
  18848. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  18849. <label>
  18850. Limit {{longNumber}} to:
  18851. <input type="number" step="1" ng-model="longNumberLimit">
  18852. </label>
  18853. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  18854. </div>
  18855. </file>
  18856. <file name="protractor.js" type="protractor">
  18857. var numLimitInput = element(by.model('numLimit'));
  18858. var letterLimitInput = element(by.model('letterLimit'));
  18859. var longNumberLimitInput = element(by.model('longNumberLimit'));
  18860. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  18861. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  18862. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  18863. it('should limit the number array to first three items', function() {
  18864. expect(numLimitInput.getAttribute('value')).toBe('3');
  18865. expect(letterLimitInput.getAttribute('value')).toBe('3');
  18866. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  18867. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  18868. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  18869. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  18870. });
  18871. // There is a bug in safari and protractor that doesn't like the minus key
  18872. // it('should update the output when -3 is entered', function() {
  18873. // numLimitInput.clear();
  18874. // numLimitInput.sendKeys('-3');
  18875. // letterLimitInput.clear();
  18876. // letterLimitInput.sendKeys('-3');
  18877. // longNumberLimitInput.clear();
  18878. // longNumberLimitInput.sendKeys('-3');
  18879. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  18880. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  18881. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  18882. // });
  18883. it('should not exceed the maximum size of input array', function() {
  18884. numLimitInput.clear();
  18885. numLimitInput.sendKeys('100');
  18886. letterLimitInput.clear();
  18887. letterLimitInput.sendKeys('100');
  18888. longNumberLimitInput.clear();
  18889. longNumberLimitInput.sendKeys('100');
  18890. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  18891. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  18892. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  18893. });
  18894. </file>
  18895. </example>
  18896. */
  18897. function limitToFilter() {
  18898. return function(input, limit, begin) {
  18899. if (Math.abs(Number(limit)) === Infinity) {
  18900. limit = Number(limit);
  18901. } else {
  18902. limit = toInt(limit);
  18903. }
  18904. if (isNaN(limit)) return input;
  18905. if (isNumber(input)) input = input.toString();
  18906. if (!isArrayLike(input)) return input;
  18907. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  18908. begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
  18909. if (limit >= 0) {
  18910. return sliceFn(input, begin, begin + limit);
  18911. } else {
  18912. if (begin === 0) {
  18913. return sliceFn(input, limit, input.length);
  18914. } else {
  18915. return sliceFn(input, Math.max(0, begin + limit), begin);
  18916. }
  18917. }
  18918. };
  18919. }
  18920. function sliceFn(input, begin, end) {
  18921. if (isString(input)) return input.slice(begin, end);
  18922. return slice.call(input, begin, end);
  18923. }
  18924. /**
  18925. * @ngdoc filter
  18926. * @name orderBy
  18927. * @kind function
  18928. *
  18929. * @description
  18930. * Returns an array containing the items from the specified `collection`, ordered by a `comparator`
  18931. * function based on the values computed using the `expression` predicate.
  18932. *
  18933. * For example, `[{id: 'foo'}, {id: 'bar'}] | orderBy:'id'` would result in
  18934. * `[{id: 'bar'}, {id: 'foo'}]`.
  18935. *
  18936. * The `collection` can be an Array or array-like object (e.g. NodeList, jQuery object, TypedArray,
  18937. * String, etc).
  18938. *
  18939. * The `expression` can be a single predicate, or a list of predicates each serving as a tie-breaker
  18940. * for the preceeding one. The `expression` is evaluated against each item and the output is used
  18941. * for comparing with other items.
  18942. *
  18943. * You can change the sorting order by setting `reverse` to `true`. By default, items are sorted in
  18944. * ascending order.
  18945. *
  18946. * The comparison is done using the `comparator` function. If none is specified, a default, built-in
  18947. * comparator is used (see below for details - in a nutshell, it compares numbers numerically and
  18948. * strings alphabetically).
  18949. *
  18950. * ### Under the hood
  18951. *
  18952. * Ordering the specified `collection` happens in two phases:
  18953. *
  18954. * 1. All items are passed through the predicate (or predicates), and the returned values are saved
  18955. * along with their type (`string`, `number` etc). For example, an item `{label: 'foo'}`, passed
  18956. * through a predicate that extracts the value of the `label` property, would be transformed to:
  18957. * ```
  18958. * {
  18959. * value: 'foo',
  18960. * type: 'string',
  18961. * index: ...
  18962. * }
  18963. * ```
  18964. * 2. The comparator function is used to sort the items, based on the derived values, types and
  18965. * indices.
  18966. *
  18967. * If you use a custom comparator, it will be called with pairs of objects of the form
  18968. * `{value: ..., type: '...', index: ...}` and is expected to return `0` if the objects are equal
  18969. * (as far as the comparator is concerned), `-1` if the 1st one should be ranked higher than the
  18970. * second, or `1` otherwise.
  18971. *
  18972. * In order to ensure that the sorting will be deterministic across platforms, if none of the
  18973. * specified predicates can distinguish between two items, `orderBy` will automatically introduce a
  18974. * dummy predicate that returns the item's index as `value`.
  18975. * (If you are using a custom comparator, make sure it can handle this predicate as well.)
  18976. *
  18977. * Finally, in an attempt to simplify things, if a predicate returns an object as the extracted
  18978. * value for an item, `orderBy` will try to convert that object to a primitive value, before passing
  18979. * it to the comparator. The following rules govern the conversion:
  18980. *
  18981. * 1. If the object has a `valueOf()` method that returns a primitive, its return value will be
  18982. * used instead.<br />
  18983. * (If the object has a `valueOf()` method that returns another object, then the returned object
  18984. * will be used in subsequent steps.)
  18985. * 2. If the object has a custom `toString()` method (i.e. not the one inherited from `Object`) that
  18986. * returns a primitive, its return value will be used instead.<br />
  18987. * (If the object has a `toString()` method that returns another object, then the returned object
  18988. * will be used in subsequent steps.)
  18989. * 3. No conversion; the object itself is used.
  18990. *
  18991. * ### The default comparator
  18992. *
  18993. * The default, built-in comparator should be sufficient for most usecases. In short, it compares
  18994. * numbers numerically, strings alphabetically (and case-insensitively), for objects falls back to
  18995. * using their index in the original collection, and sorts values of different types by type.
  18996. *
  18997. * More specifically, it follows these steps to determine the relative order of items:
  18998. *
  18999. * 1. If the compared values are of different types, compare the types themselves alphabetically.
  19000. * 2. If both values are of type `string`, compare them alphabetically in a case- and
  19001. * locale-insensitive way.
  19002. * 3. If both values are objects, compare their indices instead.
  19003. * 4. Otherwise, return:
  19004. * - `0`, if the values are equal (by strict equality comparison, i.e. using `===`).
  19005. * - `-1`, if the 1st value is "less than" the 2nd value (compared using the `<` operator).
  19006. * - `1`, otherwise.
  19007. *
  19008. * **Note:** If you notice numbers not being sorted as expected, make sure they are actually being
  19009. * saved as numbers and not strings.
  19010. *
  19011. * @param {Array|ArrayLike} collection - The collection (array or array-like object) to sort.
  19012. * @param {(Function|string|Array.<Function|string>)=} expression - A predicate (or list of
  19013. * predicates) to be used by the comparator to determine the order of elements.
  19014. *
  19015. * Can be one of:
  19016. *
  19017. * - `Function`: A getter function. This function will be called with each item as argument and
  19018. * the return value will be used for sorting.
  19019. * - `string`: An Angular expression. This expression will be evaluated against each item and the
  19020. * result will be used for sorting. For example, use `'label'` to sort by a property called
  19021. * `label` or `'label.substring(0, 3)'` to sort by the first 3 characters of the `label`
  19022. * property.<br />
  19023. * (The result of a constant expression is interpreted as a property name to be used for
  19024. * comparison. For example, use `'"special name"'` (note the extra pair of quotes) to sort by a
  19025. * property called `special name`.)<br />
  19026. * An expression can be optionally prefixed with `+` or `-` to control the sorting direction,
  19027. * ascending or descending. For example, `'+label'` or `'-label'`. If no property is provided,
  19028. * (e.g. `'+'` or `'-'`), the collection element itself is used in comparisons.
  19029. * - `Array`: An array of function and/or string predicates. If a predicate cannot determine the
  19030. * relative order of two items, the next predicate is used as a tie-breaker.
  19031. *
  19032. * **Note:** If the predicate is missing or empty then it defaults to `'+'`.
  19033. *
  19034. * @param {boolean=} reverse - If `true`, reverse the sorting order.
  19035. * @param {(Function)=} comparator - The comparator function used to determine the relative order of
  19036. * value pairs. If omitted, the built-in comparator will be used.
  19037. *
  19038. * @returns {Array} - The sorted array.
  19039. *
  19040. *
  19041. * @example
  19042. * ### Ordering a table with `ngRepeat`
  19043. *
  19044. * The example below demonstrates a simple {@link ngRepeat ngRepeat}, where the data is sorted by
  19045. * age in descending order (expression is set to `'-age'`). The `comparator` is not set, which means
  19046. * it defaults to the built-in comparator.
  19047. *
  19048. <example name="orderBy-static" module="orderByExample1">
  19049. <file name="index.html">
  19050. <div ng-controller="ExampleController">
  19051. <table class="friends">
  19052. <tr>
  19053. <th>Name</th>
  19054. <th>Phone Number</th>
  19055. <th>Age</th>
  19056. </tr>
  19057. <tr ng-repeat="friend in friends | orderBy:'-age'">
  19058. <td>{{friend.name}}</td>
  19059. <td>{{friend.phone}}</td>
  19060. <td>{{friend.age}}</td>
  19061. </tr>
  19062. </table>
  19063. </div>
  19064. </file>
  19065. <file name="script.js">
  19066. angular.module('orderByExample1', [])
  19067. .controller('ExampleController', ['$scope', function($scope) {
  19068. $scope.friends = [
  19069. {name: 'John', phone: '555-1212', age: 10},
  19070. {name: 'Mary', phone: '555-9876', age: 19},
  19071. {name: 'Mike', phone: '555-4321', age: 21},
  19072. {name: 'Adam', phone: '555-5678', age: 35},
  19073. {name: 'Julie', phone: '555-8765', age: 29}
  19074. ];
  19075. }]);
  19076. </file>
  19077. <file name="style.css">
  19078. .friends {
  19079. border-collapse: collapse;
  19080. }
  19081. .friends th {
  19082. border-bottom: 1px solid;
  19083. }
  19084. .friends td, .friends th {
  19085. border-left: 1px solid;
  19086. padding: 5px 10px;
  19087. }
  19088. .friends td:first-child, .friends th:first-child {
  19089. border-left: none;
  19090. }
  19091. </file>
  19092. <file name="protractor.js" type="protractor">
  19093. // Element locators
  19094. var names = element.all(by.repeater('friends').column('friend.name'));
  19095. it('should sort friends by age in reverse order', function() {
  19096. expect(names.get(0).getText()).toBe('Adam');
  19097. expect(names.get(1).getText()).toBe('Julie');
  19098. expect(names.get(2).getText()).toBe('Mike');
  19099. expect(names.get(3).getText()).toBe('Mary');
  19100. expect(names.get(4).getText()).toBe('John');
  19101. });
  19102. </file>
  19103. </example>
  19104. * <hr />
  19105. *
  19106. * @example
  19107. * ### Changing parameters dynamically
  19108. *
  19109. * All parameters can be changed dynamically. The next example shows how you can make the columns of
  19110. * a table sortable, by binding the `expression` and `reverse` parameters to scope properties.
  19111. *
  19112. <example name="orderBy-dynamic" module="orderByExample2">
  19113. <file name="index.html">
  19114. <div ng-controller="ExampleController">
  19115. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  19116. <hr/>
  19117. <button ng-click="propertyName = null; reverse = false">Set to unsorted</button>
  19118. <hr/>
  19119. <table class="friends">
  19120. <tr>
  19121. <th>
  19122. <button ng-click="sortBy('name')">Name</button>
  19123. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  19124. </th>
  19125. <th>
  19126. <button ng-click="sortBy('phone')">Phone Number</button>
  19127. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  19128. </th>
  19129. <th>
  19130. <button ng-click="sortBy('age')">Age</button>
  19131. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  19132. </th>
  19133. </tr>
  19134. <tr ng-repeat="friend in friends | orderBy:propertyName:reverse">
  19135. <td>{{friend.name}}</td>
  19136. <td>{{friend.phone}}</td>
  19137. <td>{{friend.age}}</td>
  19138. </tr>
  19139. </table>
  19140. </div>
  19141. </file>
  19142. <file name="script.js">
  19143. angular.module('orderByExample2', [])
  19144. .controller('ExampleController', ['$scope', function($scope) {
  19145. var friends = [
  19146. {name: 'John', phone: '555-1212', age: 10},
  19147. {name: 'Mary', phone: '555-9876', age: 19},
  19148. {name: 'Mike', phone: '555-4321', age: 21},
  19149. {name: 'Adam', phone: '555-5678', age: 35},
  19150. {name: 'Julie', phone: '555-8765', age: 29}
  19151. ];
  19152. $scope.propertyName = 'age';
  19153. $scope.reverse = true;
  19154. $scope.friends = friends;
  19155. $scope.sortBy = function(propertyName) {
  19156. $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
  19157. $scope.propertyName = propertyName;
  19158. };
  19159. }]);
  19160. </file>
  19161. <file name="style.css">
  19162. .friends {
  19163. border-collapse: collapse;
  19164. }
  19165. .friends th {
  19166. border-bottom: 1px solid;
  19167. }
  19168. .friends td, .friends th {
  19169. border-left: 1px solid;
  19170. padding: 5px 10px;
  19171. }
  19172. .friends td:first-child, .friends th:first-child {
  19173. border-left: none;
  19174. }
  19175. .sortorder:after {
  19176. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  19177. }
  19178. .sortorder.reverse:after {
  19179. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  19180. }
  19181. </file>
  19182. <file name="protractor.js" type="protractor">
  19183. // Element locators
  19184. var unsortButton = element(by.partialButtonText('unsorted'));
  19185. var nameHeader = element(by.partialButtonText('Name'));
  19186. var phoneHeader = element(by.partialButtonText('Phone'));
  19187. var ageHeader = element(by.partialButtonText('Age'));
  19188. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  19189. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  19190. it('should sort friends by some property, when clicking on the column header', function() {
  19191. expect(firstName.getText()).toBe('Adam');
  19192. expect(lastName.getText()).toBe('John');
  19193. phoneHeader.click();
  19194. expect(firstName.getText()).toBe('John');
  19195. expect(lastName.getText()).toBe('Mary');
  19196. nameHeader.click();
  19197. expect(firstName.getText()).toBe('Adam');
  19198. expect(lastName.getText()).toBe('Mike');
  19199. ageHeader.click();
  19200. expect(firstName.getText()).toBe('John');
  19201. expect(lastName.getText()).toBe('Adam');
  19202. });
  19203. it('should sort friends in reverse order, when clicking on the same column', function() {
  19204. expect(firstName.getText()).toBe('Adam');
  19205. expect(lastName.getText()).toBe('John');
  19206. ageHeader.click();
  19207. expect(firstName.getText()).toBe('John');
  19208. expect(lastName.getText()).toBe('Adam');
  19209. ageHeader.click();
  19210. expect(firstName.getText()).toBe('Adam');
  19211. expect(lastName.getText()).toBe('John');
  19212. });
  19213. it('should restore the original order, when clicking "Set to unsorted"', function() {
  19214. expect(firstName.getText()).toBe('Adam');
  19215. expect(lastName.getText()).toBe('John');
  19216. unsortButton.click();
  19217. expect(firstName.getText()).toBe('John');
  19218. expect(lastName.getText()).toBe('Julie');
  19219. });
  19220. </file>
  19221. </example>
  19222. * <hr />
  19223. *
  19224. * @example
  19225. * ### Using `orderBy` inside a controller
  19226. *
  19227. * It is also possible to call the `orderBy` filter manually, by injecting `orderByFilter`, and
  19228. * calling it with the desired parameters. (Alternatively, you could inject the `$filter` factory
  19229. * and retrieve the `orderBy` filter with `$filter('orderBy')`.)
  19230. *
  19231. <example name="orderBy-call-manually" module="orderByExample3">
  19232. <file name="index.html">
  19233. <div ng-controller="ExampleController">
  19234. <pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
  19235. <hr/>
  19236. <button ng-click="sortBy(null)">Set to unsorted</button>
  19237. <hr/>
  19238. <table class="friends">
  19239. <tr>
  19240. <th>
  19241. <button ng-click="sortBy('name')">Name</button>
  19242. <span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
  19243. </th>
  19244. <th>
  19245. <button ng-click="sortBy('phone')">Phone Number</button>
  19246. <span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
  19247. </th>
  19248. <th>
  19249. <button ng-click="sortBy('age')">Age</button>
  19250. <span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
  19251. </th>
  19252. </tr>
  19253. <tr ng-repeat="friend in friends">
  19254. <td>{{friend.name}}</td>
  19255. <td>{{friend.phone}}</td>
  19256. <td>{{friend.age}}</td>
  19257. </tr>
  19258. </table>
  19259. </div>
  19260. </file>
  19261. <file name="script.js">
  19262. angular.module('orderByExample3', [])
  19263. .controller('ExampleController', ['$scope', 'orderByFilter', function($scope, orderBy) {
  19264. var friends = [
  19265. {name: 'John', phone: '555-1212', age: 10},
  19266. {name: 'Mary', phone: '555-9876', age: 19},
  19267. {name: 'Mike', phone: '555-4321', age: 21},
  19268. {name: 'Adam', phone: '555-5678', age: 35},
  19269. {name: 'Julie', phone: '555-8765', age: 29}
  19270. ];
  19271. $scope.propertyName = 'age';
  19272. $scope.reverse = true;
  19273. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  19274. $scope.sortBy = function(propertyName) {
  19275. $scope.reverse = (propertyName !== null && $scope.propertyName === propertyName)
  19276. ? !$scope.reverse : false;
  19277. $scope.propertyName = propertyName;
  19278. $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse);
  19279. };
  19280. }]);
  19281. </file>
  19282. <file name="style.css">
  19283. .friends {
  19284. border-collapse: collapse;
  19285. }
  19286. .friends th {
  19287. border-bottom: 1px solid;
  19288. }
  19289. .friends td, .friends th {
  19290. border-left: 1px solid;
  19291. padding: 5px 10px;
  19292. }
  19293. .friends td:first-child, .friends th:first-child {
  19294. border-left: none;
  19295. }
  19296. .sortorder:after {
  19297. content: '\25b2'; // BLACK UP-POINTING TRIANGLE
  19298. }
  19299. .sortorder.reverse:after {
  19300. content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
  19301. }
  19302. </file>
  19303. <file name="protractor.js" type="protractor">
  19304. // Element locators
  19305. var unsortButton = element(by.partialButtonText('unsorted'));
  19306. var nameHeader = element(by.partialButtonText('Name'));
  19307. var phoneHeader = element(by.partialButtonText('Phone'));
  19308. var ageHeader = element(by.partialButtonText('Age'));
  19309. var firstName = element(by.repeater('friends').column('friend.name').row(0));
  19310. var lastName = element(by.repeater('friends').column('friend.name').row(4));
  19311. it('should sort friends by some property, when clicking on the column header', function() {
  19312. expect(firstName.getText()).toBe('Adam');
  19313. expect(lastName.getText()).toBe('John');
  19314. phoneHeader.click();
  19315. expect(firstName.getText()).toBe('John');
  19316. expect(lastName.getText()).toBe('Mary');
  19317. nameHeader.click();
  19318. expect(firstName.getText()).toBe('Adam');
  19319. expect(lastName.getText()).toBe('Mike');
  19320. ageHeader.click();
  19321. expect(firstName.getText()).toBe('John');
  19322. expect(lastName.getText()).toBe('Adam');
  19323. });
  19324. it('should sort friends in reverse order, when clicking on the same column', function() {
  19325. expect(firstName.getText()).toBe('Adam');
  19326. expect(lastName.getText()).toBe('John');
  19327. ageHeader.click();
  19328. expect(firstName.getText()).toBe('John');
  19329. expect(lastName.getText()).toBe('Adam');
  19330. ageHeader.click();
  19331. expect(firstName.getText()).toBe('Adam');
  19332. expect(lastName.getText()).toBe('John');
  19333. });
  19334. it('should restore the original order, when clicking "Set to unsorted"', function() {
  19335. expect(firstName.getText()).toBe('Adam');
  19336. expect(lastName.getText()).toBe('John');
  19337. unsortButton.click();
  19338. expect(firstName.getText()).toBe('John');
  19339. expect(lastName.getText()).toBe('Julie');
  19340. });
  19341. </file>
  19342. </example>
  19343. * <hr />
  19344. *
  19345. * @example
  19346. * ### Using a custom comparator
  19347. *
  19348. * If you have very specific requirements about the way items are sorted, you can pass your own
  19349. * comparator function. For example, you might need to compare some strings in a locale-sensitive
  19350. * way. (When specifying a custom comparator, you also need to pass a value for the `reverse`
  19351. * argument - passing `false` retains the default sorting order, i.e. ascending.)
  19352. *
  19353. <example name="orderBy-custom-comparator" module="orderByExample4">
  19354. <file name="index.html">
  19355. <div ng-controller="ExampleController">
  19356. <div class="friends-container custom-comparator">
  19357. <h3>Locale-sensitive Comparator</h3>
  19358. <table class="friends">
  19359. <tr>
  19360. <th>Name</th>
  19361. <th>Favorite Letter</th>
  19362. </tr>
  19363. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter':false:localeSensitiveComparator">
  19364. <td>{{friend.name}}</td>
  19365. <td>{{friend.favoriteLetter}}</td>
  19366. </tr>
  19367. </table>
  19368. </div>
  19369. <div class="friends-container default-comparator">
  19370. <h3>Default Comparator</h3>
  19371. <table class="friends">
  19372. <tr>
  19373. <th>Name</th>
  19374. <th>Favorite Letter</th>
  19375. </tr>
  19376. <tr ng-repeat="friend in friends | orderBy:'favoriteLetter'">
  19377. <td>{{friend.name}}</td>
  19378. <td>{{friend.favoriteLetter}}</td>
  19379. </tr>
  19380. </table>
  19381. </div>
  19382. </div>
  19383. </file>
  19384. <file name="script.js">
  19385. angular.module('orderByExample4', [])
  19386. .controller('ExampleController', ['$scope', function($scope) {
  19387. $scope.friends = [
  19388. {name: 'John', favoriteLetter: 'Ä'},
  19389. {name: 'Mary', favoriteLetter: 'Ü'},
  19390. {name: 'Mike', favoriteLetter: 'Ö'},
  19391. {name: 'Adam', favoriteLetter: 'H'},
  19392. {name: 'Julie', favoriteLetter: 'Z'}
  19393. ];
  19394. $scope.localeSensitiveComparator = function(v1, v2) {
  19395. // If we don't get strings, just compare by index
  19396. if (v1.type !== 'string' || v2.type !== 'string') {
  19397. return (v1.index < v2.index) ? -1 : 1;
  19398. }
  19399. // Compare strings alphabetically, taking locale into account
  19400. return v1.value.localeCompare(v2.value);
  19401. };
  19402. }]);
  19403. </file>
  19404. <file name="style.css">
  19405. .friends-container {
  19406. display: inline-block;
  19407. margin: 0 30px;
  19408. }
  19409. .friends {
  19410. border-collapse: collapse;
  19411. }
  19412. .friends th {
  19413. border-bottom: 1px solid;
  19414. }
  19415. .friends td, .friends th {
  19416. border-left: 1px solid;
  19417. padding: 5px 10px;
  19418. }
  19419. .friends td:first-child, .friends th:first-child {
  19420. border-left: none;
  19421. }
  19422. </file>
  19423. <file name="protractor.js" type="protractor">
  19424. // Element locators
  19425. var container = element(by.css('.custom-comparator'));
  19426. var names = container.all(by.repeater('friends').column('friend.name'));
  19427. it('should sort friends by favorite letter (in correct alphabetical order)', function() {
  19428. expect(names.get(0).getText()).toBe('John');
  19429. expect(names.get(1).getText()).toBe('Adam');
  19430. expect(names.get(2).getText()).toBe('Mike');
  19431. expect(names.get(3).getText()).toBe('Mary');
  19432. expect(names.get(4).getText()).toBe('Julie');
  19433. });
  19434. </file>
  19435. </example>
  19436. *
  19437. */
  19438. orderByFilter.$inject = ['$parse'];
  19439. function orderByFilter($parse) {
  19440. return function(array, sortPredicate, reverseOrder, compareFn) {
  19441. if (array == null) return array;
  19442. if (!isArrayLike(array)) {
  19443. throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
  19444. }
  19445. if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
  19446. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  19447. var predicates = processPredicates(sortPredicate);
  19448. var descending = reverseOrder ? -1 : 1;
  19449. // Define the `compare()` function. Use a default comparator if none is specified.
  19450. var compare = isFunction(compareFn) ? compareFn : defaultCompare;
  19451. // The next three lines are a version of a Swartzian Transform idiom from Perl
  19452. // (sometimes called the Decorate-Sort-Undecorate idiom)
  19453. // See https://en.wikipedia.org/wiki/Schwartzian_transform
  19454. var compareValues = Array.prototype.map.call(array, getComparisonObject);
  19455. compareValues.sort(doComparison);
  19456. array = compareValues.map(function(item) { return item.value; });
  19457. return array;
  19458. function getComparisonObject(value, index) {
  19459. // NOTE: We are adding an extra `tieBreaker` value based on the element's index.
  19460. // This will be used to keep the sort stable when none of the input predicates can
  19461. // distinguish between two elements.
  19462. return {
  19463. value: value,
  19464. tieBreaker: {value: index, type: 'number', index: index},
  19465. predicateValues: predicates.map(function(predicate) {
  19466. return getPredicateValue(predicate.get(value), index);
  19467. })
  19468. };
  19469. }
  19470. function doComparison(v1, v2) {
  19471. for (var i = 0, ii = predicates.length; i < ii; i++) {
  19472. var result = compare(v1.predicateValues[i], v2.predicateValues[i]);
  19473. if (result) {
  19474. return result * predicates[i].descending * descending;
  19475. }
  19476. }
  19477. return compare(v1.tieBreaker, v2.tieBreaker) * descending;
  19478. }
  19479. };
  19480. function processPredicates(sortPredicates) {
  19481. return sortPredicates.map(function(predicate) {
  19482. var descending = 1, get = identity;
  19483. if (isFunction(predicate)) {
  19484. get = predicate;
  19485. } else if (isString(predicate)) {
  19486. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  19487. descending = predicate.charAt(0) == '-' ? -1 : 1;
  19488. predicate = predicate.substring(1);
  19489. }
  19490. if (predicate !== '') {
  19491. get = $parse(predicate);
  19492. if (get.constant) {
  19493. var key = get();
  19494. get = function(value) { return value[key]; };
  19495. }
  19496. }
  19497. }
  19498. return {get: get, descending: descending};
  19499. });
  19500. }
  19501. function isPrimitive(value) {
  19502. switch (typeof value) {
  19503. case 'number': /* falls through */
  19504. case 'boolean': /* falls through */
  19505. case 'string':
  19506. return true;
  19507. default:
  19508. return false;
  19509. }
  19510. }
  19511. function objectValue(value) {
  19512. // If `valueOf` is a valid function use that
  19513. if (isFunction(value.valueOf)) {
  19514. value = value.valueOf();
  19515. if (isPrimitive(value)) return value;
  19516. }
  19517. // If `toString` is a valid function and not the one from `Object.prototype` use that
  19518. if (hasCustomToString(value)) {
  19519. value = value.toString();
  19520. if (isPrimitive(value)) return value;
  19521. }
  19522. return value;
  19523. }
  19524. function getPredicateValue(value, index) {
  19525. var type = typeof value;
  19526. if (value === null) {
  19527. type = 'string';
  19528. value = 'null';
  19529. } else if (type === 'object') {
  19530. value = objectValue(value);
  19531. }
  19532. return {value: value, type: type, index: index};
  19533. }
  19534. function defaultCompare(v1, v2) {
  19535. var result = 0;
  19536. var type1 = v1.type;
  19537. var type2 = v2.type;
  19538. if (type1 === type2) {
  19539. var value1 = v1.value;
  19540. var value2 = v2.value;
  19541. if (type1 === 'string') {
  19542. // Compare strings case-insensitively
  19543. value1 = value1.toLowerCase();
  19544. value2 = value2.toLowerCase();
  19545. } else if (type1 === 'object') {
  19546. // For basic objects, use the position of the object
  19547. // in the collection instead of the value
  19548. if (isObject(value1)) value1 = v1.index;
  19549. if (isObject(value2)) value2 = v2.index;
  19550. }
  19551. if (value1 !== value2) {
  19552. result = value1 < value2 ? -1 : 1;
  19553. }
  19554. } else {
  19555. result = type1 < type2 ? -1 : 1;
  19556. }
  19557. return result;
  19558. }
  19559. }
  19560. function ngDirective(directive) {
  19561. if (isFunction(directive)) {
  19562. directive = {
  19563. link: directive
  19564. };
  19565. }
  19566. directive.restrict = directive.restrict || 'AC';
  19567. return valueFn(directive);
  19568. }
  19569. /**
  19570. * @ngdoc directive
  19571. * @name a
  19572. * @restrict E
  19573. *
  19574. * @description
  19575. * Modifies the default behavior of the html A tag so that the default action is prevented when
  19576. * the href attribute is empty.
  19577. *
  19578. * This change permits the easy creation of action links with the `ngClick` directive
  19579. * without changing the location or causing page reloads, e.g.:
  19580. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  19581. */
  19582. var htmlAnchorDirective = valueFn({
  19583. restrict: 'E',
  19584. compile: function(element, attr) {
  19585. if (!attr.href && !attr.xlinkHref) {
  19586. return function(scope, element) {
  19587. // If the linked element is not an anchor tag anymore, do nothing
  19588. if (element[0].nodeName.toLowerCase() !== 'a') return;
  19589. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  19590. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  19591. 'xlink:href' : 'href';
  19592. element.on('click', function(event) {
  19593. // if we have no href url, then don't navigate anywhere.
  19594. if (!element.attr(href)) {
  19595. event.preventDefault();
  19596. }
  19597. });
  19598. };
  19599. }
  19600. }
  19601. });
  19602. /**
  19603. * @ngdoc directive
  19604. * @name ngHref
  19605. * @restrict A
  19606. * @priority 99
  19607. *
  19608. * @description
  19609. * Using Angular markup like `{{hash}}` in an href attribute will
  19610. * make the link go to the wrong URL if the user clicks it before
  19611. * Angular has a chance to replace the `{{hash}}` markup with its
  19612. * value. Until Angular replaces the markup the link will be broken
  19613. * and will most likely return a 404 error. The `ngHref` directive
  19614. * solves this problem.
  19615. *
  19616. * The wrong way to write it:
  19617. * ```html
  19618. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  19619. * ```
  19620. *
  19621. * The correct way to write it:
  19622. * ```html
  19623. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  19624. * ```
  19625. *
  19626. * @element A
  19627. * @param {template} ngHref any string which can contain `{{}}` markup.
  19628. *
  19629. * @example
  19630. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  19631. * in links and their different behaviors:
  19632. <example>
  19633. <file name="index.html">
  19634. <input ng-model="value" /><br />
  19635. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  19636. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  19637. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  19638. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  19639. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  19640. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  19641. </file>
  19642. <file name="protractor.js" type="protractor">
  19643. it('should execute ng-click but not reload when href without value', function() {
  19644. element(by.id('link-1')).click();
  19645. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  19646. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  19647. });
  19648. it('should execute ng-click but not reload when href empty string', function() {
  19649. element(by.id('link-2')).click();
  19650. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  19651. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  19652. });
  19653. it('should execute ng-click and change url when ng-href specified', function() {
  19654. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  19655. element(by.id('link-3')).click();
  19656. // At this point, we navigate away from an Angular page, so we need
  19657. // to use browser.driver to get the base webdriver.
  19658. browser.wait(function() {
  19659. return browser.driver.getCurrentUrl().then(function(url) {
  19660. return url.match(/\/123$/);
  19661. });
  19662. }, 5000, 'page should navigate to /123');
  19663. });
  19664. it('should execute ng-click but not reload when href empty string and name specified', function() {
  19665. element(by.id('link-4')).click();
  19666. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  19667. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  19668. });
  19669. it('should execute ng-click but not reload when no href but name specified', function() {
  19670. element(by.id('link-5')).click();
  19671. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  19672. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  19673. });
  19674. it('should only change url when only ng-href', function() {
  19675. element(by.model('value')).clear();
  19676. element(by.model('value')).sendKeys('6');
  19677. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  19678. element(by.id('link-6')).click();
  19679. // At this point, we navigate away from an Angular page, so we need
  19680. // to use browser.driver to get the base webdriver.
  19681. browser.wait(function() {
  19682. return browser.driver.getCurrentUrl().then(function(url) {
  19683. return url.match(/\/6$/);
  19684. });
  19685. }, 5000, 'page should navigate to /6');
  19686. });
  19687. </file>
  19688. </example>
  19689. */
  19690. /**
  19691. * @ngdoc directive
  19692. * @name ngSrc
  19693. * @restrict A
  19694. * @priority 99
  19695. *
  19696. * @description
  19697. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  19698. * work right: The browser will fetch from the URL with the literal
  19699. * text `{{hash}}` until Angular replaces the expression inside
  19700. * `{{hash}}`. The `ngSrc` directive solves this problem.
  19701. *
  19702. * The buggy way to write it:
  19703. * ```html
  19704. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  19705. * ```
  19706. *
  19707. * The correct way to write it:
  19708. * ```html
  19709. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  19710. * ```
  19711. *
  19712. * @element IMG
  19713. * @param {template} ngSrc any string which can contain `{{}}` markup.
  19714. */
  19715. /**
  19716. * @ngdoc directive
  19717. * @name ngSrcset
  19718. * @restrict A
  19719. * @priority 99
  19720. *
  19721. * @description
  19722. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  19723. * work right: The browser will fetch from the URL with the literal
  19724. * text `{{hash}}` until Angular replaces the expression inside
  19725. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  19726. *
  19727. * The buggy way to write it:
  19728. * ```html
  19729. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  19730. * ```
  19731. *
  19732. * The correct way to write it:
  19733. * ```html
  19734. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  19735. * ```
  19736. *
  19737. * @element IMG
  19738. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  19739. */
  19740. /**
  19741. * @ngdoc directive
  19742. * @name ngDisabled
  19743. * @restrict A
  19744. * @priority 100
  19745. *
  19746. * @description
  19747. *
  19748. * This directive sets the `disabled` attribute on the element if the
  19749. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  19750. *
  19751. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  19752. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  19753. *
  19754. * @example
  19755. <example>
  19756. <file name="index.html">
  19757. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  19758. <button ng-model="button" ng-disabled="checked">Button</button>
  19759. </file>
  19760. <file name="protractor.js" type="protractor">
  19761. it('should toggle button', function() {
  19762. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  19763. element(by.model('checked')).click();
  19764. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  19765. });
  19766. </file>
  19767. </example>
  19768. *
  19769. * @element INPUT
  19770. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  19771. * then the `disabled` attribute will be set on the element
  19772. */
  19773. /**
  19774. * @ngdoc directive
  19775. * @name ngChecked
  19776. * @restrict A
  19777. * @priority 100
  19778. *
  19779. * @description
  19780. * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
  19781. *
  19782. * Note that this directive should not be used together with {@link ngModel `ngModel`},
  19783. * as this can lead to unexpected behavior.
  19784. *
  19785. * A special directive is necessary because we cannot use interpolation inside the `checked`
  19786. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  19787. *
  19788. * @example
  19789. <example>
  19790. <file name="index.html">
  19791. <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
  19792. <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
  19793. </file>
  19794. <file name="protractor.js" type="protractor">
  19795. it('should check both checkBoxes', function() {
  19796. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  19797. element(by.model('master')).click();
  19798. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  19799. });
  19800. </file>
  19801. </example>
  19802. *
  19803. * @element INPUT
  19804. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  19805. * then the `checked` attribute will be set on the element
  19806. */
  19807. /**
  19808. * @ngdoc directive
  19809. * @name ngReadonly
  19810. * @restrict A
  19811. * @priority 100
  19812. *
  19813. * @description
  19814. *
  19815. * Sets the `readOnly` attribute on the element, if the expression inside `ngReadonly` is truthy.
  19816. *
  19817. * A special directive is necessary because we cannot use interpolation inside the `readOnly`
  19818. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  19819. *
  19820. * @example
  19821. <example>
  19822. <file name="index.html">
  19823. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  19824. <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
  19825. </file>
  19826. <file name="protractor.js" type="protractor">
  19827. it('should toggle readonly attr', function() {
  19828. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  19829. element(by.model('checked')).click();
  19830. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  19831. });
  19832. </file>
  19833. </example>
  19834. *
  19835. * @element INPUT
  19836. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  19837. * then special attribute "readonly" will be set on the element
  19838. */
  19839. /**
  19840. * @ngdoc directive
  19841. * @name ngSelected
  19842. * @restrict A
  19843. * @priority 100
  19844. *
  19845. * @description
  19846. *
  19847. * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy.
  19848. *
  19849. * A special directive is necessary because we cannot use interpolation inside the `selected`
  19850. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  19851. *
  19852. * @example
  19853. <example>
  19854. <file name="index.html">
  19855. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  19856. <select aria-label="ngSelected demo">
  19857. <option>Hello!</option>
  19858. <option id="greet" ng-selected="selected">Greetings!</option>
  19859. </select>
  19860. </file>
  19861. <file name="protractor.js" type="protractor">
  19862. it('should select Greetings!', function() {
  19863. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  19864. element(by.model('selected')).click();
  19865. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  19866. });
  19867. </file>
  19868. </example>
  19869. *
  19870. * @element OPTION
  19871. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  19872. * then special attribute "selected" will be set on the element
  19873. */
  19874. /**
  19875. * @ngdoc directive
  19876. * @name ngOpen
  19877. * @restrict A
  19878. * @priority 100
  19879. *
  19880. * @description
  19881. *
  19882. * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy.
  19883. *
  19884. * A special directive is necessary because we cannot use interpolation inside the `open`
  19885. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  19886. *
  19887. * @example
  19888. <example>
  19889. <file name="index.html">
  19890. <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
  19891. <details id="details" ng-open="open">
  19892. <summary>Show/Hide me</summary>
  19893. </details>
  19894. </file>
  19895. <file name="protractor.js" type="protractor">
  19896. it('should toggle open', function() {
  19897. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  19898. element(by.model('open')).click();
  19899. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  19900. });
  19901. </file>
  19902. </example>
  19903. *
  19904. * @element DETAILS
  19905. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  19906. * then special attribute "open" will be set on the element
  19907. */
  19908. var ngAttributeAliasDirectives = {};
  19909. // boolean attrs are evaluated
  19910. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  19911. // binding to multiple is not supported
  19912. if (propName == "multiple") return;
  19913. function defaultLinkFn(scope, element, attr) {
  19914. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  19915. attr.$set(attrName, !!value);
  19916. });
  19917. }
  19918. var normalized = directiveNormalize('ng-' + attrName);
  19919. var linkFn = defaultLinkFn;
  19920. if (propName === 'checked') {
  19921. linkFn = function(scope, element, attr) {
  19922. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  19923. if (attr.ngModel !== attr[normalized]) {
  19924. defaultLinkFn(scope, element, attr);
  19925. }
  19926. };
  19927. }
  19928. ngAttributeAliasDirectives[normalized] = function() {
  19929. return {
  19930. restrict: 'A',
  19931. priority: 100,
  19932. link: linkFn
  19933. };
  19934. };
  19935. });
  19936. // aliased input attrs are evaluated
  19937. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  19938. ngAttributeAliasDirectives[ngAttr] = function() {
  19939. return {
  19940. priority: 100,
  19941. link: function(scope, element, attr) {
  19942. //special case ngPattern when a literal regular expression value
  19943. //is used as the expression (this way we don't have to watch anything).
  19944. if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
  19945. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  19946. if (match) {
  19947. attr.$set("ngPattern", new RegExp(match[1], match[2]));
  19948. return;
  19949. }
  19950. }
  19951. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  19952. attr.$set(ngAttr, value);
  19953. });
  19954. }
  19955. };
  19956. };
  19957. });
  19958. // ng-src, ng-srcset, ng-href are interpolated
  19959. forEach(['src', 'srcset', 'href'], function(attrName) {
  19960. var normalized = directiveNormalize('ng-' + attrName);
  19961. ngAttributeAliasDirectives[normalized] = function() {
  19962. return {
  19963. priority: 99, // it needs to run after the attributes are interpolated
  19964. link: function(scope, element, attr) {
  19965. var propName = attrName,
  19966. name = attrName;
  19967. if (attrName === 'href' &&
  19968. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  19969. name = 'xlinkHref';
  19970. attr.$attr[name] = 'xlink:href';
  19971. propName = null;
  19972. }
  19973. attr.$observe(normalized, function(value) {
  19974. if (!value) {
  19975. if (attrName === 'href') {
  19976. attr.$set(name, null);
  19977. }
  19978. return;
  19979. }
  19980. attr.$set(name, value);
  19981. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  19982. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  19983. // to set the property as well to achieve the desired effect.
  19984. // we use attr[attrName] value since $set can sanitize the url.
  19985. if (msie && propName) element.prop(propName, attr[name]);
  19986. });
  19987. }
  19988. };
  19989. };
  19990. });
  19991. /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
  19992. */
  19993. var nullFormCtrl = {
  19994. $addControl: noop,
  19995. $$renameControl: nullFormRenameControl,
  19996. $removeControl: noop,
  19997. $setValidity: noop,
  19998. $setDirty: noop,
  19999. $setPristine: noop,
  20000. $setSubmitted: noop
  20001. },
  20002. SUBMITTED_CLASS = 'ng-submitted';
  20003. function nullFormRenameControl(control, name) {
  20004. control.$name = name;
  20005. }
  20006. /**
  20007. * @ngdoc type
  20008. * @name form.FormController
  20009. *
  20010. * @property {boolean} $pristine True if user has not interacted with the form yet.
  20011. * @property {boolean} $dirty True if user has already interacted with the form.
  20012. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  20013. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  20014. * @property {boolean} $pending True if at least one containing control or form is pending.
  20015. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  20016. *
  20017. * @property {Object} $error Is an object hash, containing references to controls or
  20018. * forms with failing validators, where:
  20019. *
  20020. * - keys are validation tokens (error names),
  20021. * - values are arrays of controls or forms that have a failing validator for given error name.
  20022. *
  20023. * Built-in validation tokens:
  20024. *
  20025. * - `email`
  20026. * - `max`
  20027. * - `maxlength`
  20028. * - `min`
  20029. * - `minlength`
  20030. * - `number`
  20031. * - `pattern`
  20032. * - `required`
  20033. * - `url`
  20034. * - `date`
  20035. * - `datetimelocal`
  20036. * - `time`
  20037. * - `week`
  20038. * - `month`
  20039. *
  20040. * @description
  20041. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  20042. * such as being valid/invalid or dirty/pristine.
  20043. *
  20044. * Each {@link ng.directive:form form} directive creates an instance
  20045. * of `FormController`.
  20046. *
  20047. */
  20048. //asks for $scope to fool the BC controller module
  20049. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  20050. function FormController(element, attrs, $scope, $animate, $interpolate) {
  20051. var form = this,
  20052. controls = [];
  20053. // init state
  20054. form.$error = {};
  20055. form.$$success = {};
  20056. form.$pending = undefined;
  20057. form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
  20058. form.$dirty = false;
  20059. form.$pristine = true;
  20060. form.$valid = true;
  20061. form.$invalid = false;
  20062. form.$submitted = false;
  20063. form.$$parentForm = nullFormCtrl;
  20064. /**
  20065. * @ngdoc method
  20066. * @name form.FormController#$rollbackViewValue
  20067. *
  20068. * @description
  20069. * Rollback all form controls pending updates to the `$modelValue`.
  20070. *
  20071. * Updates may be pending by a debounced event or because the input is waiting for a some future
  20072. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  20073. * a form that uses `ng-model-options` to pend updates.
  20074. */
  20075. form.$rollbackViewValue = function() {
  20076. forEach(controls, function(control) {
  20077. control.$rollbackViewValue();
  20078. });
  20079. };
  20080. /**
  20081. * @ngdoc method
  20082. * @name form.FormController#$commitViewValue
  20083. *
  20084. * @description
  20085. * Commit all form controls pending updates to the `$modelValue`.
  20086. *
  20087. * Updates may be pending by a debounced event or because the input is waiting for a some future
  20088. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  20089. * usually handles calling this in response to input events.
  20090. */
  20091. form.$commitViewValue = function() {
  20092. forEach(controls, function(control) {
  20093. control.$commitViewValue();
  20094. });
  20095. };
  20096. /**
  20097. * @ngdoc method
  20098. * @name form.FormController#$addControl
  20099. * @param {object} control control object, either a {@link form.FormController} or an
  20100. * {@link ngModel.NgModelController}
  20101. *
  20102. * @description
  20103. * Register a control with the form. Input elements using ngModelController do this automatically
  20104. * when they are linked.
  20105. *
  20106. * Note that the current state of the control will not be reflected on the new parent form. This
  20107. * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
  20108. * state.
  20109. *
  20110. * However, if the method is used programmatically, for example by adding dynamically created controls,
  20111. * or controls that have been previously removed without destroying their corresponding DOM element,
  20112. * it's the developers responsibility to make sure the current state propagates to the parent form.
  20113. *
  20114. * For example, if an input control is added that is already `$dirty` and has `$error` properties,
  20115. * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
  20116. */
  20117. form.$addControl = function(control) {
  20118. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  20119. // and not added to the scope. Now we throw an error.
  20120. assertNotHasOwnProperty(control.$name, 'input');
  20121. controls.push(control);
  20122. if (control.$name) {
  20123. form[control.$name] = control;
  20124. }
  20125. control.$$parentForm = form;
  20126. };
  20127. // Private API: rename a form control
  20128. form.$$renameControl = function(control, newName) {
  20129. var oldName = control.$name;
  20130. if (form[oldName] === control) {
  20131. delete form[oldName];
  20132. }
  20133. form[newName] = control;
  20134. control.$name = newName;
  20135. };
  20136. /**
  20137. * @ngdoc method
  20138. * @name form.FormController#$removeControl
  20139. * @param {object} control control object, either a {@link form.FormController} or an
  20140. * {@link ngModel.NgModelController}
  20141. *
  20142. * @description
  20143. * Deregister a control from the form.
  20144. *
  20145. * Input elements using ngModelController do this automatically when they are destroyed.
  20146. *
  20147. * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
  20148. * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
  20149. * different from case to case. For example, removing the only `$dirty` control from a form may or
  20150. * may not mean that the form is still `$dirty`.
  20151. */
  20152. form.$removeControl = function(control) {
  20153. if (control.$name && form[control.$name] === control) {
  20154. delete form[control.$name];
  20155. }
  20156. forEach(form.$pending, function(value, name) {
  20157. form.$setValidity(name, null, control);
  20158. });
  20159. forEach(form.$error, function(value, name) {
  20160. form.$setValidity(name, null, control);
  20161. });
  20162. forEach(form.$$success, function(value, name) {
  20163. form.$setValidity(name, null, control);
  20164. });
  20165. arrayRemove(controls, control);
  20166. control.$$parentForm = nullFormCtrl;
  20167. };
  20168. /**
  20169. * @ngdoc method
  20170. * @name form.FormController#$setValidity
  20171. *
  20172. * @description
  20173. * Sets the validity of a form control.
  20174. *
  20175. * This method will also propagate to parent forms.
  20176. */
  20177. addSetValidityMethod({
  20178. ctrl: this,
  20179. $element: element,
  20180. set: function(object, property, controller) {
  20181. var list = object[property];
  20182. if (!list) {
  20183. object[property] = [controller];
  20184. } else {
  20185. var index = list.indexOf(controller);
  20186. if (index === -1) {
  20187. list.push(controller);
  20188. }
  20189. }
  20190. },
  20191. unset: function(object, property, controller) {
  20192. var list = object[property];
  20193. if (!list) {
  20194. return;
  20195. }
  20196. arrayRemove(list, controller);
  20197. if (list.length === 0) {
  20198. delete object[property];
  20199. }
  20200. },
  20201. $animate: $animate
  20202. });
  20203. /**
  20204. * @ngdoc method
  20205. * @name form.FormController#$setDirty
  20206. *
  20207. * @description
  20208. * Sets the form to a dirty state.
  20209. *
  20210. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  20211. * state (ng-dirty class). This method will also propagate to parent forms.
  20212. */
  20213. form.$setDirty = function() {
  20214. $animate.removeClass(element, PRISTINE_CLASS);
  20215. $animate.addClass(element, DIRTY_CLASS);
  20216. form.$dirty = true;
  20217. form.$pristine = false;
  20218. form.$$parentForm.$setDirty();
  20219. };
  20220. /**
  20221. * @ngdoc method
  20222. * @name form.FormController#$setPristine
  20223. *
  20224. * @description
  20225. * Sets the form to its pristine state.
  20226. *
  20227. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  20228. * state (ng-pristine class). This method will also propagate to all the controls contained
  20229. * in this form.
  20230. *
  20231. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  20232. * saving or resetting it.
  20233. */
  20234. form.$setPristine = function() {
  20235. $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  20236. form.$dirty = false;
  20237. form.$pristine = true;
  20238. form.$submitted = false;
  20239. forEach(controls, function(control) {
  20240. control.$setPristine();
  20241. });
  20242. };
  20243. /**
  20244. * @ngdoc method
  20245. * @name form.FormController#$setUntouched
  20246. *
  20247. * @description
  20248. * Sets the form to its untouched state.
  20249. *
  20250. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  20251. * untouched state (ng-untouched class).
  20252. *
  20253. * Setting a form controls back to their untouched state is often useful when setting the form
  20254. * back to its pristine state.
  20255. */
  20256. form.$setUntouched = function() {
  20257. forEach(controls, function(control) {
  20258. control.$setUntouched();
  20259. });
  20260. };
  20261. /**
  20262. * @ngdoc method
  20263. * @name form.FormController#$setSubmitted
  20264. *
  20265. * @description
  20266. * Sets the form to its submitted state.
  20267. */
  20268. form.$setSubmitted = function() {
  20269. $animate.addClass(element, SUBMITTED_CLASS);
  20270. form.$submitted = true;
  20271. form.$$parentForm.$setSubmitted();
  20272. };
  20273. }
  20274. /**
  20275. * @ngdoc directive
  20276. * @name ngForm
  20277. * @restrict EAC
  20278. *
  20279. * @description
  20280. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  20281. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  20282. * sub-group of controls needs to be determined.
  20283. *
  20284. * Note: the purpose of `ngForm` is to group controls,
  20285. * but not to be a replacement for the `<form>` tag with all of its capabilities
  20286. * (e.g. posting to the server, ...).
  20287. *
  20288. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  20289. * related scope, under this name.
  20290. *
  20291. */
  20292. /**
  20293. * @ngdoc directive
  20294. * @name form
  20295. * @restrict E
  20296. *
  20297. * @description
  20298. * Directive that instantiates
  20299. * {@link form.FormController FormController}.
  20300. *
  20301. * If the `name` attribute is specified, the form controller is published onto the current scope under
  20302. * this name.
  20303. *
  20304. * # Alias: {@link ng.directive:ngForm `ngForm`}
  20305. *
  20306. * In Angular, forms can be nested. This means that the outer form is valid when all of the child
  20307. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  20308. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to
  20309. * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group
  20310. * of controls needs to be determined.
  20311. *
  20312. * # CSS classes
  20313. * - `ng-valid` is set if the form is valid.
  20314. * - `ng-invalid` is set if the form is invalid.
  20315. * - `ng-pending` is set if the form is pending.
  20316. * - `ng-pristine` is set if the form is pristine.
  20317. * - `ng-dirty` is set if the form is dirty.
  20318. * - `ng-submitted` is set if the form was submitted.
  20319. *
  20320. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  20321. *
  20322. *
  20323. * # Submitting a form and preventing the default action
  20324. *
  20325. * Since the role of forms in client-side Angular applications is different than in classical
  20326. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  20327. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  20328. * to handle the form submission in an application-specific way.
  20329. *
  20330. * For this reason, Angular prevents the default action (form submission to the server) unless the
  20331. * `<form>` element has an `action` attribute specified.
  20332. *
  20333. * You can use one of the following two ways to specify what javascript method should be called when
  20334. * a form is submitted:
  20335. *
  20336. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  20337. * - {@link ng.directive:ngClick ngClick} directive on the first
  20338. * button or input field of type submit (input[type=submit])
  20339. *
  20340. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  20341. * or {@link ng.directive:ngClick ngClick} directives.
  20342. * This is because of the following form submission rules in the HTML specification:
  20343. *
  20344. * - If a form has only one input field then hitting enter in this field triggers form submit
  20345. * (`ngSubmit`)
  20346. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  20347. * doesn't trigger submit
  20348. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  20349. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  20350. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  20351. *
  20352. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  20353. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  20354. * to have access to the updated model.
  20355. *
  20356. * ## Animation Hooks
  20357. *
  20358. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  20359. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  20360. * other validations that are performed within the form. Animations in ngForm are similar to how
  20361. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  20362. * as JS animations.
  20363. *
  20364. * The following example shows a simple way to utilize CSS transitions to style a form element
  20365. * that has been rendered as invalid after it has been validated:
  20366. *
  20367. * <pre>
  20368. * //be sure to include ngAnimate as a module to hook into more
  20369. * //advanced animations
  20370. * .my-form {
  20371. * transition:0.5s linear all;
  20372. * background: white;
  20373. * }
  20374. * .my-form.ng-invalid {
  20375. * background: red;
  20376. * color:white;
  20377. * }
  20378. * </pre>
  20379. *
  20380. * @example
  20381. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  20382. <file name="index.html">
  20383. <script>
  20384. angular.module('formExample', [])
  20385. .controller('FormController', ['$scope', function($scope) {
  20386. $scope.userType = 'guest';
  20387. }]);
  20388. </script>
  20389. <style>
  20390. .my-form {
  20391. transition:all linear 0.5s;
  20392. background: transparent;
  20393. }
  20394. .my-form.ng-invalid {
  20395. background: red;
  20396. }
  20397. </style>
  20398. <form name="myForm" ng-controller="FormController" class="my-form">
  20399. userType: <input name="input" ng-model="userType" required>
  20400. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  20401. <code>userType = {{userType}}</code><br>
  20402. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  20403. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  20404. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  20405. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  20406. </form>
  20407. </file>
  20408. <file name="protractor.js" type="protractor">
  20409. it('should initialize to model', function() {
  20410. var userType = element(by.binding('userType'));
  20411. var valid = element(by.binding('myForm.input.$valid'));
  20412. expect(userType.getText()).toContain('guest');
  20413. expect(valid.getText()).toContain('true');
  20414. });
  20415. it('should be invalid if empty', function() {
  20416. var userType = element(by.binding('userType'));
  20417. var valid = element(by.binding('myForm.input.$valid'));
  20418. var userInput = element(by.model('userType'));
  20419. userInput.clear();
  20420. userInput.sendKeys('');
  20421. expect(userType.getText()).toEqual('userType =');
  20422. expect(valid.getText()).toContain('false');
  20423. });
  20424. </file>
  20425. </example>
  20426. *
  20427. * @param {string=} name Name of the form. If specified, the form controller will be published into
  20428. * related scope, under this name.
  20429. */
  20430. var formDirectiveFactory = function(isNgForm) {
  20431. return ['$timeout', '$parse', function($timeout, $parse) {
  20432. var formDirective = {
  20433. name: 'form',
  20434. restrict: isNgForm ? 'EAC' : 'E',
  20435. require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
  20436. controller: FormController,
  20437. compile: function ngFormCompile(formElement, attr) {
  20438. // Setup initial state of the control
  20439. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  20440. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  20441. return {
  20442. pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
  20443. var controller = ctrls[0];
  20444. // if `action` attr is not present on the form, prevent the default action (submission)
  20445. if (!('action' in attr)) {
  20446. // we can't use jq events because if a form is destroyed during submission the default
  20447. // action is not prevented. see #1238
  20448. //
  20449. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  20450. // page reload if the form was destroyed by submission of the form via a click handler
  20451. // on a button in the form. Looks like an IE9 specific bug.
  20452. var handleFormSubmission = function(event) {
  20453. scope.$apply(function() {
  20454. controller.$commitViewValue();
  20455. controller.$setSubmitted();
  20456. });
  20457. event.preventDefault();
  20458. };
  20459. addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  20460. // unregister the preventDefault listener so that we don't not leak memory but in a
  20461. // way that will achieve the prevention of the default action.
  20462. formElement.on('$destroy', function() {
  20463. $timeout(function() {
  20464. removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  20465. }, 0, false);
  20466. });
  20467. }
  20468. var parentFormCtrl = ctrls[1] || controller.$$parentForm;
  20469. parentFormCtrl.$addControl(controller);
  20470. var setter = nameAttr ? getSetter(controller.$name) : noop;
  20471. if (nameAttr) {
  20472. setter(scope, controller);
  20473. attr.$observe(nameAttr, function(newValue) {
  20474. if (controller.$name === newValue) return;
  20475. setter(scope, undefined);
  20476. controller.$$parentForm.$$renameControl(controller, newValue);
  20477. setter = getSetter(controller.$name);
  20478. setter(scope, controller);
  20479. });
  20480. }
  20481. formElement.on('$destroy', function() {
  20482. controller.$$parentForm.$removeControl(controller);
  20483. setter(scope, undefined);
  20484. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  20485. });
  20486. }
  20487. };
  20488. }
  20489. };
  20490. return formDirective;
  20491. function getSetter(expression) {
  20492. if (expression === '') {
  20493. //create an assignable expression, so forms with an empty name can be renamed later
  20494. return $parse('this[""]').assign;
  20495. }
  20496. return $parse(expression).assign || noop;
  20497. }
  20498. }];
  20499. };
  20500. var formDirective = formDirectiveFactory();
  20501. var ngFormDirective = formDirectiveFactory(true);
  20502. /* global VALID_CLASS: false,
  20503. INVALID_CLASS: false,
  20504. PRISTINE_CLASS: false,
  20505. DIRTY_CLASS: false,
  20506. UNTOUCHED_CLASS: false,
  20507. TOUCHED_CLASS: false,
  20508. ngModelMinErr: false,
  20509. */
  20510. // Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  20511. 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)$/;
  20512. // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
  20513. // Note: We are being more lenient, because browsers are too.
  20514. // 1. Scheme
  20515. // 2. Slashes
  20516. // 3. Username
  20517. // 4. Password
  20518. // 5. Hostname
  20519. // 6. Port
  20520. // 7. Path
  20521. // 8. Query
  20522. // 9. Fragment
  20523. // 1111111111111111 222 333333 44444 555555555555555555555555 666 77777777 8888888 999
  20524. var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+\])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
  20525. /* jshint maxlen:220 */
  20526. var EMAIL_REGEXP = /^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+\/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+\/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
  20527. /* jshint maxlen:200 */
  20528. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
  20529. var DATE_REGEXP = /^(\d{4,})-(\d{2})-(\d{2})$/;
  20530. var DATETIMELOCAL_REGEXP = /^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  20531. var WEEK_REGEXP = /^(\d{4,})-W(\d\d)$/;
  20532. var MONTH_REGEXP = /^(\d{4,})-(\d\d)$/;
  20533. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  20534. var PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown';
  20535. var PARTIAL_VALIDATION_TYPES = createMap();
  20536. forEach('date,datetime-local,month,time,week'.split(','), function(type) {
  20537. PARTIAL_VALIDATION_TYPES[type] = true;
  20538. });
  20539. var inputType = {
  20540. /**
  20541. * @ngdoc input
  20542. * @name input[text]
  20543. *
  20544. * @description
  20545. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  20546. *
  20547. *
  20548. * @param {string} ngModel Assignable angular expression to data-bind to.
  20549. * @param {string=} name Property name of the form under which the control is published.
  20550. * @param {string=} required Adds `required` validation error key if the value is not entered.
  20551. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20552. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20553. * `required` when you want to data-bind to the `required` attribute.
  20554. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  20555. * minlength.
  20556. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  20557. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  20558. * any length.
  20559. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  20560. * that contains the regular expression body that will be converted to a regular expression
  20561. * as in the ngPattern directive.
  20562. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  20563. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  20564. * If the expression evaluates to a RegExp object, then this is used directly.
  20565. * If the expression evaluates to a string, then it will be converted to a RegExp
  20566. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  20567. * `new RegExp('^abc$')`.<br />
  20568. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  20569. * start at the index of the last search's match, thus not taking the whole input value into
  20570. * account.
  20571. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20572. * interaction with the input element.
  20573. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  20574. * This parameter is ignored for input[type=password] controls, which will never trim the
  20575. * input.
  20576. *
  20577. * @example
  20578. <example name="text-input-directive" module="textInputExample">
  20579. <file name="index.html">
  20580. <script>
  20581. angular.module('textInputExample', [])
  20582. .controller('ExampleController', ['$scope', function($scope) {
  20583. $scope.example = {
  20584. text: 'guest',
  20585. word: /^\s*\w*\s*$/
  20586. };
  20587. }]);
  20588. </script>
  20589. <form name="myForm" ng-controller="ExampleController">
  20590. <label>Single word:
  20591. <input type="text" name="input" ng-model="example.text"
  20592. ng-pattern="example.word" required ng-trim="false">
  20593. </label>
  20594. <div role="alert">
  20595. <span class="error" ng-show="myForm.input.$error.required">
  20596. Required!</span>
  20597. <span class="error" ng-show="myForm.input.$error.pattern">
  20598. Single word only!</span>
  20599. </div>
  20600. <code>text = {{example.text}}</code><br/>
  20601. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br/>
  20602. <code>myForm.input.$error = {{myForm.input.$error}}</code><br/>
  20603. <code>myForm.$valid = {{myForm.$valid}}</code><br/>
  20604. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br/>
  20605. </form>
  20606. </file>
  20607. <file name="protractor.js" type="protractor">
  20608. var text = element(by.binding('example.text'));
  20609. var valid = element(by.binding('myForm.input.$valid'));
  20610. var input = element(by.model('example.text'));
  20611. it('should initialize to model', function() {
  20612. expect(text.getText()).toContain('guest');
  20613. expect(valid.getText()).toContain('true');
  20614. });
  20615. it('should be invalid if empty', function() {
  20616. input.clear();
  20617. input.sendKeys('');
  20618. expect(text.getText()).toEqual('text =');
  20619. expect(valid.getText()).toContain('false');
  20620. });
  20621. it('should be invalid if multi word', function() {
  20622. input.clear();
  20623. input.sendKeys('hello world');
  20624. expect(valid.getText()).toContain('false');
  20625. });
  20626. </file>
  20627. </example>
  20628. */
  20629. 'text': textInputType,
  20630. /**
  20631. * @ngdoc input
  20632. * @name input[date]
  20633. *
  20634. * @description
  20635. * Input with date validation and transformation. In browsers that do not yet support
  20636. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  20637. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  20638. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  20639. * expected input format via a placeholder or label.
  20640. *
  20641. * The model must always be a Date object, otherwise Angular will throw an error.
  20642. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  20643. *
  20644. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  20645. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  20646. *
  20647. * @param {string} ngModel Assignable angular expression to data-bind to.
  20648. * @param {string=} name Property name of the form under which the control is published.
  20649. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  20650. * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  20651. * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
  20652. * constraint validation.
  20653. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  20654. * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  20655. * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
  20656. * constraint validation.
  20657. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
  20658. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  20659. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
  20660. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  20661. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20662. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20663. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20664. * `required` when you want to data-bind to the `required` attribute.
  20665. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20666. * interaction with the input element.
  20667. *
  20668. * @example
  20669. <example name="date-input-directive" module="dateInputExample">
  20670. <file name="index.html">
  20671. <script>
  20672. angular.module('dateInputExample', [])
  20673. .controller('DateController', ['$scope', function($scope) {
  20674. $scope.example = {
  20675. value: new Date(2013, 9, 22)
  20676. };
  20677. }]);
  20678. </script>
  20679. <form name="myForm" ng-controller="DateController as dateCtrl">
  20680. <label for="exampleInput">Pick a date in 2013:</label>
  20681. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  20682. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  20683. <div role="alert">
  20684. <span class="error" ng-show="myForm.input.$error.required">
  20685. Required!</span>
  20686. <span class="error" ng-show="myForm.input.$error.date">
  20687. Not a valid date!</span>
  20688. </div>
  20689. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  20690. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  20691. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  20692. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20693. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20694. </form>
  20695. </file>
  20696. <file name="protractor.js" type="protractor">
  20697. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  20698. var valid = element(by.binding('myForm.input.$valid'));
  20699. var input = element(by.model('example.value'));
  20700. // currently protractor/webdriver does not support
  20701. // sending keys to all known HTML5 input controls
  20702. // for various browsers (see https://github.com/angular/protractor/issues/562).
  20703. function setInput(val) {
  20704. // set the value of the element and force validation.
  20705. var scr = "var ipt = document.getElementById('exampleInput'); " +
  20706. "ipt.value = '" + val + "';" +
  20707. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  20708. browser.executeScript(scr);
  20709. }
  20710. it('should initialize to model', function() {
  20711. expect(value.getText()).toContain('2013-10-22');
  20712. expect(valid.getText()).toContain('myForm.input.$valid = true');
  20713. });
  20714. it('should be invalid if empty', function() {
  20715. setInput('');
  20716. expect(value.getText()).toEqual('value =');
  20717. expect(valid.getText()).toContain('myForm.input.$valid = false');
  20718. });
  20719. it('should be invalid if over max', function() {
  20720. setInput('2015-01-01');
  20721. expect(value.getText()).toContain('');
  20722. expect(valid.getText()).toContain('myForm.input.$valid = false');
  20723. });
  20724. </file>
  20725. </example>
  20726. */
  20727. 'date': createDateInputType('date', DATE_REGEXP,
  20728. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  20729. 'yyyy-MM-dd'),
  20730. /**
  20731. * @ngdoc input
  20732. * @name input[datetime-local]
  20733. *
  20734. * @description
  20735. * Input with datetime validation and transformation. In browsers that do not yet support
  20736. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  20737. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  20738. *
  20739. * The model must always be a Date object, otherwise Angular will throw an error.
  20740. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  20741. *
  20742. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  20743. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  20744. *
  20745. * @param {string} ngModel Assignable angular expression to data-bind to.
  20746. * @param {string=} name Property name of the form under which the control is published.
  20747. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  20748. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  20749. * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  20750. * Note that `min` will also add native HTML5 constraint validation.
  20751. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  20752. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  20753. * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  20754. * Note that `max` will also add native HTML5 constraint validation.
  20755. * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
  20756. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  20757. * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
  20758. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  20759. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20760. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20761. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20762. * `required` when you want to data-bind to the `required` attribute.
  20763. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20764. * interaction with the input element.
  20765. *
  20766. * @example
  20767. <example name="datetimelocal-input-directive" module="dateExample">
  20768. <file name="index.html">
  20769. <script>
  20770. angular.module('dateExample', [])
  20771. .controller('DateController', ['$scope', function($scope) {
  20772. $scope.example = {
  20773. value: new Date(2010, 11, 28, 14, 57)
  20774. };
  20775. }]);
  20776. </script>
  20777. <form name="myForm" ng-controller="DateController as dateCtrl">
  20778. <label for="exampleInput">Pick a date between in 2013:</label>
  20779. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  20780. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  20781. <div role="alert">
  20782. <span class="error" ng-show="myForm.input.$error.required">
  20783. Required!</span>
  20784. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  20785. Not a valid date!</span>
  20786. </div>
  20787. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  20788. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  20789. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  20790. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20791. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20792. </form>
  20793. </file>
  20794. <file name="protractor.js" type="protractor">
  20795. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  20796. var valid = element(by.binding('myForm.input.$valid'));
  20797. var input = element(by.model('example.value'));
  20798. // currently protractor/webdriver does not support
  20799. // sending keys to all known HTML5 input controls
  20800. // for various browsers (https://github.com/angular/protractor/issues/562).
  20801. function setInput(val) {
  20802. // set the value of the element and force validation.
  20803. var scr = "var ipt = document.getElementById('exampleInput'); " +
  20804. "ipt.value = '" + val + "';" +
  20805. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  20806. browser.executeScript(scr);
  20807. }
  20808. it('should initialize to model', function() {
  20809. expect(value.getText()).toContain('2010-12-28T14:57:00');
  20810. expect(valid.getText()).toContain('myForm.input.$valid = true');
  20811. });
  20812. it('should be invalid if empty', function() {
  20813. setInput('');
  20814. expect(value.getText()).toEqual('value =');
  20815. expect(valid.getText()).toContain('myForm.input.$valid = false');
  20816. });
  20817. it('should be invalid if over max', function() {
  20818. setInput('2015-01-01T23:59:00');
  20819. expect(value.getText()).toContain('');
  20820. expect(valid.getText()).toContain('myForm.input.$valid = false');
  20821. });
  20822. </file>
  20823. </example>
  20824. */
  20825. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  20826. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  20827. 'yyyy-MM-ddTHH:mm:ss.sss'),
  20828. /**
  20829. * @ngdoc input
  20830. * @name input[time]
  20831. *
  20832. * @description
  20833. * Input with time validation and transformation. In browsers that do not yet support
  20834. * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  20835. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  20836. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  20837. *
  20838. * The model must always be a Date object, otherwise Angular will throw an error.
  20839. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  20840. *
  20841. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  20842. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  20843. *
  20844. * @param {string} ngModel Assignable angular expression to data-bind to.
  20845. * @param {string=} name Property name of the form under which the control is published.
  20846. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  20847. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  20848. * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
  20849. * native HTML5 constraint validation.
  20850. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  20851. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  20852. * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
  20853. * native HTML5 constraint validation.
  20854. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
  20855. * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  20856. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
  20857. * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  20858. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20859. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20860. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20861. * `required` when you want to data-bind to the `required` attribute.
  20862. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20863. * interaction with the input element.
  20864. *
  20865. * @example
  20866. <example name="time-input-directive" module="timeExample">
  20867. <file name="index.html">
  20868. <script>
  20869. angular.module('timeExample', [])
  20870. .controller('DateController', ['$scope', function($scope) {
  20871. $scope.example = {
  20872. value: new Date(1970, 0, 1, 14, 57, 0)
  20873. };
  20874. }]);
  20875. </script>
  20876. <form name="myForm" ng-controller="DateController as dateCtrl">
  20877. <label for="exampleInput">Pick a time between 8am and 5pm:</label>
  20878. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  20879. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  20880. <div role="alert">
  20881. <span class="error" ng-show="myForm.input.$error.required">
  20882. Required!</span>
  20883. <span class="error" ng-show="myForm.input.$error.time">
  20884. Not a valid date!</span>
  20885. </div>
  20886. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  20887. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  20888. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  20889. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20890. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20891. </form>
  20892. </file>
  20893. <file name="protractor.js" type="protractor">
  20894. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  20895. var valid = element(by.binding('myForm.input.$valid'));
  20896. var input = element(by.model('example.value'));
  20897. // currently protractor/webdriver does not support
  20898. // sending keys to all known HTML5 input controls
  20899. // for various browsers (https://github.com/angular/protractor/issues/562).
  20900. function setInput(val) {
  20901. // set the value of the element and force validation.
  20902. var scr = "var ipt = document.getElementById('exampleInput'); " +
  20903. "ipt.value = '" + val + "';" +
  20904. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  20905. browser.executeScript(scr);
  20906. }
  20907. it('should initialize to model', function() {
  20908. expect(value.getText()).toContain('14:57:00');
  20909. expect(valid.getText()).toContain('myForm.input.$valid = true');
  20910. });
  20911. it('should be invalid if empty', function() {
  20912. setInput('');
  20913. expect(value.getText()).toEqual('value =');
  20914. expect(valid.getText()).toContain('myForm.input.$valid = false');
  20915. });
  20916. it('should be invalid if over max', function() {
  20917. setInput('23:59:00');
  20918. expect(value.getText()).toContain('');
  20919. expect(valid.getText()).toContain('myForm.input.$valid = false');
  20920. });
  20921. </file>
  20922. </example>
  20923. */
  20924. 'time': createDateInputType('time', TIME_REGEXP,
  20925. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  20926. 'HH:mm:ss.sss'),
  20927. /**
  20928. * @ngdoc input
  20929. * @name input[week]
  20930. *
  20931. * @description
  20932. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  20933. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  20934. * week format (yyyy-W##), for example: `2013-W02`.
  20935. *
  20936. * The model must always be a Date object, otherwise Angular will throw an error.
  20937. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  20938. *
  20939. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  20940. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  20941. *
  20942. * @param {string} ngModel Assignable angular expression to data-bind to.
  20943. * @param {string=} name Property name of the form under which the control is published.
  20944. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  20945. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  20946. * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
  20947. * native HTML5 constraint validation.
  20948. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  20949. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  20950. * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
  20951. * native HTML5 constraint validation.
  20952. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  20953. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  20954. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  20955. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  20956. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20957. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20958. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20959. * `required` when you want to data-bind to the `required` attribute.
  20960. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20961. * interaction with the input element.
  20962. *
  20963. * @example
  20964. <example name="week-input-directive" module="weekExample">
  20965. <file name="index.html">
  20966. <script>
  20967. angular.module('weekExample', [])
  20968. .controller('DateController', ['$scope', function($scope) {
  20969. $scope.example = {
  20970. value: new Date(2013, 0, 3)
  20971. };
  20972. }]);
  20973. </script>
  20974. <form name="myForm" ng-controller="DateController as dateCtrl">
  20975. <label>Pick a date between in 2013:
  20976. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  20977. placeholder="YYYY-W##" min="2012-W32"
  20978. max="2013-W52" required />
  20979. </label>
  20980. <div role="alert">
  20981. <span class="error" ng-show="myForm.input.$error.required">
  20982. Required!</span>
  20983. <span class="error" ng-show="myForm.input.$error.week">
  20984. Not a valid date!</span>
  20985. </div>
  20986. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  20987. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  20988. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  20989. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20990. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20991. </form>
  20992. </file>
  20993. <file name="protractor.js" type="protractor">
  20994. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  20995. var valid = element(by.binding('myForm.input.$valid'));
  20996. var input = element(by.model('example.value'));
  20997. // currently protractor/webdriver does not support
  20998. // sending keys to all known HTML5 input controls
  20999. // for various browsers (https://github.com/angular/protractor/issues/562).
  21000. function setInput(val) {
  21001. // set the value of the element and force validation.
  21002. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21003. "ipt.value = '" + val + "';" +
  21004. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21005. browser.executeScript(scr);
  21006. }
  21007. it('should initialize to model', function() {
  21008. expect(value.getText()).toContain('2013-W01');
  21009. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21010. });
  21011. it('should be invalid if empty', function() {
  21012. setInput('');
  21013. expect(value.getText()).toEqual('value =');
  21014. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21015. });
  21016. it('should be invalid if over max', function() {
  21017. setInput('2015-W01');
  21018. expect(value.getText()).toContain('');
  21019. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21020. });
  21021. </file>
  21022. </example>
  21023. */
  21024. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  21025. /**
  21026. * @ngdoc input
  21027. * @name input[month]
  21028. *
  21029. * @description
  21030. * Input with month validation and transformation. In browsers that do not yet support
  21031. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  21032. * month format (yyyy-MM), for example: `2009-01`.
  21033. *
  21034. * The model must always be a Date object, otherwise Angular will throw an error.
  21035. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  21036. * If the model is not set to the first of the month, the next view to model update will set it
  21037. * to the first of the month.
  21038. *
  21039. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  21040. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  21041. *
  21042. * @param {string} ngModel Assignable angular expression to data-bind to.
  21043. * @param {string=} name Property name of the form under which the control is published.
  21044. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21045. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  21046. * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
  21047. * native HTML5 constraint validation.
  21048. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21049. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  21050. * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
  21051. * native HTML5 constraint validation.
  21052. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  21053. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  21054. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  21055. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  21056. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21057. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21058. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21059. * `required` when you want to data-bind to the `required` attribute.
  21060. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21061. * interaction with the input element.
  21062. *
  21063. * @example
  21064. <example name="month-input-directive" module="monthExample">
  21065. <file name="index.html">
  21066. <script>
  21067. angular.module('monthExample', [])
  21068. .controller('DateController', ['$scope', function($scope) {
  21069. $scope.example = {
  21070. value: new Date(2013, 9, 1)
  21071. };
  21072. }]);
  21073. </script>
  21074. <form name="myForm" ng-controller="DateController as dateCtrl">
  21075. <label for="exampleInput">Pick a month in 2013:</label>
  21076. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  21077. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  21078. <div role="alert">
  21079. <span class="error" ng-show="myForm.input.$error.required">
  21080. Required!</span>
  21081. <span class="error" ng-show="myForm.input.$error.month">
  21082. Not a valid month!</span>
  21083. </div>
  21084. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  21085. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21086. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21087. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21088. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21089. </form>
  21090. </file>
  21091. <file name="protractor.js" type="protractor">
  21092. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  21093. var valid = element(by.binding('myForm.input.$valid'));
  21094. var input = element(by.model('example.value'));
  21095. // currently protractor/webdriver does not support
  21096. // sending keys to all known HTML5 input controls
  21097. // for various browsers (https://github.com/angular/protractor/issues/562).
  21098. function setInput(val) {
  21099. // set the value of the element and force validation.
  21100. var scr = "var ipt = document.getElementById('exampleInput'); " +
  21101. "ipt.value = '" + val + "';" +
  21102. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  21103. browser.executeScript(scr);
  21104. }
  21105. it('should initialize to model', function() {
  21106. expect(value.getText()).toContain('2013-10');
  21107. expect(valid.getText()).toContain('myForm.input.$valid = true');
  21108. });
  21109. it('should be invalid if empty', function() {
  21110. setInput('');
  21111. expect(value.getText()).toEqual('value =');
  21112. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21113. });
  21114. it('should be invalid if over max', function() {
  21115. setInput('2015-01');
  21116. expect(value.getText()).toContain('');
  21117. expect(valid.getText()).toContain('myForm.input.$valid = false');
  21118. });
  21119. </file>
  21120. </example>
  21121. */
  21122. 'month': createDateInputType('month', MONTH_REGEXP,
  21123. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  21124. 'yyyy-MM'),
  21125. /**
  21126. * @ngdoc input
  21127. * @name input[number]
  21128. *
  21129. * @description
  21130. * Text input with number validation and transformation. Sets the `number` validation
  21131. * error if not a valid number.
  21132. *
  21133. * <div class="alert alert-warning">
  21134. * The model must always be of type `number` otherwise Angular will throw an error.
  21135. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  21136. * error docs for more information and an example of how to convert your model if necessary.
  21137. * </div>
  21138. *
  21139. * ## Issues with HTML5 constraint validation
  21140. *
  21141. * In browsers that follow the
  21142. * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
  21143. * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
  21144. * If a non-number is entered in the input, the browser will report the value as an empty string,
  21145. * which means the view / model values in `ngModel` and subsequently the scope value
  21146. * will also be an empty string.
  21147. *
  21148. *
  21149. * @param {string} ngModel Assignable angular expression to data-bind to.
  21150. * @param {string=} name Property name of the form under which the control is published.
  21151. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  21152. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  21153. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21154. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21155. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21156. * `required` when you want to data-bind to the `required` attribute.
  21157. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21158. * minlength.
  21159. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21160. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  21161. * any length.
  21162. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  21163. * that contains the regular expression body that will be converted to a regular expression
  21164. * as in the ngPattern directive.
  21165. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21166. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21167. * If the expression evaluates to a RegExp object, then this is used directly.
  21168. * If the expression evaluates to a string, then it will be converted to a RegExp
  21169. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21170. * `new RegExp('^abc$')`.<br />
  21171. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21172. * start at the index of the last search's match, thus not taking the whole input value into
  21173. * account.
  21174. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21175. * interaction with the input element.
  21176. *
  21177. * @example
  21178. <example name="number-input-directive" module="numberExample">
  21179. <file name="index.html">
  21180. <script>
  21181. angular.module('numberExample', [])
  21182. .controller('ExampleController', ['$scope', function($scope) {
  21183. $scope.example = {
  21184. value: 12
  21185. };
  21186. }]);
  21187. </script>
  21188. <form name="myForm" ng-controller="ExampleController">
  21189. <label>Number:
  21190. <input type="number" name="input" ng-model="example.value"
  21191. min="0" max="99" required>
  21192. </label>
  21193. <div role="alert">
  21194. <span class="error" ng-show="myForm.input.$error.required">
  21195. Required!</span>
  21196. <span class="error" ng-show="myForm.input.$error.number">
  21197. Not valid number!</span>
  21198. </div>
  21199. <tt>value = {{example.value}}</tt><br/>
  21200. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21201. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21202. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21203. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21204. </form>
  21205. </file>
  21206. <file name="protractor.js" type="protractor">
  21207. var value = element(by.binding('example.value'));
  21208. var valid = element(by.binding('myForm.input.$valid'));
  21209. var input = element(by.model('example.value'));
  21210. it('should initialize to model', function() {
  21211. expect(value.getText()).toContain('12');
  21212. expect(valid.getText()).toContain('true');
  21213. });
  21214. it('should be invalid if empty', function() {
  21215. input.clear();
  21216. input.sendKeys('');
  21217. expect(value.getText()).toEqual('value =');
  21218. expect(valid.getText()).toContain('false');
  21219. });
  21220. it('should be invalid if over max', function() {
  21221. input.clear();
  21222. input.sendKeys('123');
  21223. expect(value.getText()).toEqual('value =');
  21224. expect(valid.getText()).toContain('false');
  21225. });
  21226. </file>
  21227. </example>
  21228. */
  21229. 'number': numberInputType,
  21230. /**
  21231. * @ngdoc input
  21232. * @name input[url]
  21233. *
  21234. * @description
  21235. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  21236. * valid URL.
  21237. *
  21238. * <div class="alert alert-warning">
  21239. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  21240. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  21241. * the built-in validators (see the {@link guide/forms Forms guide})
  21242. * </div>
  21243. *
  21244. * @param {string} ngModel Assignable angular expression to data-bind to.
  21245. * @param {string=} name Property name of the form under which the control is published.
  21246. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21247. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21248. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21249. * `required` when you want to data-bind to the `required` attribute.
  21250. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21251. * minlength.
  21252. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21253. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  21254. * any length.
  21255. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  21256. * that contains the regular expression body that will be converted to a regular expression
  21257. * as in the ngPattern directive.
  21258. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21259. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21260. * If the expression evaluates to a RegExp object, then this is used directly.
  21261. * If the expression evaluates to a string, then it will be converted to a RegExp
  21262. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21263. * `new RegExp('^abc$')`.<br />
  21264. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21265. * start at the index of the last search's match, thus not taking the whole input value into
  21266. * account.
  21267. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21268. * interaction with the input element.
  21269. *
  21270. * @example
  21271. <example name="url-input-directive" module="urlExample">
  21272. <file name="index.html">
  21273. <script>
  21274. angular.module('urlExample', [])
  21275. .controller('ExampleController', ['$scope', function($scope) {
  21276. $scope.url = {
  21277. text: 'http://google.com'
  21278. };
  21279. }]);
  21280. </script>
  21281. <form name="myForm" ng-controller="ExampleController">
  21282. <label>URL:
  21283. <input type="url" name="input" ng-model="url.text" required>
  21284. <label>
  21285. <div role="alert">
  21286. <span class="error" ng-show="myForm.input.$error.required">
  21287. Required!</span>
  21288. <span class="error" ng-show="myForm.input.$error.url">
  21289. Not valid url!</span>
  21290. </div>
  21291. <tt>text = {{url.text}}</tt><br/>
  21292. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21293. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21294. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21295. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21296. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  21297. </form>
  21298. </file>
  21299. <file name="protractor.js" type="protractor">
  21300. var text = element(by.binding('url.text'));
  21301. var valid = element(by.binding('myForm.input.$valid'));
  21302. var input = element(by.model('url.text'));
  21303. it('should initialize to model', function() {
  21304. expect(text.getText()).toContain('http://google.com');
  21305. expect(valid.getText()).toContain('true');
  21306. });
  21307. it('should be invalid if empty', function() {
  21308. input.clear();
  21309. input.sendKeys('');
  21310. expect(text.getText()).toEqual('text =');
  21311. expect(valid.getText()).toContain('false');
  21312. });
  21313. it('should be invalid if not url', function() {
  21314. input.clear();
  21315. input.sendKeys('box');
  21316. expect(valid.getText()).toContain('false');
  21317. });
  21318. </file>
  21319. </example>
  21320. */
  21321. 'url': urlInputType,
  21322. /**
  21323. * @ngdoc input
  21324. * @name input[email]
  21325. *
  21326. * @description
  21327. * Text input with email validation. Sets the `email` validation error key if not a valid email
  21328. * address.
  21329. *
  21330. * <div class="alert alert-warning">
  21331. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  21332. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  21333. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  21334. * </div>
  21335. *
  21336. * @param {string} ngModel Assignable angular expression to data-bind to.
  21337. * @param {string=} name Property name of the form under which the control is published.
  21338. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21339. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21340. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21341. * `required` when you want to data-bind to the `required` attribute.
  21342. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21343. * minlength.
  21344. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21345. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  21346. * any length.
  21347. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  21348. * that contains the regular expression body that will be converted to a regular expression
  21349. * as in the ngPattern directive.
  21350. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21351. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21352. * If the expression evaluates to a RegExp object, then this is used directly.
  21353. * If the expression evaluates to a string, then it will be converted to a RegExp
  21354. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21355. * `new RegExp('^abc$')`.<br />
  21356. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21357. * start at the index of the last search's match, thus not taking the whole input value into
  21358. * account.
  21359. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21360. * interaction with the input element.
  21361. *
  21362. * @example
  21363. <example name="email-input-directive" module="emailExample">
  21364. <file name="index.html">
  21365. <script>
  21366. angular.module('emailExample', [])
  21367. .controller('ExampleController', ['$scope', function($scope) {
  21368. $scope.email = {
  21369. text: 'me@example.com'
  21370. };
  21371. }]);
  21372. </script>
  21373. <form name="myForm" ng-controller="ExampleController">
  21374. <label>Email:
  21375. <input type="email" name="input" ng-model="email.text" required>
  21376. </label>
  21377. <div role="alert">
  21378. <span class="error" ng-show="myForm.input.$error.required">
  21379. Required!</span>
  21380. <span class="error" ng-show="myForm.input.$error.email">
  21381. Not valid email!</span>
  21382. </div>
  21383. <tt>text = {{email.text}}</tt><br/>
  21384. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  21385. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  21386. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  21387. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  21388. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  21389. </form>
  21390. </file>
  21391. <file name="protractor.js" type="protractor">
  21392. var text = element(by.binding('email.text'));
  21393. var valid = element(by.binding('myForm.input.$valid'));
  21394. var input = element(by.model('email.text'));
  21395. it('should initialize to model', function() {
  21396. expect(text.getText()).toContain('me@example.com');
  21397. expect(valid.getText()).toContain('true');
  21398. });
  21399. it('should be invalid if empty', function() {
  21400. input.clear();
  21401. input.sendKeys('');
  21402. expect(text.getText()).toEqual('text =');
  21403. expect(valid.getText()).toContain('false');
  21404. });
  21405. it('should be invalid if not email', function() {
  21406. input.clear();
  21407. input.sendKeys('xxx');
  21408. expect(valid.getText()).toContain('false');
  21409. });
  21410. </file>
  21411. </example>
  21412. */
  21413. 'email': emailInputType,
  21414. /**
  21415. * @ngdoc input
  21416. * @name input[radio]
  21417. *
  21418. * @description
  21419. * HTML radio button.
  21420. *
  21421. * @param {string} ngModel Assignable angular expression to data-bind to.
  21422. * @param {string} value The value to which the `ngModel` expression should be set when selected.
  21423. * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
  21424. * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
  21425. * @param {string=} name Property name of the form under which the control is published.
  21426. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21427. * interaction with the input element.
  21428. * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
  21429. * is selected. Should be used instead of the `value` attribute if you need
  21430. * a non-string `ngModel` (`boolean`, `array`, ...).
  21431. *
  21432. * @example
  21433. <example name="radio-input-directive" module="radioExample">
  21434. <file name="index.html">
  21435. <script>
  21436. angular.module('radioExample', [])
  21437. .controller('ExampleController', ['$scope', function($scope) {
  21438. $scope.color = {
  21439. name: 'blue'
  21440. };
  21441. $scope.specialValue = {
  21442. "id": "12345",
  21443. "value": "green"
  21444. };
  21445. }]);
  21446. </script>
  21447. <form name="myForm" ng-controller="ExampleController">
  21448. <label>
  21449. <input type="radio" ng-model="color.name" value="red">
  21450. Red
  21451. </label><br/>
  21452. <label>
  21453. <input type="radio" ng-model="color.name" ng-value="specialValue">
  21454. Green
  21455. </label><br/>
  21456. <label>
  21457. <input type="radio" ng-model="color.name" value="blue">
  21458. Blue
  21459. </label><br/>
  21460. <tt>color = {{color.name | json}}</tt><br/>
  21461. </form>
  21462. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  21463. </file>
  21464. <file name="protractor.js" type="protractor">
  21465. it('should change state', function() {
  21466. var color = element(by.binding('color.name'));
  21467. expect(color.getText()).toContain('blue');
  21468. element.all(by.model('color.name')).get(0).click();
  21469. expect(color.getText()).toContain('red');
  21470. });
  21471. </file>
  21472. </example>
  21473. */
  21474. 'radio': radioInputType,
  21475. /**
  21476. * @ngdoc input
  21477. * @name input[checkbox]
  21478. *
  21479. * @description
  21480. * HTML checkbox.
  21481. *
  21482. * @param {string} ngModel Assignable angular expression to data-bind to.
  21483. * @param {string=} name Property name of the form under which the control is published.
  21484. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  21485. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  21486. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21487. * interaction with the input element.
  21488. *
  21489. * @example
  21490. <example name="checkbox-input-directive" module="checkboxExample">
  21491. <file name="index.html">
  21492. <script>
  21493. angular.module('checkboxExample', [])
  21494. .controller('ExampleController', ['$scope', function($scope) {
  21495. $scope.checkboxModel = {
  21496. value1 : true,
  21497. value2 : 'YES'
  21498. };
  21499. }]);
  21500. </script>
  21501. <form name="myForm" ng-controller="ExampleController">
  21502. <label>Value1:
  21503. <input type="checkbox" ng-model="checkboxModel.value1">
  21504. </label><br/>
  21505. <label>Value2:
  21506. <input type="checkbox" ng-model="checkboxModel.value2"
  21507. ng-true-value="'YES'" ng-false-value="'NO'">
  21508. </label><br/>
  21509. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  21510. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  21511. </form>
  21512. </file>
  21513. <file name="protractor.js" type="protractor">
  21514. it('should change state', function() {
  21515. var value1 = element(by.binding('checkboxModel.value1'));
  21516. var value2 = element(by.binding('checkboxModel.value2'));
  21517. expect(value1.getText()).toContain('true');
  21518. expect(value2.getText()).toContain('YES');
  21519. element(by.model('checkboxModel.value1')).click();
  21520. element(by.model('checkboxModel.value2')).click();
  21521. expect(value1.getText()).toContain('false');
  21522. expect(value2.getText()).toContain('NO');
  21523. });
  21524. </file>
  21525. </example>
  21526. */
  21527. 'checkbox': checkboxInputType,
  21528. 'hidden': noop,
  21529. 'button': noop,
  21530. 'submit': noop,
  21531. 'reset': noop,
  21532. 'file': noop
  21533. };
  21534. function stringBasedInputType(ctrl) {
  21535. ctrl.$formatters.push(function(value) {
  21536. return ctrl.$isEmpty(value) ? value : value.toString();
  21537. });
  21538. }
  21539. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  21540. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  21541. stringBasedInputType(ctrl);
  21542. }
  21543. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  21544. var type = lowercase(element[0].type);
  21545. // In composition mode, users are still inputing intermediate text buffer,
  21546. // hold the listener until composition is done.
  21547. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  21548. if (!$sniffer.android) {
  21549. var composing = false;
  21550. element.on('compositionstart', function() {
  21551. composing = true;
  21552. });
  21553. element.on('compositionend', function() {
  21554. composing = false;
  21555. listener();
  21556. });
  21557. }
  21558. var timeout;
  21559. var listener = function(ev) {
  21560. if (timeout) {
  21561. $browser.defer.cancel(timeout);
  21562. timeout = null;
  21563. }
  21564. if (composing) return;
  21565. var value = element.val(),
  21566. event = ev && ev.type;
  21567. // By default we will trim the value
  21568. // If the attribute ng-trim exists we will avoid trimming
  21569. // If input type is 'password', the value is never trimmed
  21570. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  21571. value = trim(value);
  21572. }
  21573. // If a control is suffering from bad input (due to native validators), browsers discard its
  21574. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  21575. // control's value is the same empty value twice in a row.
  21576. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  21577. ctrl.$setViewValue(value, event);
  21578. }
  21579. };
  21580. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  21581. // input event on backspace, delete or cut
  21582. if ($sniffer.hasEvent('input')) {
  21583. element.on('input', listener);
  21584. } else {
  21585. var deferListener = function(ev, input, origValue) {
  21586. if (!timeout) {
  21587. timeout = $browser.defer(function() {
  21588. timeout = null;
  21589. if (!input || input.value !== origValue) {
  21590. listener(ev);
  21591. }
  21592. });
  21593. }
  21594. };
  21595. element.on('keydown', function(event) {
  21596. var key = event.keyCode;
  21597. // ignore
  21598. // command modifiers arrows
  21599. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  21600. deferListener(event, this, this.value);
  21601. });
  21602. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  21603. if ($sniffer.hasEvent('paste')) {
  21604. element.on('paste cut', deferListener);
  21605. }
  21606. }
  21607. // if user paste into input using mouse on older browser
  21608. // or form autocomplete on newer browser, we need "change" event to catch it
  21609. element.on('change', listener);
  21610. // Some native input types (date-family) have the ability to change validity without
  21611. // firing any input/change events.
  21612. // For these event types, when native validators are present and the browser supports the type,
  21613. // check for validity changes on various DOM events.
  21614. if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) {
  21615. element.on(PARTIAL_VALIDATION_EVENTS, function(ev) {
  21616. if (!timeout) {
  21617. var validity = this[VALIDITY_STATE_PROPERTY];
  21618. var origBadInput = validity.badInput;
  21619. var origTypeMismatch = validity.typeMismatch;
  21620. timeout = $browser.defer(function() {
  21621. timeout = null;
  21622. if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) {
  21623. listener(ev);
  21624. }
  21625. });
  21626. }
  21627. });
  21628. }
  21629. ctrl.$render = function() {
  21630. // Workaround for Firefox validation #12102.
  21631. var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
  21632. if (element.val() !== value) {
  21633. element.val(value);
  21634. }
  21635. };
  21636. }
  21637. function weekParser(isoWeek, existingDate) {
  21638. if (isDate(isoWeek)) {
  21639. return isoWeek;
  21640. }
  21641. if (isString(isoWeek)) {
  21642. WEEK_REGEXP.lastIndex = 0;
  21643. var parts = WEEK_REGEXP.exec(isoWeek);
  21644. if (parts) {
  21645. var year = +parts[1],
  21646. week = +parts[2],
  21647. hours = 0,
  21648. minutes = 0,
  21649. seconds = 0,
  21650. milliseconds = 0,
  21651. firstThurs = getFirstThursdayOfYear(year),
  21652. addDays = (week - 1) * 7;
  21653. if (existingDate) {
  21654. hours = existingDate.getHours();
  21655. minutes = existingDate.getMinutes();
  21656. seconds = existingDate.getSeconds();
  21657. milliseconds = existingDate.getMilliseconds();
  21658. }
  21659. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  21660. }
  21661. }
  21662. return NaN;
  21663. }
  21664. function createDateParser(regexp, mapping) {
  21665. return function(iso, date) {
  21666. var parts, map;
  21667. if (isDate(iso)) {
  21668. return iso;
  21669. }
  21670. if (isString(iso)) {
  21671. // When a date is JSON'ified to wraps itself inside of an extra
  21672. // set of double quotes. This makes the date parsing code unable
  21673. // to match the date string and parse it as a date.
  21674. if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
  21675. iso = iso.substring(1, iso.length - 1);
  21676. }
  21677. if (ISO_DATE_REGEXP.test(iso)) {
  21678. return new Date(iso);
  21679. }
  21680. regexp.lastIndex = 0;
  21681. parts = regexp.exec(iso);
  21682. if (parts) {
  21683. parts.shift();
  21684. if (date) {
  21685. map = {
  21686. yyyy: date.getFullYear(),
  21687. MM: date.getMonth() + 1,
  21688. dd: date.getDate(),
  21689. HH: date.getHours(),
  21690. mm: date.getMinutes(),
  21691. ss: date.getSeconds(),
  21692. sss: date.getMilliseconds() / 1000
  21693. };
  21694. } else {
  21695. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  21696. }
  21697. forEach(parts, function(part, index) {
  21698. if (index < mapping.length) {
  21699. map[mapping[index]] = +part;
  21700. }
  21701. });
  21702. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  21703. }
  21704. }
  21705. return NaN;
  21706. };
  21707. }
  21708. function createDateInputType(type, regexp, parseDate, format) {
  21709. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  21710. badInputChecker(scope, element, attr, ctrl);
  21711. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  21712. var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
  21713. var previousDate;
  21714. ctrl.$$parserName = type;
  21715. ctrl.$parsers.push(function(value) {
  21716. if (ctrl.$isEmpty(value)) return null;
  21717. if (regexp.test(value)) {
  21718. // Note: We cannot read ctrl.$modelValue, as there might be a different
  21719. // parser/formatter in the processing chain so that the model
  21720. // contains some different data format!
  21721. var parsedDate = parseDate(value, previousDate);
  21722. if (timezone) {
  21723. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  21724. }
  21725. return parsedDate;
  21726. }
  21727. return undefined;
  21728. });
  21729. ctrl.$formatters.push(function(value) {
  21730. if (value && !isDate(value)) {
  21731. throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  21732. }
  21733. if (isValidDate(value)) {
  21734. previousDate = value;
  21735. if (previousDate && timezone) {
  21736. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  21737. }
  21738. return $filter('date')(value, format, timezone);
  21739. } else {
  21740. previousDate = null;
  21741. return '';
  21742. }
  21743. });
  21744. if (isDefined(attr.min) || attr.ngMin) {
  21745. var minVal;
  21746. ctrl.$validators.min = function(value) {
  21747. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  21748. };
  21749. attr.$observe('min', function(val) {
  21750. minVal = parseObservedDateValue(val);
  21751. ctrl.$validate();
  21752. });
  21753. }
  21754. if (isDefined(attr.max) || attr.ngMax) {
  21755. var maxVal;
  21756. ctrl.$validators.max = function(value) {
  21757. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  21758. };
  21759. attr.$observe('max', function(val) {
  21760. maxVal = parseObservedDateValue(val);
  21761. ctrl.$validate();
  21762. });
  21763. }
  21764. function isValidDate(value) {
  21765. // Invalid Date: getTime() returns NaN
  21766. return value && !(value.getTime && value.getTime() !== value.getTime());
  21767. }
  21768. function parseObservedDateValue(val) {
  21769. return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
  21770. }
  21771. };
  21772. }
  21773. function badInputChecker(scope, element, attr, ctrl) {
  21774. var node = element[0];
  21775. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  21776. if (nativeValidation) {
  21777. ctrl.$parsers.push(function(value) {
  21778. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  21779. return validity.badInput || validity.typeMismatch ? undefined : value;
  21780. });
  21781. }
  21782. }
  21783. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  21784. badInputChecker(scope, element, attr, ctrl);
  21785. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  21786. ctrl.$$parserName = 'number';
  21787. ctrl.$parsers.push(function(value) {
  21788. if (ctrl.$isEmpty(value)) return null;
  21789. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  21790. return undefined;
  21791. });
  21792. ctrl.$formatters.push(function(value) {
  21793. if (!ctrl.$isEmpty(value)) {
  21794. if (!isNumber(value)) {
  21795. throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  21796. }
  21797. value = value.toString();
  21798. }
  21799. return value;
  21800. });
  21801. if (isDefined(attr.min) || attr.ngMin) {
  21802. var minVal;
  21803. ctrl.$validators.min = function(value) {
  21804. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  21805. };
  21806. attr.$observe('min', function(val) {
  21807. if (isDefined(val) && !isNumber(val)) {
  21808. val = parseFloat(val, 10);
  21809. }
  21810. minVal = isNumber(val) && !isNaN(val) ? val : undefined;
  21811. // TODO(matsko): implement validateLater to reduce number of validations
  21812. ctrl.$validate();
  21813. });
  21814. }
  21815. if (isDefined(attr.max) || attr.ngMax) {
  21816. var maxVal;
  21817. ctrl.$validators.max = function(value) {
  21818. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  21819. };
  21820. attr.$observe('max', function(val) {
  21821. if (isDefined(val) && !isNumber(val)) {
  21822. val = parseFloat(val, 10);
  21823. }
  21824. maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
  21825. // TODO(matsko): implement validateLater to reduce number of validations
  21826. ctrl.$validate();
  21827. });
  21828. }
  21829. }
  21830. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  21831. // Note: no badInputChecker here by purpose as `url` is only a validation
  21832. // in browsers, i.e. we can always read out input.value even if it is not valid!
  21833. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  21834. stringBasedInputType(ctrl);
  21835. ctrl.$$parserName = 'url';
  21836. ctrl.$validators.url = function(modelValue, viewValue) {
  21837. var value = modelValue || viewValue;
  21838. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  21839. };
  21840. }
  21841. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  21842. // Note: no badInputChecker here by purpose as `url` is only a validation
  21843. // in browsers, i.e. we can always read out input.value even if it is not valid!
  21844. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  21845. stringBasedInputType(ctrl);
  21846. ctrl.$$parserName = 'email';
  21847. ctrl.$validators.email = function(modelValue, viewValue) {
  21848. var value = modelValue || viewValue;
  21849. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  21850. };
  21851. }
  21852. function radioInputType(scope, element, attr, ctrl) {
  21853. // make the name unique, if not defined
  21854. if (isUndefined(attr.name)) {
  21855. element.attr('name', nextUid());
  21856. }
  21857. var listener = function(ev) {
  21858. if (element[0].checked) {
  21859. ctrl.$setViewValue(attr.value, ev && ev.type);
  21860. }
  21861. };
  21862. element.on('click', listener);
  21863. ctrl.$render = function() {
  21864. var value = attr.value;
  21865. element[0].checked = (value == ctrl.$viewValue);
  21866. };
  21867. attr.$observe('value', ctrl.$render);
  21868. }
  21869. function parseConstantExpr($parse, context, name, expression, fallback) {
  21870. var parseFn;
  21871. if (isDefined(expression)) {
  21872. parseFn = $parse(expression);
  21873. if (!parseFn.constant) {
  21874. throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  21875. '`{1}`.', name, expression);
  21876. }
  21877. return parseFn(context);
  21878. }
  21879. return fallback;
  21880. }
  21881. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  21882. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  21883. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  21884. var listener = function(ev) {
  21885. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  21886. };
  21887. element.on('click', listener);
  21888. ctrl.$render = function() {
  21889. element[0].checked = ctrl.$viewValue;
  21890. };
  21891. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  21892. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  21893. // it to a boolean.
  21894. ctrl.$isEmpty = function(value) {
  21895. return value === false;
  21896. };
  21897. ctrl.$formatters.push(function(value) {
  21898. return equals(value, trueValue);
  21899. });
  21900. ctrl.$parsers.push(function(value) {
  21901. return value ? trueValue : falseValue;
  21902. });
  21903. }
  21904. /**
  21905. * @ngdoc directive
  21906. * @name textarea
  21907. * @restrict E
  21908. *
  21909. * @description
  21910. * HTML textarea element control with angular data-binding. The data-binding and validation
  21911. * properties of this element are exactly the same as those of the
  21912. * {@link ng.directive:input input element}.
  21913. *
  21914. * @param {string} ngModel Assignable angular expression to data-bind to.
  21915. * @param {string=} name Property name of the form under which the control is published.
  21916. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21917. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  21918. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  21919. * `required` when you want to data-bind to the `required` attribute.
  21920. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21921. * minlength.
  21922. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21923. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  21924. * length.
  21925. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21926. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21927. * If the expression evaluates to a RegExp object, then this is used directly.
  21928. * If the expression evaluates to a string, then it will be converted to a RegExp
  21929. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21930. * `new RegExp('^abc$')`.<br />
  21931. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21932. * start at the index of the last search's match, thus not taking the whole input value into
  21933. * account.
  21934. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21935. * interaction with the input element.
  21936. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  21937. */
  21938. /**
  21939. * @ngdoc directive
  21940. * @name input
  21941. * @restrict E
  21942. *
  21943. * @description
  21944. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  21945. * input state control, and validation.
  21946. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  21947. *
  21948. * <div class="alert alert-warning">
  21949. * **Note:** Not every feature offered is available for all input types.
  21950. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  21951. * </div>
  21952. *
  21953. * @param {string} ngModel Assignable angular expression to data-bind to.
  21954. * @param {string=} name Property name of the form under which the control is published.
  21955. * @param {string=} required Sets `required` validation error key if the value is not entered.
  21956. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  21957. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  21958. * minlength.
  21959. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  21960. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  21961. * length.
  21962. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  21963. * value does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  21964. * If the expression evaluates to a RegExp object, then this is used directly.
  21965. * If the expression evaluates to a string, then it will be converted to a RegExp
  21966. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  21967. * `new RegExp('^abc$')`.<br />
  21968. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  21969. * start at the index of the last search's match, thus not taking the whole input value into
  21970. * account.
  21971. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  21972. * interaction with the input element.
  21973. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  21974. * This parameter is ignored for input[type=password] controls, which will never trim the
  21975. * input.
  21976. *
  21977. * @example
  21978. <example name="input-directive" module="inputExample">
  21979. <file name="index.html">
  21980. <script>
  21981. angular.module('inputExample', [])
  21982. .controller('ExampleController', ['$scope', function($scope) {
  21983. $scope.user = {name: 'guest', last: 'visitor'};
  21984. }]);
  21985. </script>
  21986. <div ng-controller="ExampleController">
  21987. <form name="myForm">
  21988. <label>
  21989. User name:
  21990. <input type="text" name="userName" ng-model="user.name" required>
  21991. </label>
  21992. <div role="alert">
  21993. <span class="error" ng-show="myForm.userName.$error.required">
  21994. Required!</span>
  21995. </div>
  21996. <label>
  21997. Last name:
  21998. <input type="text" name="lastName" ng-model="user.last"
  21999. ng-minlength="3" ng-maxlength="10">
  22000. </label>
  22001. <div role="alert">
  22002. <span class="error" ng-show="myForm.lastName.$error.minlength">
  22003. Too short!</span>
  22004. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  22005. Too long!</span>
  22006. </div>
  22007. </form>
  22008. <hr>
  22009. <tt>user = {{user}}</tt><br/>
  22010. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  22011. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  22012. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  22013. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  22014. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22015. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22016. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  22017. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  22018. </div>
  22019. </file>
  22020. <file name="protractor.js" type="protractor">
  22021. var user = element(by.exactBinding('user'));
  22022. var userNameValid = element(by.binding('myForm.userName.$valid'));
  22023. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  22024. var lastNameError = element(by.binding('myForm.lastName.$error'));
  22025. var formValid = element(by.binding('myForm.$valid'));
  22026. var userNameInput = element(by.model('user.name'));
  22027. var userLastInput = element(by.model('user.last'));
  22028. it('should initialize to model', function() {
  22029. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  22030. expect(userNameValid.getText()).toContain('true');
  22031. expect(formValid.getText()).toContain('true');
  22032. });
  22033. it('should be invalid if empty when required', function() {
  22034. userNameInput.clear();
  22035. userNameInput.sendKeys('');
  22036. expect(user.getText()).toContain('{"last":"visitor"}');
  22037. expect(userNameValid.getText()).toContain('false');
  22038. expect(formValid.getText()).toContain('false');
  22039. });
  22040. it('should be valid if empty when min length is set', function() {
  22041. userLastInput.clear();
  22042. userLastInput.sendKeys('');
  22043. expect(user.getText()).toContain('{"name":"guest","last":""}');
  22044. expect(lastNameValid.getText()).toContain('true');
  22045. expect(formValid.getText()).toContain('true');
  22046. });
  22047. it('should be invalid if less than required min length', function() {
  22048. userLastInput.clear();
  22049. userLastInput.sendKeys('xx');
  22050. expect(user.getText()).toContain('{"name":"guest"}');
  22051. expect(lastNameValid.getText()).toContain('false');
  22052. expect(lastNameError.getText()).toContain('minlength');
  22053. expect(formValid.getText()).toContain('false');
  22054. });
  22055. it('should be invalid if longer than max length', function() {
  22056. userLastInput.clear();
  22057. userLastInput.sendKeys('some ridiculously long name');
  22058. expect(user.getText()).toContain('{"name":"guest"}');
  22059. expect(lastNameValid.getText()).toContain('false');
  22060. expect(lastNameError.getText()).toContain('maxlength');
  22061. expect(formValid.getText()).toContain('false');
  22062. });
  22063. </file>
  22064. </example>
  22065. */
  22066. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  22067. function($browser, $sniffer, $filter, $parse) {
  22068. return {
  22069. restrict: 'E',
  22070. require: ['?ngModel'],
  22071. link: {
  22072. pre: function(scope, element, attr, ctrls) {
  22073. if (ctrls[0]) {
  22074. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  22075. $browser, $filter, $parse);
  22076. }
  22077. }
  22078. }
  22079. };
  22080. }];
  22081. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  22082. /**
  22083. * @ngdoc directive
  22084. * @name ngValue
  22085. *
  22086. * @description
  22087. * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
  22088. * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
  22089. * the bound value.
  22090. *
  22091. * `ngValue` is useful when dynamically generating lists of radio buttons using
  22092. * {@link ngRepeat `ngRepeat`}, as shown below.
  22093. *
  22094. * Likewise, `ngValue` can be used to generate `<option>` elements for
  22095. * the {@link select `select`} element. In that case however, only strings are supported
  22096. * for the `value `attribute, so the resulting `ngModel` will always be a string.
  22097. * Support for `select` models with non-string values is available via `ngOptions`.
  22098. *
  22099. * @element input
  22100. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  22101. * of the `input` element
  22102. *
  22103. * @example
  22104. <example name="ngValue-directive" module="valueExample">
  22105. <file name="index.html">
  22106. <script>
  22107. angular.module('valueExample', [])
  22108. .controller('ExampleController', ['$scope', function($scope) {
  22109. $scope.names = ['pizza', 'unicorns', 'robots'];
  22110. $scope.my = { favorite: 'unicorns' };
  22111. }]);
  22112. </script>
  22113. <form ng-controller="ExampleController">
  22114. <h2>Which is your favorite?</h2>
  22115. <label ng-repeat="name in names" for="{{name}}">
  22116. {{name}}
  22117. <input type="radio"
  22118. ng-model="my.favorite"
  22119. ng-value="name"
  22120. id="{{name}}"
  22121. name="favorite">
  22122. </label>
  22123. <div>You chose {{my.favorite}}</div>
  22124. </form>
  22125. </file>
  22126. <file name="protractor.js" type="protractor">
  22127. var favorite = element(by.binding('my.favorite'));
  22128. it('should initialize to model', function() {
  22129. expect(favorite.getText()).toContain('unicorns');
  22130. });
  22131. it('should bind the values to the inputs', function() {
  22132. element.all(by.model('my.favorite')).get(0).click();
  22133. expect(favorite.getText()).toContain('pizza');
  22134. });
  22135. </file>
  22136. </example>
  22137. */
  22138. var ngValueDirective = function() {
  22139. return {
  22140. restrict: 'A',
  22141. priority: 100,
  22142. compile: function(tpl, tplAttr) {
  22143. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  22144. return function ngValueConstantLink(scope, elm, attr) {
  22145. attr.$set('value', scope.$eval(attr.ngValue));
  22146. };
  22147. } else {
  22148. return function ngValueLink(scope, elm, attr) {
  22149. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  22150. attr.$set('value', value);
  22151. });
  22152. };
  22153. }
  22154. }
  22155. };
  22156. };
  22157. /**
  22158. * @ngdoc directive
  22159. * @name ngBind
  22160. * @restrict AC
  22161. *
  22162. * @description
  22163. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  22164. * with the value of a given expression, and to update the text content when the value of that
  22165. * expression changes.
  22166. *
  22167. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  22168. * `{{ expression }}` which is similar but less verbose.
  22169. *
  22170. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  22171. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  22172. * element attribute, it makes the bindings invisible to the user while the page is loading.
  22173. *
  22174. * An alternative solution to this problem would be using the
  22175. * {@link ng.directive:ngCloak ngCloak} directive.
  22176. *
  22177. *
  22178. * @element ANY
  22179. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  22180. *
  22181. * @example
  22182. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  22183. <example module="bindExample">
  22184. <file name="index.html">
  22185. <script>
  22186. angular.module('bindExample', [])
  22187. .controller('ExampleController', ['$scope', function($scope) {
  22188. $scope.name = 'Whirled';
  22189. }]);
  22190. </script>
  22191. <div ng-controller="ExampleController">
  22192. <label>Enter name: <input type="text" ng-model="name"></label><br>
  22193. Hello <span ng-bind="name"></span>!
  22194. </div>
  22195. </file>
  22196. <file name="protractor.js" type="protractor">
  22197. it('should check ng-bind', function() {
  22198. var nameInput = element(by.model('name'));
  22199. expect(element(by.binding('name')).getText()).toBe('Whirled');
  22200. nameInput.clear();
  22201. nameInput.sendKeys('world');
  22202. expect(element(by.binding('name')).getText()).toBe('world');
  22203. });
  22204. </file>
  22205. </example>
  22206. */
  22207. var ngBindDirective = ['$compile', function($compile) {
  22208. return {
  22209. restrict: 'AC',
  22210. compile: function ngBindCompile(templateElement) {
  22211. $compile.$$addBindingClass(templateElement);
  22212. return function ngBindLink(scope, element, attr) {
  22213. $compile.$$addBindingInfo(element, attr.ngBind);
  22214. element = element[0];
  22215. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  22216. element.textContent = isUndefined(value) ? '' : value;
  22217. });
  22218. };
  22219. }
  22220. };
  22221. }];
  22222. /**
  22223. * @ngdoc directive
  22224. * @name ngBindTemplate
  22225. *
  22226. * @description
  22227. * The `ngBindTemplate` directive specifies that the element
  22228. * text content should be replaced with the interpolation of the template
  22229. * in the `ngBindTemplate` attribute.
  22230. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  22231. * expressions. This directive is needed since some HTML elements
  22232. * (such as TITLE and OPTION) cannot contain SPAN elements.
  22233. *
  22234. * @element ANY
  22235. * @param {string} ngBindTemplate template of form
  22236. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  22237. *
  22238. * @example
  22239. * Try it here: enter text in text box and watch the greeting change.
  22240. <example module="bindExample">
  22241. <file name="index.html">
  22242. <script>
  22243. angular.module('bindExample', [])
  22244. .controller('ExampleController', ['$scope', function($scope) {
  22245. $scope.salutation = 'Hello';
  22246. $scope.name = 'World';
  22247. }]);
  22248. </script>
  22249. <div ng-controller="ExampleController">
  22250. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  22251. <label>Name: <input type="text" ng-model="name"></label><br>
  22252. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  22253. </div>
  22254. </file>
  22255. <file name="protractor.js" type="protractor">
  22256. it('should check ng-bind', function() {
  22257. var salutationElem = element(by.binding('salutation'));
  22258. var salutationInput = element(by.model('salutation'));
  22259. var nameInput = element(by.model('name'));
  22260. expect(salutationElem.getText()).toBe('Hello World!');
  22261. salutationInput.clear();
  22262. salutationInput.sendKeys('Greetings');
  22263. nameInput.clear();
  22264. nameInput.sendKeys('user');
  22265. expect(salutationElem.getText()).toBe('Greetings user!');
  22266. });
  22267. </file>
  22268. </example>
  22269. */
  22270. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  22271. return {
  22272. compile: function ngBindTemplateCompile(templateElement) {
  22273. $compile.$$addBindingClass(templateElement);
  22274. return function ngBindTemplateLink(scope, element, attr) {
  22275. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  22276. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  22277. element = element[0];
  22278. attr.$observe('ngBindTemplate', function(value) {
  22279. element.textContent = isUndefined(value) ? '' : value;
  22280. });
  22281. };
  22282. }
  22283. };
  22284. }];
  22285. /**
  22286. * @ngdoc directive
  22287. * @name ngBindHtml
  22288. *
  22289. * @description
  22290. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  22291. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  22292. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  22293. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  22294. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  22295. *
  22296. * You may also bypass sanitization for values you know are safe. To do so, bind to
  22297. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  22298. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  22299. *
  22300. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  22301. * will have an exception (instead of an exploit.)
  22302. *
  22303. * @element ANY
  22304. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  22305. *
  22306. * @example
  22307. <example module="bindHtmlExample" deps="angular-sanitize.js">
  22308. <file name="index.html">
  22309. <div ng-controller="ExampleController">
  22310. <p ng-bind-html="myHTML"></p>
  22311. </div>
  22312. </file>
  22313. <file name="script.js">
  22314. angular.module('bindHtmlExample', ['ngSanitize'])
  22315. .controller('ExampleController', ['$scope', function($scope) {
  22316. $scope.myHTML =
  22317. 'I am an <code>HTML</code>string with ' +
  22318. '<a href="#">links!</a> and other <em>stuff</em>';
  22319. }]);
  22320. </file>
  22321. <file name="protractor.js" type="protractor">
  22322. it('should check ng-bind-html', function() {
  22323. expect(element(by.binding('myHTML')).getText()).toBe(
  22324. 'I am an HTMLstring with links! and other stuff');
  22325. });
  22326. </file>
  22327. </example>
  22328. */
  22329. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  22330. return {
  22331. restrict: 'A',
  22332. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  22333. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  22334. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function sceValueOf(val) {
  22335. // Unwrap the value to compare the actual inner safe value, not the wrapper object.
  22336. return $sce.valueOf(val);
  22337. });
  22338. $compile.$$addBindingClass(tElement);
  22339. return function ngBindHtmlLink(scope, element, attr) {
  22340. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  22341. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  22342. // The watched value is the unwrapped value. To avoid re-escaping, use the direct getter.
  22343. var value = ngBindHtmlGetter(scope);
  22344. element.html($sce.getTrustedHtml(value) || '');
  22345. });
  22346. };
  22347. }
  22348. };
  22349. }];
  22350. /**
  22351. * @ngdoc directive
  22352. * @name ngChange
  22353. *
  22354. * @description
  22355. * Evaluate the given expression when the user changes the input.
  22356. * The expression is evaluated immediately, unlike the JavaScript onchange event
  22357. * which only triggers at the end of a change (usually, when the user leaves the
  22358. * form element or presses the return key).
  22359. *
  22360. * The `ngChange` expression is only evaluated when a change in the input value causes
  22361. * a new value to be committed to the model.
  22362. *
  22363. * It will not be evaluated:
  22364. * * if the value returned from the `$parsers` transformation pipeline has not changed
  22365. * * if the input has continued to be invalid since the model will stay `null`
  22366. * * if the model is changed programmatically and not by a change to the input value
  22367. *
  22368. *
  22369. * Note, this directive requires `ngModel` to be present.
  22370. *
  22371. * @element input
  22372. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  22373. * in input value.
  22374. *
  22375. * @example
  22376. * <example name="ngChange-directive" module="changeExample">
  22377. * <file name="index.html">
  22378. * <script>
  22379. * angular.module('changeExample', [])
  22380. * .controller('ExampleController', ['$scope', function($scope) {
  22381. * $scope.counter = 0;
  22382. * $scope.change = function() {
  22383. * $scope.counter++;
  22384. * };
  22385. * }]);
  22386. * </script>
  22387. * <div ng-controller="ExampleController">
  22388. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  22389. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  22390. * <label for="ng-change-example2">Confirmed</label><br />
  22391. * <tt>debug = {{confirmed}}</tt><br/>
  22392. * <tt>counter = {{counter}}</tt><br/>
  22393. * </div>
  22394. * </file>
  22395. * <file name="protractor.js" type="protractor">
  22396. * var counter = element(by.binding('counter'));
  22397. * var debug = element(by.binding('confirmed'));
  22398. *
  22399. * it('should evaluate the expression if changing from view', function() {
  22400. * expect(counter.getText()).toContain('0');
  22401. *
  22402. * element(by.id('ng-change-example1')).click();
  22403. *
  22404. * expect(counter.getText()).toContain('1');
  22405. * expect(debug.getText()).toContain('true');
  22406. * });
  22407. *
  22408. * it('should not evaluate the expression if changing from model', function() {
  22409. * element(by.id('ng-change-example2')).click();
  22410. * expect(counter.getText()).toContain('0');
  22411. * expect(debug.getText()).toContain('true');
  22412. * });
  22413. * </file>
  22414. * </example>
  22415. */
  22416. var ngChangeDirective = valueFn({
  22417. restrict: 'A',
  22418. require: 'ngModel',
  22419. link: function(scope, element, attr, ctrl) {
  22420. ctrl.$viewChangeListeners.push(function() {
  22421. scope.$eval(attr.ngChange);
  22422. });
  22423. }
  22424. });
  22425. function classDirective(name, selector) {
  22426. name = 'ngClass' + name;
  22427. return ['$animate', function($animate) {
  22428. return {
  22429. restrict: 'AC',
  22430. link: function(scope, element, attr) {
  22431. var oldVal;
  22432. scope.$watch(attr[name], ngClassWatchAction, true);
  22433. attr.$observe('class', function(value) {
  22434. ngClassWatchAction(scope.$eval(attr[name]));
  22435. });
  22436. if (name !== 'ngClass') {
  22437. scope.$watch('$index', function($index, old$index) {
  22438. // jshint bitwise: false
  22439. var mod = $index & 1;
  22440. if (mod !== (old$index & 1)) {
  22441. var classes = arrayClasses(scope.$eval(attr[name]));
  22442. mod === selector ?
  22443. addClasses(classes) :
  22444. removeClasses(classes);
  22445. }
  22446. });
  22447. }
  22448. function addClasses(classes) {
  22449. var newClasses = digestClassCounts(classes, 1);
  22450. attr.$addClass(newClasses);
  22451. }
  22452. function removeClasses(classes) {
  22453. var newClasses = digestClassCounts(classes, -1);
  22454. attr.$removeClass(newClasses);
  22455. }
  22456. function digestClassCounts(classes, count) {
  22457. // Use createMap() to prevent class assumptions involving property
  22458. // names in Object.prototype
  22459. var classCounts = element.data('$classCounts') || createMap();
  22460. var classesToUpdate = [];
  22461. forEach(classes, function(className) {
  22462. if (count > 0 || classCounts[className]) {
  22463. classCounts[className] = (classCounts[className] || 0) + count;
  22464. if (classCounts[className] === +(count > 0)) {
  22465. classesToUpdate.push(className);
  22466. }
  22467. }
  22468. });
  22469. element.data('$classCounts', classCounts);
  22470. return classesToUpdate.join(' ');
  22471. }
  22472. function updateClasses(oldClasses, newClasses) {
  22473. var toAdd = arrayDifference(newClasses, oldClasses);
  22474. var toRemove = arrayDifference(oldClasses, newClasses);
  22475. toAdd = digestClassCounts(toAdd, 1);
  22476. toRemove = digestClassCounts(toRemove, -1);
  22477. if (toAdd && toAdd.length) {
  22478. $animate.addClass(element, toAdd);
  22479. }
  22480. if (toRemove && toRemove.length) {
  22481. $animate.removeClass(element, toRemove);
  22482. }
  22483. }
  22484. function ngClassWatchAction(newVal) {
  22485. // jshint bitwise: false
  22486. if (selector === true || (scope.$index & 1) === selector) {
  22487. // jshint bitwise: true
  22488. var newClasses = arrayClasses(newVal || []);
  22489. if (!oldVal) {
  22490. addClasses(newClasses);
  22491. } else if (!equals(newVal,oldVal)) {
  22492. var oldClasses = arrayClasses(oldVal);
  22493. updateClasses(oldClasses, newClasses);
  22494. }
  22495. }
  22496. if (isArray(newVal)) {
  22497. oldVal = newVal.map(function(v) { return shallowCopy(v); });
  22498. } else {
  22499. oldVal = shallowCopy(newVal);
  22500. }
  22501. }
  22502. }
  22503. };
  22504. function arrayDifference(tokens1, tokens2) {
  22505. var values = [];
  22506. outer:
  22507. for (var i = 0; i < tokens1.length; i++) {
  22508. var token = tokens1[i];
  22509. for (var j = 0; j < tokens2.length; j++) {
  22510. if (token == tokens2[j]) continue outer;
  22511. }
  22512. values.push(token);
  22513. }
  22514. return values;
  22515. }
  22516. function arrayClasses(classVal) {
  22517. var classes = [];
  22518. if (isArray(classVal)) {
  22519. forEach(classVal, function(v) {
  22520. classes = classes.concat(arrayClasses(v));
  22521. });
  22522. return classes;
  22523. } else if (isString(classVal)) {
  22524. return classVal.split(' ');
  22525. } else if (isObject(classVal)) {
  22526. forEach(classVal, function(v, k) {
  22527. if (v) {
  22528. classes = classes.concat(k.split(' '));
  22529. }
  22530. });
  22531. return classes;
  22532. }
  22533. return classVal;
  22534. }
  22535. }];
  22536. }
  22537. /**
  22538. * @ngdoc directive
  22539. * @name ngClass
  22540. * @restrict AC
  22541. *
  22542. * @description
  22543. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  22544. * an expression that represents all classes to be added.
  22545. *
  22546. * The directive operates in three different ways, depending on which of three types the expression
  22547. * evaluates to:
  22548. *
  22549. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  22550. * names.
  22551. *
  22552. * 2. If the expression evaluates to an object, then for each key-value pair of the
  22553. * object with a truthy value the corresponding key is used as a class name.
  22554. *
  22555. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  22556. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  22557. * to give you more control over what CSS classes appear. See the code below for an example of this.
  22558. *
  22559. *
  22560. * The directive won't add duplicate classes if a particular class was already set.
  22561. *
  22562. * When the expression changes, the previously added classes are removed and only then are the
  22563. * new classes added.
  22564. *
  22565. * @animations
  22566. * | Animation | Occurs |
  22567. * |----------------------------------|-------------------------------------|
  22568. * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element |
  22569. * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element |
  22570. *
  22571. * @element ANY
  22572. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  22573. * of the evaluation can be a string representing space delimited class
  22574. * names, an array, or a map of class names to boolean values. In the case of a map, the
  22575. * names of the properties whose values are truthy will be added as css classes to the
  22576. * element.
  22577. *
  22578. * @example Example that demonstrates basic bindings via ngClass directive.
  22579. <example>
  22580. <file name="index.html">
  22581. <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
  22582. <label>
  22583. <input type="checkbox" ng-model="deleted">
  22584. deleted (apply "strike" class)
  22585. </label><br>
  22586. <label>
  22587. <input type="checkbox" ng-model="important">
  22588. important (apply "bold" class)
  22589. </label><br>
  22590. <label>
  22591. <input type="checkbox" ng-model="error">
  22592. error (apply "has-error" class)
  22593. </label>
  22594. <hr>
  22595. <p ng-class="style">Using String Syntax</p>
  22596. <input type="text" ng-model="style"
  22597. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  22598. <hr>
  22599. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  22600. <input ng-model="style1"
  22601. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  22602. <input ng-model="style2"
  22603. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  22604. <input ng-model="style3"
  22605. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  22606. <hr>
  22607. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  22608. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  22609. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  22610. </file>
  22611. <file name="style.css">
  22612. .strike {
  22613. text-decoration: line-through;
  22614. }
  22615. .bold {
  22616. font-weight: bold;
  22617. }
  22618. .red {
  22619. color: red;
  22620. }
  22621. .has-error {
  22622. color: red;
  22623. background-color: yellow;
  22624. }
  22625. .orange {
  22626. color: orange;
  22627. }
  22628. </file>
  22629. <file name="protractor.js" type="protractor">
  22630. var ps = element.all(by.css('p'));
  22631. it('should let you toggle the class', function() {
  22632. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  22633. expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
  22634. element(by.model('important')).click();
  22635. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  22636. element(by.model('error')).click();
  22637. expect(ps.first().getAttribute('class')).toMatch(/has-error/);
  22638. });
  22639. it('should let you toggle string example', function() {
  22640. expect(ps.get(1).getAttribute('class')).toBe('');
  22641. element(by.model('style')).clear();
  22642. element(by.model('style')).sendKeys('red');
  22643. expect(ps.get(1).getAttribute('class')).toBe('red');
  22644. });
  22645. it('array example should have 3 classes', function() {
  22646. expect(ps.get(2).getAttribute('class')).toBe('');
  22647. element(by.model('style1')).sendKeys('bold');
  22648. element(by.model('style2')).sendKeys('strike');
  22649. element(by.model('style3')).sendKeys('red');
  22650. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  22651. });
  22652. it('array with map example should have 2 classes', function() {
  22653. expect(ps.last().getAttribute('class')).toBe('');
  22654. element(by.model('style4')).sendKeys('bold');
  22655. element(by.model('warning')).click();
  22656. expect(ps.last().getAttribute('class')).toBe('bold orange');
  22657. });
  22658. </file>
  22659. </example>
  22660. ## Animations
  22661. The example below demonstrates how to perform animations using ngClass.
  22662. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  22663. <file name="index.html">
  22664. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  22665. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  22666. <br>
  22667. <span class="base-class" ng-class="myVar">Sample Text</span>
  22668. </file>
  22669. <file name="style.css">
  22670. .base-class {
  22671. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  22672. }
  22673. .base-class.my-class {
  22674. color: red;
  22675. font-size:3em;
  22676. }
  22677. </file>
  22678. <file name="protractor.js" type="protractor">
  22679. it('should check ng-class', function() {
  22680. expect(element(by.css('.base-class')).getAttribute('class')).not.
  22681. toMatch(/my-class/);
  22682. element(by.id('setbtn')).click();
  22683. expect(element(by.css('.base-class')).getAttribute('class')).
  22684. toMatch(/my-class/);
  22685. element(by.id('clearbtn')).click();
  22686. expect(element(by.css('.base-class')).getAttribute('class')).not.
  22687. toMatch(/my-class/);
  22688. });
  22689. </file>
  22690. </example>
  22691. ## ngClass and pre-existing CSS3 Transitions/Animations
  22692. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  22693. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  22694. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  22695. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  22696. {@link $animate#removeClass $animate.removeClass}.
  22697. */
  22698. var ngClassDirective = classDirective('', true);
  22699. /**
  22700. * @ngdoc directive
  22701. * @name ngClassOdd
  22702. * @restrict AC
  22703. *
  22704. * @description
  22705. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  22706. * {@link ng.directive:ngClass ngClass}, except they work in
  22707. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  22708. *
  22709. * This directive can be applied only within the scope of an
  22710. * {@link ng.directive:ngRepeat ngRepeat}.
  22711. *
  22712. * @element ANY
  22713. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  22714. * of the evaluation can be a string representing space delimited class names or an array.
  22715. *
  22716. * @example
  22717. <example>
  22718. <file name="index.html">
  22719. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  22720. <li ng-repeat="name in names">
  22721. <span ng-class-odd="'odd'" ng-class-even="'even'">
  22722. {{name}}
  22723. </span>
  22724. </li>
  22725. </ol>
  22726. </file>
  22727. <file name="style.css">
  22728. .odd {
  22729. color: red;
  22730. }
  22731. .even {
  22732. color: blue;
  22733. }
  22734. </file>
  22735. <file name="protractor.js" type="protractor">
  22736. it('should check ng-class-odd and ng-class-even', function() {
  22737. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  22738. toMatch(/odd/);
  22739. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  22740. toMatch(/even/);
  22741. });
  22742. </file>
  22743. </example>
  22744. */
  22745. var ngClassOddDirective = classDirective('Odd', 0);
  22746. /**
  22747. * @ngdoc directive
  22748. * @name ngClassEven
  22749. * @restrict AC
  22750. *
  22751. * @description
  22752. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  22753. * {@link ng.directive:ngClass ngClass}, except they work in
  22754. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  22755. *
  22756. * This directive can be applied only within the scope of an
  22757. * {@link ng.directive:ngRepeat ngRepeat}.
  22758. *
  22759. * @element ANY
  22760. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  22761. * result of the evaluation can be a string representing space delimited class names or an array.
  22762. *
  22763. * @example
  22764. <example>
  22765. <file name="index.html">
  22766. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  22767. <li ng-repeat="name in names">
  22768. <span ng-class-odd="'odd'" ng-class-even="'even'">
  22769. {{name}} &nbsp; &nbsp; &nbsp;
  22770. </span>
  22771. </li>
  22772. </ol>
  22773. </file>
  22774. <file name="style.css">
  22775. .odd {
  22776. color: red;
  22777. }
  22778. .even {
  22779. color: blue;
  22780. }
  22781. </file>
  22782. <file name="protractor.js" type="protractor">
  22783. it('should check ng-class-odd and ng-class-even', function() {
  22784. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  22785. toMatch(/odd/);
  22786. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  22787. toMatch(/even/);
  22788. });
  22789. </file>
  22790. </example>
  22791. */
  22792. var ngClassEvenDirective = classDirective('Even', 1);
  22793. /**
  22794. * @ngdoc directive
  22795. * @name ngCloak
  22796. * @restrict AC
  22797. *
  22798. * @description
  22799. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  22800. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  22801. * directive to avoid the undesirable flicker effect caused by the html template display.
  22802. *
  22803. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  22804. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  22805. * of the browser view.
  22806. *
  22807. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  22808. * `angular.min.js`.
  22809. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  22810. *
  22811. * ```css
  22812. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  22813. * display: none !important;
  22814. * }
  22815. * ```
  22816. *
  22817. * When this css rule is loaded by the browser, all html elements (including their children) that
  22818. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  22819. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  22820. * the compiled element visible.
  22821. *
  22822. * For the best result, the `angular.js` script must be loaded in the head section of the html
  22823. * document; alternatively, the css rule above must be included in the external stylesheet of the
  22824. * application.
  22825. *
  22826. * @element ANY
  22827. *
  22828. * @example
  22829. <example>
  22830. <file name="index.html">
  22831. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  22832. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  22833. </file>
  22834. <file name="protractor.js" type="protractor">
  22835. it('should remove the template directive and css class', function() {
  22836. expect($('#template1').getAttribute('ng-cloak')).
  22837. toBeNull();
  22838. expect($('#template2').getAttribute('ng-cloak')).
  22839. toBeNull();
  22840. });
  22841. </file>
  22842. </example>
  22843. *
  22844. */
  22845. var ngCloakDirective = ngDirective({
  22846. compile: function(element, attr) {
  22847. attr.$set('ngCloak', undefined);
  22848. element.removeClass('ng-cloak');
  22849. }
  22850. });
  22851. /**
  22852. * @ngdoc directive
  22853. * @name ngController
  22854. *
  22855. * @description
  22856. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  22857. * supports the principles behind the Model-View-Controller design pattern.
  22858. *
  22859. * MVC components in angular:
  22860. *
  22861. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  22862. * are accessed through bindings.
  22863. * * View — The template (HTML with data bindings) that is rendered into the View.
  22864. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  22865. * logic behind the application to decorate the scope with functions and values
  22866. *
  22867. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  22868. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  22869. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  22870. * and executed twice.
  22871. *
  22872. * @element ANY
  22873. * @scope
  22874. * @priority 500
  22875. * @param {expression} ngController Name of a constructor function registered with the current
  22876. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  22877. * that on the current scope evaluates to a constructor function.
  22878. *
  22879. * The controller instance can be published into a scope property by specifying
  22880. * `ng-controller="as propertyName"`.
  22881. *
  22882. * If the current `$controllerProvider` is configured to use globals (via
  22883. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  22884. * also be the name of a globally accessible constructor function (not recommended).
  22885. *
  22886. * @example
  22887. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  22888. * greeting are methods declared on the controller (see source tab). These methods can
  22889. * easily be called from the angular markup. Any changes to the data are automatically reflected
  22890. * in the View without the need for a manual update.
  22891. *
  22892. * Two different declaration styles are included below:
  22893. *
  22894. * * one binds methods and properties directly onto the controller using `this`:
  22895. * `ng-controller="SettingsController1 as settings"`
  22896. * * one injects `$scope` into the controller:
  22897. * `ng-controller="SettingsController2"`
  22898. *
  22899. * The second option is more common in the Angular community, and is generally used in boilerplates
  22900. * and in this guide. However, there are advantages to binding properties directly to the controller
  22901. * and avoiding scope.
  22902. *
  22903. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  22904. * multiple controllers apply to an element.
  22905. * * If you are writing your controllers as classes you have easier access to the properties and
  22906. * methods, which will appear on the scope, from inside the controller code.
  22907. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  22908. * inheritance masking primitives.
  22909. *
  22910. * This example demonstrates the `controller as` syntax.
  22911. *
  22912. * <example name="ngControllerAs" module="controllerAsExample">
  22913. * <file name="index.html">
  22914. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  22915. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  22916. * <button ng-click="settings.greet()">greet</button><br/>
  22917. * Contact:
  22918. * <ul>
  22919. * <li ng-repeat="contact in settings.contacts">
  22920. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  22921. * <option>phone</option>
  22922. * <option>email</option>
  22923. * </select>
  22924. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  22925. * <button ng-click="settings.clearContact(contact)">clear</button>
  22926. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  22927. * </li>
  22928. * <li><button ng-click="settings.addContact()">add</button></li>
  22929. * </ul>
  22930. * </div>
  22931. * </file>
  22932. * <file name="app.js">
  22933. * angular.module('controllerAsExample', [])
  22934. * .controller('SettingsController1', SettingsController1);
  22935. *
  22936. * function SettingsController1() {
  22937. * this.name = "John Smith";
  22938. * this.contacts = [
  22939. * {type: 'phone', value: '408 555 1212'},
  22940. * {type: 'email', value: 'john.smith@example.org'} ];
  22941. * }
  22942. *
  22943. * SettingsController1.prototype.greet = function() {
  22944. * alert(this.name);
  22945. * };
  22946. *
  22947. * SettingsController1.prototype.addContact = function() {
  22948. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  22949. * };
  22950. *
  22951. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  22952. * var index = this.contacts.indexOf(contactToRemove);
  22953. * this.contacts.splice(index, 1);
  22954. * };
  22955. *
  22956. * SettingsController1.prototype.clearContact = function(contact) {
  22957. * contact.type = 'phone';
  22958. * contact.value = '';
  22959. * };
  22960. * </file>
  22961. * <file name="protractor.js" type="protractor">
  22962. * it('should check controller as', function() {
  22963. * var container = element(by.id('ctrl-as-exmpl'));
  22964. * expect(container.element(by.model('settings.name'))
  22965. * .getAttribute('value')).toBe('John Smith');
  22966. *
  22967. * var firstRepeat =
  22968. * container.element(by.repeater('contact in settings.contacts').row(0));
  22969. * var secondRepeat =
  22970. * container.element(by.repeater('contact in settings.contacts').row(1));
  22971. *
  22972. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  22973. * .toBe('408 555 1212');
  22974. *
  22975. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  22976. * .toBe('john.smith@example.org');
  22977. *
  22978. * firstRepeat.element(by.buttonText('clear')).click();
  22979. *
  22980. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  22981. * .toBe('');
  22982. *
  22983. * container.element(by.buttonText('add')).click();
  22984. *
  22985. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  22986. * .element(by.model('contact.value'))
  22987. * .getAttribute('value'))
  22988. * .toBe('yourname@example.org');
  22989. * });
  22990. * </file>
  22991. * </example>
  22992. *
  22993. * This example demonstrates the "attach to `$scope`" style of controller.
  22994. *
  22995. * <example name="ngController" module="controllerExample">
  22996. * <file name="index.html">
  22997. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  22998. * <label>Name: <input type="text" ng-model="name"/></label>
  22999. * <button ng-click="greet()">greet</button><br/>
  23000. * Contact:
  23001. * <ul>
  23002. * <li ng-repeat="contact in contacts">
  23003. * <select ng-model="contact.type" id="select_{{$index}}">
  23004. * <option>phone</option>
  23005. * <option>email</option>
  23006. * </select>
  23007. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  23008. * <button ng-click="clearContact(contact)">clear</button>
  23009. * <button ng-click="removeContact(contact)">X</button>
  23010. * </li>
  23011. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  23012. * </ul>
  23013. * </div>
  23014. * </file>
  23015. * <file name="app.js">
  23016. * angular.module('controllerExample', [])
  23017. * .controller('SettingsController2', ['$scope', SettingsController2]);
  23018. *
  23019. * function SettingsController2($scope) {
  23020. * $scope.name = "John Smith";
  23021. * $scope.contacts = [
  23022. * {type:'phone', value:'408 555 1212'},
  23023. * {type:'email', value:'john.smith@example.org'} ];
  23024. *
  23025. * $scope.greet = function() {
  23026. * alert($scope.name);
  23027. * };
  23028. *
  23029. * $scope.addContact = function() {
  23030. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  23031. * };
  23032. *
  23033. * $scope.removeContact = function(contactToRemove) {
  23034. * var index = $scope.contacts.indexOf(contactToRemove);
  23035. * $scope.contacts.splice(index, 1);
  23036. * };
  23037. *
  23038. * $scope.clearContact = function(contact) {
  23039. * contact.type = 'phone';
  23040. * contact.value = '';
  23041. * };
  23042. * }
  23043. * </file>
  23044. * <file name="protractor.js" type="protractor">
  23045. * it('should check controller', function() {
  23046. * var container = element(by.id('ctrl-exmpl'));
  23047. *
  23048. * expect(container.element(by.model('name'))
  23049. * .getAttribute('value')).toBe('John Smith');
  23050. *
  23051. * var firstRepeat =
  23052. * container.element(by.repeater('contact in contacts').row(0));
  23053. * var secondRepeat =
  23054. * container.element(by.repeater('contact in contacts').row(1));
  23055. *
  23056. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  23057. * .toBe('408 555 1212');
  23058. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  23059. * .toBe('john.smith@example.org');
  23060. *
  23061. * firstRepeat.element(by.buttonText('clear')).click();
  23062. *
  23063. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  23064. * .toBe('');
  23065. *
  23066. * container.element(by.buttonText('add')).click();
  23067. *
  23068. * expect(container.element(by.repeater('contact in contacts').row(2))
  23069. * .element(by.model('contact.value'))
  23070. * .getAttribute('value'))
  23071. * .toBe('yourname@example.org');
  23072. * });
  23073. * </file>
  23074. *</example>
  23075. */
  23076. var ngControllerDirective = [function() {
  23077. return {
  23078. restrict: 'A',
  23079. scope: true,
  23080. controller: '@',
  23081. priority: 500
  23082. };
  23083. }];
  23084. /**
  23085. * @ngdoc directive
  23086. * @name ngCsp
  23087. *
  23088. * @element html
  23089. * @description
  23090. *
  23091. * Angular has some features that can break certain
  23092. * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
  23093. *
  23094. * If you intend to implement these rules then you must tell Angular not to use these features.
  23095. *
  23096. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  23097. *
  23098. *
  23099. * The following rules affect Angular:
  23100. *
  23101. * * `unsafe-eval`: this rule forbids apps to use `eval` or `Function(string)` generated functions
  23102. * (among other things). Angular makes use of this in the {@link $parse} service to provide a 30%
  23103. * increase in the speed of evaluating Angular expressions.
  23104. *
  23105. * * `unsafe-inline`: this rule forbids apps from inject custom styles into the document. Angular
  23106. * makes use of this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}).
  23107. * To make these directives work when a CSP rule is blocking inline styles, you must link to the
  23108. * `angular-csp.css` in your HTML manually.
  23109. *
  23110. * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking unsafe-eval
  23111. * and automatically deactivates this feature in the {@link $parse} service. This autodetection,
  23112. * however, triggers a CSP error to be logged in the console:
  23113. *
  23114. * ```
  23115. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  23116. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  23117. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  23118. * ```
  23119. *
  23120. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  23121. * directive on an element of the HTML document that appears before the `<script>` tag that loads
  23122. * the `angular.js` file.
  23123. *
  23124. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  23125. *
  23126. * You can specify which of the CSP related Angular features should be deactivated by providing
  23127. * a value for the `ng-csp` attribute. The options are as follows:
  23128. *
  23129. * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
  23130. *
  23131. * * no-unsafe-eval: this stops Angular from optimizing $parse with unsafe eval of strings
  23132. *
  23133. * You can use these values in the following combinations:
  23134. *
  23135. *
  23136. * * No declaration means that Angular will assume that you can do inline styles, but it will do
  23137. * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous versions
  23138. * of Angular.
  23139. *
  23140. * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
  23141. * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous versions
  23142. * of Angular.
  23143. *
  23144. * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can inject
  23145. * inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
  23146. *
  23147. * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
  23148. * run eval - no automatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
  23149. *
  23150. * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
  23151. * styles nor use eval, which is the same as an empty: ng-csp.
  23152. * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
  23153. *
  23154. * @example
  23155. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  23156. ```html
  23157. <!doctype html>
  23158. <html ng-app ng-csp>
  23159. ...
  23160. ...
  23161. </html>
  23162. ```
  23163. * @example
  23164. // Note: the suffix `.csp` in the example name triggers
  23165. // csp mode in our http server!
  23166. <example name="example.csp" module="cspExample" ng-csp="true">
  23167. <file name="index.html">
  23168. <div ng-controller="MainController as ctrl">
  23169. <div>
  23170. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  23171. <span id="counter">
  23172. {{ctrl.counter}}
  23173. </span>
  23174. </div>
  23175. <div>
  23176. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  23177. <span id="evilError">
  23178. {{ctrl.evilError}}
  23179. </span>
  23180. </div>
  23181. </div>
  23182. </file>
  23183. <file name="script.js">
  23184. angular.module('cspExample', [])
  23185. .controller('MainController', function() {
  23186. this.counter = 0;
  23187. this.inc = function() {
  23188. this.counter++;
  23189. };
  23190. this.evil = function() {
  23191. // jshint evil:true
  23192. try {
  23193. eval('1+2');
  23194. } catch (e) {
  23195. this.evilError = e.message;
  23196. }
  23197. };
  23198. });
  23199. </file>
  23200. <file name="protractor.js" type="protractor">
  23201. var util, webdriver;
  23202. var incBtn = element(by.id('inc'));
  23203. var counter = element(by.id('counter'));
  23204. var evilBtn = element(by.id('evil'));
  23205. var evilError = element(by.id('evilError'));
  23206. function getAndClearSevereErrors() {
  23207. return browser.manage().logs().get('browser').then(function(browserLog) {
  23208. return browserLog.filter(function(logEntry) {
  23209. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  23210. });
  23211. });
  23212. }
  23213. function clearErrors() {
  23214. getAndClearSevereErrors();
  23215. }
  23216. function expectNoErrors() {
  23217. getAndClearSevereErrors().then(function(filteredLog) {
  23218. expect(filteredLog.length).toEqual(0);
  23219. if (filteredLog.length) {
  23220. console.log('browser console errors: ' + util.inspect(filteredLog));
  23221. }
  23222. });
  23223. }
  23224. function expectError(regex) {
  23225. getAndClearSevereErrors().then(function(filteredLog) {
  23226. var found = false;
  23227. filteredLog.forEach(function(log) {
  23228. if (log.message.match(regex)) {
  23229. found = true;
  23230. }
  23231. });
  23232. if (!found) {
  23233. throw new Error('expected an error that matches ' + regex);
  23234. }
  23235. });
  23236. }
  23237. beforeEach(function() {
  23238. util = require('util');
  23239. webdriver = require('protractor/node_modules/selenium-webdriver');
  23240. });
  23241. // For now, we only test on Chrome,
  23242. // as Safari does not load the page with Protractor's injected scripts,
  23243. // and Firefox webdriver always disables content security policy (#6358)
  23244. if (browser.params.browser !== 'chrome') {
  23245. return;
  23246. }
  23247. it('should not report errors when the page is loaded', function() {
  23248. // clear errors so we are not dependent on previous tests
  23249. clearErrors();
  23250. // Need to reload the page as the page is already loaded when
  23251. // we come here
  23252. browser.driver.getCurrentUrl().then(function(url) {
  23253. browser.get(url);
  23254. });
  23255. expectNoErrors();
  23256. });
  23257. it('should evaluate expressions', function() {
  23258. expect(counter.getText()).toEqual('0');
  23259. incBtn.click();
  23260. expect(counter.getText()).toEqual('1');
  23261. expectNoErrors();
  23262. });
  23263. it('should throw and report an error when using "eval"', function() {
  23264. evilBtn.click();
  23265. expect(evilError.getText()).toMatch(/Content Security Policy/);
  23266. expectError(/Content Security Policy/);
  23267. });
  23268. </file>
  23269. </example>
  23270. */
  23271. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  23272. // bootstrap the system (before $parse is instantiated), for this reason we just have
  23273. // the csp() fn that looks for the `ng-csp` attribute anywhere in the current doc
  23274. /**
  23275. * @ngdoc directive
  23276. * @name ngClick
  23277. *
  23278. * @description
  23279. * The ngClick directive allows you to specify custom behavior when
  23280. * an element is clicked.
  23281. *
  23282. * @element ANY
  23283. * @priority 0
  23284. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  23285. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  23286. *
  23287. * @example
  23288. <example>
  23289. <file name="index.html">
  23290. <button ng-click="count = count + 1" ng-init="count=0">
  23291. Increment
  23292. </button>
  23293. <span>
  23294. count: {{count}}
  23295. </span>
  23296. </file>
  23297. <file name="protractor.js" type="protractor">
  23298. it('should check ng-click', function() {
  23299. expect(element(by.binding('count')).getText()).toMatch('0');
  23300. element(by.css('button')).click();
  23301. expect(element(by.binding('count')).getText()).toMatch('1');
  23302. });
  23303. </file>
  23304. </example>
  23305. */
  23306. /*
  23307. * A collection of directives that allows creation of custom event handlers that are defined as
  23308. * angular expressions and are compiled and executed within the current scope.
  23309. */
  23310. var ngEventDirectives = {};
  23311. // For events that might fire synchronously during DOM manipulation
  23312. // we need to execute their event handlers asynchronously using $evalAsync,
  23313. // so that they are not executed in an inconsistent state.
  23314. var forceAsyncEvents = {
  23315. 'blur': true,
  23316. 'focus': true
  23317. };
  23318. forEach(
  23319. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  23320. function(eventName) {
  23321. var directiveName = directiveNormalize('ng-' + eventName);
  23322. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  23323. return {
  23324. restrict: 'A',
  23325. compile: function($element, attr) {
  23326. // We expose the powerful $event object on the scope that provides access to the Window,
  23327. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  23328. // checks at the cost of speed since event handler expressions are not executed as
  23329. // frequently as regular change detection.
  23330. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
  23331. return function ngEventHandler(scope, element) {
  23332. element.on(eventName, function(event) {
  23333. var callback = function() {
  23334. fn(scope, {$event:event});
  23335. };
  23336. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  23337. scope.$evalAsync(callback);
  23338. } else {
  23339. scope.$apply(callback);
  23340. }
  23341. });
  23342. };
  23343. }
  23344. };
  23345. }];
  23346. }
  23347. );
  23348. /**
  23349. * @ngdoc directive
  23350. * @name ngDblclick
  23351. *
  23352. * @description
  23353. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  23354. *
  23355. * @element ANY
  23356. * @priority 0
  23357. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  23358. * a dblclick. (The Event object is available as `$event`)
  23359. *
  23360. * @example
  23361. <example>
  23362. <file name="index.html">
  23363. <button ng-dblclick="count = count + 1" ng-init="count=0">
  23364. Increment (on double click)
  23365. </button>
  23366. count: {{count}}
  23367. </file>
  23368. </example>
  23369. */
  23370. /**
  23371. * @ngdoc directive
  23372. * @name ngMousedown
  23373. *
  23374. * @description
  23375. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  23376. *
  23377. * @element ANY
  23378. * @priority 0
  23379. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  23380. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  23381. *
  23382. * @example
  23383. <example>
  23384. <file name="index.html">
  23385. <button ng-mousedown="count = count + 1" ng-init="count=0">
  23386. Increment (on mouse down)
  23387. </button>
  23388. count: {{count}}
  23389. </file>
  23390. </example>
  23391. */
  23392. /**
  23393. * @ngdoc directive
  23394. * @name ngMouseup
  23395. *
  23396. * @description
  23397. * Specify custom behavior on mouseup event.
  23398. *
  23399. * @element ANY
  23400. * @priority 0
  23401. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  23402. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  23403. *
  23404. * @example
  23405. <example>
  23406. <file name="index.html">
  23407. <button ng-mouseup="count = count + 1" ng-init="count=0">
  23408. Increment (on mouse up)
  23409. </button>
  23410. count: {{count}}
  23411. </file>
  23412. </example>
  23413. */
  23414. /**
  23415. * @ngdoc directive
  23416. * @name ngMouseover
  23417. *
  23418. * @description
  23419. * Specify custom behavior on mouseover event.
  23420. *
  23421. * @element ANY
  23422. * @priority 0
  23423. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  23424. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  23425. *
  23426. * @example
  23427. <example>
  23428. <file name="index.html">
  23429. <button ng-mouseover="count = count + 1" ng-init="count=0">
  23430. Increment (when mouse is over)
  23431. </button>
  23432. count: {{count}}
  23433. </file>
  23434. </example>
  23435. */
  23436. /**
  23437. * @ngdoc directive
  23438. * @name ngMouseenter
  23439. *
  23440. * @description
  23441. * Specify custom behavior on mouseenter event.
  23442. *
  23443. * @element ANY
  23444. * @priority 0
  23445. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  23446. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  23447. *
  23448. * @example
  23449. <example>
  23450. <file name="index.html">
  23451. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  23452. Increment (when mouse enters)
  23453. </button>
  23454. count: {{count}}
  23455. </file>
  23456. </example>
  23457. */
  23458. /**
  23459. * @ngdoc directive
  23460. * @name ngMouseleave
  23461. *
  23462. * @description
  23463. * Specify custom behavior on mouseleave event.
  23464. *
  23465. * @element ANY
  23466. * @priority 0
  23467. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  23468. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  23469. *
  23470. * @example
  23471. <example>
  23472. <file name="index.html">
  23473. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  23474. Increment (when mouse leaves)
  23475. </button>
  23476. count: {{count}}
  23477. </file>
  23478. </example>
  23479. */
  23480. /**
  23481. * @ngdoc directive
  23482. * @name ngMousemove
  23483. *
  23484. * @description
  23485. * Specify custom behavior on mousemove event.
  23486. *
  23487. * @element ANY
  23488. * @priority 0
  23489. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  23490. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  23491. *
  23492. * @example
  23493. <example>
  23494. <file name="index.html">
  23495. <button ng-mousemove="count = count + 1" ng-init="count=0">
  23496. Increment (when mouse moves)
  23497. </button>
  23498. count: {{count}}
  23499. </file>
  23500. </example>
  23501. */
  23502. /**
  23503. * @ngdoc directive
  23504. * @name ngKeydown
  23505. *
  23506. * @description
  23507. * Specify custom behavior on keydown event.
  23508. *
  23509. * @element ANY
  23510. * @priority 0
  23511. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  23512. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  23513. *
  23514. * @example
  23515. <example>
  23516. <file name="index.html">
  23517. <input ng-keydown="count = count + 1" ng-init="count=0">
  23518. key down count: {{count}}
  23519. </file>
  23520. </example>
  23521. */
  23522. /**
  23523. * @ngdoc directive
  23524. * @name ngKeyup
  23525. *
  23526. * @description
  23527. * Specify custom behavior on keyup event.
  23528. *
  23529. * @element ANY
  23530. * @priority 0
  23531. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  23532. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  23533. *
  23534. * @example
  23535. <example>
  23536. <file name="index.html">
  23537. <p>Typing in the input box below updates the key count</p>
  23538. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  23539. <p>Typing in the input box below updates the keycode</p>
  23540. <input ng-keyup="event=$event">
  23541. <p>event keyCode: {{ event.keyCode }}</p>
  23542. <p>event altKey: {{ event.altKey }}</p>
  23543. </file>
  23544. </example>
  23545. */
  23546. /**
  23547. * @ngdoc directive
  23548. * @name ngKeypress
  23549. *
  23550. * @description
  23551. * Specify custom behavior on keypress event.
  23552. *
  23553. * @element ANY
  23554. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  23555. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  23556. * and can be interrogated for keyCode, altKey, etc.)
  23557. *
  23558. * @example
  23559. <example>
  23560. <file name="index.html">
  23561. <input ng-keypress="count = count + 1" ng-init="count=0">
  23562. key press count: {{count}}
  23563. </file>
  23564. </example>
  23565. */
  23566. /**
  23567. * @ngdoc directive
  23568. * @name ngSubmit
  23569. *
  23570. * @description
  23571. * Enables binding angular expressions to onsubmit events.
  23572. *
  23573. * Additionally it prevents the default action (which for form means sending the request to the
  23574. * server and reloading the current page), but only if the form does not contain `action`,
  23575. * `data-action`, or `x-action` attributes.
  23576. *
  23577. * <div class="alert alert-warning">
  23578. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  23579. * `ngSubmit` handlers together. See the
  23580. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  23581. * for a detailed discussion of when `ngSubmit` may be triggered.
  23582. * </div>
  23583. *
  23584. * @element form
  23585. * @priority 0
  23586. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  23587. * ({@link guide/expression#-event- Event object is available as `$event`})
  23588. *
  23589. * @example
  23590. <example module="submitExample">
  23591. <file name="index.html">
  23592. <script>
  23593. angular.module('submitExample', [])
  23594. .controller('ExampleController', ['$scope', function($scope) {
  23595. $scope.list = [];
  23596. $scope.text = 'hello';
  23597. $scope.submit = function() {
  23598. if ($scope.text) {
  23599. $scope.list.push(this.text);
  23600. $scope.text = '';
  23601. }
  23602. };
  23603. }]);
  23604. </script>
  23605. <form ng-submit="submit()" ng-controller="ExampleController">
  23606. Enter text and hit enter:
  23607. <input type="text" ng-model="text" name="text" />
  23608. <input type="submit" id="submit" value="Submit" />
  23609. <pre>list={{list}}</pre>
  23610. </form>
  23611. </file>
  23612. <file name="protractor.js" type="protractor">
  23613. it('should check ng-submit', function() {
  23614. expect(element(by.binding('list')).getText()).toBe('list=[]');
  23615. element(by.css('#submit')).click();
  23616. expect(element(by.binding('list')).getText()).toContain('hello');
  23617. expect(element(by.model('text')).getAttribute('value')).toBe('');
  23618. });
  23619. it('should ignore empty strings', function() {
  23620. expect(element(by.binding('list')).getText()).toBe('list=[]');
  23621. element(by.css('#submit')).click();
  23622. element(by.css('#submit')).click();
  23623. expect(element(by.binding('list')).getText()).toContain('hello');
  23624. });
  23625. </file>
  23626. </example>
  23627. */
  23628. /**
  23629. * @ngdoc directive
  23630. * @name ngFocus
  23631. *
  23632. * @description
  23633. * Specify custom behavior on focus event.
  23634. *
  23635. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  23636. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  23637. * during an `$apply` to ensure a consistent state.
  23638. *
  23639. * @element window, input, select, textarea, a
  23640. * @priority 0
  23641. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  23642. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  23643. *
  23644. * @example
  23645. * See {@link ng.directive:ngClick ngClick}
  23646. */
  23647. /**
  23648. * @ngdoc directive
  23649. * @name ngBlur
  23650. *
  23651. * @description
  23652. * Specify custom behavior on blur event.
  23653. *
  23654. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  23655. * an element has lost focus.
  23656. *
  23657. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  23658. * (e.g. removing a focussed input),
  23659. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  23660. * during an `$apply` to ensure a consistent state.
  23661. *
  23662. * @element window, input, select, textarea, a
  23663. * @priority 0
  23664. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  23665. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  23666. *
  23667. * @example
  23668. * See {@link ng.directive:ngClick ngClick}
  23669. */
  23670. /**
  23671. * @ngdoc directive
  23672. * @name ngCopy
  23673. *
  23674. * @description
  23675. * Specify custom behavior on copy event.
  23676. *
  23677. * @element window, input, select, textarea, a
  23678. * @priority 0
  23679. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  23680. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  23681. *
  23682. * @example
  23683. <example>
  23684. <file name="index.html">
  23685. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  23686. copied: {{copied}}
  23687. </file>
  23688. </example>
  23689. */
  23690. /**
  23691. * @ngdoc directive
  23692. * @name ngCut
  23693. *
  23694. * @description
  23695. * Specify custom behavior on cut event.
  23696. *
  23697. * @element window, input, select, textarea, a
  23698. * @priority 0
  23699. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  23700. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  23701. *
  23702. * @example
  23703. <example>
  23704. <file name="index.html">
  23705. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  23706. cut: {{cut}}
  23707. </file>
  23708. </example>
  23709. */
  23710. /**
  23711. * @ngdoc directive
  23712. * @name ngPaste
  23713. *
  23714. * @description
  23715. * Specify custom behavior on paste event.
  23716. *
  23717. * @element window, input, select, textarea, a
  23718. * @priority 0
  23719. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  23720. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  23721. *
  23722. * @example
  23723. <example>
  23724. <file name="index.html">
  23725. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  23726. pasted: {{paste}}
  23727. </file>
  23728. </example>
  23729. */
  23730. /**
  23731. * @ngdoc directive
  23732. * @name ngIf
  23733. * @restrict A
  23734. * @multiElement
  23735. *
  23736. * @description
  23737. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  23738. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  23739. * value then the element is removed from the DOM, otherwise a clone of the
  23740. * element is reinserted into the DOM.
  23741. *
  23742. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  23743. * element in the DOM rather than changing its visibility via the `display` css property. A common
  23744. * case when this difference is significant is when using css selectors that rely on an element's
  23745. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  23746. *
  23747. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  23748. * is created when the element is restored. The scope created within `ngIf` inherits from
  23749. * its parent scope using
  23750. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  23751. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  23752. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  23753. * variable within the child scope will override (hide) the value in the parent scope.
  23754. *
  23755. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  23756. * is if an element's class attribute is directly modified after it's compiled, using something like
  23757. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  23758. * the added class will be lost because the original compiled state is used to regenerate the element.
  23759. *
  23760. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  23761. * and `leave` effects.
  23762. *
  23763. * @animations
  23764. * | Animation | Occurs |
  23765. * |----------------------------------|-------------------------------------|
  23766. * | {@link ng.$animate#enter enter} | just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container |
  23767. * | {@link ng.$animate#leave leave} | just before the `ngIf` contents are removed from the DOM |
  23768. *
  23769. * @element ANY
  23770. * @scope
  23771. * @priority 600
  23772. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  23773. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  23774. * element is added to the DOM tree.
  23775. *
  23776. * @example
  23777. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  23778. <file name="index.html">
  23779. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  23780. Show when checked:
  23781. <span ng-if="checked" class="animate-if">
  23782. This is removed when the checkbox is unchecked.
  23783. </span>
  23784. </file>
  23785. <file name="animations.css">
  23786. .animate-if {
  23787. background:white;
  23788. border:1px solid black;
  23789. padding:10px;
  23790. }
  23791. .animate-if.ng-enter, .animate-if.ng-leave {
  23792. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  23793. }
  23794. .animate-if.ng-enter,
  23795. .animate-if.ng-leave.ng-leave-active {
  23796. opacity:0;
  23797. }
  23798. .animate-if.ng-leave,
  23799. .animate-if.ng-enter.ng-enter-active {
  23800. opacity:1;
  23801. }
  23802. </file>
  23803. </example>
  23804. */
  23805. var ngIfDirective = ['$animate', '$compile', function($animate, $compile) {
  23806. return {
  23807. multiElement: true,
  23808. transclude: 'element',
  23809. priority: 600,
  23810. terminal: true,
  23811. restrict: 'A',
  23812. $$tlb: true,
  23813. link: function($scope, $element, $attr, ctrl, $transclude) {
  23814. var block, childScope, previousElements;
  23815. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  23816. if (value) {
  23817. if (!childScope) {
  23818. $transclude(function(clone, newScope) {
  23819. childScope = newScope;
  23820. clone[clone.length++] = $compile.$$createComment('end ngIf', $attr.ngIf);
  23821. // Note: We only need the first/last node of the cloned nodes.
  23822. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  23823. // by a directive with templateUrl when its template arrives.
  23824. block = {
  23825. clone: clone
  23826. };
  23827. $animate.enter(clone, $element.parent(), $element);
  23828. });
  23829. }
  23830. } else {
  23831. if (previousElements) {
  23832. previousElements.remove();
  23833. previousElements = null;
  23834. }
  23835. if (childScope) {
  23836. childScope.$destroy();
  23837. childScope = null;
  23838. }
  23839. if (block) {
  23840. previousElements = getBlockNodes(block.clone);
  23841. $animate.leave(previousElements).then(function() {
  23842. previousElements = null;
  23843. });
  23844. block = null;
  23845. }
  23846. }
  23847. });
  23848. }
  23849. };
  23850. }];
  23851. /**
  23852. * @ngdoc directive
  23853. * @name ngInclude
  23854. * @restrict ECA
  23855. *
  23856. * @description
  23857. * Fetches, compiles and includes an external HTML fragment.
  23858. *
  23859. * By default, the template URL is restricted to the same domain and protocol as the
  23860. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  23861. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  23862. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  23863. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  23864. * ng.$sce Strict Contextual Escaping}.
  23865. *
  23866. * In addition, the browser's
  23867. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  23868. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  23869. * policy may further restrict whether the template is successfully loaded.
  23870. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  23871. * access on some browsers.
  23872. *
  23873. * @animations
  23874. * | Animation | Occurs |
  23875. * |----------------------------------|-------------------------------------|
  23876. * | {@link ng.$animate#enter enter} | when the expression changes, on the new include |
  23877. * | {@link ng.$animate#leave leave} | when the expression changes, on the old include |
  23878. *
  23879. * The enter and leave animation occur concurrently.
  23880. *
  23881. * @scope
  23882. * @priority 400
  23883. *
  23884. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  23885. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  23886. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  23887. * <div class="alert alert-warning">
  23888. * **Note:** When using onload on SVG elements in IE11, the browser will try to call
  23889. * a function with the name on the window element, which will usually throw a
  23890. * "function is undefined" error. To fix this, you can instead use `data-onload` or a
  23891. * different form that {@link guide/directive#normalization matches} `onload`.
  23892. * </div>
  23893. *
  23894. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  23895. * $anchorScroll} to scroll the viewport after the content is loaded.
  23896. *
  23897. * - If the attribute is not set, disable scrolling.
  23898. * - If the attribute is set without value, enable scrolling.
  23899. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  23900. *
  23901. * @example
  23902. <example module="includeExample" deps="angular-animate.js" animations="true">
  23903. <file name="index.html">
  23904. <div ng-controller="ExampleController">
  23905. <select ng-model="template" ng-options="t.name for t in templates">
  23906. <option value="">(blank)</option>
  23907. </select>
  23908. url of the template: <code>{{template.url}}</code>
  23909. <hr/>
  23910. <div class="slide-animate-container">
  23911. <div class="slide-animate" ng-include="template.url"></div>
  23912. </div>
  23913. </div>
  23914. </file>
  23915. <file name="script.js">
  23916. angular.module('includeExample', ['ngAnimate'])
  23917. .controller('ExampleController', ['$scope', function($scope) {
  23918. $scope.templates =
  23919. [ { name: 'template1.html', url: 'template1.html'},
  23920. { name: 'template2.html', url: 'template2.html'} ];
  23921. $scope.template = $scope.templates[0];
  23922. }]);
  23923. </file>
  23924. <file name="template1.html">
  23925. Content of template1.html
  23926. </file>
  23927. <file name="template2.html">
  23928. Content of template2.html
  23929. </file>
  23930. <file name="animations.css">
  23931. .slide-animate-container {
  23932. position:relative;
  23933. background:white;
  23934. border:1px solid black;
  23935. height:40px;
  23936. overflow:hidden;
  23937. }
  23938. .slide-animate {
  23939. padding:10px;
  23940. }
  23941. .slide-animate.ng-enter, .slide-animate.ng-leave {
  23942. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  23943. position:absolute;
  23944. top:0;
  23945. left:0;
  23946. right:0;
  23947. bottom:0;
  23948. display:block;
  23949. padding:10px;
  23950. }
  23951. .slide-animate.ng-enter {
  23952. top:-50px;
  23953. }
  23954. .slide-animate.ng-enter.ng-enter-active {
  23955. top:0;
  23956. }
  23957. .slide-animate.ng-leave {
  23958. top:0;
  23959. }
  23960. .slide-animate.ng-leave.ng-leave-active {
  23961. top:50px;
  23962. }
  23963. </file>
  23964. <file name="protractor.js" type="protractor">
  23965. var templateSelect = element(by.model('template'));
  23966. var includeElem = element(by.css('[ng-include]'));
  23967. it('should load template1.html', function() {
  23968. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  23969. });
  23970. it('should load template2.html', function() {
  23971. if (browser.params.browser == 'firefox') {
  23972. // Firefox can't handle using selects
  23973. // See https://github.com/angular/protractor/issues/480
  23974. return;
  23975. }
  23976. templateSelect.click();
  23977. templateSelect.all(by.css('option')).get(2).click();
  23978. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  23979. });
  23980. it('should change to blank', function() {
  23981. if (browser.params.browser == 'firefox') {
  23982. // Firefox can't handle using selects
  23983. return;
  23984. }
  23985. templateSelect.click();
  23986. templateSelect.all(by.css('option')).get(0).click();
  23987. expect(includeElem.isPresent()).toBe(false);
  23988. });
  23989. </file>
  23990. </example>
  23991. */
  23992. /**
  23993. * @ngdoc event
  23994. * @name ngInclude#$includeContentRequested
  23995. * @eventType emit on the scope ngInclude was declared in
  23996. * @description
  23997. * Emitted every time the ngInclude content is requested.
  23998. *
  23999. * @param {Object} angularEvent Synthetic event object.
  24000. * @param {String} src URL of content to load.
  24001. */
  24002. /**
  24003. * @ngdoc event
  24004. * @name ngInclude#$includeContentLoaded
  24005. * @eventType emit on the current ngInclude scope
  24006. * @description
  24007. * Emitted every time the ngInclude content is reloaded.
  24008. *
  24009. * @param {Object} angularEvent Synthetic event object.
  24010. * @param {String} src URL of content to load.
  24011. */
  24012. /**
  24013. * @ngdoc event
  24014. * @name ngInclude#$includeContentError
  24015. * @eventType emit on the scope ngInclude was declared in
  24016. * @description
  24017. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  24018. *
  24019. * @param {Object} angularEvent Synthetic event object.
  24020. * @param {String} src URL of content to load.
  24021. */
  24022. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
  24023. function($templateRequest, $anchorScroll, $animate) {
  24024. return {
  24025. restrict: 'ECA',
  24026. priority: 400,
  24027. terminal: true,
  24028. transclude: 'element',
  24029. controller: angular.noop,
  24030. compile: function(element, attr) {
  24031. var srcExp = attr.ngInclude || attr.src,
  24032. onloadExp = attr.onload || '',
  24033. autoScrollExp = attr.autoscroll;
  24034. return function(scope, $element, $attr, ctrl, $transclude) {
  24035. var changeCounter = 0,
  24036. currentScope,
  24037. previousElement,
  24038. currentElement;
  24039. var cleanupLastIncludeContent = function() {
  24040. if (previousElement) {
  24041. previousElement.remove();
  24042. previousElement = null;
  24043. }
  24044. if (currentScope) {
  24045. currentScope.$destroy();
  24046. currentScope = null;
  24047. }
  24048. if (currentElement) {
  24049. $animate.leave(currentElement).then(function() {
  24050. previousElement = null;
  24051. });
  24052. previousElement = currentElement;
  24053. currentElement = null;
  24054. }
  24055. };
  24056. scope.$watch(srcExp, function ngIncludeWatchAction(src) {
  24057. var afterAnimation = function() {
  24058. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  24059. $anchorScroll();
  24060. }
  24061. };
  24062. var thisChangeId = ++changeCounter;
  24063. if (src) {
  24064. //set the 2nd param to true to ignore the template request error so that the inner
  24065. //contents and scope can be cleaned up.
  24066. $templateRequest(src, true).then(function(response) {
  24067. if (scope.$$destroyed) return;
  24068. if (thisChangeId !== changeCounter) return;
  24069. var newScope = scope.$new();
  24070. ctrl.template = response;
  24071. // Note: This will also link all children of ng-include that were contained in the original
  24072. // html. If that content contains controllers, ... they could pollute/change the scope.
  24073. // However, using ng-include on an element with additional content does not make sense...
  24074. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  24075. // function is called before linking the content, which would apply child
  24076. // directives to non existing elements.
  24077. var clone = $transclude(newScope, function(clone) {
  24078. cleanupLastIncludeContent();
  24079. $animate.enter(clone, null, $element).then(afterAnimation);
  24080. });
  24081. currentScope = newScope;
  24082. currentElement = clone;
  24083. currentScope.$emit('$includeContentLoaded', src);
  24084. scope.$eval(onloadExp);
  24085. }, function() {
  24086. if (scope.$$destroyed) return;
  24087. if (thisChangeId === changeCounter) {
  24088. cleanupLastIncludeContent();
  24089. scope.$emit('$includeContentError', src);
  24090. }
  24091. });
  24092. scope.$emit('$includeContentRequested', src);
  24093. } else {
  24094. cleanupLastIncludeContent();
  24095. ctrl.template = null;
  24096. }
  24097. });
  24098. };
  24099. }
  24100. };
  24101. }];
  24102. // This directive is called during the $transclude call of the first `ngInclude` directive.
  24103. // It will replace and compile the content of the element with the loaded template.
  24104. // We need this directive so that the element content is already filled when
  24105. // the link function of another directive on the same element as ngInclude
  24106. // is called.
  24107. var ngIncludeFillContentDirective = ['$compile',
  24108. function($compile) {
  24109. return {
  24110. restrict: 'ECA',
  24111. priority: -400,
  24112. require: 'ngInclude',
  24113. link: function(scope, $element, $attr, ctrl) {
  24114. if (toString.call($element[0]).match(/SVG/)) {
  24115. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  24116. // support innerHTML, so detect this here and try to generate the contents
  24117. // specially.
  24118. $element.empty();
  24119. $compile(jqLiteBuildFragment(ctrl.template, window.document).childNodes)(scope,
  24120. function namespaceAdaptedClone(clone) {
  24121. $element.append(clone);
  24122. }, {futureParentElement: $element});
  24123. return;
  24124. }
  24125. $element.html(ctrl.template);
  24126. $compile($element.contents())(scope);
  24127. }
  24128. };
  24129. }];
  24130. /**
  24131. * @ngdoc directive
  24132. * @name ngInit
  24133. * @restrict AC
  24134. *
  24135. * @description
  24136. * The `ngInit` directive allows you to evaluate an expression in the
  24137. * current scope.
  24138. *
  24139. * <div class="alert alert-danger">
  24140. * This directive can be abused to add unnecessary amounts of logic into your templates.
  24141. * There are only a few appropriate uses of `ngInit`, such as for aliasing special properties of
  24142. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below; and for injecting data via
  24143. * server side scripting. Besides these few cases, you should use {@link guide/controller controllers}
  24144. * rather than `ngInit` to initialize values on a scope.
  24145. * </div>
  24146. *
  24147. * <div class="alert alert-warning">
  24148. * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
  24149. * sure you have parentheses to ensure correct operator precedence:
  24150. * <pre class="prettyprint">
  24151. * `<div ng-init="test1 = ($index | toString)"></div>`
  24152. * </pre>
  24153. * </div>
  24154. *
  24155. * @priority 450
  24156. *
  24157. * @element ANY
  24158. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  24159. *
  24160. * @example
  24161. <example module="initExample">
  24162. <file name="index.html">
  24163. <script>
  24164. angular.module('initExample', [])
  24165. .controller('ExampleController', ['$scope', function($scope) {
  24166. $scope.list = [['a', 'b'], ['c', 'd']];
  24167. }]);
  24168. </script>
  24169. <div ng-controller="ExampleController">
  24170. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  24171. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  24172. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  24173. </div>
  24174. </div>
  24175. </div>
  24176. </file>
  24177. <file name="protractor.js" type="protractor">
  24178. it('should alias index positions', function() {
  24179. var elements = element.all(by.css('.example-init'));
  24180. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  24181. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  24182. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  24183. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  24184. });
  24185. </file>
  24186. </example>
  24187. */
  24188. var ngInitDirective = ngDirective({
  24189. priority: 450,
  24190. compile: function() {
  24191. return {
  24192. pre: function(scope, element, attrs) {
  24193. scope.$eval(attrs.ngInit);
  24194. }
  24195. };
  24196. }
  24197. });
  24198. /**
  24199. * @ngdoc directive
  24200. * @name ngList
  24201. *
  24202. * @description
  24203. * Text input that converts between a delimited string and an array of strings. The default
  24204. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  24205. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  24206. *
  24207. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  24208. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  24209. * list item is respected. This implies that the user of the directive is responsible for
  24210. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  24211. * tab or newline character.
  24212. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  24213. * when joining the list items back together) and whitespace around each list item is stripped
  24214. * before it is added to the model.
  24215. *
  24216. * ### Example with Validation
  24217. *
  24218. * <example name="ngList-directive" module="listExample">
  24219. * <file name="app.js">
  24220. * angular.module('listExample', [])
  24221. * .controller('ExampleController', ['$scope', function($scope) {
  24222. * $scope.names = ['morpheus', 'neo', 'trinity'];
  24223. * }]);
  24224. * </file>
  24225. * <file name="index.html">
  24226. * <form name="myForm" ng-controller="ExampleController">
  24227. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  24228. * <span role="alert">
  24229. * <span class="error" ng-show="myForm.namesInput.$error.required">
  24230. * Required!</span>
  24231. * </span>
  24232. * <br>
  24233. * <tt>names = {{names}}</tt><br/>
  24234. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  24235. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  24236. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  24237. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  24238. * </form>
  24239. * </file>
  24240. * <file name="protractor.js" type="protractor">
  24241. * var listInput = element(by.model('names'));
  24242. * var names = element(by.exactBinding('names'));
  24243. * var valid = element(by.binding('myForm.namesInput.$valid'));
  24244. * var error = element(by.css('span.error'));
  24245. *
  24246. * it('should initialize to model', function() {
  24247. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  24248. * expect(valid.getText()).toContain('true');
  24249. * expect(error.getCssValue('display')).toBe('none');
  24250. * });
  24251. *
  24252. * it('should be invalid if empty', function() {
  24253. * listInput.clear();
  24254. * listInput.sendKeys('');
  24255. *
  24256. * expect(names.getText()).toContain('');
  24257. * expect(valid.getText()).toContain('false');
  24258. * expect(error.getCssValue('display')).not.toBe('none');
  24259. * });
  24260. * </file>
  24261. * </example>
  24262. *
  24263. * ### Example - splitting on newline
  24264. * <example name="ngList-directive-newlines">
  24265. * <file name="index.html">
  24266. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  24267. * <pre>{{ list | json }}</pre>
  24268. * </file>
  24269. * <file name="protractor.js" type="protractor">
  24270. * it("should split the text by newlines", function() {
  24271. * var listInput = element(by.model('list'));
  24272. * var output = element(by.binding('list | json'));
  24273. * listInput.sendKeys('abc\ndef\nghi');
  24274. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  24275. * });
  24276. * </file>
  24277. * </example>
  24278. *
  24279. * @element input
  24280. * @param {string=} ngList optional delimiter that should be used to split the value.
  24281. */
  24282. var ngListDirective = function() {
  24283. return {
  24284. restrict: 'A',
  24285. priority: 100,
  24286. require: 'ngModel',
  24287. link: function(scope, element, attr, ctrl) {
  24288. // We want to control whitespace trimming so we use this convoluted approach
  24289. // to access the ngList attribute, which doesn't pre-trim the attribute
  24290. var ngList = element.attr(attr.$attr.ngList) || ', ';
  24291. var trimValues = attr.ngTrim !== 'false';
  24292. var separator = trimValues ? trim(ngList) : ngList;
  24293. var parse = function(viewValue) {
  24294. // If the viewValue is invalid (say required but empty) it will be `undefined`
  24295. if (isUndefined(viewValue)) return;
  24296. var list = [];
  24297. if (viewValue) {
  24298. forEach(viewValue.split(separator), function(value) {
  24299. if (value) list.push(trimValues ? trim(value) : value);
  24300. });
  24301. }
  24302. return list;
  24303. };
  24304. ctrl.$parsers.push(parse);
  24305. ctrl.$formatters.push(function(value) {
  24306. if (isArray(value)) {
  24307. return value.join(ngList);
  24308. }
  24309. return undefined;
  24310. });
  24311. // Override the standard $isEmpty because an empty array means the input is empty.
  24312. ctrl.$isEmpty = function(value) {
  24313. return !value || !value.length;
  24314. };
  24315. }
  24316. };
  24317. };
  24318. /* global VALID_CLASS: true,
  24319. INVALID_CLASS: true,
  24320. PRISTINE_CLASS: true,
  24321. DIRTY_CLASS: true,
  24322. UNTOUCHED_CLASS: true,
  24323. TOUCHED_CLASS: true,
  24324. */
  24325. var VALID_CLASS = 'ng-valid',
  24326. INVALID_CLASS = 'ng-invalid',
  24327. PRISTINE_CLASS = 'ng-pristine',
  24328. DIRTY_CLASS = 'ng-dirty',
  24329. UNTOUCHED_CLASS = 'ng-untouched',
  24330. TOUCHED_CLASS = 'ng-touched',
  24331. PENDING_CLASS = 'ng-pending',
  24332. EMPTY_CLASS = 'ng-empty',
  24333. NOT_EMPTY_CLASS = 'ng-not-empty';
  24334. var ngModelMinErr = minErr('ngModel');
  24335. /**
  24336. * @ngdoc type
  24337. * @name ngModel.NgModelController
  24338. *
  24339. * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
  24340. * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
  24341. * is set.
  24342. * @property {*} $modelValue The value in the model that the control is bound to.
  24343. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  24344. the control reads value from the DOM. The functions are called in array order, each passing
  24345. its return value through to the next. The last return value is forwarded to the
  24346. {@link ngModel.NgModelController#$validators `$validators`} collection.
  24347. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  24348. `$viewValue`}.
  24349. Returning `undefined` from a parser means a parse error occurred. In that case,
  24350. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  24351. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  24352. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  24353. *
  24354. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  24355. the model value changes. The functions are called in reverse array order, each passing the value through to the
  24356. next. The last return value is used as the actual DOM value.
  24357. Used to format / convert values for display in the control.
  24358. * ```js
  24359. * function formatter(value) {
  24360. * if (value) {
  24361. * return value.toUpperCase();
  24362. * }
  24363. * }
  24364. * ngModel.$formatters.push(formatter);
  24365. * ```
  24366. *
  24367. * @property {Object.<string, function>} $validators A collection of validators that are applied
  24368. * whenever the model value changes. The key value within the object refers to the name of the
  24369. * validator while the function refers to the validation operation. The validation operation is
  24370. * provided with the model value as an argument and must return a true or false value depending
  24371. * on the response of that validation.
  24372. *
  24373. * ```js
  24374. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  24375. * var value = modelValue || viewValue;
  24376. * return /[0-9]+/.test(value) &&
  24377. * /[a-z]+/.test(value) &&
  24378. * /[A-Z]+/.test(value) &&
  24379. * /\W+/.test(value);
  24380. * };
  24381. * ```
  24382. *
  24383. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  24384. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  24385. * is expected to return a promise when it is run during the model validation process. Once the promise
  24386. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  24387. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  24388. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  24389. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  24390. * will only run once all synchronous validators have passed.
  24391. *
  24392. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  24393. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  24394. *
  24395. * ```js
  24396. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  24397. * var value = modelValue || viewValue;
  24398. *
  24399. * // Lookup user by username
  24400. * return $http.get('/api/users/' + value).
  24401. * then(function resolved() {
  24402. * //username exists, this means validation fails
  24403. * return $q.reject('exists');
  24404. * }, function rejected() {
  24405. * //username does not exist, therefore this validation passes
  24406. * return true;
  24407. * });
  24408. * };
  24409. * ```
  24410. *
  24411. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  24412. * view value has changed. It is called with no arguments, and its return value is ignored.
  24413. * This can be used in place of additional $watches against the model value.
  24414. *
  24415. * @property {Object} $error An object hash with all failing validator ids as keys.
  24416. * @property {Object} $pending An object hash with all pending validator ids as keys.
  24417. *
  24418. * @property {boolean} $untouched True if control has not lost focus yet.
  24419. * @property {boolean} $touched True if control has lost focus.
  24420. * @property {boolean} $pristine True if user has not interacted with the control yet.
  24421. * @property {boolean} $dirty True if user has already interacted with the control.
  24422. * @property {boolean} $valid True if there is no error.
  24423. * @property {boolean} $invalid True if at least one error on the control.
  24424. * @property {string} $name The name attribute of the control.
  24425. *
  24426. * @description
  24427. *
  24428. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  24429. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  24430. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  24431. * listening to DOM events.
  24432. * Such DOM related logic should be provided by other directives which make use of
  24433. * `NgModelController` for data-binding to control elements.
  24434. * Angular provides this DOM logic for most {@link input `input`} elements.
  24435. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  24436. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  24437. *
  24438. * @example
  24439. * ### Custom Control Example
  24440. * This example shows how to use `NgModelController` with a custom control to achieve
  24441. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  24442. * collaborate together to achieve the desired result.
  24443. *
  24444. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  24445. * contents be edited in place by the user.
  24446. *
  24447. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  24448. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  24449. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  24450. * that content using the `$sce` service.
  24451. *
  24452. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  24453. <file name="style.css">
  24454. [contenteditable] {
  24455. border: 1px solid black;
  24456. background-color: white;
  24457. min-height: 20px;
  24458. }
  24459. .ng-invalid {
  24460. border: 1px solid red;
  24461. }
  24462. </file>
  24463. <file name="script.js">
  24464. angular.module('customControl', ['ngSanitize']).
  24465. directive('contenteditable', ['$sce', function($sce) {
  24466. return {
  24467. restrict: 'A', // only activate on element attribute
  24468. require: '?ngModel', // get a hold of NgModelController
  24469. link: function(scope, element, attrs, ngModel) {
  24470. if (!ngModel) return; // do nothing if no ng-model
  24471. // Specify how UI should be updated
  24472. ngModel.$render = function() {
  24473. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  24474. };
  24475. // Listen for change events to enable binding
  24476. element.on('blur keyup change', function() {
  24477. scope.$evalAsync(read);
  24478. });
  24479. read(); // initialize
  24480. // Write data to the model
  24481. function read() {
  24482. var html = element.html();
  24483. // When we clear the content editable the browser leaves a <br> behind
  24484. // If strip-br attribute is provided then we strip this out
  24485. if ( attrs.stripBr && html == '<br>' ) {
  24486. html = '';
  24487. }
  24488. ngModel.$setViewValue(html);
  24489. }
  24490. }
  24491. };
  24492. }]);
  24493. </file>
  24494. <file name="index.html">
  24495. <form name="myForm">
  24496. <div contenteditable
  24497. name="myWidget" ng-model="userContent"
  24498. strip-br="true"
  24499. required>Change me!</div>
  24500. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  24501. <hr>
  24502. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  24503. </form>
  24504. </file>
  24505. <file name="protractor.js" type="protractor">
  24506. it('should data-bind and become invalid', function() {
  24507. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  24508. // SafariDriver can't handle contenteditable
  24509. // and Firefox driver can't clear contenteditables very well
  24510. return;
  24511. }
  24512. var contentEditable = element(by.css('[contenteditable]'));
  24513. var content = 'Change me!';
  24514. expect(contentEditable.getText()).toEqual(content);
  24515. contentEditable.clear();
  24516. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  24517. expect(contentEditable.getText()).toEqual('');
  24518. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  24519. });
  24520. </file>
  24521. * </example>
  24522. *
  24523. *
  24524. */
  24525. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
  24526. function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
  24527. this.$viewValue = Number.NaN;
  24528. this.$modelValue = Number.NaN;
  24529. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  24530. this.$validators = {};
  24531. this.$asyncValidators = {};
  24532. this.$parsers = [];
  24533. this.$formatters = [];
  24534. this.$viewChangeListeners = [];
  24535. this.$untouched = true;
  24536. this.$touched = false;
  24537. this.$pristine = true;
  24538. this.$dirty = false;
  24539. this.$valid = true;
  24540. this.$invalid = false;
  24541. this.$error = {}; // keep invalid keys here
  24542. this.$$success = {}; // keep valid keys here
  24543. this.$pending = undefined; // keep pending keys here
  24544. this.$name = $interpolate($attr.name || '', false)($scope);
  24545. this.$$parentForm = nullFormCtrl;
  24546. var parsedNgModel = $parse($attr.ngModel),
  24547. parsedNgModelAssign = parsedNgModel.assign,
  24548. ngModelGet = parsedNgModel,
  24549. ngModelSet = parsedNgModelAssign,
  24550. pendingDebounce = null,
  24551. parserValid,
  24552. ctrl = this;
  24553. this.$$setOptions = function(options) {
  24554. ctrl.$options = options;
  24555. if (options && options.getterSetter) {
  24556. var invokeModelGetter = $parse($attr.ngModel + '()'),
  24557. invokeModelSetter = $parse($attr.ngModel + '($$$p)');
  24558. ngModelGet = function($scope) {
  24559. var modelValue = parsedNgModel($scope);
  24560. if (isFunction(modelValue)) {
  24561. modelValue = invokeModelGetter($scope);
  24562. }
  24563. return modelValue;
  24564. };
  24565. ngModelSet = function($scope, newValue) {
  24566. if (isFunction(parsedNgModel($scope))) {
  24567. invokeModelSetter($scope, {$$$p: newValue});
  24568. } else {
  24569. parsedNgModelAssign($scope, newValue);
  24570. }
  24571. };
  24572. } else if (!parsedNgModel.assign) {
  24573. throw ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  24574. $attr.ngModel, startingTag($element));
  24575. }
  24576. };
  24577. /**
  24578. * @ngdoc method
  24579. * @name ngModel.NgModelController#$render
  24580. *
  24581. * @description
  24582. * Called when the view needs to be updated. It is expected that the user of the ng-model
  24583. * directive will implement this method.
  24584. *
  24585. * The `$render()` method is invoked in the following situations:
  24586. *
  24587. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  24588. * committed value then `$render()` is called to update the input control.
  24589. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  24590. * the `$viewValue` are different from last time.
  24591. *
  24592. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  24593. * `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue`
  24594. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  24595. * invoked if you only change a property on the objects.
  24596. */
  24597. this.$render = noop;
  24598. /**
  24599. * @ngdoc method
  24600. * @name ngModel.NgModelController#$isEmpty
  24601. *
  24602. * @description
  24603. * This is called when we need to determine if the value of an input is empty.
  24604. *
  24605. * For instance, the required directive does this to work out if the input has data or not.
  24606. *
  24607. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  24608. *
  24609. * You can override this for input directives whose concept of being empty is different from the
  24610. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  24611. * implies empty.
  24612. *
  24613. * @param {*} value The value of the input to check for emptiness.
  24614. * @returns {boolean} True if `value` is "empty".
  24615. */
  24616. this.$isEmpty = function(value) {
  24617. return isUndefined(value) || value === '' || value === null || value !== value;
  24618. };
  24619. this.$$updateEmptyClasses = function(value) {
  24620. if (ctrl.$isEmpty(value)) {
  24621. $animate.removeClass($element, NOT_EMPTY_CLASS);
  24622. $animate.addClass($element, EMPTY_CLASS);
  24623. } else {
  24624. $animate.removeClass($element, EMPTY_CLASS);
  24625. $animate.addClass($element, NOT_EMPTY_CLASS);
  24626. }
  24627. };
  24628. var currentValidationRunId = 0;
  24629. /**
  24630. * @ngdoc method
  24631. * @name ngModel.NgModelController#$setValidity
  24632. *
  24633. * @description
  24634. * Change the validity state, and notify the form.
  24635. *
  24636. * This method can be called within $parsers/$formatters or a custom validation implementation.
  24637. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  24638. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  24639. *
  24640. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  24641. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  24642. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  24643. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  24644. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  24645. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  24646. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  24647. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  24648. * Skipped is used by Angular when validators do not run because of parse errors and
  24649. * when `$asyncValidators` do not run because any of the `$validators` failed.
  24650. */
  24651. addSetValidityMethod({
  24652. ctrl: this,
  24653. $element: $element,
  24654. set: function(object, property) {
  24655. object[property] = true;
  24656. },
  24657. unset: function(object, property) {
  24658. delete object[property];
  24659. },
  24660. $animate: $animate
  24661. });
  24662. /**
  24663. * @ngdoc method
  24664. * @name ngModel.NgModelController#$setPristine
  24665. *
  24666. * @description
  24667. * Sets the control to its pristine state.
  24668. *
  24669. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  24670. * state (`ng-pristine` class). A model is considered to be pristine when the control
  24671. * has not been changed from when first compiled.
  24672. */
  24673. this.$setPristine = function() {
  24674. ctrl.$dirty = false;
  24675. ctrl.$pristine = true;
  24676. $animate.removeClass($element, DIRTY_CLASS);
  24677. $animate.addClass($element, PRISTINE_CLASS);
  24678. };
  24679. /**
  24680. * @ngdoc method
  24681. * @name ngModel.NgModelController#$setDirty
  24682. *
  24683. * @description
  24684. * Sets the control to its dirty state.
  24685. *
  24686. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  24687. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  24688. * from when first compiled.
  24689. */
  24690. this.$setDirty = function() {
  24691. ctrl.$dirty = true;
  24692. ctrl.$pristine = false;
  24693. $animate.removeClass($element, PRISTINE_CLASS);
  24694. $animate.addClass($element, DIRTY_CLASS);
  24695. ctrl.$$parentForm.$setDirty();
  24696. };
  24697. /**
  24698. * @ngdoc method
  24699. * @name ngModel.NgModelController#$setUntouched
  24700. *
  24701. * @description
  24702. * Sets the control to its untouched state.
  24703. *
  24704. * This method can be called to remove the `ng-touched` class and set the control to its
  24705. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  24706. * by default, however this function can be used to restore that state if the model has
  24707. * already been touched by the user.
  24708. */
  24709. this.$setUntouched = function() {
  24710. ctrl.$touched = false;
  24711. ctrl.$untouched = true;
  24712. $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  24713. };
  24714. /**
  24715. * @ngdoc method
  24716. * @name ngModel.NgModelController#$setTouched
  24717. *
  24718. * @description
  24719. * Sets the control to its touched state.
  24720. *
  24721. * This method can be called to remove the `ng-untouched` class and set the control to its
  24722. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  24723. * first focused the control element and then shifted focus away from the control (blur event).
  24724. */
  24725. this.$setTouched = function() {
  24726. ctrl.$touched = true;
  24727. ctrl.$untouched = false;
  24728. $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  24729. };
  24730. /**
  24731. * @ngdoc method
  24732. * @name ngModel.NgModelController#$rollbackViewValue
  24733. *
  24734. * @description
  24735. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  24736. * which may be caused by a pending debounced event or because the input is waiting for a some
  24737. * future event.
  24738. *
  24739. * If you have an input that uses `ng-model-options` to set up debounced updates or updates that
  24740. * depend on special events such as blur, you can have a situation where there is a period when
  24741. * the `$viewValue` is out of sync with the ngModel's `$modelValue`.
  24742. *
  24743. * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update
  24744. * and reset the input to the last committed view value.
  24745. *
  24746. * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`
  24747. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  24748. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  24749. *
  24750. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  24751. * input which may have such events pending. This is important in order to make sure that the
  24752. * input field will be updated with the new model value and any pending operations are cancelled.
  24753. *
  24754. * <example name="ng-model-cancel-update" module="cancel-update-example">
  24755. * <file name="app.js">
  24756. * angular.module('cancel-update-example', [])
  24757. *
  24758. * .controller('CancelUpdateController', ['$scope', function($scope) {
  24759. * $scope.model = {};
  24760. *
  24761. * $scope.setEmpty = function(e, value, rollback) {
  24762. * if (e.keyCode == 27) {
  24763. * e.preventDefault();
  24764. * if (rollback) {
  24765. * $scope.myForm[value].$rollbackViewValue();
  24766. * }
  24767. * $scope.model[value] = '';
  24768. * }
  24769. * };
  24770. * }]);
  24771. * </file>
  24772. * <file name="index.html">
  24773. * <div ng-controller="CancelUpdateController">
  24774. * <p>Both of these inputs are only updated if they are blurred. Hitting escape should
  24775. * empty them. Follow these steps and observe the difference:</p>
  24776. * <ol>
  24777. * <li>Type something in the input. You will see that the model is not yet updated</li>
  24778. * <li>Press the Escape key.
  24779. * <ol>
  24780. * <li> In the first example, nothing happens, because the model is already '', and no
  24781. * update is detected. If you blur the input, the model will be set to the current view.
  24782. * </li>
  24783. * <li> In the second example, the pending update is cancelled, and the input is set back
  24784. * to the last committed view value (''). Blurring the input does nothing.
  24785. * </li>
  24786. * </ol>
  24787. * </li>
  24788. * </ol>
  24789. *
  24790. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  24791. * <div>
  24792. * <p id="inputDescription1">Without $rollbackViewValue():</p>
  24793. * <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1"
  24794. * ng-keydown="setEmpty($event, 'value1')">
  24795. * value1: "{{ model.value1 }}"
  24796. * </div>
  24797. *
  24798. * <div>
  24799. * <p id="inputDescription2">With $rollbackViewValue():</p>
  24800. * <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2"
  24801. * ng-keydown="setEmpty($event, 'value2', true)">
  24802. * value2: "{{ model.value2 }}"
  24803. * </div>
  24804. * </form>
  24805. * </div>
  24806. * </file>
  24807. <file name="style.css">
  24808. div {
  24809. display: table-cell;
  24810. }
  24811. div:nth-child(1) {
  24812. padding-right: 30px;
  24813. }
  24814. </file>
  24815. * </example>
  24816. */
  24817. this.$rollbackViewValue = function() {
  24818. $timeout.cancel(pendingDebounce);
  24819. ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
  24820. ctrl.$render();
  24821. };
  24822. /**
  24823. * @ngdoc method
  24824. * @name ngModel.NgModelController#$validate
  24825. *
  24826. * @description
  24827. * Runs each of the registered validators (first synchronous validators and then
  24828. * asynchronous validators).
  24829. * If the validity changes to invalid, the model will be set to `undefined`,
  24830. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  24831. * If the validity changes to valid, it will set the model to the last available valid
  24832. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  24833. */
  24834. this.$validate = function() {
  24835. // ignore $validate before model is initialized
  24836. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  24837. return;
  24838. }
  24839. var viewValue = ctrl.$$lastCommittedViewValue;
  24840. // Note: we use the $$rawModelValue as $modelValue might have been
  24841. // set to undefined during a view -> model update that found validation
  24842. // errors. We can't parse the view here, since that could change
  24843. // the model although neither viewValue nor the model on the scope changed
  24844. var modelValue = ctrl.$$rawModelValue;
  24845. var prevValid = ctrl.$valid;
  24846. var prevModelValue = ctrl.$modelValue;
  24847. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  24848. ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
  24849. // If there was no change in validity, don't update the model
  24850. // This prevents changing an invalid modelValue to undefined
  24851. if (!allowInvalid && prevValid !== allValid) {
  24852. // Note: Don't check ctrl.$valid here, as we could have
  24853. // external validators (e.g. calculated on the server),
  24854. // that just call $setValidity and need the model value
  24855. // to calculate their validity.
  24856. ctrl.$modelValue = allValid ? modelValue : undefined;
  24857. if (ctrl.$modelValue !== prevModelValue) {
  24858. ctrl.$$writeModelToScope();
  24859. }
  24860. }
  24861. });
  24862. };
  24863. this.$$runValidators = function(modelValue, viewValue, doneCallback) {
  24864. currentValidationRunId++;
  24865. var localValidationRunId = currentValidationRunId;
  24866. // check parser error
  24867. if (!processParseErrors()) {
  24868. validationDone(false);
  24869. return;
  24870. }
  24871. if (!processSyncValidators()) {
  24872. validationDone(false);
  24873. return;
  24874. }
  24875. processAsyncValidators();
  24876. function processParseErrors() {
  24877. var errorKey = ctrl.$$parserName || 'parse';
  24878. if (isUndefined(parserValid)) {
  24879. setValidity(errorKey, null);
  24880. } else {
  24881. if (!parserValid) {
  24882. forEach(ctrl.$validators, function(v, name) {
  24883. setValidity(name, null);
  24884. });
  24885. forEach(ctrl.$asyncValidators, function(v, name) {
  24886. setValidity(name, null);
  24887. });
  24888. }
  24889. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  24890. setValidity(errorKey, parserValid);
  24891. return parserValid;
  24892. }
  24893. return true;
  24894. }
  24895. function processSyncValidators() {
  24896. var syncValidatorsValid = true;
  24897. forEach(ctrl.$validators, function(validator, name) {
  24898. var result = validator(modelValue, viewValue);
  24899. syncValidatorsValid = syncValidatorsValid && result;
  24900. setValidity(name, result);
  24901. });
  24902. if (!syncValidatorsValid) {
  24903. forEach(ctrl.$asyncValidators, function(v, name) {
  24904. setValidity(name, null);
  24905. });
  24906. return false;
  24907. }
  24908. return true;
  24909. }
  24910. function processAsyncValidators() {
  24911. var validatorPromises = [];
  24912. var allValid = true;
  24913. forEach(ctrl.$asyncValidators, function(validator, name) {
  24914. var promise = validator(modelValue, viewValue);
  24915. if (!isPromiseLike(promise)) {
  24916. throw ngModelMinErr('nopromise',
  24917. "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
  24918. }
  24919. setValidity(name, undefined);
  24920. validatorPromises.push(promise.then(function() {
  24921. setValidity(name, true);
  24922. }, function() {
  24923. allValid = false;
  24924. setValidity(name, false);
  24925. }));
  24926. });
  24927. if (!validatorPromises.length) {
  24928. validationDone(true);
  24929. } else {
  24930. $q.all(validatorPromises).then(function() {
  24931. validationDone(allValid);
  24932. }, noop);
  24933. }
  24934. }
  24935. function setValidity(name, isValid) {
  24936. if (localValidationRunId === currentValidationRunId) {
  24937. ctrl.$setValidity(name, isValid);
  24938. }
  24939. }
  24940. function validationDone(allValid) {
  24941. if (localValidationRunId === currentValidationRunId) {
  24942. doneCallback(allValid);
  24943. }
  24944. }
  24945. };
  24946. /**
  24947. * @ngdoc method
  24948. * @name ngModel.NgModelController#$commitViewValue
  24949. *
  24950. * @description
  24951. * Commit a pending update to the `$modelValue`.
  24952. *
  24953. * Updates may be pending by a debounced event or because the input is waiting for a some future
  24954. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  24955. * usually handles calling this in response to input events.
  24956. */
  24957. this.$commitViewValue = function() {
  24958. var viewValue = ctrl.$viewValue;
  24959. $timeout.cancel(pendingDebounce);
  24960. // If the view value has not changed then we should just exit, except in the case where there is
  24961. // a native validator on the element. In this case the validation state may have changed even though
  24962. // the viewValue has stayed empty.
  24963. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
  24964. return;
  24965. }
  24966. ctrl.$$updateEmptyClasses(viewValue);
  24967. ctrl.$$lastCommittedViewValue = viewValue;
  24968. // change to dirty
  24969. if (ctrl.$pristine) {
  24970. this.$setDirty();
  24971. }
  24972. this.$$parseAndValidate();
  24973. };
  24974. this.$$parseAndValidate = function() {
  24975. var viewValue = ctrl.$$lastCommittedViewValue;
  24976. var modelValue = viewValue;
  24977. parserValid = isUndefined(modelValue) ? undefined : true;
  24978. if (parserValid) {
  24979. for (var i = 0; i < ctrl.$parsers.length; i++) {
  24980. modelValue = ctrl.$parsers[i](modelValue);
  24981. if (isUndefined(modelValue)) {
  24982. parserValid = false;
  24983. break;
  24984. }
  24985. }
  24986. }
  24987. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  24988. // ctrl.$modelValue has not been touched yet...
  24989. ctrl.$modelValue = ngModelGet($scope);
  24990. }
  24991. var prevModelValue = ctrl.$modelValue;
  24992. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  24993. ctrl.$$rawModelValue = modelValue;
  24994. if (allowInvalid) {
  24995. ctrl.$modelValue = modelValue;
  24996. writeToModelIfNeeded();
  24997. }
  24998. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  24999. // This can happen if e.g. $setViewValue is called from inside a parser
  25000. ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
  25001. if (!allowInvalid) {
  25002. // Note: Don't check ctrl.$valid here, as we could have
  25003. // external validators (e.g. calculated on the server),
  25004. // that just call $setValidity and need the model value
  25005. // to calculate their validity.
  25006. ctrl.$modelValue = allValid ? modelValue : undefined;
  25007. writeToModelIfNeeded();
  25008. }
  25009. });
  25010. function writeToModelIfNeeded() {
  25011. if (ctrl.$modelValue !== prevModelValue) {
  25012. ctrl.$$writeModelToScope();
  25013. }
  25014. }
  25015. };
  25016. this.$$writeModelToScope = function() {
  25017. ngModelSet($scope, ctrl.$modelValue);
  25018. forEach(ctrl.$viewChangeListeners, function(listener) {
  25019. try {
  25020. listener();
  25021. } catch (e) {
  25022. $exceptionHandler(e);
  25023. }
  25024. });
  25025. };
  25026. /**
  25027. * @ngdoc method
  25028. * @name ngModel.NgModelController#$setViewValue
  25029. *
  25030. * @description
  25031. * Update the view value.
  25032. *
  25033. * This method should be called when a control wants to change the view value; typically,
  25034. * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
  25035. * directive calls it when the value of the input changes and {@link ng.directive:select select}
  25036. * calls it when an option is selected.
  25037. *
  25038. * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
  25039. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  25040. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  25041. * **expression** specified in the `ng-model` attribute. Lastly, all the registered change listeners,
  25042. * in the `$viewChangeListeners` list, are called.
  25043. *
  25044. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  25045. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  25046. * `updateOn` events is triggered on the DOM element.
  25047. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  25048. * directive is used with a custom debounce for this particular event.
  25049. * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
  25050. * is specified, once the timer runs out.
  25051. *
  25052. * When used with standard inputs, the view value will always be a string (which is in some cases
  25053. * parsed into another type, such as a `Date` object for `input[date]`.)
  25054. * However, custom controls might also pass objects to this method. In this case, we should make
  25055. * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
  25056. * perform a deep watch of objects, it only looks for a change of identity. If you only change
  25057. * the property of the object then ngModel will not realize that the object has changed and
  25058. * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
  25059. * not change properties of the copy once it has been passed to `$setViewValue`.
  25060. * Otherwise you may cause the model value on the scope to change incorrectly.
  25061. *
  25062. * <div class="alert alert-info">
  25063. * In any case, the value passed to the method should always reflect the current value
  25064. * of the control. For example, if you are calling `$setViewValue` for an input element,
  25065. * you should pass the input DOM value. Otherwise, the control and the scope model become
  25066. * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
  25067. * the control's DOM value in any way. If we want to change the control's DOM value
  25068. * programmatically, we should update the `ngModel` scope expression. Its new value will be
  25069. * picked up by the model controller, which will run it through the `$formatters`, `$render` it
  25070. * to update the DOM, and finally call `$validate` on it.
  25071. * </div>
  25072. *
  25073. * @param {*} value value from the view.
  25074. * @param {string} trigger Event that triggered the update.
  25075. */
  25076. this.$setViewValue = function(value, trigger) {
  25077. ctrl.$viewValue = value;
  25078. if (!ctrl.$options || ctrl.$options.updateOnDefault) {
  25079. ctrl.$$debounceViewValueCommit(trigger);
  25080. }
  25081. };
  25082. this.$$debounceViewValueCommit = function(trigger) {
  25083. var debounceDelay = 0,
  25084. options = ctrl.$options,
  25085. debounce;
  25086. if (options && isDefined(options.debounce)) {
  25087. debounce = options.debounce;
  25088. if (isNumber(debounce)) {
  25089. debounceDelay = debounce;
  25090. } else if (isNumber(debounce[trigger])) {
  25091. debounceDelay = debounce[trigger];
  25092. } else if (isNumber(debounce['default'])) {
  25093. debounceDelay = debounce['default'];
  25094. }
  25095. }
  25096. $timeout.cancel(pendingDebounce);
  25097. if (debounceDelay) {
  25098. pendingDebounce = $timeout(function() {
  25099. ctrl.$commitViewValue();
  25100. }, debounceDelay);
  25101. } else if ($rootScope.$$phase) {
  25102. ctrl.$commitViewValue();
  25103. } else {
  25104. $scope.$apply(function() {
  25105. ctrl.$commitViewValue();
  25106. });
  25107. }
  25108. };
  25109. // model -> value
  25110. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  25111. // 1. scope value is 'a'
  25112. // 2. user enters 'b'
  25113. // 3. ng-change kicks in and reverts scope value to 'a'
  25114. // -> scope value did not change since the last digest as
  25115. // ng-change executes in apply phase
  25116. // 4. view should be changed back to 'a'
  25117. $scope.$watch(function ngModelWatch() {
  25118. var modelValue = ngModelGet($scope);
  25119. // if scope model value and ngModel value are out of sync
  25120. // TODO(perf): why not move this to the action fn?
  25121. if (modelValue !== ctrl.$modelValue &&
  25122. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  25123. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  25124. ) {
  25125. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  25126. parserValid = undefined;
  25127. var formatters = ctrl.$formatters,
  25128. idx = formatters.length;
  25129. var viewValue = modelValue;
  25130. while (idx--) {
  25131. viewValue = formatters[idx](viewValue);
  25132. }
  25133. if (ctrl.$viewValue !== viewValue) {
  25134. ctrl.$$updateEmptyClasses(viewValue);
  25135. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  25136. ctrl.$render();
  25137. ctrl.$$runValidators(modelValue, viewValue, noop);
  25138. }
  25139. }
  25140. return modelValue;
  25141. });
  25142. }];
  25143. /**
  25144. * @ngdoc directive
  25145. * @name ngModel
  25146. *
  25147. * @element input
  25148. * @priority 1
  25149. *
  25150. * @description
  25151. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  25152. * property on the scope using {@link ngModel.NgModelController NgModelController},
  25153. * which is created and exposed by this directive.
  25154. *
  25155. * `ngModel` is responsible for:
  25156. *
  25157. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  25158. * require.
  25159. * - Providing validation behavior (i.e. required, number, email, url).
  25160. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  25161. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
  25162. * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
  25163. * - Registering the control with its parent {@link ng.directive:form form}.
  25164. *
  25165. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  25166. * current scope. If the property doesn't already exist on this scope, it will be created
  25167. * implicitly and added to the scope.
  25168. *
  25169. * For best practices on using `ngModel`, see:
  25170. *
  25171. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  25172. *
  25173. * For basic examples, how to use `ngModel`, see:
  25174. *
  25175. * - {@link ng.directive:input input}
  25176. * - {@link input[text] text}
  25177. * - {@link input[checkbox] checkbox}
  25178. * - {@link input[radio] radio}
  25179. * - {@link input[number] number}
  25180. * - {@link input[email] email}
  25181. * - {@link input[url] url}
  25182. * - {@link input[date] date}
  25183. * - {@link input[datetime-local] datetime-local}
  25184. * - {@link input[time] time}
  25185. * - {@link input[month] month}
  25186. * - {@link input[week] week}
  25187. * - {@link ng.directive:select select}
  25188. * - {@link ng.directive:textarea textarea}
  25189. *
  25190. * # Complex Models (objects or collections)
  25191. *
  25192. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  25193. * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the
  25194. * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered.
  25195. *
  25196. * The model must be assigned an entirely new object or collection before a re-rendering will occur.
  25197. *
  25198. * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression
  25199. * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or
  25200. * if the select is given the `multiple` attribute.
  25201. *
  25202. * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the
  25203. * first level of the object (or only changing the properties of an item in the collection if it's an array) will still
  25204. * not trigger a re-rendering of the model.
  25205. *
  25206. * # CSS classes
  25207. * The following CSS classes are added and removed on the associated input/select/textarea element
  25208. * depending on the validity of the model.
  25209. *
  25210. * - `ng-valid`: the model is valid
  25211. * - `ng-invalid`: the model is invalid
  25212. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  25213. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  25214. * - `ng-pristine`: the control hasn't been interacted with yet
  25215. * - `ng-dirty`: the control has been interacted with
  25216. * - `ng-touched`: the control has been blurred
  25217. * - `ng-untouched`: the control hasn't been blurred
  25218. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  25219. * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
  25220. * by the {@link ngModel.NgModelController#$isEmpty} method
  25221. * - `ng-not-empty`: the view contains a non-empty value
  25222. *
  25223. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  25224. *
  25225. * ## Animation Hooks
  25226. *
  25227. * Animations within models are triggered when any of the associated CSS classes are added and removed
  25228. * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
  25229. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  25230. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  25231. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  25232. *
  25233. * The following example shows a simple way to utilize CSS transitions to style an input element
  25234. * that has been rendered as invalid after it has been validated:
  25235. *
  25236. * <pre>
  25237. * //be sure to include ngAnimate as a module to hook into more
  25238. * //advanced animations
  25239. * .my-input {
  25240. * transition:0.5s linear all;
  25241. * background: white;
  25242. * }
  25243. * .my-input.ng-invalid {
  25244. * background: red;
  25245. * color:white;
  25246. * }
  25247. * </pre>
  25248. *
  25249. * @example
  25250. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  25251. <file name="index.html">
  25252. <script>
  25253. angular.module('inputExample', [])
  25254. .controller('ExampleController', ['$scope', function($scope) {
  25255. $scope.val = '1';
  25256. }]);
  25257. </script>
  25258. <style>
  25259. .my-input {
  25260. transition:all linear 0.5s;
  25261. background: transparent;
  25262. }
  25263. .my-input.ng-invalid {
  25264. color:white;
  25265. background: red;
  25266. }
  25267. </style>
  25268. <p id="inputDescription">
  25269. Update input to see transitions when valid/invalid.
  25270. Integer is a valid value.
  25271. </p>
  25272. <form name="testForm" ng-controller="ExampleController">
  25273. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  25274. aria-describedby="inputDescription" />
  25275. </form>
  25276. </file>
  25277. * </example>
  25278. *
  25279. * ## Binding to a getter/setter
  25280. *
  25281. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  25282. * function that returns a representation of the model when called with zero arguments, and sets
  25283. * the internal state of a model when called with an argument. It's sometimes useful to use this
  25284. * for models that have an internal representation that's different from what the model exposes
  25285. * to the view.
  25286. *
  25287. * <div class="alert alert-success">
  25288. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  25289. * frequently than other parts of your code.
  25290. * </div>
  25291. *
  25292. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  25293. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  25294. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  25295. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  25296. *
  25297. * The following example shows how to use `ngModel` with a getter/setter:
  25298. *
  25299. * @example
  25300. * <example name="ngModel-getter-setter" module="getterSetterExample">
  25301. <file name="index.html">
  25302. <div ng-controller="ExampleController">
  25303. <form name="userForm">
  25304. <label>Name:
  25305. <input type="text" name="userName"
  25306. ng-model="user.name"
  25307. ng-model-options="{ getterSetter: true }" />
  25308. </label>
  25309. </form>
  25310. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  25311. </div>
  25312. </file>
  25313. <file name="app.js">
  25314. angular.module('getterSetterExample', [])
  25315. .controller('ExampleController', ['$scope', function($scope) {
  25316. var _name = 'Brian';
  25317. $scope.user = {
  25318. name: function(newName) {
  25319. // Note that newName can be undefined for two reasons:
  25320. // 1. Because it is called as a getter and thus called with no arguments
  25321. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  25322. // input is invalid
  25323. return arguments.length ? (_name = newName) : _name;
  25324. }
  25325. };
  25326. }]);
  25327. </file>
  25328. * </example>
  25329. */
  25330. var ngModelDirective = ['$rootScope', function($rootScope) {
  25331. return {
  25332. restrict: 'A',
  25333. require: ['ngModel', '^?form', '^?ngModelOptions'],
  25334. controller: NgModelController,
  25335. // Prelink needs to run before any input directive
  25336. // so that we can set the NgModelOptions in NgModelController
  25337. // before anyone else uses it.
  25338. priority: 1,
  25339. compile: function ngModelCompile(element) {
  25340. // Setup initial state of the control
  25341. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  25342. return {
  25343. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  25344. var modelCtrl = ctrls[0],
  25345. formCtrl = ctrls[1] || modelCtrl.$$parentForm;
  25346. modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
  25347. // notify others, especially parent forms
  25348. formCtrl.$addControl(modelCtrl);
  25349. attr.$observe('name', function(newValue) {
  25350. if (modelCtrl.$name !== newValue) {
  25351. modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
  25352. }
  25353. });
  25354. scope.$on('$destroy', function() {
  25355. modelCtrl.$$parentForm.$removeControl(modelCtrl);
  25356. });
  25357. },
  25358. post: function ngModelPostLink(scope, element, attr, ctrls) {
  25359. var modelCtrl = ctrls[0];
  25360. if (modelCtrl.$options && modelCtrl.$options.updateOn) {
  25361. element.on(modelCtrl.$options.updateOn, function(ev) {
  25362. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  25363. });
  25364. }
  25365. element.on('blur', function() {
  25366. if (modelCtrl.$touched) return;
  25367. if ($rootScope.$$phase) {
  25368. scope.$evalAsync(modelCtrl.$setTouched);
  25369. } else {
  25370. scope.$apply(modelCtrl.$setTouched);
  25371. }
  25372. });
  25373. }
  25374. };
  25375. }
  25376. };
  25377. }];
  25378. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  25379. /**
  25380. * @ngdoc directive
  25381. * @name ngModelOptions
  25382. *
  25383. * @description
  25384. * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
  25385. * events that will trigger a model update and/or a debouncing delay so that the actual update only
  25386. * takes place when a timer expires; this timer will be reset after another change takes place.
  25387. *
  25388. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  25389. * be different from the value in the actual model. This means that if you update the model you
  25390. * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
  25391. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  25392. *
  25393. * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
  25394. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  25395. * important because `form` controllers are published to the related scope under the name in their
  25396. * `name` attribute.
  25397. *
  25398. * Any pending changes will take place immediately when an enclosing form is submitted via the
  25399. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  25400. * to have access to the updated model.
  25401. *
  25402. * `ngModelOptions` has an effect on the element it's declared on and its descendants.
  25403. *
  25404. * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
  25405. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  25406. * events using an space delimited list. There is a special event called `default` that
  25407. * matches the default events belonging of the control.
  25408. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  25409. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  25410. * custom value for each event. For example:
  25411. * `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
  25412. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  25413. * not validate correctly instead of the default behavior of setting the model to undefined.
  25414. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  25415. `ngModel` as getters/setters.
  25416. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  25417. * `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
  25418. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  25419. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  25420. * If not specified, the timezone of the browser will be used.
  25421. *
  25422. * @example
  25423. The following example shows how to override immediate updates. Changes on the inputs within the
  25424. form will update the model only when the control loses focus (blur event). If `escape` key is
  25425. pressed while the input field is focused, the value is reset to the value in the current model.
  25426. <example name="ngModelOptions-directive-blur" module="optionsExample">
  25427. <file name="index.html">
  25428. <div ng-controller="ExampleController">
  25429. <form name="userForm">
  25430. <label>Name:
  25431. <input type="text" name="userName"
  25432. ng-model="user.name"
  25433. ng-model-options="{ updateOn: 'blur' }"
  25434. ng-keyup="cancel($event)" />
  25435. </label><br />
  25436. <label>Other data:
  25437. <input type="text" ng-model="user.data" />
  25438. </label><br />
  25439. </form>
  25440. <pre>user.name = <span ng-bind="user.name"></span></pre>
  25441. <pre>user.data = <span ng-bind="user.data"></span></pre>
  25442. </div>
  25443. </file>
  25444. <file name="app.js">
  25445. angular.module('optionsExample', [])
  25446. .controller('ExampleController', ['$scope', function($scope) {
  25447. $scope.user = { name: 'John', data: '' };
  25448. $scope.cancel = function(e) {
  25449. if (e.keyCode == 27) {
  25450. $scope.userForm.userName.$rollbackViewValue();
  25451. }
  25452. };
  25453. }]);
  25454. </file>
  25455. <file name="protractor.js" type="protractor">
  25456. var model = element(by.binding('user.name'));
  25457. var input = element(by.model('user.name'));
  25458. var other = element(by.model('user.data'));
  25459. it('should allow custom events', function() {
  25460. input.sendKeys(' Doe');
  25461. input.click();
  25462. expect(model.getText()).toEqual('John');
  25463. other.click();
  25464. expect(model.getText()).toEqual('John Doe');
  25465. });
  25466. it('should $rollbackViewValue when model changes', function() {
  25467. input.sendKeys(' Doe');
  25468. expect(input.getAttribute('value')).toEqual('John Doe');
  25469. input.sendKeys(protractor.Key.ESCAPE);
  25470. expect(input.getAttribute('value')).toEqual('John');
  25471. other.click();
  25472. expect(model.getText()).toEqual('John');
  25473. });
  25474. </file>
  25475. </example>
  25476. This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
  25477. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  25478. <example name="ngModelOptions-directive-debounce" module="optionsExample">
  25479. <file name="index.html">
  25480. <div ng-controller="ExampleController">
  25481. <form name="userForm">
  25482. <label>Name:
  25483. <input type="text" name="userName"
  25484. ng-model="user.name"
  25485. ng-model-options="{ debounce: 1000 }" />
  25486. </label>
  25487. <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
  25488. <br />
  25489. </form>
  25490. <pre>user.name = <span ng-bind="user.name"></span></pre>
  25491. </div>
  25492. </file>
  25493. <file name="app.js">
  25494. angular.module('optionsExample', [])
  25495. .controller('ExampleController', ['$scope', function($scope) {
  25496. $scope.user = { name: 'Igor' };
  25497. }]);
  25498. </file>
  25499. </example>
  25500. This one shows how to bind to getter/setters:
  25501. <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  25502. <file name="index.html">
  25503. <div ng-controller="ExampleController">
  25504. <form name="userForm">
  25505. <label>Name:
  25506. <input type="text" name="userName"
  25507. ng-model="user.name"
  25508. ng-model-options="{ getterSetter: true }" />
  25509. </label>
  25510. </form>
  25511. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  25512. </div>
  25513. </file>
  25514. <file name="app.js">
  25515. angular.module('getterSetterExample', [])
  25516. .controller('ExampleController', ['$scope', function($scope) {
  25517. var _name = 'Brian';
  25518. $scope.user = {
  25519. name: function(newName) {
  25520. // Note that newName can be undefined for two reasons:
  25521. // 1. Because it is called as a getter and thus called with no arguments
  25522. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  25523. // input is invalid
  25524. return arguments.length ? (_name = newName) : _name;
  25525. }
  25526. };
  25527. }]);
  25528. </file>
  25529. </example>
  25530. */
  25531. var ngModelOptionsDirective = function() {
  25532. return {
  25533. restrict: 'A',
  25534. controller: ['$scope', '$attrs', function($scope, $attrs) {
  25535. var that = this;
  25536. this.$options = copy($scope.$eval($attrs.ngModelOptions));
  25537. // Allow adding/overriding bound events
  25538. if (isDefined(this.$options.updateOn)) {
  25539. this.$options.updateOnDefault = false;
  25540. // extract "default" pseudo-event from list of events that can trigger a model update
  25541. this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
  25542. that.$options.updateOnDefault = true;
  25543. return ' ';
  25544. }));
  25545. } else {
  25546. this.$options.updateOnDefault = true;
  25547. }
  25548. }]
  25549. };
  25550. };
  25551. // helper methods
  25552. function addSetValidityMethod(context) {
  25553. var ctrl = context.ctrl,
  25554. $element = context.$element,
  25555. classCache = {},
  25556. set = context.set,
  25557. unset = context.unset,
  25558. $animate = context.$animate;
  25559. classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
  25560. ctrl.$setValidity = setValidity;
  25561. function setValidity(validationErrorKey, state, controller) {
  25562. if (isUndefined(state)) {
  25563. createAndSet('$pending', validationErrorKey, controller);
  25564. } else {
  25565. unsetAndCleanup('$pending', validationErrorKey, controller);
  25566. }
  25567. if (!isBoolean(state)) {
  25568. unset(ctrl.$error, validationErrorKey, controller);
  25569. unset(ctrl.$$success, validationErrorKey, controller);
  25570. } else {
  25571. if (state) {
  25572. unset(ctrl.$error, validationErrorKey, controller);
  25573. set(ctrl.$$success, validationErrorKey, controller);
  25574. } else {
  25575. set(ctrl.$error, validationErrorKey, controller);
  25576. unset(ctrl.$$success, validationErrorKey, controller);
  25577. }
  25578. }
  25579. if (ctrl.$pending) {
  25580. cachedToggleClass(PENDING_CLASS, true);
  25581. ctrl.$valid = ctrl.$invalid = undefined;
  25582. toggleValidationCss('', null);
  25583. } else {
  25584. cachedToggleClass(PENDING_CLASS, false);
  25585. ctrl.$valid = isObjectEmpty(ctrl.$error);
  25586. ctrl.$invalid = !ctrl.$valid;
  25587. toggleValidationCss('', ctrl.$valid);
  25588. }
  25589. // re-read the state as the set/unset methods could have
  25590. // combined state in ctrl.$error[validationError] (used for forms),
  25591. // where setting/unsetting only increments/decrements the value,
  25592. // and does not replace it.
  25593. var combinedState;
  25594. if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
  25595. combinedState = undefined;
  25596. } else if (ctrl.$error[validationErrorKey]) {
  25597. combinedState = false;
  25598. } else if (ctrl.$$success[validationErrorKey]) {
  25599. combinedState = true;
  25600. } else {
  25601. combinedState = null;
  25602. }
  25603. toggleValidationCss(validationErrorKey, combinedState);
  25604. ctrl.$$parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
  25605. }
  25606. function createAndSet(name, value, controller) {
  25607. if (!ctrl[name]) {
  25608. ctrl[name] = {};
  25609. }
  25610. set(ctrl[name], value, controller);
  25611. }
  25612. function unsetAndCleanup(name, value, controller) {
  25613. if (ctrl[name]) {
  25614. unset(ctrl[name], value, controller);
  25615. }
  25616. if (isObjectEmpty(ctrl[name])) {
  25617. ctrl[name] = undefined;
  25618. }
  25619. }
  25620. function cachedToggleClass(className, switchValue) {
  25621. if (switchValue && !classCache[className]) {
  25622. $animate.addClass($element, className);
  25623. classCache[className] = true;
  25624. } else if (!switchValue && classCache[className]) {
  25625. $animate.removeClass($element, className);
  25626. classCache[className] = false;
  25627. }
  25628. }
  25629. function toggleValidationCss(validationErrorKey, isValid) {
  25630. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  25631. cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
  25632. cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
  25633. }
  25634. }
  25635. function isObjectEmpty(obj) {
  25636. if (obj) {
  25637. for (var prop in obj) {
  25638. if (obj.hasOwnProperty(prop)) {
  25639. return false;
  25640. }
  25641. }
  25642. }
  25643. return true;
  25644. }
  25645. /**
  25646. * @ngdoc directive
  25647. * @name ngNonBindable
  25648. * @restrict AC
  25649. * @priority 1000
  25650. *
  25651. * @description
  25652. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  25653. * DOM element. This is useful if the element contains what appears to be Angular directives and
  25654. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  25655. * displays snippets of code, for instance.
  25656. *
  25657. * @element ANY
  25658. *
  25659. * @example
  25660. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  25661. * but the one wrapped in `ngNonBindable` is left alone.
  25662. *
  25663. * @example
  25664. <example>
  25665. <file name="index.html">
  25666. <div>Normal: {{1 + 2}}</div>
  25667. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  25668. </file>
  25669. <file name="protractor.js" type="protractor">
  25670. it('should check ng-non-bindable', function() {
  25671. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  25672. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  25673. });
  25674. </file>
  25675. </example>
  25676. */
  25677. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  25678. /* global jqLiteRemove */
  25679. var ngOptionsMinErr = minErr('ngOptions');
  25680. /**
  25681. * @ngdoc directive
  25682. * @name ngOptions
  25683. * @restrict A
  25684. *
  25685. * @description
  25686. *
  25687. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  25688. * elements for the `<select>` element using the array or object obtained by evaluating the
  25689. * `ngOptions` comprehension expression.
  25690. *
  25691. * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
  25692. * similar result. However, `ngOptions` provides some benefits such as reducing memory and
  25693. * increasing speed by not creating a new scope for each repeated instance, as well as providing
  25694. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  25695. * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
  25696. * to a non-string value. This is because an option element can only be bound to string values at
  25697. * present.
  25698. *
  25699. * When an item in the `<select>` menu is selected, the array element or object property
  25700. * represented by the selected option will be bound to the model identified by the `ngModel`
  25701. * directive.
  25702. *
  25703. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  25704. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  25705. * option. See example below for demonstration.
  25706. *
  25707. * ## Complex Models (objects or collections)
  25708. *
  25709. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  25710. * binding the select to a model that is an object or a collection.
  25711. *
  25712. * One issue occurs if you want to preselect an option. For example, if you set
  25713. * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
  25714. * because the objects are not identical. So by default, you should always reference the item in your collection
  25715. * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
  25716. *
  25717. * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
  25718. * of the item not by reference, but by the result of the `track by` expression. For example, if your
  25719. * collection items have an id property, you would `track by item.id`.
  25720. *
  25721. * A different issue with objects or collections is that ngModel won't detect if an object property or
  25722. * a collection item changes. For that reason, `ngOptions` additionally watches the model using
  25723. * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
  25724. * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
  25725. * has not changed identity, but only a property on the object or an item in the collection changes.
  25726. *
  25727. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  25728. * if the model is an array). This means that changing a property deeper than the first level inside the
  25729. * object/collection will not trigger a re-rendering.
  25730. *
  25731. * ## `select` **`as`**
  25732. *
  25733. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  25734. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  25735. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  25736. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  25737. *
  25738. *
  25739. * ### `select` **`as`** and **`track by`**
  25740. *
  25741. * <div class="alert alert-warning">
  25742. * Be careful when using `select` **`as`** and **`track by`** in the same expression.
  25743. * </div>
  25744. *
  25745. * Given this array of items on the $scope:
  25746. *
  25747. * ```js
  25748. * $scope.items = [{
  25749. * id: 1,
  25750. * label: 'aLabel',
  25751. * subItem: { name: 'aSubItem' }
  25752. * }, {
  25753. * id: 2,
  25754. * label: 'bLabel',
  25755. * subItem: { name: 'bSubItem' }
  25756. * }];
  25757. * ```
  25758. *
  25759. * This will work:
  25760. *
  25761. * ```html
  25762. * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
  25763. * ```
  25764. * ```js
  25765. * $scope.selected = $scope.items[0];
  25766. * ```
  25767. *
  25768. * but this will not work:
  25769. *
  25770. * ```html
  25771. * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
  25772. * ```
  25773. * ```js
  25774. * $scope.selected = $scope.items[0].subItem;
  25775. * ```
  25776. *
  25777. * In both examples, the **`track by`** expression is applied successfully to each `item` in the
  25778. * `items` array. Because the selected option has been set programmatically in the controller, the
  25779. * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
  25780. * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
  25781. * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
  25782. * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
  25783. * is not matched against any `<option>` and the `<select>` appears as having no selected value.
  25784. *
  25785. *
  25786. * @param {string} ngModel Assignable angular expression to data-bind to.
  25787. * @param {string=} name Property name of the form under which the control is published.
  25788. * @param {string=} required The control is considered valid only if value is entered.
  25789. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  25790. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  25791. * `required` when you want to data-bind to the `required` attribute.
  25792. * @param {comprehension_expression=} ngOptions in one of the following forms:
  25793. *
  25794. * * for array data sources:
  25795. * * `label` **`for`** `value` **`in`** `array`
  25796. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  25797. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  25798. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  25799. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  25800. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  25801. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  25802. * (for including a filter with `track by`)
  25803. * * for object data sources:
  25804. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  25805. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  25806. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  25807. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  25808. * * `select` **`as`** `label` **`group by`** `group`
  25809. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  25810. * * `select` **`as`** `label` **`disable when`** `disable`
  25811. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  25812. *
  25813. * Where:
  25814. *
  25815. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  25816. * * `value`: local variable which will refer to each item in the `array` or each property value
  25817. * of `object` during iteration.
  25818. * * `key`: local variable which will refer to a property name in `object` during iteration.
  25819. * * `label`: The result of this expression will be the label for `<option>` element. The
  25820. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  25821. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  25822. * element. If not specified, `select` expression will default to `value`.
  25823. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  25824. * DOM element.
  25825. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  25826. * element. Return `true` to disable.
  25827. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  25828. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  25829. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  25830. * even when the options are recreated (e.g. reloaded from the server).
  25831. *
  25832. * @example
  25833. <example module="selectExample">
  25834. <file name="index.html">
  25835. <script>
  25836. angular.module('selectExample', [])
  25837. .controller('ExampleController', ['$scope', function($scope) {
  25838. $scope.colors = [
  25839. {name:'black', shade:'dark'},
  25840. {name:'white', shade:'light', notAnOption: true},
  25841. {name:'red', shade:'dark'},
  25842. {name:'blue', shade:'dark', notAnOption: true},
  25843. {name:'yellow', shade:'light', notAnOption: false}
  25844. ];
  25845. $scope.myColor = $scope.colors[2]; // red
  25846. }]);
  25847. </script>
  25848. <div ng-controller="ExampleController">
  25849. <ul>
  25850. <li ng-repeat="color in colors">
  25851. <label>Name: <input ng-model="color.name"></label>
  25852. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  25853. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  25854. </li>
  25855. <li>
  25856. <button ng-click="colors.push({})">add</button>
  25857. </li>
  25858. </ul>
  25859. <hr/>
  25860. <label>Color (null not allowed):
  25861. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  25862. </label><br/>
  25863. <label>Color (null allowed):
  25864. <span class="nullable">
  25865. <select ng-model="myColor" ng-options="color.name for color in colors">
  25866. <option value="">-- choose color --</option>
  25867. </select>
  25868. </span></label><br/>
  25869. <label>Color grouped by shade:
  25870. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  25871. </select>
  25872. </label><br/>
  25873. <label>Color grouped by shade, with some disabled:
  25874. <select ng-model="myColor"
  25875. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  25876. </select>
  25877. </label><br/>
  25878. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  25879. <br/>
  25880. <hr/>
  25881. Currently selected: {{ {selected_color:myColor} }}
  25882. <div style="border:solid 1px black; height:20px"
  25883. ng-style="{'background-color':myColor.name}">
  25884. </div>
  25885. </div>
  25886. </file>
  25887. <file name="protractor.js" type="protractor">
  25888. it('should check ng-options', function() {
  25889. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  25890. element.all(by.model('myColor')).first().click();
  25891. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  25892. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  25893. element(by.css('.nullable select[ng-model="myColor"]')).click();
  25894. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  25895. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  25896. });
  25897. </file>
  25898. </example>
  25899. */
  25900. // jshint maxlen: false
  25901. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
  25902. 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]+?))?$/;
  25903. // 1: value expression (valueFn)
  25904. // 2: label expression (displayFn)
  25905. // 3: group by expression (groupByFn)
  25906. // 4: disable when expression (disableWhenFn)
  25907. // 5: array item variable name
  25908. // 6: object item key variable name
  25909. // 7: object item value variable name
  25910. // 8: collection expression
  25911. // 9: track by expression
  25912. // jshint maxlen: 100
  25913. var ngOptionsDirective = ['$compile', '$document', '$parse', function($compile, $document, $parse) {
  25914. function parseOptionsExpression(optionsExp, selectElement, scope) {
  25915. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  25916. if (!(match)) {
  25917. throw ngOptionsMinErr('iexp',
  25918. "Expected expression in form of " +
  25919. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  25920. " but got '{0}'. Element: {1}",
  25921. optionsExp, startingTag(selectElement));
  25922. }
  25923. // Extract the parts from the ngOptions expression
  25924. // The variable name for the value of the item in the collection
  25925. var valueName = match[5] || match[7];
  25926. // The variable name for the key of the item in the collection
  25927. var keyName = match[6];
  25928. // An expression that generates the viewValue for an option if there is a label expression
  25929. var selectAs = / as /.test(match[0]) && match[1];
  25930. // An expression that is used to track the id of each object in the options collection
  25931. var trackBy = match[9];
  25932. // An expression that generates the viewValue for an option if there is no label expression
  25933. var valueFn = $parse(match[2] ? match[1] : valueName);
  25934. var selectAsFn = selectAs && $parse(selectAs);
  25935. var viewValueFn = selectAsFn || valueFn;
  25936. var trackByFn = trackBy && $parse(trackBy);
  25937. // Get the value by which we are going to track the option
  25938. // if we have a trackFn then use that (passing scope and locals)
  25939. // otherwise just hash the given viewValue
  25940. var getTrackByValueFn = trackBy ?
  25941. function(value, locals) { return trackByFn(scope, locals); } :
  25942. function getHashOfValue(value) { return hashKey(value); };
  25943. var getTrackByValue = function(value, key) {
  25944. return getTrackByValueFn(value, getLocals(value, key));
  25945. };
  25946. var displayFn = $parse(match[2] || match[1]);
  25947. var groupByFn = $parse(match[3] || '');
  25948. var disableWhenFn = $parse(match[4] || '');
  25949. var valuesFn = $parse(match[8]);
  25950. var locals = {};
  25951. var getLocals = keyName ? function(value, key) {
  25952. locals[keyName] = key;
  25953. locals[valueName] = value;
  25954. return locals;
  25955. } : function(value) {
  25956. locals[valueName] = value;
  25957. return locals;
  25958. };
  25959. function Option(selectValue, viewValue, label, group, disabled) {
  25960. this.selectValue = selectValue;
  25961. this.viewValue = viewValue;
  25962. this.label = label;
  25963. this.group = group;
  25964. this.disabled = disabled;
  25965. }
  25966. function getOptionValuesKeys(optionValues) {
  25967. var optionValuesKeys;
  25968. if (!keyName && isArrayLike(optionValues)) {
  25969. optionValuesKeys = optionValues;
  25970. } else {
  25971. // if object, extract keys, in enumeration order, unsorted
  25972. optionValuesKeys = [];
  25973. for (var itemKey in optionValues) {
  25974. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  25975. optionValuesKeys.push(itemKey);
  25976. }
  25977. }
  25978. }
  25979. return optionValuesKeys;
  25980. }
  25981. return {
  25982. trackBy: trackBy,
  25983. getTrackByValue: getTrackByValue,
  25984. getWatchables: $parse(valuesFn, function(optionValues) {
  25985. // Create a collection of things that we would like to watch (watchedArray)
  25986. // so that they can all be watched using a single $watchCollection
  25987. // that only runs the handler once if anything changes
  25988. var watchedArray = [];
  25989. optionValues = optionValues || [];
  25990. var optionValuesKeys = getOptionValuesKeys(optionValues);
  25991. var optionValuesLength = optionValuesKeys.length;
  25992. for (var index = 0; index < optionValuesLength; index++) {
  25993. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  25994. var value = optionValues[key];
  25995. var locals = getLocals(value, key);
  25996. var selectValue = getTrackByValueFn(value, locals);
  25997. watchedArray.push(selectValue);
  25998. // Only need to watch the displayFn if there is a specific label expression
  25999. if (match[2] || match[1]) {
  26000. var label = displayFn(scope, locals);
  26001. watchedArray.push(label);
  26002. }
  26003. // Only need to watch the disableWhenFn if there is a specific disable expression
  26004. if (match[4]) {
  26005. var disableWhen = disableWhenFn(scope, locals);
  26006. watchedArray.push(disableWhen);
  26007. }
  26008. }
  26009. return watchedArray;
  26010. }),
  26011. getOptions: function() {
  26012. var optionItems = [];
  26013. var selectValueMap = {};
  26014. // The option values were already computed in the `getWatchables` fn,
  26015. // which must have been called to trigger `getOptions`
  26016. var optionValues = valuesFn(scope) || [];
  26017. var optionValuesKeys = getOptionValuesKeys(optionValues);
  26018. var optionValuesLength = optionValuesKeys.length;
  26019. for (var index = 0; index < optionValuesLength; index++) {
  26020. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  26021. var value = optionValues[key];
  26022. var locals = getLocals(value, key);
  26023. var viewValue = viewValueFn(scope, locals);
  26024. var selectValue = getTrackByValueFn(viewValue, locals);
  26025. var label = displayFn(scope, locals);
  26026. var group = groupByFn(scope, locals);
  26027. var disabled = disableWhenFn(scope, locals);
  26028. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  26029. optionItems.push(optionItem);
  26030. selectValueMap[selectValue] = optionItem;
  26031. }
  26032. return {
  26033. items: optionItems,
  26034. selectValueMap: selectValueMap,
  26035. getOptionFromViewValue: function(value) {
  26036. return selectValueMap[getTrackByValue(value)];
  26037. },
  26038. getViewValueFromOption: function(option) {
  26039. // If the viewValue could be an object that may be mutated by the application,
  26040. // we need to make a copy and not return the reference to the value on the option.
  26041. return trackBy ? angular.copy(option.viewValue) : option.viewValue;
  26042. }
  26043. };
  26044. }
  26045. };
  26046. }
  26047. // we can't just jqLite('<option>') since jqLite is not smart enough
  26048. // to create it in <select> and IE barfs otherwise.
  26049. var optionTemplate = window.document.createElement('option'),
  26050. optGroupTemplate = window.document.createElement('optgroup');
  26051. function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
  26052. var selectCtrl = ctrls[0];
  26053. var ngModelCtrl = ctrls[1];
  26054. var multiple = attr.multiple;
  26055. // The emptyOption allows the application developer to provide their own custom "empty"
  26056. // option when the viewValue does not match any of the option values.
  26057. var emptyOption;
  26058. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  26059. if (children[i].value === '') {
  26060. emptyOption = children.eq(i);
  26061. break;
  26062. }
  26063. }
  26064. var providedEmptyOption = !!emptyOption;
  26065. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  26066. unknownOption.val('?');
  26067. var options;
  26068. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  26069. // This stores the newly created options before they are appended to the select.
  26070. // Since the contents are removed from the fragment when it is appended,
  26071. // we only need to create it once.
  26072. var listFragment = $document[0].createDocumentFragment();
  26073. var renderEmptyOption = function() {
  26074. if (!providedEmptyOption) {
  26075. selectElement.prepend(emptyOption);
  26076. }
  26077. selectElement.val('');
  26078. emptyOption.prop('selected', true); // needed for IE
  26079. emptyOption.attr('selected', true);
  26080. };
  26081. var removeEmptyOption = function() {
  26082. if (!providedEmptyOption) {
  26083. emptyOption.remove();
  26084. }
  26085. };
  26086. var renderUnknownOption = function() {
  26087. selectElement.prepend(unknownOption);
  26088. selectElement.val('?');
  26089. unknownOption.prop('selected', true); // needed for IE
  26090. unknownOption.attr('selected', true);
  26091. };
  26092. var removeUnknownOption = function() {
  26093. unknownOption.remove();
  26094. };
  26095. // Update the controller methods for multiple selectable options
  26096. if (!multiple) {
  26097. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  26098. var option = options.getOptionFromViewValue(value);
  26099. if (option) {
  26100. // Don't update the option when it is already selected.
  26101. // For example, the browser will select the first option by default. In that case,
  26102. // most properties are set automatically - except the `selected` attribute, which we
  26103. // set always
  26104. if (selectElement[0].value !== option.selectValue) {
  26105. removeUnknownOption();
  26106. removeEmptyOption();
  26107. selectElement[0].value = option.selectValue;
  26108. option.element.selected = true;
  26109. }
  26110. option.element.setAttribute('selected', 'selected');
  26111. } else {
  26112. if (value === null || providedEmptyOption) {
  26113. removeUnknownOption();
  26114. renderEmptyOption();
  26115. } else {
  26116. removeEmptyOption();
  26117. renderUnknownOption();
  26118. }
  26119. }
  26120. };
  26121. selectCtrl.readValue = function readNgOptionsValue() {
  26122. var selectedOption = options.selectValueMap[selectElement.val()];
  26123. if (selectedOption && !selectedOption.disabled) {
  26124. removeEmptyOption();
  26125. removeUnknownOption();
  26126. return options.getViewValueFromOption(selectedOption);
  26127. }
  26128. return null;
  26129. };
  26130. // If we are using `track by` then we must watch the tracked value on the model
  26131. // since ngModel only watches for object identity change
  26132. if (ngOptions.trackBy) {
  26133. scope.$watch(
  26134. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  26135. function() { ngModelCtrl.$render(); }
  26136. );
  26137. }
  26138. } else {
  26139. ngModelCtrl.$isEmpty = function(value) {
  26140. return !value || value.length === 0;
  26141. };
  26142. selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
  26143. options.items.forEach(function(option) {
  26144. option.element.selected = false;
  26145. });
  26146. if (value) {
  26147. value.forEach(function(item) {
  26148. var option = options.getOptionFromViewValue(item);
  26149. if (option) option.element.selected = true;
  26150. });
  26151. }
  26152. };
  26153. selectCtrl.readValue = function readNgOptionsMultiple() {
  26154. var selectedValues = selectElement.val() || [],
  26155. selections = [];
  26156. forEach(selectedValues, function(value) {
  26157. var option = options.selectValueMap[value];
  26158. if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
  26159. });
  26160. return selections;
  26161. };
  26162. // If we are using `track by` then we must watch these tracked values on the model
  26163. // since ngModel only watches for object identity change
  26164. if (ngOptions.trackBy) {
  26165. scope.$watchCollection(function() {
  26166. if (isArray(ngModelCtrl.$viewValue)) {
  26167. return ngModelCtrl.$viewValue.map(function(value) {
  26168. return ngOptions.getTrackByValue(value);
  26169. });
  26170. }
  26171. }, function() {
  26172. ngModelCtrl.$render();
  26173. });
  26174. }
  26175. }
  26176. if (providedEmptyOption) {
  26177. // we need to remove it before calling selectElement.empty() because otherwise IE will
  26178. // remove the label from the element. wtf?
  26179. emptyOption.remove();
  26180. // compile the element since there might be bindings in it
  26181. $compile(emptyOption)(scope);
  26182. // remove the class, which is added automatically because we recompile the element and it
  26183. // becomes the compilation root
  26184. emptyOption.removeClass('ng-scope');
  26185. } else {
  26186. emptyOption = jqLite(optionTemplate.cloneNode(false));
  26187. }
  26188. selectElement.empty();
  26189. // We need to do this here to ensure that the options object is defined
  26190. // when we first hit it in writeNgOptionsValue
  26191. updateOptions();
  26192. // We will re-render the option elements if the option values or labels change
  26193. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  26194. // ------------------------------------------------------------------ //
  26195. function addOptionElement(option, parent) {
  26196. var optionElement = optionTemplate.cloneNode(false);
  26197. parent.appendChild(optionElement);
  26198. updateOptionElement(option, optionElement);
  26199. }
  26200. function updateOptionElement(option, element) {
  26201. option.element = element;
  26202. element.disabled = option.disabled;
  26203. // NOTE: The label must be set before the value, otherwise IE10/11/EDGE create unresponsive
  26204. // selects in certain circumstances when multiple selects are next to each other and display
  26205. // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
  26206. // See https://github.com/angular/angular.js/issues/11314 for more info.
  26207. // This is unfortunately untestable with unit / e2e tests
  26208. if (option.label !== element.label) {
  26209. element.label = option.label;
  26210. element.textContent = option.label;
  26211. }
  26212. if (option.value !== element.value) element.value = option.selectValue;
  26213. }
  26214. function updateOptions() {
  26215. var previousValue = options && selectCtrl.readValue();
  26216. // We must remove all current options, but cannot simply set innerHTML = null
  26217. // since the providedEmptyOption might have an ngIf on it that inserts comments which we
  26218. // must preserve.
  26219. // Instead, iterate over the current option elements and remove them or their optgroup
  26220. // parents
  26221. if (options) {
  26222. for (var i = options.items.length - 1; i >= 0; i--) {
  26223. var option = options.items[i];
  26224. if (option.group) {
  26225. jqLiteRemove(option.element.parentNode);
  26226. } else {
  26227. jqLiteRemove(option.element);
  26228. }
  26229. }
  26230. }
  26231. options = ngOptions.getOptions();
  26232. var groupElementMap = {};
  26233. // Ensure that the empty option is always there if it was explicitly provided
  26234. if (providedEmptyOption) {
  26235. selectElement.prepend(emptyOption);
  26236. }
  26237. options.items.forEach(function addOption(option) {
  26238. var groupElement;
  26239. if (isDefined(option.group)) {
  26240. // This option is to live in a group
  26241. // See if we have already created this group
  26242. groupElement = groupElementMap[option.group];
  26243. if (!groupElement) {
  26244. groupElement = optGroupTemplate.cloneNode(false);
  26245. listFragment.appendChild(groupElement);
  26246. // Update the label on the group element
  26247. groupElement.label = option.group;
  26248. // Store it for use later
  26249. groupElementMap[option.group] = groupElement;
  26250. }
  26251. addOptionElement(option, groupElement);
  26252. } else {
  26253. // This option is not in a group
  26254. addOptionElement(option, listFragment);
  26255. }
  26256. });
  26257. selectElement[0].appendChild(listFragment);
  26258. ngModelCtrl.$render();
  26259. // Check to see if the value has changed due to the update to the options
  26260. if (!ngModelCtrl.$isEmpty(previousValue)) {
  26261. var nextValue = selectCtrl.readValue();
  26262. var isNotPrimitive = ngOptions.trackBy || multiple;
  26263. if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
  26264. ngModelCtrl.$setViewValue(nextValue);
  26265. ngModelCtrl.$render();
  26266. }
  26267. }
  26268. }
  26269. }
  26270. return {
  26271. restrict: 'A',
  26272. terminal: true,
  26273. require: ['select', 'ngModel'],
  26274. link: {
  26275. pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
  26276. // Deactivate the SelectController.register method to prevent
  26277. // option directives from accidentally registering themselves
  26278. // (and unwanted $destroy handlers etc.)
  26279. ctrls[0].registerOption = noop;
  26280. },
  26281. post: ngOptionsPostLink
  26282. }
  26283. };
  26284. }];
  26285. /**
  26286. * @ngdoc directive
  26287. * @name ngPluralize
  26288. * @restrict EA
  26289. *
  26290. * @description
  26291. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  26292. * These rules are bundled with angular.js, but can be overridden
  26293. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  26294. * by specifying the mappings between
  26295. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  26296. * and the strings to be displayed.
  26297. *
  26298. * # Plural categories and explicit number rules
  26299. * There are two
  26300. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  26301. * in Angular's default en-US locale: "one" and "other".
  26302. *
  26303. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  26304. * any number that is not 1), an explicit number rule can only match one number. For example, the
  26305. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  26306. * and explicit number rules throughout the rest of this documentation.
  26307. *
  26308. * # Configuring ngPluralize
  26309. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  26310. * You can also provide an optional attribute, `offset`.
  26311. *
  26312. * The value of the `count` attribute can be either a string or an {@link guide/expression
  26313. * Angular expression}; these are evaluated on the current scope for its bound value.
  26314. *
  26315. * The `when` attribute specifies the mappings between plural categories and the actual
  26316. * string to be displayed. The value of the attribute should be a JSON object.
  26317. *
  26318. * The following example shows how to configure ngPluralize:
  26319. *
  26320. * ```html
  26321. * <ng-pluralize count="personCount"
  26322. when="{'0': 'Nobody is viewing.',
  26323. * 'one': '1 person is viewing.',
  26324. * 'other': '{} people are viewing.'}">
  26325. * </ng-pluralize>
  26326. *```
  26327. *
  26328. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  26329. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  26330. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  26331. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  26332. * show "a dozen people are viewing".
  26333. *
  26334. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  26335. * into pluralized strings. In the previous example, Angular will replace `{}` with
  26336. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  26337. * for <span ng-non-bindable>{{numberExpression}}</span>.
  26338. *
  26339. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  26340. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  26341. *
  26342. * # Configuring ngPluralize with offset
  26343. * The `offset` attribute allows further customization of pluralized text, which can result in
  26344. * a better user experience. For example, instead of the message "4 people are viewing this document",
  26345. * you might display "John, Kate and 2 others are viewing this document".
  26346. * The offset attribute allows you to offset a number by any desired value.
  26347. * Let's take a look at an example:
  26348. *
  26349. * ```html
  26350. * <ng-pluralize count="personCount" offset=2
  26351. * when="{'0': 'Nobody is viewing.',
  26352. * '1': '{{person1}} is viewing.',
  26353. * '2': '{{person1}} and {{person2}} are viewing.',
  26354. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  26355. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  26356. * </ng-pluralize>
  26357. * ```
  26358. *
  26359. * Notice that we are still using two plural categories(one, other), but we added
  26360. * three explicit number rules 0, 1 and 2.
  26361. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  26362. * When three people view the document, no explicit number rule is found, so
  26363. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  26364. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  26365. * is shown.
  26366. *
  26367. * Note that when you specify offsets, you must provide explicit number rules for
  26368. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  26369. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  26370. * plural categories "one" and "other".
  26371. *
  26372. * @param {string|expression} count The variable to be bound to.
  26373. * @param {string} when The mapping between plural category to its corresponding strings.
  26374. * @param {number=} offset Offset to deduct from the total number.
  26375. *
  26376. * @example
  26377. <example module="pluralizeExample">
  26378. <file name="index.html">
  26379. <script>
  26380. angular.module('pluralizeExample', [])
  26381. .controller('ExampleController', ['$scope', function($scope) {
  26382. $scope.person1 = 'Igor';
  26383. $scope.person2 = 'Misko';
  26384. $scope.personCount = 1;
  26385. }]);
  26386. </script>
  26387. <div ng-controller="ExampleController">
  26388. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  26389. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  26390. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  26391. <!--- Example with simple pluralization rules for en locale --->
  26392. Without Offset:
  26393. <ng-pluralize count="personCount"
  26394. when="{'0': 'Nobody is viewing.',
  26395. 'one': '1 person is viewing.',
  26396. 'other': '{} people are viewing.'}">
  26397. </ng-pluralize><br>
  26398. <!--- Example with offset --->
  26399. With Offset(2):
  26400. <ng-pluralize count="personCount" offset=2
  26401. when="{'0': 'Nobody is viewing.',
  26402. '1': '{{person1}} is viewing.',
  26403. '2': '{{person1}} and {{person2}} are viewing.',
  26404. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  26405. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  26406. </ng-pluralize>
  26407. </div>
  26408. </file>
  26409. <file name="protractor.js" type="protractor">
  26410. it('should show correct pluralized string', function() {
  26411. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  26412. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  26413. var countInput = element(by.model('personCount'));
  26414. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  26415. expect(withOffset.getText()).toEqual('Igor is viewing.');
  26416. countInput.clear();
  26417. countInput.sendKeys('0');
  26418. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  26419. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  26420. countInput.clear();
  26421. countInput.sendKeys('2');
  26422. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  26423. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  26424. countInput.clear();
  26425. countInput.sendKeys('3');
  26426. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  26427. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  26428. countInput.clear();
  26429. countInput.sendKeys('4');
  26430. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  26431. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  26432. });
  26433. it('should show data-bound names', function() {
  26434. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  26435. var personCount = element(by.model('personCount'));
  26436. var person1 = element(by.model('person1'));
  26437. var person2 = element(by.model('person2'));
  26438. personCount.clear();
  26439. personCount.sendKeys('4');
  26440. person1.clear();
  26441. person1.sendKeys('Di');
  26442. person2.clear();
  26443. person2.sendKeys('Vojta');
  26444. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  26445. });
  26446. </file>
  26447. </example>
  26448. */
  26449. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  26450. var BRACE = /{}/g,
  26451. IS_WHEN = /^when(Minus)?(.+)$/;
  26452. return {
  26453. link: function(scope, element, attr) {
  26454. var numberExp = attr.count,
  26455. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  26456. offset = attr.offset || 0,
  26457. whens = scope.$eval(whenExp) || {},
  26458. whensExpFns = {},
  26459. startSymbol = $interpolate.startSymbol(),
  26460. endSymbol = $interpolate.endSymbol(),
  26461. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  26462. watchRemover = angular.noop,
  26463. lastCount;
  26464. forEach(attr, function(expression, attributeName) {
  26465. var tmpMatch = IS_WHEN.exec(attributeName);
  26466. if (tmpMatch) {
  26467. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  26468. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  26469. }
  26470. });
  26471. forEach(whens, function(expression, key) {
  26472. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  26473. });
  26474. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  26475. var count = parseFloat(newVal);
  26476. var countIsNaN = isNaN(count);
  26477. if (!countIsNaN && !(count in whens)) {
  26478. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  26479. // Otherwise, check it against pluralization rules in $locale service.
  26480. count = $locale.pluralCat(count - offset);
  26481. }
  26482. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  26483. // In JS `NaN !== NaN`, so we have to explicitly check.
  26484. if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {
  26485. watchRemover();
  26486. var whenExpFn = whensExpFns[count];
  26487. if (isUndefined(whenExpFn)) {
  26488. if (newVal != null) {
  26489. $log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp);
  26490. }
  26491. watchRemover = noop;
  26492. updateElementText();
  26493. } else {
  26494. watchRemover = scope.$watch(whenExpFn, updateElementText);
  26495. }
  26496. lastCount = count;
  26497. }
  26498. });
  26499. function updateElementText(newText) {
  26500. element.text(newText || '');
  26501. }
  26502. }
  26503. };
  26504. }];
  26505. /**
  26506. * @ngdoc directive
  26507. * @name ngRepeat
  26508. * @multiElement
  26509. *
  26510. * @description
  26511. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  26512. * instance gets its own scope, where the given loop variable is set to the current collection item,
  26513. * and `$index` is set to the item index or key.
  26514. *
  26515. * Special properties are exposed on the local scope of each template instance, including:
  26516. *
  26517. * | Variable | Type | Details |
  26518. * |-----------|-----------------|-----------------------------------------------------------------------------|
  26519. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  26520. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  26521. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  26522. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  26523. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  26524. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  26525. *
  26526. * <div class="alert alert-info">
  26527. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  26528. * This may be useful when, for instance, nesting ngRepeats.
  26529. * </div>
  26530. *
  26531. *
  26532. * # Iterating over object properties
  26533. *
  26534. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  26535. * syntax:
  26536. *
  26537. * ```js
  26538. * <div ng-repeat="(key, value) in myObj"> ... </div>
  26539. * ```
  26540. *
  26541. * However, there are a limitations compared to array iteration:
  26542. *
  26543. * - The JavaScript specification does not define the order of keys
  26544. * returned for an object, so Angular relies on the order returned by the browser
  26545. * when running `for key in myObj`. Browsers generally follow the strategy of providing
  26546. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  26547. * and reinstated. See the
  26548. * [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
  26549. *
  26550. * - `ngRepeat` will silently *ignore* object keys starting with `$`, because
  26551. * it's a prefix used by Angular for public (`$`) and private (`$$`) properties.
  26552. *
  26553. * - The built-in filters {@link ng.orderBy orderBy} and {@link ng.filter filter} do not work with
  26554. * objects, and will throw an error if used with one.
  26555. *
  26556. * If you are hitting any of these limitations, the recommended workaround is to convert your object into an array
  26557. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  26558. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  26559. * or implement a `$watch` on the object yourself.
  26560. *
  26561. *
  26562. * # Tracking and Duplicates
  26563. *
  26564. * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
  26565. * the collection. When a change happens, ngRepeat then makes the corresponding changes to the DOM:
  26566. *
  26567. * * When an item is added, a new instance of the template is added to the DOM.
  26568. * * When an item is removed, its template instance is removed from the DOM.
  26569. * * When items are reordered, their respective templates are reordered in the DOM.
  26570. *
  26571. * To minimize creation of DOM elements, `ngRepeat` uses a function
  26572. * to "keep track" of all items in the collection and their corresponding DOM elements.
  26573. * For example, if an item is added to the collection, ngRepeat will know that all other items
  26574. * already have DOM elements, and will not re-render them.
  26575. *
  26576. * The default tracking function (which tracks items by their identity) does not allow
  26577. * duplicate items in arrays. This is because when there are duplicates, it is not possible
  26578. * to maintain a one-to-one mapping between collection items and DOM elements.
  26579. *
  26580. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  26581. * with your own using the `track by` expression.
  26582. *
  26583. * For example, you may track items by the index of each item in the collection, using the
  26584. * special scope property `$index`:
  26585. * ```html
  26586. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  26587. * {{n}}
  26588. * </div>
  26589. * ```
  26590. *
  26591. * You may also use arbitrary expressions in `track by`, including references to custom functions
  26592. * on the scope:
  26593. * ```html
  26594. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  26595. * {{n}}
  26596. * </div>
  26597. * ```
  26598. *
  26599. * <div class="alert alert-success">
  26600. * If you are working with objects that have an identifier property, you should track
  26601. * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
  26602. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  26603. * JavaScript objects in the collection have been substituted for new ones. For large collections,
  26604. * this significantly improves rendering performance. If you don't have a unique identifier,
  26605. * `track by $index` can also provide a performance boost.
  26606. * </div>
  26607. * ```html
  26608. * <div ng-repeat="model in collection track by model.id">
  26609. * {{model.name}}
  26610. * </div>
  26611. * ```
  26612. *
  26613. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  26614. * `$id` function, which tracks items by their identity:
  26615. * ```html
  26616. * <div ng-repeat="obj in collection track by $id(obj)">
  26617. * {{obj.prop}}
  26618. * </div>
  26619. * ```
  26620. *
  26621. * <div class="alert alert-warning">
  26622. * **Note:** `track by` must always be the last expression:
  26623. * </div>
  26624. * ```
  26625. * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
  26626. * {{model.name}}
  26627. * </div>
  26628. * ```
  26629. *
  26630. * # Special repeat start and end points
  26631. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  26632. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  26633. * 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)
  26634. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  26635. *
  26636. * The example below makes use of this feature:
  26637. * ```html
  26638. * <header ng-repeat-start="item in items">
  26639. * Header {{ item }}
  26640. * </header>
  26641. * <div class="body">
  26642. * Body {{ item }}
  26643. * </div>
  26644. * <footer ng-repeat-end>
  26645. * Footer {{ item }}
  26646. * </footer>
  26647. * ```
  26648. *
  26649. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  26650. * ```html
  26651. * <header>
  26652. * Header A
  26653. * </header>
  26654. * <div class="body">
  26655. * Body A
  26656. * </div>
  26657. * <footer>
  26658. * Footer A
  26659. * </footer>
  26660. * <header>
  26661. * Header B
  26662. * </header>
  26663. * <div class="body">
  26664. * Body B
  26665. * </div>
  26666. * <footer>
  26667. * Footer B
  26668. * </footer>
  26669. * ```
  26670. *
  26671. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  26672. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  26673. *
  26674. * @animations
  26675. * | Animation | Occurs |
  26676. * |----------------------------------|-------------------------------------|
  26677. * | {@link ng.$animate#enter enter} | when a new item is added to the list or when an item is revealed after a filter |
  26678. * | {@link ng.$animate#leave leave} | when an item is removed from the list or when an item is filtered out |
  26679. * | {@link ng.$animate#move move } | when an adjacent item is filtered out causing a reorder or when the item contents are reordered |
  26680. *
  26681. * See the example below for defining CSS animations with ngRepeat.
  26682. *
  26683. * @element ANY
  26684. * @scope
  26685. * @priority 1000
  26686. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  26687. * formats are currently supported:
  26688. *
  26689. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  26690. * is a scope expression giving the collection to enumerate.
  26691. *
  26692. * For example: `album in artist.albums`.
  26693. *
  26694. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  26695. * and `expression` is the scope expression giving the collection to enumerate.
  26696. *
  26697. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  26698. *
  26699. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  26700. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  26701. * is specified, ng-repeat associates elements by identity. It is an error to have
  26702. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  26703. * mapped to the same DOM element, which is not possible.)
  26704. *
  26705. * Note that the tracking expression must come last, after any filters, and the alias expression.
  26706. *
  26707. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  26708. * will be associated by item identity in the array.
  26709. *
  26710. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  26711. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  26712. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  26713. * element in the same way in the DOM.
  26714. *
  26715. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  26716. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  26717. * property is same.
  26718. *
  26719. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  26720. * to items in conjunction with a tracking expression.
  26721. *
  26722. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  26723. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  26724. * when a filter is active on the repeater, but the filtered result set is empty.
  26725. *
  26726. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  26727. * the items have been processed through the filter.
  26728. *
  26729. * 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
  26730. * (and not as operator, inside an expression).
  26731. *
  26732. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
  26733. *
  26734. * @example
  26735. * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed
  26736. * results by name. New (entering) and removed (leaving) items are animated.
  26737. <example module="ngRepeat" name="ngRepeat" deps="angular-animate.js" animations="true">
  26738. <file name="index.html">
  26739. <div ng-controller="repeatController">
  26740. I have {{friends.length}} friends. They are:
  26741. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  26742. <ul class="example-animate-container">
  26743. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  26744. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  26745. </li>
  26746. <li class="animate-repeat" ng-if="results.length == 0">
  26747. <strong>No results found...</strong>
  26748. </li>
  26749. </ul>
  26750. </div>
  26751. </file>
  26752. <file name="script.js">
  26753. angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
  26754. $scope.friends = [
  26755. {name:'John', age:25, gender:'boy'},
  26756. {name:'Jessie', age:30, gender:'girl'},
  26757. {name:'Johanna', age:28, gender:'girl'},
  26758. {name:'Joy', age:15, gender:'girl'},
  26759. {name:'Mary', age:28, gender:'girl'},
  26760. {name:'Peter', age:95, gender:'boy'},
  26761. {name:'Sebastian', age:50, gender:'boy'},
  26762. {name:'Erika', age:27, gender:'girl'},
  26763. {name:'Patrick', age:40, gender:'boy'},
  26764. {name:'Samantha', age:60, gender:'girl'}
  26765. ];
  26766. });
  26767. </file>
  26768. <file name="animations.css">
  26769. .example-animate-container {
  26770. background:white;
  26771. border:1px solid black;
  26772. list-style:none;
  26773. margin:0;
  26774. padding:0 10px;
  26775. }
  26776. .animate-repeat {
  26777. line-height:30px;
  26778. list-style:none;
  26779. box-sizing:border-box;
  26780. }
  26781. .animate-repeat.ng-move,
  26782. .animate-repeat.ng-enter,
  26783. .animate-repeat.ng-leave {
  26784. transition:all linear 0.5s;
  26785. }
  26786. .animate-repeat.ng-leave.ng-leave-active,
  26787. .animate-repeat.ng-move,
  26788. .animate-repeat.ng-enter {
  26789. opacity:0;
  26790. max-height:0;
  26791. }
  26792. .animate-repeat.ng-leave,
  26793. .animate-repeat.ng-move.ng-move-active,
  26794. .animate-repeat.ng-enter.ng-enter-active {
  26795. opacity:1;
  26796. max-height:30px;
  26797. }
  26798. </file>
  26799. <file name="protractor.js" type="protractor">
  26800. var friends = element.all(by.repeater('friend in friends'));
  26801. it('should render initial data set', function() {
  26802. expect(friends.count()).toBe(10);
  26803. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  26804. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  26805. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  26806. expect(element(by.binding('friends.length')).getText())
  26807. .toMatch("I have 10 friends. They are:");
  26808. });
  26809. it('should update repeater when filter predicate changes', function() {
  26810. expect(friends.count()).toBe(10);
  26811. element(by.model('q')).sendKeys('ma');
  26812. expect(friends.count()).toBe(2);
  26813. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  26814. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  26815. });
  26816. </file>
  26817. </example>
  26818. */
  26819. var ngRepeatDirective = ['$parse', '$animate', '$compile', function($parse, $animate, $compile) {
  26820. var NG_REMOVED = '$$NG_REMOVED';
  26821. var ngRepeatMinErr = minErr('ngRepeat');
  26822. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  26823. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  26824. scope[valueIdentifier] = value;
  26825. if (keyIdentifier) scope[keyIdentifier] = key;
  26826. scope.$index = index;
  26827. scope.$first = (index === 0);
  26828. scope.$last = (index === (arrayLength - 1));
  26829. scope.$middle = !(scope.$first || scope.$last);
  26830. // jshint bitwise: false
  26831. scope.$odd = !(scope.$even = (index&1) === 0);
  26832. // jshint bitwise: true
  26833. };
  26834. var getBlockStart = function(block) {
  26835. return block.clone[0];
  26836. };
  26837. var getBlockEnd = function(block) {
  26838. return block.clone[block.clone.length - 1];
  26839. };
  26840. return {
  26841. restrict: 'A',
  26842. multiElement: true,
  26843. transclude: 'element',
  26844. priority: 1000,
  26845. terminal: true,
  26846. $$tlb: true,
  26847. compile: function ngRepeatCompile($element, $attr) {
  26848. var expression = $attr.ngRepeat;
  26849. var ngRepeatEndComment = $compile.$$createComment('end ngRepeat', expression);
  26850. 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*$/);
  26851. if (!match) {
  26852. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  26853. expression);
  26854. }
  26855. var lhs = match[1];
  26856. var rhs = match[2];
  26857. var aliasAs = match[3];
  26858. var trackByExp = match[4];
  26859. match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
  26860. if (!match) {
  26861. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  26862. lhs);
  26863. }
  26864. var valueIdentifier = match[3] || match[1];
  26865. var keyIdentifier = match[2];
  26866. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  26867. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  26868. throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
  26869. aliasAs);
  26870. }
  26871. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  26872. var hashFnLocals = {$id: hashKey};
  26873. if (trackByExp) {
  26874. trackByExpGetter = $parse(trackByExp);
  26875. } else {
  26876. trackByIdArrayFn = function(key, value) {
  26877. return hashKey(value);
  26878. };
  26879. trackByIdObjFn = function(key) {
  26880. return key;
  26881. };
  26882. }
  26883. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  26884. if (trackByExpGetter) {
  26885. trackByIdExpFn = function(key, value, index) {
  26886. // assign key, value, and $index to the locals so that they can be used in hash functions
  26887. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  26888. hashFnLocals[valueIdentifier] = value;
  26889. hashFnLocals.$index = index;
  26890. return trackByExpGetter($scope, hashFnLocals);
  26891. };
  26892. }
  26893. // Store a list of elements from previous run. This is a hash where key is the item from the
  26894. // iterator, and the value is objects with following properties.
  26895. // - scope: bound scope
  26896. // - element: previous element.
  26897. // - index: position
  26898. //
  26899. // We are using no-proto object so that we don't need to guard against inherited props via
  26900. // hasOwnProperty.
  26901. var lastBlockMap = createMap();
  26902. //watch props
  26903. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  26904. var index, length,
  26905. previousNode = $element[0], // node that cloned nodes should be inserted after
  26906. // initialized to the comment node anchor
  26907. nextNode,
  26908. // Same as lastBlockMap but it has the current state. It will become the
  26909. // lastBlockMap on the next iteration.
  26910. nextBlockMap = createMap(),
  26911. collectionLength,
  26912. key, value, // key/value of iteration
  26913. trackById,
  26914. trackByIdFn,
  26915. collectionKeys,
  26916. block, // last object information {scope, element, id}
  26917. nextBlockOrder,
  26918. elementsToRemove;
  26919. if (aliasAs) {
  26920. $scope[aliasAs] = collection;
  26921. }
  26922. if (isArrayLike(collection)) {
  26923. collectionKeys = collection;
  26924. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  26925. } else {
  26926. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  26927. // if object, extract keys, in enumeration order, unsorted
  26928. collectionKeys = [];
  26929. for (var itemKey in collection) {
  26930. if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
  26931. collectionKeys.push(itemKey);
  26932. }
  26933. }
  26934. }
  26935. collectionLength = collectionKeys.length;
  26936. nextBlockOrder = new Array(collectionLength);
  26937. // locate existing items
  26938. for (index = 0; index < collectionLength; index++) {
  26939. key = (collection === collectionKeys) ? index : collectionKeys[index];
  26940. value = collection[key];
  26941. trackById = trackByIdFn(key, value, index);
  26942. if (lastBlockMap[trackById]) {
  26943. // found previously seen block
  26944. block = lastBlockMap[trackById];
  26945. delete lastBlockMap[trackById];
  26946. nextBlockMap[trackById] = block;
  26947. nextBlockOrder[index] = block;
  26948. } else if (nextBlockMap[trackById]) {
  26949. // if collision detected. restore lastBlockMap and throw an error
  26950. forEach(nextBlockOrder, function(block) {
  26951. if (block && block.scope) lastBlockMap[block.id] = block;
  26952. });
  26953. throw ngRepeatMinErr('dupes',
  26954. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  26955. expression, trackById, value);
  26956. } else {
  26957. // new never before seen block
  26958. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  26959. nextBlockMap[trackById] = true;
  26960. }
  26961. }
  26962. // remove leftover items
  26963. for (var blockKey in lastBlockMap) {
  26964. block = lastBlockMap[blockKey];
  26965. elementsToRemove = getBlockNodes(block.clone);
  26966. $animate.leave(elementsToRemove);
  26967. if (elementsToRemove[0].parentNode) {
  26968. // if the element was not removed yet because of pending animation, mark it as deleted
  26969. // so that we can ignore it later
  26970. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  26971. elementsToRemove[index][NG_REMOVED] = true;
  26972. }
  26973. }
  26974. block.scope.$destroy();
  26975. }
  26976. // we are not using forEach for perf reasons (trying to avoid #call)
  26977. for (index = 0; index < collectionLength; index++) {
  26978. key = (collection === collectionKeys) ? index : collectionKeys[index];
  26979. value = collection[key];
  26980. block = nextBlockOrder[index];
  26981. if (block.scope) {
  26982. // if we have already seen this object, then we need to reuse the
  26983. // associated scope/element
  26984. nextNode = previousNode;
  26985. // skip nodes that are already pending removal via leave animation
  26986. do {
  26987. nextNode = nextNode.nextSibling;
  26988. } while (nextNode && nextNode[NG_REMOVED]);
  26989. if (getBlockStart(block) != nextNode) {
  26990. // existing item which got moved
  26991. $animate.move(getBlockNodes(block.clone), null, previousNode);
  26992. }
  26993. previousNode = getBlockEnd(block);
  26994. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  26995. } else {
  26996. // new item which we don't know about
  26997. $transclude(function ngRepeatTransclude(clone, scope) {
  26998. block.scope = scope;
  26999. // http://jsperf.com/clone-vs-createcomment
  27000. var endNode = ngRepeatEndComment.cloneNode(false);
  27001. clone[clone.length++] = endNode;
  27002. $animate.enter(clone, null, previousNode);
  27003. previousNode = endNode;
  27004. // Note: We only need the first/last node of the cloned nodes.
  27005. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  27006. // by a directive with templateUrl when its template arrives.
  27007. block.clone = clone;
  27008. nextBlockMap[block.id] = block;
  27009. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  27010. });
  27011. }
  27012. }
  27013. lastBlockMap = nextBlockMap;
  27014. });
  27015. };
  27016. }
  27017. };
  27018. }];
  27019. var NG_HIDE_CLASS = 'ng-hide';
  27020. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  27021. /**
  27022. * @ngdoc directive
  27023. * @name ngShow
  27024. * @multiElement
  27025. *
  27026. * @description
  27027. * The `ngShow` directive shows or hides the given HTML element based on the expression
  27028. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  27029. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  27030. * in AngularJS and sets the display style to none (using an !important flag).
  27031. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  27032. *
  27033. * ```html
  27034. * <!-- when $scope.myValue is truthy (element is visible) -->
  27035. * <div ng-show="myValue"></div>
  27036. *
  27037. * <!-- when $scope.myValue is falsy (element is hidden) -->
  27038. * <div ng-show="myValue" class="ng-hide"></div>
  27039. * ```
  27040. *
  27041. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
  27042. * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
  27043. * from the element causing the element not to appear hidden.
  27044. *
  27045. * ## Why is !important used?
  27046. *
  27047. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  27048. * can be easily overridden by heavier selectors. For example, something as simple
  27049. * as changing the display style on a HTML list item would make hidden elements appear visible.
  27050. * This also becomes a bigger issue when dealing with CSS frameworks.
  27051. *
  27052. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  27053. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  27054. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  27055. *
  27056. * ### Overriding `.ng-hide`
  27057. *
  27058. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  27059. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  27060. * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
  27061. * with extra animation classes that can be added.
  27062. *
  27063. * ```css
  27064. * .ng-hide:not(.ng-hide-animate) {
  27065. * /&#42; this is just another form of hiding an element &#42;/
  27066. * display: block!important;
  27067. * position: absolute;
  27068. * top: -9999px;
  27069. * left: -9999px;
  27070. * }
  27071. * ```
  27072. *
  27073. * By default you don't need to override in CSS anything and the animations will work around the display style.
  27074. *
  27075. * ## A note about animations with `ngShow`
  27076. *
  27077. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  27078. * is true and false. This system works like the animation system present with ngClass except that
  27079. * you must also include the !important flag to override the display property
  27080. * so that you can perform an animation when the element is hidden during the time of the animation.
  27081. *
  27082. * ```css
  27083. * //
  27084. * //a working example can be found at the bottom of this page
  27085. * //
  27086. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  27087. * /&#42; this is required as of 1.3x to properly
  27088. * apply all styling in a show/hide animation &#42;/
  27089. * transition: 0s linear all;
  27090. * }
  27091. *
  27092. * .my-element.ng-hide-add-active,
  27093. * .my-element.ng-hide-remove-active {
  27094. * /&#42; the transition is defined in the active class &#42;/
  27095. * transition: 1s linear all;
  27096. * }
  27097. *
  27098. * .my-element.ng-hide-add { ... }
  27099. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  27100. * .my-element.ng-hide-remove { ... }
  27101. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  27102. * ```
  27103. *
  27104. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display
  27105. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  27106. *
  27107. * @animations
  27108. * | Animation | Occurs |
  27109. * |----------------------------------|-------------------------------------|
  27110. * | {@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 |
  27111. * | {@link $animate#removeClass removeClass} `.ng-hide` | after the `ngShow` expression evaluates to a truthy value and just before contents are set to visible |
  27112. *
  27113. * @element ANY
  27114. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  27115. * then the element is shown or hidden respectively.
  27116. *
  27117. * @example
  27118. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  27119. <file name="index.html">
  27120. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
  27121. <div>
  27122. Show:
  27123. <div class="check-element animate-show" ng-show="checked">
  27124. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  27125. </div>
  27126. </div>
  27127. <div>
  27128. Hide:
  27129. <div class="check-element animate-show" ng-hide="checked">
  27130. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  27131. </div>
  27132. </div>
  27133. </file>
  27134. <file name="glyphicons.css">
  27135. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  27136. </file>
  27137. <file name="animations.css">
  27138. .animate-show {
  27139. line-height: 20px;
  27140. opacity: 1;
  27141. padding: 10px;
  27142. border: 1px solid black;
  27143. background: white;
  27144. }
  27145. .animate-show.ng-hide-add, .animate-show.ng-hide-remove {
  27146. transition: all linear 0.5s;
  27147. }
  27148. .animate-show.ng-hide {
  27149. line-height: 0;
  27150. opacity: 0;
  27151. padding: 0 10px;
  27152. }
  27153. .check-element {
  27154. padding: 10px;
  27155. border: 1px solid black;
  27156. background: white;
  27157. }
  27158. </file>
  27159. <file name="protractor.js" type="protractor">
  27160. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  27161. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  27162. it('should check ng-show / ng-hide', function() {
  27163. expect(thumbsUp.isDisplayed()).toBeFalsy();
  27164. expect(thumbsDown.isDisplayed()).toBeTruthy();
  27165. element(by.model('checked')).click();
  27166. expect(thumbsUp.isDisplayed()).toBeTruthy();
  27167. expect(thumbsDown.isDisplayed()).toBeFalsy();
  27168. });
  27169. </file>
  27170. </example>
  27171. */
  27172. var ngShowDirective = ['$animate', function($animate) {
  27173. return {
  27174. restrict: 'A',
  27175. multiElement: true,
  27176. link: function(scope, element, attr) {
  27177. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  27178. // we're adding a temporary, animation-specific class for ng-hide since this way
  27179. // we can control when the element is actually displayed on screen without having
  27180. // to have a global/greedy CSS selector that breaks when other animations are run.
  27181. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  27182. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  27183. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  27184. });
  27185. });
  27186. }
  27187. };
  27188. }];
  27189. /**
  27190. * @ngdoc directive
  27191. * @name ngHide
  27192. * @multiElement
  27193. *
  27194. * @description
  27195. * The `ngHide` directive shows or hides the given HTML element based on the expression
  27196. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  27197. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  27198. * in AngularJS and sets the display style to none (using an !important flag).
  27199. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  27200. *
  27201. * ```html
  27202. * <!-- when $scope.myValue is truthy (element is hidden) -->
  27203. * <div ng-hide="myValue" class="ng-hide"></div>
  27204. *
  27205. * <!-- when $scope.myValue is falsy (element is visible) -->
  27206. * <div ng-hide="myValue"></div>
  27207. * ```
  27208. *
  27209. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
  27210. * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
  27211. * from the element causing the element not to appear hidden.
  27212. *
  27213. * ## Why is !important used?
  27214. *
  27215. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  27216. * can be easily overridden by heavier selectors. For example, something as simple
  27217. * as changing the display style on a HTML list item would make hidden elements appear visible.
  27218. * This also becomes a bigger issue when dealing with CSS frameworks.
  27219. *
  27220. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  27221. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  27222. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  27223. *
  27224. * ### Overriding `.ng-hide`
  27225. *
  27226. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  27227. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  27228. * class in CSS:
  27229. *
  27230. * ```css
  27231. * .ng-hide {
  27232. * /&#42; this is just another form of hiding an element &#42;/
  27233. * display: block!important;
  27234. * position: absolute;
  27235. * top: -9999px;
  27236. * left: -9999px;
  27237. * }
  27238. * ```
  27239. *
  27240. * By default you don't need to override in CSS anything and the animations will work around the display style.
  27241. *
  27242. * ## A note about animations with `ngHide`
  27243. *
  27244. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  27245. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  27246. * CSS class is added and removed for you instead of your own CSS class.
  27247. *
  27248. * ```css
  27249. * //
  27250. * //a working example can be found at the bottom of this page
  27251. * //
  27252. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  27253. * transition: 0.5s linear all;
  27254. * }
  27255. *
  27256. * .my-element.ng-hide-add { ... }
  27257. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  27258. * .my-element.ng-hide-remove { ... }
  27259. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  27260. * ```
  27261. *
  27262. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display
  27263. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  27264. *
  27265. * @animations
  27266. * | Animation | Occurs |
  27267. * |----------------------------------|-------------------------------------|
  27268. * | {@link $animate#addClass addClass} `.ng-hide` | after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden |
  27269. * | {@link $animate#removeClass removeClass} `.ng-hide` | after the `ngHide` expression evaluates to a non truthy value and just before contents are set to visible |
  27270. *
  27271. *
  27272. * @element ANY
  27273. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  27274. * the element is shown or hidden respectively.
  27275. *
  27276. * @example
  27277. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  27278. <file name="index.html">
  27279. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
  27280. <div>
  27281. Show:
  27282. <div class="check-element animate-hide" ng-show="checked">
  27283. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  27284. </div>
  27285. </div>
  27286. <div>
  27287. Hide:
  27288. <div class="check-element animate-hide" ng-hide="checked">
  27289. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  27290. </div>
  27291. </div>
  27292. </file>
  27293. <file name="glyphicons.css">
  27294. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  27295. </file>
  27296. <file name="animations.css">
  27297. .animate-hide {
  27298. transition: all linear 0.5s;
  27299. line-height: 20px;
  27300. opacity: 1;
  27301. padding: 10px;
  27302. border: 1px solid black;
  27303. background: white;
  27304. }
  27305. .animate-hide.ng-hide {
  27306. line-height: 0;
  27307. opacity: 0;
  27308. padding: 0 10px;
  27309. }
  27310. .check-element {
  27311. padding: 10px;
  27312. border: 1px solid black;
  27313. background: white;
  27314. }
  27315. </file>
  27316. <file name="protractor.js" type="protractor">
  27317. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  27318. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  27319. it('should check ng-show / ng-hide', function() {
  27320. expect(thumbsUp.isDisplayed()).toBeFalsy();
  27321. expect(thumbsDown.isDisplayed()).toBeTruthy();
  27322. element(by.model('checked')).click();
  27323. expect(thumbsUp.isDisplayed()).toBeTruthy();
  27324. expect(thumbsDown.isDisplayed()).toBeFalsy();
  27325. });
  27326. </file>
  27327. </example>
  27328. */
  27329. var ngHideDirective = ['$animate', function($animate) {
  27330. return {
  27331. restrict: 'A',
  27332. multiElement: true,
  27333. link: function(scope, element, attr) {
  27334. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  27335. // The comment inside of the ngShowDirective explains why we add and
  27336. // remove a temporary class for the show/hide animation
  27337. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  27338. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  27339. });
  27340. });
  27341. }
  27342. };
  27343. }];
  27344. /**
  27345. * @ngdoc directive
  27346. * @name ngStyle
  27347. * @restrict AC
  27348. *
  27349. * @description
  27350. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  27351. *
  27352. * @element ANY
  27353. * @param {expression} ngStyle
  27354. *
  27355. * {@link guide/expression Expression} which evals to an
  27356. * object whose keys are CSS style names and values are corresponding values for those CSS
  27357. * keys.
  27358. *
  27359. * Since some CSS style names are not valid keys for an object, they must be quoted.
  27360. * See the 'background-color' style in the example below.
  27361. *
  27362. * @example
  27363. <example>
  27364. <file name="index.html">
  27365. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  27366. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  27367. <input type="button" value="clear" ng-click="myStyle={}">
  27368. <br/>
  27369. <span ng-style="myStyle">Sample Text</span>
  27370. <pre>myStyle={{myStyle}}</pre>
  27371. </file>
  27372. <file name="style.css">
  27373. span {
  27374. color: black;
  27375. }
  27376. </file>
  27377. <file name="protractor.js" type="protractor">
  27378. var colorSpan = element(by.css('span'));
  27379. it('should check ng-style', function() {
  27380. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  27381. element(by.css('input[value=\'set color\']')).click();
  27382. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  27383. element(by.css('input[value=clear]')).click();
  27384. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  27385. });
  27386. </file>
  27387. </example>
  27388. */
  27389. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  27390. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  27391. if (oldStyles && (newStyles !== oldStyles)) {
  27392. forEach(oldStyles, function(val, style) { element.css(style, '');});
  27393. }
  27394. if (newStyles) element.css(newStyles);
  27395. }, true);
  27396. });
  27397. /**
  27398. * @ngdoc directive
  27399. * @name ngSwitch
  27400. * @restrict EA
  27401. *
  27402. * @description
  27403. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  27404. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  27405. * as specified in the template.
  27406. *
  27407. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  27408. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  27409. * matches the value obtained from the evaluated expression. In other words, you define a container element
  27410. * (where you place the directive), place an expression on the **`on="..."` attribute**
  27411. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  27412. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  27413. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  27414. * attribute is displayed.
  27415. *
  27416. * <div class="alert alert-info">
  27417. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  27418. * as literal string values to match against.
  27419. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  27420. * value of the expression `$scope.someVal`.
  27421. * </div>
  27422. * @animations
  27423. * | Animation | Occurs |
  27424. * |----------------------------------|-------------------------------------|
  27425. * | {@link ng.$animate#enter enter} | after the ngSwitch contents change and the matched child element is placed inside the container |
  27426. * | {@link ng.$animate#leave leave} | after the ngSwitch contents change and just before the former contents are removed from the DOM |
  27427. *
  27428. * @usage
  27429. *
  27430. * ```
  27431. * <ANY ng-switch="expression">
  27432. * <ANY ng-switch-when="matchValue1">...</ANY>
  27433. * <ANY ng-switch-when="matchValue2">...</ANY>
  27434. * <ANY ng-switch-default>...</ANY>
  27435. * </ANY>
  27436. * ```
  27437. *
  27438. *
  27439. * @scope
  27440. * @priority 1200
  27441. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  27442. * On child elements add:
  27443. *
  27444. * * `ngSwitchWhen`: the case statement to match against. If match then this
  27445. * case will be displayed. If the same match appears multiple times, all the
  27446. * elements will be displayed.
  27447. * * `ngSwitchDefault`: the default case when no other case match. If there
  27448. * are multiple default cases, all of them will be displayed when no other
  27449. * case match.
  27450. *
  27451. *
  27452. * @example
  27453. <example module="switchExample" deps="angular-animate.js" animations="true">
  27454. <file name="index.html">
  27455. <div ng-controller="ExampleController">
  27456. <select ng-model="selection" ng-options="item for item in items">
  27457. </select>
  27458. <code>selection={{selection}}</code>
  27459. <hr/>
  27460. <div class="animate-switch-container"
  27461. ng-switch on="selection">
  27462. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  27463. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  27464. <div class="animate-switch" ng-switch-default>default</div>
  27465. </div>
  27466. </div>
  27467. </file>
  27468. <file name="script.js">
  27469. angular.module('switchExample', ['ngAnimate'])
  27470. .controller('ExampleController', ['$scope', function($scope) {
  27471. $scope.items = ['settings', 'home', 'other'];
  27472. $scope.selection = $scope.items[0];
  27473. }]);
  27474. </file>
  27475. <file name="animations.css">
  27476. .animate-switch-container {
  27477. position:relative;
  27478. background:white;
  27479. border:1px solid black;
  27480. height:40px;
  27481. overflow:hidden;
  27482. }
  27483. .animate-switch {
  27484. padding:10px;
  27485. }
  27486. .animate-switch.ng-animate {
  27487. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  27488. position:absolute;
  27489. top:0;
  27490. left:0;
  27491. right:0;
  27492. bottom:0;
  27493. }
  27494. .animate-switch.ng-leave.ng-leave-active,
  27495. .animate-switch.ng-enter {
  27496. top:-50px;
  27497. }
  27498. .animate-switch.ng-leave,
  27499. .animate-switch.ng-enter.ng-enter-active {
  27500. top:0;
  27501. }
  27502. </file>
  27503. <file name="protractor.js" type="protractor">
  27504. var switchElem = element(by.css('[ng-switch]'));
  27505. var select = element(by.model('selection'));
  27506. it('should start in settings', function() {
  27507. expect(switchElem.getText()).toMatch(/Settings Div/);
  27508. });
  27509. it('should change to home', function() {
  27510. select.all(by.css('option')).get(1).click();
  27511. expect(switchElem.getText()).toMatch(/Home Span/);
  27512. });
  27513. it('should select default', function() {
  27514. select.all(by.css('option')).get(2).click();
  27515. expect(switchElem.getText()).toMatch(/default/);
  27516. });
  27517. </file>
  27518. </example>
  27519. */
  27520. var ngSwitchDirective = ['$animate', '$compile', function($animate, $compile) {
  27521. return {
  27522. require: 'ngSwitch',
  27523. // asks for $scope to fool the BC controller module
  27524. controller: ['$scope', function ngSwitchController() {
  27525. this.cases = {};
  27526. }],
  27527. link: function(scope, element, attr, ngSwitchController) {
  27528. var watchExpr = attr.ngSwitch || attr.on,
  27529. selectedTranscludes = [],
  27530. selectedElements = [],
  27531. previousLeaveAnimations = [],
  27532. selectedScopes = [];
  27533. var spliceFactory = function(array, index) {
  27534. return function() { array.splice(index, 1); };
  27535. };
  27536. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  27537. var i, ii;
  27538. for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
  27539. $animate.cancel(previousLeaveAnimations[i]);
  27540. }
  27541. previousLeaveAnimations.length = 0;
  27542. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  27543. var selected = getBlockNodes(selectedElements[i].clone);
  27544. selectedScopes[i].$destroy();
  27545. var promise = previousLeaveAnimations[i] = $animate.leave(selected);
  27546. promise.then(spliceFactory(previousLeaveAnimations, i));
  27547. }
  27548. selectedElements.length = 0;
  27549. selectedScopes.length = 0;
  27550. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  27551. forEach(selectedTranscludes, function(selectedTransclude) {
  27552. selectedTransclude.transclude(function(caseElement, selectedScope) {
  27553. selectedScopes.push(selectedScope);
  27554. var anchor = selectedTransclude.element;
  27555. caseElement[caseElement.length++] = $compile.$$createComment('end ngSwitchWhen');
  27556. var block = { clone: caseElement };
  27557. selectedElements.push(block);
  27558. $animate.enter(caseElement, anchor.parent(), anchor);
  27559. });
  27560. });
  27561. }
  27562. });
  27563. }
  27564. };
  27565. }];
  27566. var ngSwitchWhenDirective = ngDirective({
  27567. transclude: 'element',
  27568. priority: 1200,
  27569. require: '^ngSwitch',
  27570. multiElement: true,
  27571. link: function(scope, element, attrs, ctrl, $transclude) {
  27572. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  27573. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  27574. }
  27575. });
  27576. var ngSwitchDefaultDirective = ngDirective({
  27577. transclude: 'element',
  27578. priority: 1200,
  27579. require: '^ngSwitch',
  27580. multiElement: true,
  27581. link: function(scope, element, attr, ctrl, $transclude) {
  27582. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  27583. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  27584. }
  27585. });
  27586. /**
  27587. * @ngdoc directive
  27588. * @name ngTransclude
  27589. * @restrict EAC
  27590. *
  27591. * @description
  27592. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  27593. *
  27594. * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name
  27595. * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.
  27596. *
  27597. * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing
  27598. * content of this element will be removed before the transcluded content is inserted.
  27599. * If the transcluded content is empty, the existing content is left intact. This lets you provide fallback content in the case
  27600. * that no transcluded content is provided.
  27601. *
  27602. * @element ANY
  27603. *
  27604. * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty
  27605. * or its value is the same as the name of the attribute then the default slot is used.
  27606. *
  27607. * @example
  27608. * ### Basic transclusion
  27609. * This example demonstrates basic transclusion of content into a component directive.
  27610. * <example name="simpleTranscludeExample" module="transcludeExample">
  27611. * <file name="index.html">
  27612. * <script>
  27613. * angular.module('transcludeExample', [])
  27614. * .directive('pane', function(){
  27615. * return {
  27616. * restrict: 'E',
  27617. * transclude: true,
  27618. * scope: { title:'@' },
  27619. * template: '<div style="border: 1px solid black;">' +
  27620. * '<div style="background-color: gray">{{title}}</div>' +
  27621. * '<ng-transclude></ng-transclude>' +
  27622. * '</div>'
  27623. * };
  27624. * })
  27625. * .controller('ExampleController', ['$scope', function($scope) {
  27626. * $scope.title = 'Lorem Ipsum';
  27627. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  27628. * }]);
  27629. * </script>
  27630. * <div ng-controller="ExampleController">
  27631. * <input ng-model="title" aria-label="title"> <br/>
  27632. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  27633. * <pane title="{{title}}">{{text}}</pane>
  27634. * </div>
  27635. * </file>
  27636. * <file name="protractor.js" type="protractor">
  27637. * it('should have transcluded', function() {
  27638. * var titleElement = element(by.model('title'));
  27639. * titleElement.clear();
  27640. * titleElement.sendKeys('TITLE');
  27641. * var textElement = element(by.model('text'));
  27642. * textElement.clear();
  27643. * textElement.sendKeys('TEXT');
  27644. * expect(element(by.binding('title')).getText()).toEqual('TITLE');
  27645. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  27646. * });
  27647. * </file>
  27648. * </example>
  27649. *
  27650. * @example
  27651. * ### Transclude fallback content
  27652. * This example shows how to use `NgTransclude` with fallback content, that
  27653. * is displayed if no transcluded content is provided.
  27654. *
  27655. * <example module="transcludeFallbackContentExample">
  27656. * <file name="index.html">
  27657. * <script>
  27658. * angular.module('transcludeFallbackContentExample', [])
  27659. * .directive('myButton', function(){
  27660. * return {
  27661. * restrict: 'E',
  27662. * transclude: true,
  27663. * scope: true,
  27664. * template: '<button style="cursor: pointer;">' +
  27665. * '<ng-transclude>' +
  27666. * '<b style="color: red;">Button1</b>' +
  27667. * '</ng-transclude>' +
  27668. * '</button>'
  27669. * };
  27670. * });
  27671. * </script>
  27672. * <!-- fallback button content -->
  27673. * <my-button id="fallback"></my-button>
  27674. * <!-- modified button content -->
  27675. * <my-button id="modified">
  27676. * <i style="color: green;">Button2</i>
  27677. * </my-button>
  27678. * </file>
  27679. * <file name="protractor.js" type="protractor">
  27680. * it('should have different transclude element content', function() {
  27681. * expect(element(by.id('fallback')).getText()).toBe('Button1');
  27682. * expect(element(by.id('modified')).getText()).toBe('Button2');
  27683. * });
  27684. * </file>
  27685. * </example>
  27686. *
  27687. * @example
  27688. * ### Multi-slot transclusion
  27689. * This example demonstrates using multi-slot transclusion in a component directive.
  27690. * <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample">
  27691. * <file name="index.html">
  27692. * <style>
  27693. * .title, .footer {
  27694. * background-color: gray
  27695. * }
  27696. * </style>
  27697. * <div ng-controller="ExampleController">
  27698. * <input ng-model="title" aria-label="title"> <br/>
  27699. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  27700. * <pane>
  27701. * <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
  27702. * <pane-body><p>{{text}}</p></pane-body>
  27703. * </pane>
  27704. * </div>
  27705. * </file>
  27706. * <file name="app.js">
  27707. * angular.module('multiSlotTranscludeExample', [])
  27708. * .directive('pane', function(){
  27709. * return {
  27710. * restrict: 'E',
  27711. * transclude: {
  27712. * 'title': '?paneTitle',
  27713. * 'body': 'paneBody',
  27714. * 'footer': '?paneFooter'
  27715. * },
  27716. * template: '<div style="border: 1px solid black;">' +
  27717. * '<div class="title" ng-transclude="title">Fallback Title</div>' +
  27718. * '<div ng-transclude="body"></div>' +
  27719. * '<div class="footer" ng-transclude="footer">Fallback Footer</div>' +
  27720. * '</div>'
  27721. * };
  27722. * })
  27723. * .controller('ExampleController', ['$scope', function($scope) {
  27724. * $scope.title = 'Lorem Ipsum';
  27725. * $scope.link = "https://google.com";
  27726. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  27727. * }]);
  27728. * </file>
  27729. * <file name="protractor.js" type="protractor">
  27730. * it('should have transcluded the title and the body', function() {
  27731. * var titleElement = element(by.model('title'));
  27732. * titleElement.clear();
  27733. * titleElement.sendKeys('TITLE');
  27734. * var textElement = element(by.model('text'));
  27735. * textElement.clear();
  27736. * textElement.sendKeys('TEXT');
  27737. * expect(element(by.css('.title')).getText()).toEqual('TITLE');
  27738. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  27739. * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer');
  27740. * });
  27741. * </file>
  27742. * </example>
  27743. */
  27744. var ngTranscludeMinErr = minErr('ngTransclude');
  27745. var ngTranscludeDirective = ngDirective({
  27746. restrict: 'EAC',
  27747. link: function($scope, $element, $attrs, controller, $transclude) {
  27748. if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) {
  27749. // If the attribute is of the form: `ng-transclude="ng-transclude"`
  27750. // then treat it like the default
  27751. $attrs.ngTransclude = '';
  27752. }
  27753. function ngTranscludeCloneAttachFn(clone) {
  27754. if (clone.length) {
  27755. $element.empty();
  27756. $element.append(clone);
  27757. }
  27758. }
  27759. if (!$transclude) {
  27760. throw ngTranscludeMinErr('orphan',
  27761. 'Illegal use of ngTransclude directive in the template! ' +
  27762. 'No parent directive that requires a transclusion found. ' +
  27763. 'Element: {0}',
  27764. startingTag($element));
  27765. }
  27766. // If there is no slot name defined or the slot name is not optional
  27767. // then transclude the slot
  27768. var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot;
  27769. $transclude(ngTranscludeCloneAttachFn, null, slotName);
  27770. }
  27771. });
  27772. /**
  27773. * @ngdoc directive
  27774. * @name script
  27775. * @restrict E
  27776. *
  27777. * @description
  27778. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  27779. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  27780. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  27781. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  27782. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  27783. *
  27784. * @param {string} type Must be set to `'text/ng-template'`.
  27785. * @param {string} id Cache name of the template.
  27786. *
  27787. * @example
  27788. <example>
  27789. <file name="index.html">
  27790. <script type="text/ng-template" id="/tpl.html">
  27791. Content of the template.
  27792. </script>
  27793. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  27794. <div id="tpl-content" ng-include src="currentTpl"></div>
  27795. </file>
  27796. <file name="protractor.js" type="protractor">
  27797. it('should load template defined inside script tag', function() {
  27798. element(by.css('#tpl-link')).click();
  27799. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  27800. });
  27801. </file>
  27802. </example>
  27803. */
  27804. var scriptDirective = ['$templateCache', function($templateCache) {
  27805. return {
  27806. restrict: 'E',
  27807. terminal: true,
  27808. compile: function(element, attr) {
  27809. if (attr.type == 'text/ng-template') {
  27810. var templateUrl = attr.id,
  27811. text = element[0].text;
  27812. $templateCache.put(templateUrl, text);
  27813. }
  27814. }
  27815. };
  27816. }];
  27817. var noopNgModelController = { $setViewValue: noop, $render: noop };
  27818. function chromeHack(optionElement) {
  27819. // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
  27820. // Adding an <option selected="selected"> element to a <select required="required"> should
  27821. // automatically select the new element
  27822. if (optionElement[0].hasAttribute('selected')) {
  27823. optionElement[0].selected = true;
  27824. }
  27825. }
  27826. /**
  27827. * @ngdoc type
  27828. * @name select.SelectController
  27829. * @description
  27830. * The controller for the `<select>` directive. This provides support for reading
  27831. * and writing the selected value(s) of the control and also coordinates dynamically
  27832. * added `<option>` elements, perhaps by an `ngRepeat` directive.
  27833. */
  27834. var SelectController =
  27835. ['$element', '$scope', function($element, $scope) {
  27836. var self = this,
  27837. optionsMap = new HashMap();
  27838. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  27839. self.ngModelCtrl = noopNgModelController;
  27840. // The "unknown" option is one that is prepended to the list if the viewValue
  27841. // does not match any of the options. When it is rendered the value of the unknown
  27842. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  27843. //
  27844. // We can't just jqLite('<option>') since jqLite is not smart enough
  27845. // to create it in <select> and IE barfs otherwise.
  27846. self.unknownOption = jqLite(window.document.createElement('option'));
  27847. self.renderUnknownOption = function(val) {
  27848. var unknownVal = '? ' + hashKey(val) + ' ?';
  27849. self.unknownOption.val(unknownVal);
  27850. $element.prepend(self.unknownOption);
  27851. $element.val(unknownVal);
  27852. };
  27853. $scope.$on('$destroy', function() {
  27854. // disable unknown option so that we don't do work when the whole select is being destroyed
  27855. self.renderUnknownOption = noop;
  27856. });
  27857. self.removeUnknownOption = function() {
  27858. if (self.unknownOption.parent()) self.unknownOption.remove();
  27859. };
  27860. // Read the value of the select control, the implementation of this changes depending
  27861. // upon whether the select can have multiple values and whether ngOptions is at work.
  27862. self.readValue = function readSingleValue() {
  27863. self.removeUnknownOption();
  27864. return $element.val();
  27865. };
  27866. // Write the value to the select control, the implementation of this changes depending
  27867. // upon whether the select can have multiple values and whether ngOptions is at work.
  27868. self.writeValue = function writeSingleValue(value) {
  27869. if (self.hasOption(value)) {
  27870. self.removeUnknownOption();
  27871. $element.val(value);
  27872. if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy
  27873. } else {
  27874. if (value == null && self.emptyOption) {
  27875. self.removeUnknownOption();
  27876. $element.val('');
  27877. } else {
  27878. self.renderUnknownOption(value);
  27879. }
  27880. }
  27881. };
  27882. // Tell the select control that an option, with the given value, has been added
  27883. self.addOption = function(value, element) {
  27884. // Skip comment nodes, as they only pollute the `optionsMap`
  27885. if (element[0].nodeType === NODE_TYPE_COMMENT) return;
  27886. assertNotHasOwnProperty(value, '"option value"');
  27887. if (value === '') {
  27888. self.emptyOption = element;
  27889. }
  27890. var count = optionsMap.get(value) || 0;
  27891. optionsMap.put(value, count + 1);
  27892. self.ngModelCtrl.$render();
  27893. chromeHack(element);
  27894. };
  27895. // Tell the select control that an option, with the given value, has been removed
  27896. self.removeOption = function(value) {
  27897. var count = optionsMap.get(value);
  27898. if (count) {
  27899. if (count === 1) {
  27900. optionsMap.remove(value);
  27901. if (value === '') {
  27902. self.emptyOption = undefined;
  27903. }
  27904. } else {
  27905. optionsMap.put(value, count - 1);
  27906. }
  27907. }
  27908. };
  27909. // Check whether the select control has an option matching the given value
  27910. self.hasOption = function(value) {
  27911. return !!optionsMap.get(value);
  27912. };
  27913. self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
  27914. if (interpolateValueFn) {
  27915. // The value attribute is interpolated
  27916. var oldVal;
  27917. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  27918. if (isDefined(oldVal)) {
  27919. self.removeOption(oldVal);
  27920. }
  27921. oldVal = newVal;
  27922. self.addOption(newVal, optionElement);
  27923. });
  27924. } else if (interpolateTextFn) {
  27925. // The text content is interpolated
  27926. optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
  27927. optionAttrs.$set('value', newVal);
  27928. if (oldVal !== newVal) {
  27929. self.removeOption(oldVal);
  27930. }
  27931. self.addOption(newVal, optionElement);
  27932. });
  27933. } else {
  27934. // The value attribute is static
  27935. self.addOption(optionAttrs.value, optionElement);
  27936. }
  27937. optionElement.on('$destroy', function() {
  27938. self.removeOption(optionAttrs.value);
  27939. self.ngModelCtrl.$render();
  27940. });
  27941. };
  27942. }];
  27943. /**
  27944. * @ngdoc directive
  27945. * @name select
  27946. * @restrict E
  27947. *
  27948. * @description
  27949. * HTML `SELECT` element with angular data-binding.
  27950. *
  27951. * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
  27952. * between the scope and the `<select>` control (including setting default values).
  27953. * It also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
  27954. * {@link ngOptions `ngOptions`} directives.
  27955. *
  27956. * When an item in the `<select>` menu is selected, the value of the selected option will be bound
  27957. * to the model identified by the `ngModel` directive. With static or repeated options, this is
  27958. * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
  27959. * If you want dynamic value attributes, you can use interpolation inside the value attribute.
  27960. *
  27961. * <div class="alert alert-warning">
  27962. * Note that the value of a `select` directive used without `ngOptions` is always a string.
  27963. * When the model needs to be bound to a non-string value, you must either explicitly convert it
  27964. * using a directive (see example below) or use `ngOptions` to specify the set of options.
  27965. * This is because an option element can only be bound to string values at present.
  27966. * </div>
  27967. *
  27968. * If the viewValue of `ngModel` does not match any of the options, then the control
  27969. * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
  27970. *
  27971. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  27972. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  27973. * option. See example below for demonstration.
  27974. *
  27975. * <div class="alert alert-info">
  27976. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  27977. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits, such as
  27978. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  27979. * comprehension expression, and additionally in reducing memory and increasing speed by not creating
  27980. * a new scope for each repeated instance.
  27981. * </div>
  27982. *
  27983. *
  27984. * @param {string} ngModel Assignable angular expression to data-bind to.
  27985. * @param {string=} name Property name of the form under which the control is published.
  27986. * @param {string=} multiple Allows multiple options to be selected. The selected values will be
  27987. * bound to the model as an array.
  27988. * @param {string=} required Sets `required` validation error key if the value is not entered.
  27989. * @param {string=} ngRequired Adds required attribute and required validation constraint to
  27990. * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
  27991. * when you want to data-bind to the required attribute.
  27992. * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
  27993. * interaction with the select element.
  27994. * @param {string=} ngOptions sets the options that the select is populated with and defines what is
  27995. * set on the model on selection. See {@link ngOptions `ngOptions`}.
  27996. *
  27997. * @example
  27998. * ### Simple `select` elements with static options
  27999. *
  28000. * <example name="static-select" module="staticSelect">
  28001. * <file name="index.html">
  28002. * <div ng-controller="ExampleController">
  28003. * <form name="myForm">
  28004. * <label for="singleSelect"> Single select: </label><br>
  28005. * <select name="singleSelect" ng-model="data.singleSelect">
  28006. * <option value="option-1">Option 1</option>
  28007. * <option value="option-2">Option 2</option>
  28008. * </select><br>
  28009. *
  28010. * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
  28011. * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
  28012. * <option value="">---Please select---</option> <!-- not selected / blank option -->
  28013. * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
  28014. * <option value="option-2">Option 2</option>
  28015. * </select><br>
  28016. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  28017. * <tt>singleSelect = {{data.singleSelect}}</tt>
  28018. *
  28019. * <hr>
  28020. * <label for="multipleSelect"> Multiple select: </label><br>
  28021. * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
  28022. * <option value="option-1">Option 1</option>
  28023. * <option value="option-2">Option 2</option>
  28024. * <option value="option-3">Option 3</option>
  28025. * </select><br>
  28026. * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
  28027. * </form>
  28028. * </div>
  28029. * </file>
  28030. * <file name="app.js">
  28031. * angular.module('staticSelect', [])
  28032. * .controller('ExampleController', ['$scope', function($scope) {
  28033. * $scope.data = {
  28034. * singleSelect: null,
  28035. * multipleSelect: [],
  28036. * option1: 'option-1',
  28037. * };
  28038. *
  28039. * $scope.forceUnknownOption = function() {
  28040. * $scope.data.singleSelect = 'nonsense';
  28041. * };
  28042. * }]);
  28043. * </file>
  28044. *</example>
  28045. *
  28046. * ### Using `ngRepeat` to generate `select` options
  28047. * <example name="ngrepeat-select" module="ngrepeatSelect">
  28048. * <file name="index.html">
  28049. * <div ng-controller="ExampleController">
  28050. * <form name="myForm">
  28051. * <label for="repeatSelect"> Repeat select: </label>
  28052. * <select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect">
  28053. * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
  28054. * </select>
  28055. * </form>
  28056. * <hr>
  28057. * <tt>repeatSelect = {{data.repeatSelect}}</tt><br/>
  28058. * </div>
  28059. * </file>
  28060. * <file name="app.js">
  28061. * angular.module('ngrepeatSelect', [])
  28062. * .controller('ExampleController', ['$scope', function($scope) {
  28063. * $scope.data = {
  28064. * repeatSelect: null,
  28065. * availableOptions: [
  28066. * {id: '1', name: 'Option A'},
  28067. * {id: '2', name: 'Option B'},
  28068. * {id: '3', name: 'Option C'}
  28069. * ],
  28070. * };
  28071. * }]);
  28072. * </file>
  28073. *</example>
  28074. *
  28075. *
  28076. * ### Using `select` with `ngOptions` and setting a default value
  28077. * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
  28078. *
  28079. * <example name="select-with-default-values" module="defaultValueSelect">
  28080. * <file name="index.html">
  28081. * <div ng-controller="ExampleController">
  28082. * <form name="myForm">
  28083. * <label for="mySelect">Make a choice:</label>
  28084. * <select name="mySelect" id="mySelect"
  28085. * ng-options="option.name for option in data.availableOptions track by option.id"
  28086. * ng-model="data.selectedOption"></select>
  28087. * </form>
  28088. * <hr>
  28089. * <tt>option = {{data.selectedOption}}</tt><br/>
  28090. * </div>
  28091. * </file>
  28092. * <file name="app.js">
  28093. * angular.module('defaultValueSelect', [])
  28094. * .controller('ExampleController', ['$scope', function($scope) {
  28095. * $scope.data = {
  28096. * availableOptions: [
  28097. * {id: '1', name: 'Option A'},
  28098. * {id: '2', name: 'Option B'},
  28099. * {id: '3', name: 'Option C'}
  28100. * ],
  28101. * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
  28102. * };
  28103. * }]);
  28104. * </file>
  28105. *</example>
  28106. *
  28107. *
  28108. * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
  28109. *
  28110. * <example name="select-with-non-string-options" module="nonStringSelect">
  28111. * <file name="index.html">
  28112. * <select ng-model="model.id" convert-to-number>
  28113. * <option value="0">Zero</option>
  28114. * <option value="1">One</option>
  28115. * <option value="2">Two</option>
  28116. * </select>
  28117. * {{ model }}
  28118. * </file>
  28119. * <file name="app.js">
  28120. * angular.module('nonStringSelect', [])
  28121. * .run(function($rootScope) {
  28122. * $rootScope.model = { id: 2 };
  28123. * })
  28124. * .directive('convertToNumber', function() {
  28125. * return {
  28126. * require: 'ngModel',
  28127. * link: function(scope, element, attrs, ngModel) {
  28128. * ngModel.$parsers.push(function(val) {
  28129. * return parseInt(val, 10);
  28130. * });
  28131. * ngModel.$formatters.push(function(val) {
  28132. * return '' + val;
  28133. * });
  28134. * }
  28135. * };
  28136. * });
  28137. * </file>
  28138. * <file name="protractor.js" type="protractor">
  28139. * it('should initialize to model', function() {
  28140. * var select = element(by.css('select'));
  28141. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  28142. * });
  28143. * </file>
  28144. * </example>
  28145. *
  28146. */
  28147. var selectDirective = function() {
  28148. return {
  28149. restrict: 'E',
  28150. require: ['select', '?ngModel'],
  28151. controller: SelectController,
  28152. priority: 1,
  28153. link: {
  28154. pre: selectPreLink,
  28155. post: selectPostLink
  28156. }
  28157. };
  28158. function selectPreLink(scope, element, attr, ctrls) {
  28159. // if ngModel is not defined, we don't need to do anything
  28160. var ngModelCtrl = ctrls[1];
  28161. if (!ngModelCtrl) return;
  28162. var selectCtrl = ctrls[0];
  28163. selectCtrl.ngModelCtrl = ngModelCtrl;
  28164. // When the selected item(s) changes we delegate getting the value of the select control
  28165. // to the `readValue` method, which can be changed if the select can have multiple
  28166. // selected values or if the options are being generated by `ngOptions`
  28167. element.on('change', function() {
  28168. scope.$apply(function() {
  28169. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  28170. });
  28171. });
  28172. // If the select allows multiple values then we need to modify how we read and write
  28173. // values from and to the control; also what it means for the value to be empty and
  28174. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  28175. // doesn't trigger rendering if only an item in the array changes.
  28176. if (attr.multiple) {
  28177. // Read value now needs to check each option to see if it is selected
  28178. selectCtrl.readValue = function readMultipleValue() {
  28179. var array = [];
  28180. forEach(element.find('option'), function(option) {
  28181. if (option.selected) {
  28182. array.push(option.value);
  28183. }
  28184. });
  28185. return array;
  28186. };
  28187. // Write value now needs to set the selected property of each matching option
  28188. selectCtrl.writeValue = function writeMultipleValue(value) {
  28189. var items = new HashMap(value);
  28190. forEach(element.find('option'), function(option) {
  28191. option.selected = isDefined(items.get(option.value));
  28192. });
  28193. };
  28194. // we have to do it on each watch since ngModel watches reference, but
  28195. // we need to work of an array, so we need to see if anything was inserted/removed
  28196. var lastView, lastViewRef = NaN;
  28197. scope.$watch(function selectMultipleWatch() {
  28198. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  28199. lastView = shallowCopy(ngModelCtrl.$viewValue);
  28200. ngModelCtrl.$render();
  28201. }
  28202. lastViewRef = ngModelCtrl.$viewValue;
  28203. });
  28204. // If we are a multiple select then value is now a collection
  28205. // so the meaning of $isEmpty changes
  28206. ngModelCtrl.$isEmpty = function(value) {
  28207. return !value || value.length === 0;
  28208. };
  28209. }
  28210. }
  28211. function selectPostLink(scope, element, attrs, ctrls) {
  28212. // if ngModel is not defined, we don't need to do anything
  28213. var ngModelCtrl = ctrls[1];
  28214. if (!ngModelCtrl) return;
  28215. var selectCtrl = ctrls[0];
  28216. // We delegate rendering to the `writeValue` method, which can be changed
  28217. // if the select can have multiple selected values or if the options are being
  28218. // generated by `ngOptions`.
  28219. // This must be done in the postLink fn to prevent $render to be called before
  28220. // all nodes have been linked correctly.
  28221. ngModelCtrl.$render = function() {
  28222. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  28223. };
  28224. }
  28225. };
  28226. // The option directive is purely designed to communicate the existence (or lack of)
  28227. // of dynamically created (and destroyed) option elements to their containing select
  28228. // directive via its controller.
  28229. var optionDirective = ['$interpolate', function($interpolate) {
  28230. return {
  28231. restrict: 'E',
  28232. priority: 100,
  28233. compile: function(element, attr) {
  28234. if (isDefined(attr.value)) {
  28235. // If the value attribute is defined, check if it contains an interpolation
  28236. var interpolateValueFn = $interpolate(attr.value, true);
  28237. } else {
  28238. // If the value attribute is not defined then we fall back to the
  28239. // text content of the option element, which may be interpolated
  28240. var interpolateTextFn = $interpolate(element.text(), true);
  28241. if (!interpolateTextFn) {
  28242. attr.$set('value', element.text());
  28243. }
  28244. }
  28245. return function(scope, element, attr) {
  28246. // This is an optimization over using ^^ since we don't want to have to search
  28247. // all the way to the root of the DOM for every single option element
  28248. var selectCtrlName = '$selectController',
  28249. parent = element.parent(),
  28250. selectCtrl = parent.data(selectCtrlName) ||
  28251. parent.parent().data(selectCtrlName); // in case we are in optgroup
  28252. if (selectCtrl) {
  28253. selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
  28254. }
  28255. };
  28256. }
  28257. };
  28258. }];
  28259. var styleDirective = valueFn({
  28260. restrict: 'E',
  28261. terminal: false
  28262. });
  28263. /**
  28264. * @ngdoc directive
  28265. * @name ngRequired
  28266. * @restrict A
  28267. *
  28268. * @description
  28269. *
  28270. * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  28271. * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be
  28272. * applied to custom controls.
  28273. *
  28274. * The directive sets the `required` attribute on the element if the Angular expression inside
  28275. * `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we
  28276. * cannot use interpolation inside `required`. See the {@link guide/interpolation interpolation guide}
  28277. * for more info.
  28278. *
  28279. * The validator will set the `required` error key to true if the `required` attribute is set and
  28280. * calling {@link ngModel.NgModelController#$isEmpty `NgModelController.$isEmpty`} with the
  28281. * {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} returns `true`. For example, the
  28282. * `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing
  28283. * custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based.
  28284. *
  28285. * @example
  28286. * <example name="ngRequiredDirective" module="ngRequiredExample">
  28287. * <file name="index.html">
  28288. * <script>
  28289. * angular.module('ngRequiredExample', [])
  28290. * .controller('ExampleController', ['$scope', function($scope) {
  28291. * $scope.required = true;
  28292. * }]);
  28293. * </script>
  28294. * <div ng-controller="ExampleController">
  28295. * <form name="form">
  28296. * <label for="required">Toggle required: </label>
  28297. * <input type="checkbox" ng-model="required" id="required" />
  28298. * <br>
  28299. * <label for="input">This input must be filled if `required` is true: </label>
  28300. * <input type="text" ng-model="model" id="input" name="input" ng-required="required" /><br>
  28301. * <hr>
  28302. * required error set? = <code>{{form.input.$error.required}}</code><br>
  28303. * model = <code>{{model}}</code>
  28304. * </form>
  28305. * </div>
  28306. * </file>
  28307. * <file name="protractor.js" type="protractor">
  28308. var required = element(by.binding('form.input.$error.required'));
  28309. var model = element(by.binding('model'));
  28310. var input = element(by.id('input'));
  28311. it('should set the required error', function() {
  28312. expect(required.getText()).toContain('true');
  28313. input.sendKeys('123');
  28314. expect(required.getText()).not.toContain('true');
  28315. expect(model.getText()).toContain('123');
  28316. });
  28317. * </file>
  28318. * </example>
  28319. */
  28320. var requiredDirective = function() {
  28321. return {
  28322. restrict: 'A',
  28323. require: '?ngModel',
  28324. link: function(scope, elm, attr, ctrl) {
  28325. if (!ctrl) return;
  28326. attr.required = true; // force truthy in case we are on non input element
  28327. ctrl.$validators.required = function(modelValue, viewValue) {
  28328. return !attr.required || !ctrl.$isEmpty(viewValue);
  28329. };
  28330. attr.$observe('required', function() {
  28331. ctrl.$validate();
  28332. });
  28333. }
  28334. };
  28335. };
  28336. /**
  28337. * @ngdoc directive
  28338. * @name ngPattern
  28339. *
  28340. * @description
  28341. *
  28342. * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  28343. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  28344. *
  28345. * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  28346. * does not match a RegExp which is obtained by evaluating the Angular expression given in the
  28347. * `ngPattern` attribute value:
  28348. * * If the expression evaluates to a RegExp object, then this is used directly.
  28349. * * If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it
  28350. * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  28351. *
  28352. * <div class="alert alert-info">
  28353. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  28354. * start at the index of the last search's match, thus not taking the whole input value into
  28355. * account.
  28356. * </div>
  28357. *
  28358. * <div class="alert alert-info">
  28359. * **Note:** This directive is also added when the plain `pattern` attribute is used, with two
  28360. * differences:
  28361. * <ol>
  28362. * <li>
  28363. * `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is
  28364. * not available.
  28365. * </li>
  28366. * <li>
  28367. * The `ngPattern` attribute must be an expression, while the `pattern` value must be
  28368. * interpolated.
  28369. * </li>
  28370. * </ol>
  28371. * </div>
  28372. *
  28373. * @example
  28374. * <example name="ngPatternDirective" module="ngPatternExample">
  28375. * <file name="index.html">
  28376. * <script>
  28377. * angular.module('ngPatternExample', [])
  28378. * .controller('ExampleController', ['$scope', function($scope) {
  28379. * $scope.regex = '\\d+';
  28380. * }]);
  28381. * </script>
  28382. * <div ng-controller="ExampleController">
  28383. * <form name="form">
  28384. * <label for="regex">Set a pattern (regex string): </label>
  28385. * <input type="text" ng-model="regex" id="regex" />
  28386. * <br>
  28387. * <label for="input">This input is restricted by the current pattern: </label>
  28388. * <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
  28389. * <hr>
  28390. * input valid? = <code>{{form.input.$valid}}</code><br>
  28391. * model = <code>{{model}}</code>
  28392. * </form>
  28393. * </div>
  28394. * </file>
  28395. * <file name="protractor.js" type="protractor">
  28396. var model = element(by.binding('model'));
  28397. var input = element(by.id('input'));
  28398. it('should validate the input with the default pattern', function() {
  28399. input.sendKeys('aaa');
  28400. expect(model.getText()).not.toContain('aaa');
  28401. input.clear().then(function() {
  28402. input.sendKeys('123');
  28403. expect(model.getText()).toContain('123');
  28404. });
  28405. });
  28406. * </file>
  28407. * </example>
  28408. */
  28409. var patternDirective = function() {
  28410. return {
  28411. restrict: 'A',
  28412. require: '?ngModel',
  28413. link: function(scope, elm, attr, ctrl) {
  28414. if (!ctrl) return;
  28415. var regexp, patternExp = attr.ngPattern || attr.pattern;
  28416. attr.$observe('pattern', function(regex) {
  28417. if (isString(regex) && regex.length > 0) {
  28418. regex = new RegExp('^' + regex + '$');
  28419. }
  28420. if (regex && !regex.test) {
  28421. throw minErr('ngPattern')('noregexp',
  28422. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  28423. regex, startingTag(elm));
  28424. }
  28425. regexp = regex || undefined;
  28426. ctrl.$validate();
  28427. });
  28428. ctrl.$validators.pattern = function(modelValue, viewValue) {
  28429. // HTML5 pattern constraint validates the input value, so we validate the viewValue
  28430. return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
  28431. };
  28432. }
  28433. };
  28434. };
  28435. /**
  28436. * @ngdoc directive
  28437. * @name ngMaxlength
  28438. *
  28439. * @description
  28440. *
  28441. * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  28442. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  28443. *
  28444. * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  28445. * is longer than the integer obtained by evaluating the Angular expression given in the
  28446. * `ngMaxlength` attribute value.
  28447. *
  28448. * <div class="alert alert-info">
  28449. * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two
  28450. * differences:
  28451. * <ol>
  28452. * <li>
  28453. * `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint
  28454. * validation is not available.
  28455. * </li>
  28456. * <li>
  28457. * The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be
  28458. * interpolated.
  28459. * </li>
  28460. * </ol>
  28461. * </div>
  28462. *
  28463. * @example
  28464. * <example name="ngMaxlengthDirective" module="ngMaxlengthExample">
  28465. * <file name="index.html">
  28466. * <script>
  28467. * angular.module('ngMaxlengthExample', [])
  28468. * .controller('ExampleController', ['$scope', function($scope) {
  28469. * $scope.maxlength = 5;
  28470. * }]);
  28471. * </script>
  28472. * <div ng-controller="ExampleController">
  28473. * <form name="form">
  28474. * <label for="maxlength">Set a maxlength: </label>
  28475. * <input type="number" ng-model="maxlength" id="maxlength" />
  28476. * <br>
  28477. * <label for="input">This input is restricted by the current maxlength: </label>
  28478. * <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br>
  28479. * <hr>
  28480. * input valid? = <code>{{form.input.$valid}}</code><br>
  28481. * model = <code>{{model}}</code>
  28482. * </form>
  28483. * </div>
  28484. * </file>
  28485. * <file name="protractor.js" type="protractor">
  28486. var model = element(by.binding('model'));
  28487. var input = element(by.id('input'));
  28488. it('should validate the input with the default maxlength', function() {
  28489. input.sendKeys('abcdef');
  28490. expect(model.getText()).not.toContain('abcdef');
  28491. input.clear().then(function() {
  28492. input.sendKeys('abcde');
  28493. expect(model.getText()).toContain('abcde');
  28494. });
  28495. });
  28496. * </file>
  28497. * </example>
  28498. */
  28499. var maxlengthDirective = function() {
  28500. return {
  28501. restrict: 'A',
  28502. require: '?ngModel',
  28503. link: function(scope, elm, attr, ctrl) {
  28504. if (!ctrl) return;
  28505. var maxlength = -1;
  28506. attr.$observe('maxlength', function(value) {
  28507. var intVal = toInt(value);
  28508. maxlength = isNaN(intVal) ? -1 : intVal;
  28509. ctrl.$validate();
  28510. });
  28511. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  28512. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  28513. };
  28514. }
  28515. };
  28516. };
  28517. /**
  28518. * @ngdoc directive
  28519. * @name ngMinlength
  28520. *
  28521. * @description
  28522. *
  28523. * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  28524. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  28525. *
  28526. * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  28527. * is shorter than the integer obtained by evaluating the Angular expression given in the
  28528. * `ngMinlength` attribute value.
  28529. *
  28530. * <div class="alert alert-info">
  28531. * **Note:** This directive is also added when the plain `minlength` attribute is used, with two
  28532. * differences:
  28533. * <ol>
  28534. * <li>
  28535. * `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint
  28536. * validation is not available.
  28537. * </li>
  28538. * <li>
  28539. * The `ngMinlength` value must be an expression, while the `minlength` value must be
  28540. * interpolated.
  28541. * </li>
  28542. * </ol>
  28543. * </div>
  28544. *
  28545. * @example
  28546. * <example name="ngMinlengthDirective" module="ngMinlengthExample">
  28547. * <file name="index.html">
  28548. * <script>
  28549. * angular.module('ngMinlengthExample', [])
  28550. * .controller('ExampleController', ['$scope', function($scope) {
  28551. * $scope.minlength = 3;
  28552. * }]);
  28553. * </script>
  28554. * <div ng-controller="ExampleController">
  28555. * <form name="form">
  28556. * <label for="minlength">Set a minlength: </label>
  28557. * <input type="number" ng-model="minlength" id="minlength" />
  28558. * <br>
  28559. * <label for="input">This input is restricted by the current minlength: </label>
  28560. * <input type="text" ng-model="model" id="input" name="input" ng-minlength="minlength" /><br>
  28561. * <hr>
  28562. * input valid? = <code>{{form.input.$valid}}</code><br>
  28563. * model = <code>{{model}}</code>
  28564. * </form>
  28565. * </div>
  28566. * </file>
  28567. * <file name="protractor.js" type="protractor">
  28568. var model = element(by.binding('model'));
  28569. var input = element(by.id('input'));
  28570. it('should validate the input with the default minlength', function() {
  28571. input.sendKeys('ab');
  28572. expect(model.getText()).not.toContain('ab');
  28573. input.sendKeys('abc');
  28574. expect(model.getText()).toContain('abc');
  28575. });
  28576. * </file>
  28577. * </example>
  28578. */
  28579. var minlengthDirective = function() {
  28580. return {
  28581. restrict: 'A',
  28582. require: '?ngModel',
  28583. link: function(scope, elm, attr, ctrl) {
  28584. if (!ctrl) return;
  28585. var minlength = 0;
  28586. attr.$observe('minlength', function(value) {
  28587. minlength = toInt(value) || 0;
  28588. ctrl.$validate();
  28589. });
  28590. ctrl.$validators.minlength = function(modelValue, viewValue) {
  28591. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  28592. };
  28593. }
  28594. };
  28595. };
  28596. if (window.angular.bootstrap) {
  28597. //AngularJS is already loaded, so we can return here...
  28598. if (window.console) {
  28599. console.log('WARNING: Tried to load angular more than once.');
  28600. }
  28601. return;
  28602. }
  28603. //try to bind to jquery now so that one can write jqLite(document).ready()
  28604. //but we will rebind on bootstrap again.
  28605. bindJQuery();
  28606. publishExternalAPI(angular);
  28607. angular.module("ngLocale", [], ["$provide", function($provide) {
  28608. var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
  28609. function getDecimals(n) {
  28610. n = n + '';
  28611. var i = n.indexOf('.');
  28612. return (i == -1) ? 0 : n.length - i - 1;
  28613. }
  28614. function getVF(n, opt_precision) {
  28615. var v = opt_precision;
  28616. if (undefined === v) {
  28617. v = Math.min(getDecimals(n), 3);
  28618. }
  28619. var base = Math.pow(10, v);
  28620. var f = ((n * base) | 0) % base;
  28621. return {v: v, f: f};
  28622. }
  28623. $provide.value("$locale", {
  28624. "DATETIME_FORMATS": {
  28625. "AMPMS": [
  28626. "AM",
  28627. "PM"
  28628. ],
  28629. "DAY": [
  28630. "Sunday",
  28631. "Monday",
  28632. "Tuesday",
  28633. "Wednesday",
  28634. "Thursday",
  28635. "Friday",
  28636. "Saturday"
  28637. ],
  28638. "ERANAMES": [
  28639. "Before Christ",
  28640. "Anno Domini"
  28641. ],
  28642. "ERAS": [
  28643. "BC",
  28644. "AD"
  28645. ],
  28646. "FIRSTDAYOFWEEK": 6,
  28647. "MONTH": [
  28648. "January",
  28649. "February",
  28650. "March",
  28651. "April",
  28652. "May",
  28653. "June",
  28654. "July",
  28655. "August",
  28656. "September",
  28657. "October",
  28658. "November",
  28659. "December"
  28660. ],
  28661. "SHORTDAY": [
  28662. "Sun",
  28663. "Mon",
  28664. "Tue",
  28665. "Wed",
  28666. "Thu",
  28667. "Fri",
  28668. "Sat"
  28669. ],
  28670. "SHORTMONTH": [
  28671. "Jan",
  28672. "Feb",
  28673. "Mar",
  28674. "Apr",
  28675. "May",
  28676. "Jun",
  28677. "Jul",
  28678. "Aug",
  28679. "Sep",
  28680. "Oct",
  28681. "Nov",
  28682. "Dec"
  28683. ],
  28684. "STANDALONEMONTH": [
  28685. "January",
  28686. "February",
  28687. "March",
  28688. "April",
  28689. "May",
  28690. "June",
  28691. "July",
  28692. "August",
  28693. "September",
  28694. "October",
  28695. "November",
  28696. "December"
  28697. ],
  28698. "WEEKENDRANGE": [
  28699. 5,
  28700. 6
  28701. ],
  28702. "fullDate": "EEEE, MMMM d, y",
  28703. "longDate": "MMMM d, y",
  28704. "medium": "MMM d, y h:mm:ss a",
  28705. "mediumDate": "MMM d, y",
  28706. "mediumTime": "h:mm:ss a",
  28707. "short": "M/d/yy h:mm a",
  28708. "shortDate": "M/d/yy",
  28709. "shortTime": "h:mm a"
  28710. },
  28711. "NUMBER_FORMATS": {
  28712. "CURRENCY_SYM": "$",
  28713. "DECIMAL_SEP": ".",
  28714. "GROUP_SEP": ",",
  28715. "PATTERNS": [
  28716. {
  28717. "gSize": 3,
  28718. "lgSize": 3,
  28719. "maxFrac": 3,
  28720. "minFrac": 0,
  28721. "minInt": 1,
  28722. "negPre": "-",
  28723. "negSuf": "",
  28724. "posPre": "",
  28725. "posSuf": ""
  28726. },
  28727. {
  28728. "gSize": 3,
  28729. "lgSize": 3,
  28730. "maxFrac": 2,
  28731. "minFrac": 2,
  28732. "minInt": 1,
  28733. "negPre": "-\u00a4",
  28734. "negSuf": "",
  28735. "posPre": "\u00a4",
  28736. "posSuf": ""
  28737. }
  28738. ]
  28739. },
  28740. "id": "en-us",
  28741. "localeID": "en_US",
  28742. "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;}
  28743. });
  28744. }]);
  28745. jqLite(window.document).ready(function() {
  28746. angularInit(window.document, bootstrap);
  28747. });
  28748. })(window);
  28749. !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>');